]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
add process_lock()/unlock() in save_config()
[mirror_lxc.git] / src / lxc / lxccontainer.c
1 /* liblxcapi
2 *
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #define _GNU_SOURCE
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <pthread.h>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <sys/mount.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <sched.h>
32 #include <dirent.h>
33 #include "config.h"
34 #include "lxc.h"
35 #include "state.h"
36 #include <lxc/lxccontainer.h>
37 #include "conf.h"
38 #include "confile.h"
39 #include "console.h"
40 #include "cgroup.h"
41 #include "commands.h"
42 #include "version.h"
43 #include "log.h"
44 #include "bdev.h"
45 #include "utils.h"
46 #include "attach.h"
47 #include <lxc/utils.h>
48 #include <lxc/monitor.h>
49 #include <lxc/namespace.h>
50 #include <sched.h>
51 #include <arpa/inet.h>
52
53 #if HAVE_IFADDRS_H
54 #include <ifaddrs.h>
55 #else
56 #include <../include/ifaddrs.h>
57 #endif
58
59 #ifndef HAVE_GETLINE
60 #ifdef HAVE_FGETLN
61 #include <../include/getline.h>
62 #endif
63 #endif
64
65 lxc_log_define(lxc_container, lxc);
66
67 static bool file_exists(char *f)
68 {
69 struct stat statbuf;
70
71 return stat(f, &statbuf) == 0;
72 }
73
74 static bool config_file_exists(const char *lxcpath, const char *cname)
75 {
76 /* $lxcpath + '/' + $cname + '/config' + \0 */
77 int ret, len = strlen(lxcpath) + strlen(cname) + 9;
78 char *fname = alloca(len);
79
80 ret = snprintf(fname, len, "%s/%s/config", lxcpath, cname);
81 if (ret < 0 || ret >= len)
82 return false;
83
84 return file_exists(fname);
85 }
86
87 /*
88 * A few functions to help detect when a container creation failed.
89 * If a container creation was killed partway through, then trying
90 * to actually start that container could harm the host. We detect
91 * this by creating a 'partial' file under the container directory,
92 * and keeping an advisory lock. When container creation completes,
93 * we remove that file. When we load or try to start a container, if
94 * we find that file, without a flock, we remove the container.
95 */
96 int ongoing_create(struct lxc_container *c)
97 {
98 int len = strlen(c->config_path) + strlen(c->name) + 10;
99 char *path = alloca(len);
100 int fd, ret;
101 struct flock lk;
102
103 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
104 if (ret < 0 || ret >= len) {
105 ERROR("Error writing partial pathname");
106 return -1;
107 }
108
109 if (!file_exists(path))
110 return 0;
111 process_lock();
112 fd = open(path, O_RDWR);
113 process_unlock();
114 if (fd < 0) {
115 // give benefit of the doubt
116 SYSERROR("Error opening partial file");
117 return 0;
118 }
119 lk.l_type = F_WRLCK;
120 lk.l_whence = SEEK_SET;
121 lk.l_start = 0;
122 lk.l_len = 0;
123 lk.l_pid = -1;
124 if (fcntl(fd, F_GETLK, &lk) == 0 && lk.l_pid != -1) {
125 // create is still ongoing
126 process_lock();
127 close(fd);
128 process_unlock();
129 return 1;
130 }
131 // create completed but partial is still there.
132 process_lock();
133 close(fd);
134 process_unlock();
135 return 2;
136 }
137
138 int create_partial(struct lxc_container *c)
139 {
140 // $lxcpath + '/' + $name + '/partial' + \0
141 int len = strlen(c->config_path) + strlen(c->name) + 10;
142 char *path = alloca(len);
143 int fd, ret;
144 struct flock lk;
145
146 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
147 if (ret < 0 || ret >= len) {
148 ERROR("Error writing partial pathname");
149 return -1;
150 }
151 process_lock();
152 if ((fd=open(path, O_RDWR | O_CREAT | O_EXCL, 0755)) < 0) {
153 SYSERROR("Erorr creating partial file");
154 process_unlock();
155 return -1;
156 }
157 lk.l_type = F_WRLCK;
158 lk.l_whence = SEEK_SET;
159 lk.l_start = 0;
160 lk.l_len = 0;
161 if (fcntl(fd, F_SETLKW, &lk) < 0) {
162 SYSERROR("Error locking partial file %s", path);
163 close(fd);
164 process_unlock();
165 return -1;
166 }
167 process_unlock();
168
169 return fd;
170 }
171
172 void remove_partial(struct lxc_container *c, int fd)
173 {
174 // $lxcpath + '/' + $name + '/partial' + \0
175 int len = strlen(c->config_path) + strlen(c->name) + 10;
176 char *path = alloca(len);
177 int ret;
178
179 process_lock();
180 close(fd);
181 process_unlock();
182 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
183 if (ret < 0 || ret >= len) {
184 ERROR("Error writing partial pathname");
185 return;
186 }
187 if (unlink(path) < 0)
188 SYSERROR("Error unlink partial file %s", path);
189 }
190
191 /* LOCKING
192 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
193 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
194 * container configuration file.
195 * The container_disk_lock also takes the container_mem_lock.
196 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
197 * NOTHING mutexes two independent programs with their own struct
198 * lxc_container for the same c->name, between API calls. For instance,
199 * c->config_read(); c->start(); Between those calls, data on disk
200 * could change (which shouldn't bother the caller unless for instance
201 * the rootfs get moved). c->config_read(); update; c->config_write();
202 * Two such updaters could race. The callers should therefore check their
203 * results. Trying to prevent that would necessarily expose us to deadlocks
204 * due to hung callers. So I prefer to keep the locks only within our own
205 * functions, not across functions.
206 *
207 * If you're going to clone while holding a lxccontainer, increment
208 * c->numthreads (under privlock) before forking. When deleting,
209 * decrement numthreads under privlock, then if it hits 0 you can delete.
210 * Do not ever use a lxccontainer whose numthreads you did not bump.
211 */
212
213 static void lxc_container_free(struct lxc_container *c)
214 {
215 if (!c)
216 return;
217
218 if (c->configfile) {
219 free(c->configfile);
220 c->configfile = NULL;
221 }
222 if (c->error_string) {
223 free(c->error_string);
224 c->error_string = NULL;
225 }
226 if (c->slock) {
227 lxc_putlock(c->slock);
228 c->slock = NULL;
229 }
230 if (c->privlock) {
231 lxc_putlock(c->privlock);
232 c->privlock = NULL;
233 }
234 if (c->name) {
235 free(c->name);
236 c->name = NULL;
237 }
238 if (c->lxc_conf) {
239 lxc_conf_free(c->lxc_conf);
240 c->lxc_conf = NULL;
241 }
242 if (c->config_path) {
243 free(c->config_path);
244 c->config_path = NULL;
245 }
246 free(c);
247 }
248
249 /*
250 * Consider the following case:
251 freer | racing get()er
252 ==================================================================
253 lxc_container_put() | lxc_container_get()
254 \ lxclock(c->privlock) | c->numthreads < 1? (no)
255 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
256 \ lxcunlock() | \
257 \ lxc_container_free() | \ lxclock() returns
258 | \ c->numthreads < 1 -> return 0
259 \ \ (free stuff) |
260 \ \ sem_destroy(privlock) |
261
262 * When the get()er checks numthreads the first time, one of the following
263 * is true:
264 * 1. freer has set numthreads = 0. get() returns 0
265 * 2. freer is between lxclock and setting numthreads to 0. get()er will
266 * sem_wait on privlock, get lxclock after freer() drops it, then see
267 * numthreads is 0 and exit without touching lxclock again..
268 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
269 * will see --numthreads = 1 and not call lxc_container_free().
270 */
271
272 int lxc_container_get(struct lxc_container *c)
273 {
274 if (!c)
275 return 0;
276
277 // if someone else has already started freeing the container, don't
278 // try to take the lock, which may be invalid
279 if (c->numthreads < 1)
280 return 0;
281
282 if (container_mem_lock(c))
283 return 0;
284 if (c->numthreads < 1) {
285 // bail without trying to unlock, bc the privlock is now probably
286 // in freed memory
287 return 0;
288 }
289 c->numthreads++;
290 container_mem_unlock(c);
291 return 1;
292 }
293
294 int lxc_container_put(struct lxc_container *c)
295 {
296 if (!c)
297 return -1;
298 if (container_mem_lock(c))
299 return -1;
300 if (--c->numthreads < 1) {
301 container_mem_unlock(c);
302 lxc_container_free(c);
303 return 1;
304 }
305 container_mem_unlock(c);
306 return 0;
307 }
308
309 static bool lxcapi_is_defined(struct lxc_container *c)
310 {
311 struct stat statbuf;
312 bool ret = false;
313 int statret;
314
315 if (!c)
316 return false;
317
318 if (container_mem_lock(c))
319 return false;
320 if (!c->configfile)
321 goto out;
322 statret = stat(c->configfile, &statbuf);
323 if (statret != 0)
324 goto out;
325 ret = true;
326
327 out:
328 container_mem_unlock(c);
329 return ret;
330 }
331
332 static const char *lxcapi_state(struct lxc_container *c)
333 {
334 lxc_state_t s;
335
336 if (!c)
337 return NULL;
338 s = lxc_getstate(c->name, c->config_path);
339 return lxc_state2str(s);
340 }
341
342 static bool is_stopped(struct lxc_container *c)
343 {
344 lxc_state_t s;
345 s = lxc_getstate(c->name, c->config_path);
346 return (s == STOPPED);
347 }
348
349 static bool lxcapi_is_running(struct lxc_container *c)
350 {
351 const char *s;
352
353 if (!c)
354 return false;
355 s = lxcapi_state(c);
356 if (!s || strcmp(s, "STOPPED") == 0)
357 return false;
358 return true;
359 }
360
361 static bool lxcapi_freeze(struct lxc_container *c)
362 {
363 int ret;
364 if (!c)
365 return false;
366
367 ret = lxc_freeze(c->name, c->config_path);
368 if (ret)
369 return false;
370 return true;
371 }
372
373 static bool lxcapi_unfreeze(struct lxc_container *c)
374 {
375 int ret;
376 if (!c)
377 return false;
378
379 ret = lxc_unfreeze(c->name, c->config_path);
380 if (ret)
381 return false;
382 return true;
383 }
384
385 static int lxcapi_console_getfd(struct lxc_container *c, int *ttynum, int *masterfd)
386 {
387 int ttyfd;
388 if (!c)
389 return -1;
390
391 ttyfd = lxc_console_getfd(c, ttynum, masterfd);
392 return ttyfd;
393 }
394
395 static int lxcapi_console(struct lxc_container *c, int ttynum, int stdinfd,
396 int stdoutfd, int stderrfd, int escape)
397 {
398 return lxc_console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape);
399 }
400
401 static pid_t lxcapi_init_pid(struct lxc_container *c)
402 {
403 if (!c)
404 return -1;
405
406 return lxc_cmd_get_init_pid(c->name, c->config_path);
407 }
408
409 static bool load_config_locked(struct lxc_container *c, const char *fname)
410 {
411 if (!c->lxc_conf)
412 c->lxc_conf = lxc_conf_init();
413 if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
414 return true;
415 return false;
416 }
417
418 static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
419 {
420 bool ret = false, need_disklock = false;
421 int lret;
422 const char *fname;
423 if (!c)
424 return false;
425
426 fname = c->configfile;
427 if (alt_file)
428 fname = alt_file;
429 if (!fname)
430 return false;
431 /*
432 * If we're reading something other than the container's config,
433 * we only need to lock the in-memory container. If loading the
434 * container's config file, take the disk lock.
435 */
436 if (strcmp(fname, c->configfile) == 0)
437 need_disklock = true;
438
439 if (need_disklock)
440 lret = container_disk_lock(c);
441 else
442 lret = container_mem_lock(c);
443 if (lret)
444 return false;
445
446 ret = load_config_locked(c, fname);
447
448 if (need_disklock)
449 container_disk_unlock(c);
450 else
451 container_mem_unlock(c);
452 return ret;
453 }
454
455 static void lxcapi_want_daemonize(struct lxc_container *c)
456 {
457 if (!c || !c->lxc_conf)
458 return;
459 if (container_mem_lock(c)) {
460 ERROR("Error getting mem lock");
461 return;
462 }
463 c->daemonize = 1;
464 /* daemonize implies close_all_fds so set it */
465 c->lxc_conf->close_all_fds = 1;
466 container_mem_unlock(c);
467 }
468
469 static bool lxcapi_want_close_all_fds(struct lxc_container *c)
470 {
471 if (!c || !c->lxc_conf)
472 return false;
473 if (container_mem_lock(c)) {
474 ERROR("Error getting mem lock");
475 return false;
476 }
477 c->lxc_conf->close_all_fds = 1;
478 container_mem_unlock(c);
479 return true;
480 }
481
482 static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
483 {
484 int ret;
485
486 if (!c)
487 return false;
488
489 ret = lxc_wait(c->name, state, timeout, c->config_path);
490 return ret == 0;
491 }
492
493
494 static bool wait_on_daemonized_start(struct lxc_container *c, int pid)
495 {
496 /* we'll probably want to make this timeout configurable? */
497 int timeout = 5, ret, status;
498
499 /*
500 * our child is going to fork again, then exit. reap the
501 * child
502 */
503 ret = waitpid(pid, &status, 0);
504 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
505 DEBUG("failed waiting for first dual-fork child");
506 return lxcapi_wait(c, "RUNNING", timeout);
507 }
508
509 static bool am_single_threaded(void)
510 {
511 struct dirent dirent, *direntp;
512 DIR *dir;
513 int count=0;
514
515 process_lock();
516 dir = opendir("/proc/self/task");
517 process_unlock();
518 if (!dir) {
519 INFO("failed to open /proc/self/task");
520 return false;
521 }
522
523 while (!readdir_r(dir, &dirent, &direntp)) {
524 if (!direntp)
525 break;
526
527 if (!strcmp(direntp->d_name, "."))
528 continue;
529
530 if (!strcmp(direntp->d_name, ".."))
531 continue;
532 if (++count > 1)
533 break;
534 }
535 process_lock();
536 closedir(dir);
537 process_unlock();
538 return count == 1;
539 }
540
541 /*
542 * I can't decide if it'd be more convenient for callers if we accept '...',
543 * or a null-terminated array (i.e. execl vs execv)
544 */
545 static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
546 {
547 int ret;
548 struct lxc_conf *conf;
549 int daemonize = 0;
550 char *default_args[] = {
551 "/sbin/init",
552 '\0',
553 };
554
555 /* container exists */
556 if (!c)
557 return false;
558 /* container has been setup */
559 if (!c->lxc_conf)
560 return false;
561
562 if ((ret = ongoing_create(c)) < 0) {
563 ERROR("Error checking for incomplete creation");
564 return false;
565 }
566 if (ret == 2) {
567 ERROR("Error: %s creation was not completed", c->name);
568 c->destroy(c);
569 return false;
570 } else if (ret == 1) {
571 ERROR("Error: creation of %s is ongoing", c->name);
572 return false;
573 }
574
575 /* is this app meant to be run through lxcinit, as in lxc-execute? */
576 if (useinit && !argv)
577 return false;
578
579 if (container_mem_lock(c))
580 return false;
581 conf = c->lxc_conf;
582 daemonize = c->daemonize;
583 container_mem_unlock(c);
584
585 if (useinit) {
586 ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
587 return ret == 0 ? true : false;
588 }
589
590 if (!argv)
591 argv = default_args;
592
593 /*
594 * say, I'm not sure - what locks do we want here? Any?
595 * Is liblxc's locking enough here to protect the on disk
596 * container? We don't want to exclude things like lxc_info
597 * while container is running...
598 */
599 if (daemonize) {
600 if (!lxc_container_get(c))
601 return false;
602 lxc_monitord_spawn(c->config_path);
603
604 pid_t pid = fork();
605 if (pid < 0) {
606 lxc_container_put(c);
607 return false;
608 }
609 if (pid != 0)
610 return wait_on_daemonized_start(c, pid);
611
612 process_unlock(); // we're no longer sharing
613 /* second fork to be reparented by init */
614 pid = fork();
615 if (pid < 0) {
616 SYSERROR("Error doing dual-fork");
617 return false;
618 }
619 if (pid != 0)
620 exit(0);
621 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
622 if (chdir("/")) {
623 SYSERROR("Error chdir()ing to /.");
624 return false;
625 }
626 close(0);
627 close(1);
628 close(2);
629 open("/dev/zero", O_RDONLY);
630 open("/dev/null", O_RDWR);
631 open("/dev/null", O_RDWR);
632 setsid();
633 } else {
634 if (!am_single_threaded()) {
635 ERROR("Cannot start non-daemonized container when threaded");
636 return false;
637 }
638 }
639
640 reboot:
641 conf->reboot = 0;
642 ret = lxc_start(c->name, argv, conf, c->config_path);
643
644 if (conf->reboot) {
645 INFO("container requested reboot");
646 conf->reboot = 0;
647 goto reboot;
648 }
649
650 if (daemonize) {
651 lxc_container_put(c);
652 exit (ret == 0 ? true : false);
653 } else {
654 return (ret == 0 ? true : false);
655 }
656 }
657
658 /*
659 * note there MUST be an ending NULL
660 */
661 static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
662 {
663 va_list ap;
664 char **inargs = NULL;
665 bool bret = false;
666
667 /* container exists */
668 if (!c)
669 return false;
670
671 va_start(ap, useinit);
672 inargs = lxc_va_arg_list_to_argv(ap, 0, 1);
673 va_end(ap);
674
675 if (!inargs) {
676 ERROR("Memory allocation error.");
677 goto out;
678 }
679
680 /* pass NULL if no arguments were supplied */
681 bret = lxcapi_start(c, useinit, *inargs ? inargs : NULL);
682
683 out:
684 if (inargs) {
685 char **arg;
686 for (arg = inargs; *arg; arg++)
687 free(*arg);
688 free(inargs);
689 }
690
691 return bret;
692 }
693
694 static bool lxcapi_stop(struct lxc_container *c)
695 {
696 int ret;
697
698 if (!c)
699 return false;
700
701 ret = lxc_cmd_stop(c->name, c->config_path);
702
703 return ret == 0;
704 }
705
706 /*
707 * create the standard expected container dir
708 */
709 static bool create_container_dir(struct lxc_container *c)
710 {
711 char *s;
712 int len, ret;
713
714 len = strlen(c->config_path) + strlen(c->name) + 2;
715 s = malloc(len);
716 if (!s)
717 return false;
718 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
719 if (ret < 0 || ret >= len) {
720 free(s);
721 return false;
722 }
723 ret = mkdir(s, 0755);
724 if (ret) {
725 if (errno == EEXIST)
726 ret = 0;
727 else
728 SYSERROR("failed to create container path for %s\n", c->name);
729 }
730 free(s);
731 return ret == 0;
732 }
733
734 static const char *lxcapi_get_config_path(struct lxc_container *c);
735 static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v);
736
737 /*
738 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
739 * it returns a mounted bdev on success, NULL on error.
740 */
741 static struct bdev *do_bdev_create(struct lxc_container *c, const char *type,
742 struct bdev_specs *specs)
743 {
744 char *dest;
745 size_t len;
746 struct bdev *bdev;
747 int ret;
748
749 /* rootfs.path or lxcpath/lxcname/rootfs */
750 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0) {
751 const char *rpath = c->lxc_conf->rootfs.path;
752 len = strlen(rpath) + 1;
753 dest = alloca(len);
754 ret = snprintf(dest, len, "%s", rpath);
755 } else {
756 const char *lxcpath = lxcapi_get_config_path(c);
757 len = strlen(c->name) + strlen(lxcpath) + 9;
758 dest = alloca(len);
759 ret = snprintf(dest, len, "%s/%s/rootfs", lxcpath, c->name);
760 }
761 if (ret < 0 || ret >= len)
762 return NULL;
763
764 bdev = bdev_create(dest, type, c->name, specs);
765 if (!bdev) {
766 ERROR("Failed to create backing store type %s\n", type);
767 return NULL;
768 }
769
770 lxcapi_set_config_item(c, "lxc.rootfs", bdev->src);
771
772 /* if we are not root, chown the rootfs dir to root in the
773 * target uidmap */
774
775 if (geteuid() != 0) {
776 if (chown_mapped_root(bdev->dest, c->lxc_conf) < 0) {
777 ERROR("Error chowning %s to container root\n", bdev->dest);
778 bdev_put(bdev);
779 return NULL;
780 }
781 }
782
783 return bdev;
784 }
785
786 /*
787 * Given the '-t' template option to lxc-create, figure out what to
788 * do. If the template is a full executable path, use that. If it
789 * is something like 'sshd', then return $templatepath/lxc-sshd.
790 * On success return the template, on error return NULL.
791 */
792 static char *get_template_path(const char *t)
793 {
794 int ret, len;
795 char *tpath;
796
797 if (t[0] == '/' && access(t, X_OK) == 0) {
798 tpath = strdup(t);
799 return tpath;
800 }
801
802 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
803 tpath = malloc(len);
804 if (!tpath)
805 return NULL;
806 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
807 if (ret < 0 || ret >= len) {
808 free(tpath);
809 return NULL;
810 }
811 if (access(tpath, X_OK) < 0) {
812 SYSERROR("bad template: %s\n", t);
813 free(tpath);
814 return NULL;
815 }
816
817 return tpath;
818 }
819
820 static char *lxcbasename(char *path)
821 {
822 char *p = path + strlen(path) - 1;
823 while (*p != '/' && p > path)
824 p--;
825 return p;
826 }
827
828 static bool create_run_template(struct lxc_container *c, char *tpath, bool quiet,
829 char *const argv[])
830 {
831 pid_t pid;
832
833 if (!tpath)
834 return true;
835
836 pid = fork();
837 if (pid < 0) {
838 SYSERROR("failed to fork task for container creation template\n");
839 return false;
840 }
841
842 if (pid == 0) { // child
843 char *patharg, *namearg, *rootfsarg, *src;
844 struct bdev *bdev = NULL;
845 int i;
846 int ret, len, nargs = 0;
847 char **newargv;
848 struct lxc_conf *conf = c->lxc_conf;
849
850 process_unlock(); // we're no longer sharing
851 if (quiet) {
852 close(0);
853 close(1);
854 close(2);
855 open("/dev/zero", O_RDONLY);
856 open("/dev/null", O_RDWR);
857 open("/dev/null", O_RDWR);
858 }
859
860 src = c->lxc_conf->rootfs.path;
861 /*
862 * for an overlayfs create, what the user wants is the template to fill
863 * in what will become the readonly lower layer. So don't mount for
864 * the template
865 */
866 if (strncmp(src, "overlayfs:", 10) == 0) {
867 src = overlayfs_getlower(src+10);
868 }
869 bdev = bdev_init(src, c->lxc_conf->rootfs.mount, NULL);
870 if (!bdev) {
871 ERROR("Error opening rootfs");
872 exit(1);
873 }
874
875 if (geteuid() == 0) {
876 if (unshare(CLONE_NEWNS) < 0) {
877 ERROR("error unsharing mounts");
878 exit(1);
879 }
880 if (detect_shared_rootfs()) {
881 if (mount("", "", NULL, MS_SLAVE|MS_REC, 0)) {
882 SYSERROR("Failed to make / rslave to run template");
883 ERROR("Continuing...");
884 }
885 }
886 }
887 if (strcmp(bdev->type, "dir") != 0) {
888 if (geteuid() != 0) {
889 ERROR("non-root users can only create directory-backed containers");
890 exit(1);
891 }
892 if (bdev->ops->mount(bdev) < 0) {
893 ERROR("Error mounting rootfs");
894 exit(1);
895 }
896 } else { // TODO come up with a better way here!
897 if (bdev->dest)
898 free(bdev->dest);
899 bdev->dest = strdup(bdev->src);
900 }
901
902 /*
903 * create our new array, pre-pend the template name and
904 * base args
905 */
906 if (argv)
907 for (nargs = 0; argv[nargs]; nargs++) ;
908 nargs += 4; // template, path, rootfs and name args
909
910 newargv = malloc(nargs * sizeof(*newargv));
911 if (!newargv)
912 exit(1);
913 newargv[0] = lxcbasename(tpath);
914
915 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
916 patharg = malloc(len);
917 if (!patharg)
918 exit(1);
919 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
920 if (ret < 0 || ret >= len)
921 exit(1);
922 newargv[1] = patharg;
923 len = strlen("--name=") + strlen(c->name) + 1;
924 namearg = malloc(len);
925 if (!namearg)
926 exit(1);
927 ret = snprintf(namearg, len, "--name=%s", c->name);
928 if (ret < 0 || ret >= len)
929 exit(1);
930 newargv[2] = namearg;
931
932 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
933 rootfsarg = malloc(len);
934 if (!rootfsarg)
935 exit(1);
936 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
937 if (ret < 0 || ret >= len)
938 exit(1);
939 newargv[3] = rootfsarg;
940
941 /* add passed-in args */
942 if (argv)
943 for (i = 4; i < nargs; i++)
944 newargv[i] = argv[i-4];
945
946 /* add trailing NULL */
947 nargs++;
948 newargv = realloc(newargv, nargs * sizeof(*newargv));
949 if (!newargv)
950 exit(1);
951 newargv[nargs - 1] = NULL;
952
953 /*
954 * If we're running the template in a mapped userns, then
955 * we prepend the template command with:
956 * lxc-usernsexec <-m map1> ... <-m mapn> --
957 * and we append "--mapped-uid x", where x is the mapped uid
958 * for our geteuid()
959 */
960 if (geteuid() != 0 && !lxc_list_empty(&conf->id_map)) {
961 int n2args = 1;
962 char txtuid[20];
963 char **n2 = malloc(n2args * sizeof(*n2));
964 struct lxc_list *it;
965 struct id_map *map;
966
967 if (!n2) {
968 SYSERROR("out of memory");
969 exit(1);
970 }
971 newargv[0] = tpath;
972 tpath = "lxc-usernsexec";
973 n2[0] = "lxc-usernsexec";
974 lxc_list_for_each(it, &conf->id_map) {
975 map = it->elem;
976 n2args += 2;
977 n2 = realloc(n2, n2args * sizeof(char *));
978 if (!n2)
979 exit(1);
980 n2[n2args-2] = "-m";
981 n2[n2args-1] = malloc(200);
982 if (!n2[n2args-1])
983 exit(1);
984 ret = snprintf(n2[n2args-1], 200, "%c:%lu:%lu:%lu",
985 map->idtype == ID_TYPE_UID ? 'u' : 'g',
986 map->nsid, map->hostid, map->range);
987 if (ret < 0 || ret >= 200)
988 exit(1);
989 }
990 int hostid_mapped = mapped_hostid(geteuid(), conf);
991 int extraargs = hostid_mapped >= 0 ? 1 : 3;
992 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
993 if (!n2)
994 exit(1);
995 if (hostid_mapped < 0) {
996 hostid_mapped = find_unmapped_nsuid(conf);
997 n2[n2args++] = "-m";
998 if (hostid_mapped < 0) {
999 ERROR("Could not find free uid to map");
1000 exit(1);
1001 }
1002 n2[n2args++] = malloc(200);
1003 if (!n2[n2args-1]) {
1004 SYSERROR("out of memory");
1005 exit(1);
1006 }
1007 ret = snprintf(n2[n2args-1], 200, "u:%d:%d:1",
1008 hostid_mapped, geteuid());
1009 if (ret < 0 || ret >= 200) {
1010 ERROR("string too long");
1011 exit(1);
1012 }
1013 }
1014 n2[n2args++] = "--";
1015 for (i = 0; i < nargs; i++)
1016 n2[i + n2args] = newargv[i];
1017 n2args += nargs;
1018 // Finally add "--mapped-uid $uid" to tell template what to chown
1019 // cached images to
1020 n2args += 2;
1021 n2 = realloc(n2, n2args * sizeof(char *));
1022 if (!n2) {
1023 SYSERROR("out of memory");
1024 exit(1);
1025 }
1026 // note n2[n2args-1] is NULL
1027 n2[n2args-3] = "--mapped-uid";
1028 snprintf(txtuid, 20, "%d", hostid_mapped);
1029 n2[n2args-2] = txtuid;
1030 n2[n2args-1] = NULL;
1031 free(newargv);
1032 newargv = n2;
1033 }
1034 /* execute */
1035 execvp(tpath, newargv);
1036 SYSERROR("failed to execute template %s", tpath);
1037 exit(1);
1038 }
1039
1040 if (wait_for_pid(pid) != 0) {
1041 ERROR("container creation template for %s failed\n", c->name);
1042 return false;
1043 }
1044
1045 return true;
1046 }
1047
1048 bool prepend_lxc_header(char *path, const char *t, char *const argv[])
1049 {
1050 long flen;
1051 char *contents;
1052 FILE *f;
1053 int ret = -1;
1054 #if HAVE_LIBGNUTLS
1055 int i;
1056 unsigned char md_value[SHA_DIGEST_LENGTH];
1057 char *tpath;
1058 #endif
1059
1060 process_lock();
1061 f = fopen(path, "r");
1062 process_unlock();
1063 if (f == NULL)
1064 return false;
1065
1066 if (fseek(f, 0, SEEK_END) < 0)
1067 goto out_error;
1068 if ((flen = ftell(f)) < 0)
1069 goto out_error;
1070 if (fseek(f, 0, SEEK_SET) < 0)
1071 goto out_error;
1072 if ((contents = malloc(flen + 1)) == NULL)
1073 goto out_error;
1074 if (fread(contents, 1, flen, f) != flen)
1075 goto out_free_contents;
1076
1077 contents[flen] = '\0';
1078 process_lock();
1079 ret = fclose(f);
1080 process_unlock();
1081 f = NULL;
1082 if (ret < 0)
1083 goto out_free_contents;
1084
1085 #if HAVE_LIBGNUTLS
1086 tpath = get_template_path(t);
1087 if (!tpath) {
1088 ERROR("bad template: %s\n", t);
1089 goto out_free_contents;
1090 }
1091
1092 ret = sha1sum_file(tpath, md_value);
1093 if (ret < 0) {
1094 ERROR("Error getting sha1sum of %s", tpath);
1095 free(tpath);
1096 goto out_free_contents;
1097 }
1098 free(tpath);
1099 #endif
1100
1101 process_lock();
1102 f = fopen(path, "w");
1103 process_unlock();
1104 if (f == NULL) {
1105 SYSERROR("reopening config for writing");
1106 free(contents);
1107 return false;
1108 }
1109 fprintf(f, "# Template used to create this container: %s\n", t);
1110 if (argv) {
1111 fprintf(f, "# Parameters passed to the template:");
1112 while (*argv) {
1113 fprintf(f, " %s", *argv);
1114 argv++;
1115 }
1116 fprintf(f, "\n");
1117 }
1118 #if HAVE_LIBGNUTLS
1119 fprintf(f, "# Template script checksum (SHA-1): ");
1120 for (i=0; i<SHA_DIGEST_LENGTH; i++)
1121 fprintf(f, "%02x", md_value[i]);
1122 fprintf(f, "\n");
1123 #endif
1124 if (fwrite(contents, 1, flen, f) != flen) {
1125 SYSERROR("Writing original contents");
1126 free(contents);
1127 process_lock();
1128 fclose(f);
1129 process_unlock();
1130 return false;
1131 }
1132 ret = 0;
1133 out_free_contents:
1134 free(contents);
1135 out_error:
1136 if (f) {
1137 int newret;
1138 process_lock();
1139 newret = fclose(f);
1140 process_unlock();
1141 if (ret == 0)
1142 ret = newret;
1143 }
1144 if (ret < 0) {
1145 SYSERROR("Error prepending header");
1146 return false;
1147 }
1148 return true;
1149 }
1150
1151 static bool lxcapi_destroy(struct lxc_container *c);
1152 /*
1153 * lxcapi_create:
1154 * create a container with the given parameters.
1155 * @c: container to be created. It has the lxcpath, name, and a starting
1156 * configuration already set
1157 * @t: the template to execute to instantiate the root filesystem and
1158 * adjust the configuration.
1159 * @bdevtype: backing store type to use. If NULL, dir will be used.
1160 * @specs: additional parameters for the backing store, i.e. LVM vg to
1161 * use.
1162 *
1163 * @argv: the arguments to pass to the template, terminated by NULL. If no
1164 * arguments, you can just pass NULL.
1165 */
1166 static bool lxcapi_create(struct lxc_container *c, const char *t,
1167 const char *bdevtype, struct bdev_specs *specs, int flags,
1168 char *const argv[])
1169 {
1170 bool ret = false;
1171 pid_t pid;
1172 char *tpath = NULL;
1173 int partial_fd;
1174
1175 if (!c)
1176 return false;
1177
1178 if (t) {
1179 tpath = get_template_path(t);
1180 if (!tpath) {
1181 ERROR("bad template: %s\n", t);
1182 goto out;
1183 }
1184 }
1185
1186 /*
1187 * If a template is passed in, and the rootfs already is defined in
1188 * the container config and exists, then * caller is trying to create
1189 * an existing container. Return an error, but do NOT delete the
1190 * container.
1191 */
1192 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
1193 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
1194 ERROR("Container %s:%s already exists", c->config_path, c->name);
1195 goto free_tpath;
1196 }
1197
1198 if (!c->lxc_conf) {
1199 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
1200 ERROR("Error loading default configuration file %s\n", LXC_DEFAULT_CONFIG);
1201 goto free_tpath;
1202 }
1203 }
1204
1205 if (!create_container_dir(c))
1206 goto free_tpath;
1207
1208 /*
1209 * either template or rootfs.path should be set.
1210 * if both template and rootfs.path are set, template is setup as rootfs.path.
1211 * container is already created if we have a config and rootfs.path is accessible
1212 */
1213 if (!c->lxc_conf->rootfs.path && !tpath)
1214 /* no template passed in and rootfs does not exist: error */
1215 goto out;
1216 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
1217 /* rootfs passed into configuration, but does not exist: error */
1218 goto out;
1219 if (lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
1220 /* Rootfs already existed, user just wanted to save the
1221 * loaded configuration */
1222 ret = true;
1223 goto out;
1224 }
1225
1226 /* Mark that this container is being created */
1227 if ((partial_fd = create_partial(c)) < 0)
1228 goto out;
1229
1230 /* no need to get disk lock bc we have the partial locked */
1231
1232 /*
1233 * Create the backing store
1234 * Note we can't do this in the same task as we use to execute the
1235 * template because of the way zfs works.
1236 * After you 'zfs create', zfs mounts the fs only in the initial
1237 * namespace.
1238 */
1239 pid = fork();
1240 if (pid < 0) {
1241 SYSERROR("failed to fork task for container creation template\n");
1242 goto out_unlock;
1243 }
1244
1245 if (pid == 0) { // child
1246 struct bdev *bdev = NULL;
1247
1248 process_unlock(); // we're no longer sharing
1249 if (!(bdev = do_bdev_create(c, bdevtype, specs))) {
1250 ERROR("Error creating backing store type %s for %s",
1251 bdevtype ? bdevtype : "(none)", c->name);
1252 exit(1);
1253 }
1254
1255 /* save config file again to store the new rootfs location */
1256 if (!c->save_config(c, NULL)) {
1257 ERROR("failed to save starting configuration for %s\n", c->name);
1258 // parent task won't see bdev in config so we delete it
1259 bdev->ops->umount(bdev);
1260 bdev->ops->destroy(bdev);
1261 exit(1);
1262 }
1263 exit(0);
1264 }
1265 if (wait_for_pid(pid) != 0)
1266 goto out_unlock;
1267
1268 /* reload config to get the rootfs */
1269 if (c->lxc_conf)
1270 lxc_conf_free(c->lxc_conf);
1271 c->lxc_conf = NULL;
1272 if (!load_config_locked(c, c->configfile))
1273 goto out_unlock;
1274
1275 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
1276 goto out_unlock;
1277
1278 // now clear out the lxc_conf we have, reload from the created
1279 // container
1280 if (c->lxc_conf)
1281 lxc_conf_free(c->lxc_conf);
1282 c->lxc_conf = NULL;
1283
1284 if (t) {
1285 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
1286 ERROR("Error prepending header to configuration file");
1287 goto out_unlock;
1288 }
1289 }
1290 ret = load_config_locked(c, c->configfile);
1291
1292 out_unlock:
1293 if (partial_fd >= 0)
1294 remove_partial(c, partial_fd);
1295 out:
1296 if (!ret && c)
1297 lxcapi_destroy(c);
1298 free_tpath:
1299 if (tpath)
1300 free(tpath);
1301 return ret;
1302 }
1303
1304 static bool lxcapi_reboot(struct lxc_container *c)
1305 {
1306 pid_t pid;
1307
1308 if (!c)
1309 return false;
1310 if (!c->is_running(c))
1311 return false;
1312 pid = c->init_pid(c);
1313 if (pid <= 0)
1314 return false;
1315 if (kill(pid, SIGINT) < 0)
1316 return false;
1317 return true;
1318
1319 }
1320
1321 static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
1322 {
1323 bool retv;
1324 pid_t pid;
1325
1326 if (!c)
1327 return false;
1328
1329 if (!timeout)
1330 timeout = -1;
1331 if (!c->is_running(c))
1332 return true;
1333 pid = c->init_pid(c);
1334 if (pid <= 0)
1335 return true;
1336 kill(pid, SIGPWR);
1337 retv = c->wait(c, "STOPPED", timeout);
1338 if (!retv && timeout > 0) {
1339 c->stop(c);
1340 retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
1341 }
1342 return retv;
1343 }
1344
1345 static bool lxcapi_createl(struct lxc_container *c, const char *t,
1346 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
1347 {
1348 bool bret = false;
1349 char **args = NULL;
1350 va_list ap;
1351
1352 if (!c)
1353 return false;
1354
1355 /*
1356 * since we're going to wait for create to finish, I don't think we
1357 * need to get a copy of the arguments.
1358 */
1359 va_start(ap, flags);
1360 args = lxc_va_arg_list_to_argv(ap, 0, 0);
1361 va_end(ap);
1362 if (!args) {
1363 ERROR("Memory allocation error.");
1364 goto out;
1365 }
1366
1367 bret = c->create(c, t, bdevtype, specs, flags, args);
1368
1369 out:
1370 free(args);
1371 return bret;
1372 }
1373
1374 static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
1375 {
1376 int ret;
1377
1378 if (!c || !c->lxc_conf)
1379 return false;
1380 if (container_mem_lock(c))
1381 return false;
1382 ret = lxc_clear_config_item(c->lxc_conf, key);
1383 container_mem_unlock(c);
1384 return ret == 0;
1385 }
1386
1387 static inline void exit_from_ns(struct lxc_container *c, int *old_netns, int *new_netns) {
1388 /* Switch back to original netns */
1389 if (*old_netns >= 0 && setns(*old_netns, CLONE_NEWNET))
1390 SYSERROR("failed to setns");
1391 process_lock();
1392 if (*new_netns >= 0)
1393 close(*new_netns);
1394 if (*old_netns >= 0)
1395 close(*old_netns);
1396 process_unlock();
1397 }
1398
1399 static inline bool enter_to_ns(struct lxc_container *c, int *old_netns, int *new_netns) {
1400 int ret = 0;
1401 char new_netns_path[MAXPATHLEN];
1402
1403 if (!c->is_running(c))
1404 goto out;
1405
1406 /* Save reference to old netns */
1407 process_lock();
1408 *old_netns = open("/proc/self/ns/net", O_RDONLY);
1409 process_unlock();
1410 if (*old_netns < 0) {
1411 SYSERROR("failed to open /proc/self/ns/net");
1412 goto out;
1413 }
1414
1415 /* Switch to new netns */
1416 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", c->init_pid(c));
1417 if (ret < 0 || ret >= MAXPATHLEN)
1418 goto out;
1419
1420 process_lock();
1421 *new_netns = open(new_netns_path, O_RDONLY);
1422 process_unlock();
1423 if (*new_netns < 0) {
1424 SYSERROR("failed to open %s", new_netns_path);
1425 goto out;
1426 }
1427
1428 if (setns(*new_netns, CLONE_NEWNET)) {
1429 SYSERROR("failed to setns");
1430 goto out;
1431 }
1432 return true;
1433 out:
1434 exit_from_ns(c, old_netns, new_netns);
1435 return false;
1436 }
1437
1438 // used by qsort and bsearch functions for comparing names
1439 static inline int string_cmp(char **first, char **second)
1440 {
1441 return strcmp(*first, *second);
1442 }
1443
1444 // used by qsort and bsearch functions for comparing container names
1445 static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1446 {
1447 return strcmp((*first)->name, (*second)->name);
1448 }
1449
1450 static bool add_to_array(char ***names, char *cname, int pos)
1451 {
1452 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1453 if (!newnames) {
1454 ERROR("Out of memory");
1455 return false;
1456 }
1457
1458 *names = newnames;
1459 newnames[pos] = strdup(cname);
1460 if (!newnames[pos])
1461 return false;
1462
1463 // sort the arrray as we will use binary search on it
1464 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1465
1466 return true;
1467 }
1468
1469 static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
1470 {
1471 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1472 if (!newlist) {
1473 ERROR("Out of memory");
1474 return false;
1475 }
1476
1477 *list = newlist;
1478 newlist[pos] = c;
1479
1480 // sort the arrray as we will use binary search on it
1481 if (sort)
1482 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
1483
1484 return true;
1485 }
1486
1487 static char** get_from_array(char ***names, char *cname, int size)
1488 {
1489 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1490 }
1491
1492
1493 static bool array_contains(char ***names, char *cname, int size) {
1494 if(get_from_array(names, cname, size) != NULL)
1495 return true;
1496 return false;
1497 }
1498
1499 static bool remove_from_array(char ***names, char *cname, int size)
1500 {
1501 char **result = get_from_array(names, cname, size);
1502 if (result != NULL) {
1503 free(result);
1504 return true;
1505 }
1506 return false;
1507 }
1508
1509 static char** lxcapi_get_interfaces(struct lxc_container *c)
1510 {
1511 int i, count = 0;
1512 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1513 char **interfaces = NULL;
1514 int old_netns = -1, new_netns = -1;
1515
1516 if (!enter_to_ns(c, &old_netns, &new_netns))
1517 goto out;
1518
1519 /* Grab the list of interfaces */
1520 if (getifaddrs(&interfaceArray)) {
1521 SYSERROR("failed to get interfaces list");
1522 goto out;
1523 }
1524
1525 /* Iterate through the interfaces */
1526 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1527 if (array_contains(&interfaces, tempIfAddr->ifa_name, count))
1528 continue;
1529
1530 if(!add_to_array(&interfaces, tempIfAddr->ifa_name, count))
1531 goto err;
1532 count++;
1533 }
1534
1535 out:
1536 if (interfaceArray)
1537 freeifaddrs(interfaceArray);
1538
1539 exit_from_ns(c, &old_netns, &new_netns);
1540
1541 /* Append NULL to the array */
1542 if(interfaces)
1543 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
1544
1545 return interfaces;
1546
1547 err:
1548 for(i=0;i<count;i++)
1549 free(interfaces[i]);
1550 free(interfaces);
1551 interfaces = NULL;
1552 goto out;
1553 }
1554
1555 static char** lxcapi_get_ips(struct lxc_container *c, char* interface, char* family, int scope)
1556 {
1557 int i, count = 0;
1558 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1559 char addressOutputBuffer[INET6_ADDRSTRLEN];
1560 void *tempAddrPtr = NULL;
1561 char **addresses = NULL;
1562 char *address = NULL;
1563 int old_netns = -1, new_netns = -1;
1564
1565 if (!enter_to_ns(c, &old_netns, &new_netns))
1566 goto out;
1567
1568 /* Grab the list of interfaces */
1569 if (getifaddrs(&interfaceArray)) {
1570 SYSERROR("failed to get interfaces list");
1571 goto out;
1572 }
1573
1574 /* Iterate through the interfaces */
1575 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1576 if (tempIfAddr->ifa_addr == NULL)
1577 continue;
1578
1579 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1580 if (family && strcmp(family, "inet"))
1581 continue;
1582 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1583 }
1584 else {
1585 if (family && strcmp(family, "inet6"))
1586 continue;
1587
1588 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1589 continue;
1590
1591 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1592 }
1593
1594 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1595 continue;
1596 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
1597 continue;
1598
1599 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1600 tempAddrPtr,
1601 addressOutputBuffer,
1602 sizeof(addressOutputBuffer));
1603 if (!address)
1604 continue;
1605
1606 if(!add_to_array(&addresses, address, count))
1607 goto err;
1608 count++;
1609 }
1610
1611 out:
1612 if(interfaceArray)
1613 freeifaddrs(interfaceArray);
1614
1615 exit_from_ns(c, &old_netns, &new_netns);
1616
1617 /* Append NULL to the array */
1618 if(addresses)
1619 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
1620
1621 return addresses;
1622
1623 err:
1624 for(i=0;i<count;i++)
1625 free(addresses[i]);
1626 free(addresses);
1627 addresses = NULL;
1628
1629 goto out;
1630 }
1631
1632 static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
1633 {
1634 int ret;
1635
1636 if (!c || !c->lxc_conf)
1637 return -1;
1638 if (container_mem_lock(c))
1639 return -1;
1640 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
1641 container_mem_unlock(c);
1642 return ret;
1643 }
1644
1645 static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
1646 {
1647 if (!key)
1648 return lxc_listconfigs(retv, inlen);
1649 /*
1650 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1651 * This is an intelligent result to show which keys are valid given
1652 * the type of nic it is
1653 */
1654 if (!c || !c->lxc_conf)
1655 return -1;
1656 if (container_mem_lock(c))
1657 return -1;
1658 int ret = -1;
1659 if (strncmp(key, "lxc.network.", 12) == 0)
1660 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
1661 container_mem_unlock(c);
1662 return ret;
1663 }
1664
1665 static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
1666 {
1667 FILE *fout;
1668 bool ret = false, need_disklock = false;
1669 int lret;
1670
1671 if (!alt_file)
1672 alt_file = c->configfile;
1673 if (!alt_file)
1674 return false; // should we write to stdout if no file is specified?
1675
1676 // If we haven't yet loaded a config, load the stock config
1677 if (!c->lxc_conf) {
1678 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
1679 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
1680 return false;
1681 }
1682 }
1683
1684 if (!create_container_dir(c))
1685 return false;
1686
1687 /*
1688 * If we're writing to the container's config file, take the
1689 * disk lock. Otherwise just take the memlock to protect the
1690 * struct lxc_container while we're traversing it.
1691 */
1692 if (strcmp(c->configfile, alt_file) == 0)
1693 need_disklock = true;
1694
1695 if (need_disklock)
1696 lret = container_disk_lock(c);
1697 else
1698 lret = container_mem_lock(c);
1699
1700 if (lret)
1701 return false;
1702
1703 process_lock();
1704 fout = fopen(alt_file, "w");
1705 process_unlock();
1706 if (!fout)
1707 goto out;
1708 write_config(fout, c->lxc_conf);
1709 process_lock();
1710 fclose(fout);
1711 process_unlock();
1712 ret = true;
1713
1714 out:
1715 if (need_disklock)
1716 container_disk_unlock(c);
1717 else
1718 container_mem_unlock(c);
1719 return ret;
1720 }
1721
1722 static bool mod_rdep(struct lxc_container *c, bool inc)
1723 {
1724 char path[MAXPATHLEN];
1725 int ret, v = 0;
1726 FILE *f;
1727 bool bret = false;
1728
1729 if (container_disk_lock(c))
1730 return false;
1731 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1732 c->name);
1733 if (ret < 0 || ret > MAXPATHLEN)
1734 goto out;
1735 process_lock();
1736 f = fopen(path, "r");
1737 process_unlock();
1738 if (f) {
1739 ret = fscanf(f, "%d", &v);
1740 process_lock();
1741 fclose(f);
1742 process_unlock();
1743 if (ret != 1) {
1744 ERROR("Corrupted file %s", path);
1745 goto out;
1746 }
1747 }
1748 v += inc ? 1 : -1;
1749 process_lock();
1750 f = fopen(path, "w");
1751 process_unlock();
1752 if (!f)
1753 goto out;
1754 if (fprintf(f, "%d\n", v) < 0) {
1755 ERROR("Error writing new snapshots value");
1756 process_lock();
1757 fclose(f);
1758 process_unlock();
1759 goto out;
1760 }
1761 process_lock();
1762 ret = fclose(f);
1763 process_unlock();
1764 if (ret != 0) {
1765 SYSERROR("Error writing to or closing snapshots file");
1766 goto out;
1767 }
1768
1769 bret = true;
1770
1771 out:
1772 container_disk_unlock(c);
1773 return bret;
1774 }
1775
1776 static void strip_newline(char *p)
1777 {
1778 size_t len = strlen(p);
1779 if (len < 1)
1780 return;
1781 if (p[len-1] == '\n')
1782 p[len-1] = '\0';
1783 }
1784
1785 static void mod_all_rdeps(struct lxc_container *c, bool inc)
1786 {
1787 struct lxc_container *p;
1788 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
1789 size_t pathlen = 0, namelen = 0;
1790 FILE *f;
1791 int ret;
1792
1793 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
1794 c->config_path, c->name);
1795 if (ret < 0 || ret >= MAXPATHLEN) {
1796 ERROR("Path name too long");
1797 return;
1798 }
1799 process_lock();
1800 f = fopen(path, "r");
1801 process_unlock();
1802 if (f == NULL)
1803 return;
1804 while (getline(&lxcpath, &pathlen, f) != -1) {
1805 if (getline(&lxcname, &namelen, f) == -1) {
1806 ERROR("badly formatted file %s\n", path);
1807 goto out;
1808 }
1809 strip_newline(lxcpath);
1810 strip_newline(lxcname);
1811 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
1812 ERROR("Unable to find dependent container %s:%s",
1813 lxcpath, lxcname);
1814 continue;
1815 }
1816 if (!mod_rdep(p, inc))
1817 ERROR("Failed to increase numsnapshots for %s:%s",
1818 lxcpath, lxcname);
1819 lxc_container_put(p);
1820 }
1821 out:
1822 if (lxcpath) free(lxcpath);
1823 if (lxcname) free(lxcname);
1824 process_lock();
1825 fclose(f);
1826 process_unlock();
1827 }
1828
1829 static bool has_snapshots(struct lxc_container *c)
1830 {
1831 char path[MAXPATHLEN];
1832 int ret, v;
1833 FILE *f;
1834 bool bret = false;
1835
1836 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1837 c->name);
1838 if (ret < 0 || ret > MAXPATHLEN)
1839 goto out;
1840 process_lock();
1841 f = fopen(path, "r");
1842 process_unlock();
1843 if (!f)
1844 goto out;
1845 ret = fscanf(f, "%d", &v);
1846 process_lock();
1847 fclose(f);
1848 process_unlock();
1849 if (ret != 1)
1850 goto out;
1851 bret = v != 0;
1852
1853 out:
1854 return bret;
1855 }
1856
1857 // do we want the api to support --force, or leave that to the caller?
1858 static bool lxcapi_destroy(struct lxc_container *c)
1859 {
1860 struct bdev *r = NULL;
1861 bool ret = false;
1862
1863 if (!c || !lxcapi_is_defined(c))
1864 return false;
1865
1866 if (container_disk_lock(c))
1867 return false;
1868
1869 if (!is_stopped(c)) {
1870 // we should queue some sort of error - in c->error_string?
1871 ERROR("container %s is not stopped", c->name);
1872 goto out;
1873 }
1874
1875 if (c->lxc_conf && has_snapshots(c)) {
1876 ERROR("container %s has dependent snapshots", c->name);
1877 goto out;
1878 }
1879
1880 if (c->lxc_conf && c->lxc_conf->rootfs.path && c->lxc_conf->rootfs.mount)
1881 r = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
1882 if (r) {
1883 if (r->ops->destroy(r) < 0) {
1884 bdev_put(r);
1885 ERROR("Error destroying rootfs for %s", c->name);
1886 goto out;
1887 }
1888 bdev_put(r);
1889 }
1890
1891 mod_all_rdeps(c, false);
1892
1893 const char *p1 = lxcapi_get_config_path(c);
1894 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
1895 sprintf(path, "%s/%s", p1, c->name);
1896 if (lxc_rmdir_onedev(path) < 0) {
1897 ERROR("Error destroying container directory for %s", c->name);
1898 goto out;
1899 }
1900 ret = true;
1901
1902 out:
1903 container_disk_unlock(c);
1904 return ret;
1905 }
1906
1907 static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
1908 {
1909 struct lxc_config_t *config;
1910
1911 if (!c->lxc_conf)
1912 c->lxc_conf = lxc_conf_init();
1913 if (!c->lxc_conf)
1914 return false;
1915 config = lxc_getconfig(key);
1916 if (!config)
1917 return false;
1918 return (0 == config->cb(key, v, c->lxc_conf));
1919 }
1920
1921 static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
1922 {
1923 bool b = false;
1924
1925 if (!c)
1926 return false;
1927
1928 if (container_mem_lock(c))
1929 return false;
1930
1931 b = set_config_item_locked(c, key, v);
1932
1933 container_mem_unlock(c);
1934 return b;
1935 }
1936
1937 static char *lxcapi_config_file_name(struct lxc_container *c)
1938 {
1939 if (!c || !c->configfile)
1940 return NULL;
1941 return strdup(c->configfile);
1942 }
1943
1944 static const char *lxcapi_get_config_path(struct lxc_container *c)
1945 {
1946 if (!c || !c->config_path)
1947 return NULL;
1948 return (const char *)(c->config_path);
1949 }
1950
1951 /*
1952 * not for export
1953 * Just recalculate the c->configfile based on the
1954 * c->config_path, which must be set.
1955 * The lxc_container must be locked or not yet public.
1956 */
1957 static bool set_config_filename(struct lxc_container *c)
1958 {
1959 char *newpath;
1960 int len, ret;
1961
1962 if (!c->config_path)
1963 return false;
1964
1965 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1966 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
1967 newpath = malloc(len);
1968 if (!newpath)
1969 return false;
1970
1971 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
1972 if (ret < 0 || ret >= len) {
1973 fprintf(stderr, "Error printing out config file name\n");
1974 free(newpath);
1975 return false;
1976 }
1977
1978 if (c->configfile)
1979 free(c->configfile);
1980 c->configfile = newpath;
1981
1982 return true;
1983 }
1984
1985 static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
1986 {
1987 char *p;
1988 bool b = false;
1989 char *oldpath = NULL;
1990
1991 if (!c)
1992 return b;
1993
1994 if (container_mem_lock(c))
1995 return b;
1996
1997 p = strdup(path);
1998 if (!p) {
1999 ERROR("Out of memory setting new lxc path");
2000 goto err;
2001 }
2002
2003 b = true;
2004 if (c->config_path)
2005 oldpath = c->config_path;
2006 c->config_path = p;
2007
2008 /* Since we've changed the config path, we have to change the
2009 * config file name too */
2010 if (!set_config_filename(c)) {
2011 ERROR("Out of memory setting new config filename");
2012 b = false;
2013 free(c->config_path);
2014 c->config_path = oldpath;
2015 oldpath = NULL;
2016 }
2017 err:
2018 if (oldpath)
2019 free(oldpath);
2020 container_mem_unlock(c);
2021 return b;
2022 }
2023
2024
2025 static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
2026 {
2027 int ret;
2028
2029 if (!c)
2030 return false;
2031
2032 if (is_stopped(c))
2033 return false;
2034
2035 if (container_disk_lock(c))
2036 return false;
2037
2038 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
2039
2040 container_disk_unlock(c);
2041 return ret == 0;
2042 }
2043
2044 static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
2045 {
2046 int ret;
2047
2048 if (!c)
2049 return -1;
2050
2051 if (is_stopped(c))
2052 return -1;
2053
2054 if (container_disk_lock(c))
2055 return -1;
2056
2057 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
2058
2059 container_disk_unlock(c);
2060 return ret;
2061 }
2062
2063 const char *lxc_get_default_config_path(void)
2064 {
2065 return default_lxc_path();
2066 }
2067
2068 const char *lxc_get_default_lvm_vg(void)
2069 {
2070 return default_lvm_vg();
2071 }
2072
2073 const char *lxc_get_default_lvm_thin_pool(void)
2074 {
2075 return default_lvm_thin_pool();
2076 }
2077
2078 const char *lxc_get_default_zfs_root(void)
2079 {
2080 return default_zfs_root();
2081 }
2082
2083 const char *lxc_get_version(void)
2084 {
2085 return lxc_version();
2086 }
2087
2088 static int copy_file(char *old, char *new)
2089 {
2090 int in, out;
2091 ssize_t len, ret;
2092 char buf[8096];
2093 struct stat sbuf;
2094
2095 if (file_exists(new)) {
2096 ERROR("copy destination %s exists", new);
2097 return -1;
2098 }
2099 ret = stat(old, &sbuf);
2100 if (ret < 0) {
2101 INFO("Error stat'ing %s", old);
2102 return -1;
2103 }
2104
2105 process_lock();
2106 in = open(old, O_RDONLY);
2107 process_unlock();
2108 if (in < 0) {
2109 SYSERROR("Error opening original file %s", old);
2110 return -1;
2111 }
2112 process_lock();
2113 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
2114 process_unlock();
2115 if (out < 0) {
2116 SYSERROR("Error opening new file %s", new);
2117 process_lock();
2118 close(in);
2119 process_unlock();
2120 return -1;
2121 }
2122
2123 while (1) {
2124 len = read(in, buf, 8096);
2125 if (len < 0) {
2126 SYSERROR("Error reading old file %s", old);
2127 goto err;
2128 }
2129 if (len == 0)
2130 break;
2131 ret = write(out, buf, len);
2132 if (ret < len) { // should we retry?
2133 SYSERROR("Error: write to new file %s was interrupted", new);
2134 goto err;
2135 }
2136 }
2137 process_lock();
2138 close(in);
2139 close(out);
2140 process_unlock();
2141
2142 // we set mode, but not owner/group
2143 ret = chmod(new, sbuf.st_mode);
2144 if (ret) {
2145 SYSERROR("Error setting mode on %s", new);
2146 return -1;
2147 }
2148
2149 return 0;
2150
2151 err:
2152 process_lock();
2153 close(in);
2154 close(out);
2155 process_unlock();
2156 return -1;
2157 }
2158
2159 static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2160 {
2161 int i;
2162 int ret;
2163 struct lxc_list *it;
2164
2165 for (i=0; i<NUM_LXC_HOOKS; i++) {
2166 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2167 char *hookname = it->elem;
2168 char *fname = strrchr(hookname, '/');
2169 char tmppath[MAXPATHLEN];
2170 if (!fname) // relative path - we don't support, but maybe we should
2171 return 0;
2172 // copy the script, and change the entry in confile
2173 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2174 c->config_path, c->name, fname+1);
2175 if (ret < 0 || ret >= MAXPATHLEN)
2176 return -1;
2177 ret = copy_file(it->elem, tmppath);
2178 if (ret < 0)
2179 return -1;
2180 free(it->elem);
2181 it->elem = strdup(tmppath);
2182 if (!it->elem) {
2183 ERROR("out of memory copying hook path");
2184 return -1;
2185 }
2186 }
2187 }
2188
2189 c->save_config(c, NULL);
2190 return 0;
2191 }
2192
2193 static void new_hwaddr(char *hwaddr)
2194 {
2195 FILE *f;
2196 process_lock();
2197 f = fopen("/dev/urandom", "r");
2198 process_unlock();
2199 if (f) {
2200 unsigned int seed;
2201 int ret = fread(&seed, sizeof(seed), 1, f);
2202 if (ret != 1)
2203 seed = time(NULL);
2204 process_lock();
2205 fclose(f);
2206 process_unlock();
2207 srand(seed);
2208 } else
2209 srand(time(NULL));
2210 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
2211 rand() % 255, rand() % 255, rand() % 255);
2212 }
2213
2214 static void network_new_hwaddrs(struct lxc_container *c)
2215 {
2216 struct lxc_list *it;
2217
2218 lxc_list_for_each(it, &c->lxc_conf->network) {
2219 struct lxc_netdev *n = it->elem;
2220 if (n->hwaddr)
2221 new_hwaddr(n->hwaddr);
2222 }
2223 }
2224
2225 static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2226 {
2227 char newpath[MAXPATHLEN];
2228 char *oldpath = oldc->lxc_conf->fstab;
2229 int ret;
2230
2231 if (!oldpath)
2232 return 0;
2233
2234 char *p = strrchr(oldpath, '/');
2235 if (!p)
2236 return -1;
2237 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2238 c->config_path, c->name, p);
2239 if (ret < 0 || ret >= MAXPATHLEN) {
2240 ERROR("error printing new path for %s", oldpath);
2241 return -1;
2242 }
2243 if (file_exists(newpath)) {
2244 ERROR("error: fstab file %s exists", newpath);
2245 return -1;
2246 }
2247
2248 if (copy_file(oldpath, newpath) < 0) {
2249 ERROR("error: copying %s to %s", oldpath, newpath);
2250 return -1;
2251 }
2252 free(c->lxc_conf->fstab);
2253 c->lxc_conf->fstab = strdup(newpath);
2254 if (!c->lxc_conf->fstab) {
2255 ERROR("error: allocating pathname");
2256 return -1;
2257 }
2258
2259 return 0;
2260 }
2261
2262 static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2263 {
2264 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2265 int ret;
2266
2267 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2268 c0->name);
2269 if (ret < 0 || ret >= MAXPATHLEN) {
2270 WARN("Error copying reverse dependencies");
2271 return;
2272 }
2273 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2274 c->name);
2275 if (ret < 0 || ret >= MAXPATHLEN) {
2276 WARN("Error copying reverse dependencies");
2277 return;
2278 }
2279 if (copy_file(path0, path1) < 0) {
2280 INFO("Error copying reverse dependencies");
2281 return;
2282 }
2283 }
2284
2285 static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2286 {
2287 int ret;
2288 char path[MAXPATHLEN];
2289 FILE *f;
2290 bool bret;
2291
2292 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2293 c->name);
2294 if (ret < 0 || ret >= MAXPATHLEN)
2295 return false;
2296 process_lock();
2297 f = fopen(path, "a");
2298 process_unlock();
2299 if (!f)
2300 return false;
2301 bret = true;
2302 // if anything goes wrong, just return an error
2303 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2304 bret = false;
2305 process_lock();
2306 if (fclose(f) != 0)
2307 bret = false;
2308 process_unlock();
2309 return bret;
2310 }
2311
2312 static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
2313 const char *newtype, int flags, const char *bdevdata, unsigned long newsize)
2314 {
2315 struct bdev *bdev;
2316 int need_rdep;
2317
2318 bdev = bdev_copy(c0->lxc_conf->rootfs.path, c0->name, c->name,
2319 c0->config_path, c->config_path, newtype, !!(flags & LXC_CLONE_SNAPSHOT),
2320 bdevdata, newsize, &need_rdep);
2321 if (!bdev) {
2322 ERROR("Error copying storage");
2323 return -1;
2324 }
2325 free(c->lxc_conf->rootfs.path);
2326 c->lxc_conf->rootfs.path = strdup(bdev->src);
2327 bdev_put(bdev);
2328 if (!c->lxc_conf->rootfs.path) {
2329 ERROR("Out of memory while setting storage path");
2330 return -1;
2331 }
2332 if (flags & LXC_CLONE_SNAPSHOT)
2333 copy_rdepends(c, c0);
2334 if (need_rdep) {
2335 if (!add_rdepends(c, c0))
2336 WARN("Error adding reverse dependency from %s to %s",
2337 c->name, c0->name);
2338 }
2339
2340 mod_all_rdeps(c, true);
2341
2342 return 0;
2343 }
2344
2345 static int clone_update_rootfs(struct lxc_container *c0,
2346 struct lxc_container *c, int flags,
2347 char **hookargs)
2348 {
2349 int ret = -1;
2350 char path[MAXPATHLEN];
2351 struct bdev *bdev;
2352 FILE *fout;
2353 pid_t pid;
2354 struct lxc_conf *conf = c->lxc_conf;
2355
2356 /* update hostname in rootfs */
2357 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2358
2359 pid = fork();
2360 if (pid < 0)
2361 return -1;
2362 if (pid > 0)
2363 return wait_for_pid(pid);
2364
2365 process_unlock(); // we're no longer sharing
2366 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2367 if (!bdev)
2368 exit(1);
2369 if (strcmp(bdev->type, "dir") != 0) {
2370 if (unshare(CLONE_NEWNS) < 0) {
2371 ERROR("error unsharing mounts");
2372 exit(1);
2373 }
2374 if (bdev->ops->mount(bdev) < 0)
2375 exit(1);
2376 } else { // TODO come up with a better way
2377 if (bdev->dest)
2378 free(bdev->dest);
2379 bdev->dest = strdup(bdev->src);
2380 }
2381
2382 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2383 /* Start of environment variable setup for hooks */
2384 if (setenv("LXC_SRC_NAME", c0->name, 1)) {
2385 SYSERROR("failed to set environment variable for source container name");
2386 }
2387 if (setenv("LXC_NAME", c->name, 1)) {
2388 SYSERROR("failed to set environment variable for container name");
2389 }
2390 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
2391 SYSERROR("failed to set environment variable for config path");
2392 }
2393 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
2394 SYSERROR("failed to set environment variable for rootfs mount");
2395 }
2396 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
2397 SYSERROR("failed to set environment variable for rootfs mount");
2398 }
2399
2400 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
2401 ERROR("Error executing clone hook for %s", c->name);
2402 exit(1);
2403 }
2404 }
2405
2406 if (!(flags & LXC_CLONE_KEEPNAME)) {
2407 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
2408 if (ret < 0 || ret >= MAXPATHLEN)
2409 exit(1);
2410 if (!file_exists(path))
2411 exit(0);
2412 if (!(fout = fopen(path, "w"))) {
2413 SYSERROR("unable to open %s: ignoring\n", path);
2414 exit(0);
2415 }
2416 if (fprintf(fout, "%s", c->name) < 0)
2417 exit(1);
2418 if (fclose(fout) < 0)
2419 exit(1);
2420 }
2421 exit(0);
2422 }
2423
2424 /*
2425 * We want to support:
2426 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2427 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2428
2429 -s [ implies overlayfs]
2430 -s -B overlayfs
2431 -s -B aufs
2432
2433 only rootfs gets converted (copied/snapshotted) on clone.
2434 */
2435
2436 static int create_file_dirname(char *path)
2437 {
2438 char *p = strrchr(path, '/');
2439 int ret;
2440
2441 if (!p)
2442 return -1;
2443 *p = '\0';
2444 ret = mkdir(path, 0755);
2445 if (ret && errno != EEXIST)
2446 SYSERROR("creating container path %s\n", path);
2447 *p = '/';
2448 return ret;
2449 }
2450
2451 struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
2452 const char *lxcpath, int flags,
2453 const char *bdevtype, const char *bdevdata, unsigned long newsize,
2454 char **hookargs)
2455 {
2456 struct lxc_container *c2 = NULL;
2457 char newpath[MAXPATHLEN];
2458 int ret, storage_copied = 0;
2459 const char *n, *l;
2460 FILE *fout;
2461
2462 if (!c || !c->is_defined(c))
2463 return NULL;
2464
2465 if (container_mem_lock(c))
2466 return NULL;
2467
2468 if (!is_stopped(c)) {
2469 ERROR("error: Original container (%s) is running", c->name);
2470 goto out;
2471 }
2472
2473 // Make sure the container doesn't yet exist.
2474 n = newname ? newname : c->name;
2475 l = lxcpath ? lxcpath : c->get_config_path(c);
2476 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
2477 if (ret < 0 || ret >= MAXPATHLEN) {
2478 SYSERROR("clone: failed making config pathname");
2479 goto out;
2480 }
2481 if (file_exists(newpath)) {
2482 ERROR("error: clone: %s exists", newpath);
2483 goto out;
2484 }
2485
2486 ret = create_file_dirname(newpath);
2487 if (ret < 0 && errno != EEXIST) {
2488 ERROR("Error creating container dir for %s", newpath);
2489 goto out;
2490 }
2491
2492 // copy the configuration, tweak it as needed,
2493 process_lock();
2494 fout = fopen(newpath, "w");
2495 process_unlock();
2496 if (!fout) {
2497 SYSERROR("open %s", newpath);
2498 goto out;
2499 }
2500 write_config(fout, c->lxc_conf);
2501 process_lock();
2502 fclose(fout);
2503 process_unlock();
2504
2505 sprintf(newpath, "%s/%s/rootfs", l, n);
2506 if (mkdir(newpath, 0755) < 0) {
2507 SYSERROR("error creating %s", newpath);
2508 goto out;
2509 }
2510
2511 c2 = lxc_container_new(n, l);
2512 if (!c2) {
2513 ERROR("clone: failed to create new container (%s %s)", n, l);
2514 goto out;
2515 }
2516
2517 // update utsname
2518 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
2519 ERROR("Error setting new hostname");
2520 goto out;
2521 }
2522
2523
2524 // copy hooks if requested
2525 if (flags & LXC_CLONE_COPYHOOKS) {
2526 ret = copyhooks(c, c2);
2527 if (ret < 0) {
2528 ERROR("error copying hooks");
2529 goto out;
2530 }
2531 }
2532
2533 if (copy_fstab(c, c2) < 0) {
2534 ERROR("error copying fstab");
2535 goto out;
2536 }
2537
2538 // update macaddrs
2539 if (!(flags & LXC_CLONE_KEEPMACADDR))
2540 network_new_hwaddrs(c2);
2541
2542 // copy/snapshot rootfs's
2543 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
2544 if (ret < 0)
2545 goto out;
2546
2547 // We've now successfully created c2's storage, so clear it out if we
2548 // fail after this
2549 storage_copied = 1;
2550
2551 if (!c2->save_config(c2, NULL))
2552 goto out;
2553
2554 if (clone_update_rootfs(c, c2, flags, hookargs) < 0)
2555 goto out;
2556
2557 // TODO: update c's lxc.snapshot = count
2558 container_mem_unlock(c);
2559 return c2;
2560
2561 out:
2562 container_mem_unlock(c);
2563 if (c2) {
2564 if (!storage_copied)
2565 c2->lxc_conf->rootfs.path = NULL;
2566 c2->destroy(c2);
2567 lxc_container_put(c2);
2568 }
2569
2570 return NULL;
2571 }
2572
2573 static int lxcapi_attach(struct lxc_container *c, lxc_attach_exec_t exec_function, void *exec_payload, lxc_attach_options_t *options, pid_t *attached_process)
2574 {
2575 if (!c)
2576 return -1;
2577
2578 return lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
2579 }
2580
2581 static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
2582 {
2583 lxc_attach_command_t command;
2584 pid_t pid;
2585 int r;
2586
2587 if (!c)
2588 return -1;
2589
2590 command.program = (char*)program;
2591 command.argv = (char**)argv;
2592 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
2593 if (r < 0) {
2594 ERROR("ups");
2595 return r;
2596 }
2597 return lxc_wait_for_pid_status(pid);
2598 }
2599
2600 int get_next_index(const char *lxcpath, char *cname)
2601 {
2602 char *fname;
2603 struct stat sb;
2604 int i = 0, ret;
2605
2606 fname = alloca(strlen(lxcpath) + 20);
2607 while (1) {
2608 sprintf(fname, "%s/snap%d", lxcpath, i);
2609 ret = stat(fname, &sb);
2610 if (ret != 0)
2611 return i;
2612 i++;
2613 }
2614 }
2615
2616 static int lxcapi_snapshot(struct lxc_container *c, char *commentfile)
2617 {
2618 int i, flags, ret;
2619 struct lxc_container *c2;
2620 char snappath[MAXPATHLEN], newname[20];
2621
2622 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2623 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2624 if (ret < 0 || ret >= MAXPATHLEN)
2625 return -1;
2626 i = get_next_index(snappath, c->name);
2627
2628 if (mkdir_p(snappath, 0755) < 0) {
2629 ERROR("Failed to create snapshot directory %s", snappath);
2630 return -1;
2631 }
2632
2633 ret = snprintf(newname, 20, "snap%d", i);
2634 if (ret < 0 || ret >= 20)
2635 return -1;
2636
2637 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME;
2638 c2 = c->clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
2639 if (!c2) {
2640 ERROR("clone of %s:%s failed\n", c->config_path, c->name);
2641 return -1;
2642 }
2643
2644 lxc_container_put(c2);
2645
2646 // Now write down the creation time
2647 time_t timer;
2648 char buffer[25];
2649 struct tm* tm_info;
2650 FILE *f;
2651
2652 time(&timer);
2653 tm_info = localtime(&timer);
2654
2655 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
2656
2657 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
2658 sprintf(dfnam, "%s/%s/ts", snappath, newname);
2659 process_lock();
2660 f = fopen(dfnam, "w");
2661 process_unlock();
2662 if (!f) {
2663 ERROR("Failed to open %s\n", dfnam);
2664 return -1;
2665 }
2666 if (fprintf(f, "%s", buffer) < 0) {
2667 SYSERROR("Writing timestamp");
2668 fclose(f);
2669 return -1;
2670 }
2671 process_lock();
2672 ret = fclose(f);
2673 process_unlock();
2674 if (ret != 0) {
2675 SYSERROR("Writing timestamp");
2676 return -1;
2677 }
2678
2679 if (commentfile) {
2680 // $p / $name / comment \0
2681 int len = strlen(snappath) + strlen(newname) + 10;
2682 char *path = alloca(len);
2683 sprintf(path, "%s/%s/comment", snappath, newname);
2684 return copy_file(commentfile, path) < 0 ? -1 : i;
2685 }
2686
2687 return i;
2688 }
2689
2690 static void lxcsnap_free(struct lxc_snapshot *s)
2691 {
2692 if (s->name)
2693 free(s->name);
2694 if (s->comment_pathname)
2695 free(s->comment_pathname);
2696 if (s->timestamp)
2697 free(s->timestamp);
2698 if (s->lxcpath)
2699 free(s->lxcpath);
2700 }
2701
2702 static char *get_snapcomment_path(char* snappath, char *name)
2703 {
2704 // $snappath/$name/comment
2705 int ret, len = strlen(snappath) + strlen(name) + 10;
2706 char *s = malloc(len);
2707
2708 if (s) {
2709 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
2710 if (ret < 0 || ret >= len) {
2711 free(s);
2712 s = NULL;
2713 }
2714 }
2715 return s;
2716 }
2717
2718 static char *get_timestamp(char* snappath, char *name)
2719 {
2720 char path[MAXPATHLEN], *s = NULL;
2721 int ret, len;
2722 FILE *fin;
2723
2724 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
2725 if (ret < 0 || ret >= MAXPATHLEN)
2726 return NULL;
2727 process_lock();
2728 fin = fopen(path, "r");
2729 process_unlock();
2730 if (!fin)
2731 return NULL;
2732 (void) fseek(fin, 0, SEEK_END);
2733 len = ftell(fin);
2734 (void) fseek(fin, 0, SEEK_SET);
2735 if (len > 0) {
2736 s = malloc(len+1);
2737 if (s) {
2738 s[len] = '\0';
2739 if (fread(s, 1, len, fin) != len) {
2740 SYSERROR("reading timestamp");
2741 free(s);
2742 s = NULL;
2743 }
2744 }
2745 }
2746 process_lock();
2747 fclose(fin);
2748 process_unlock();
2749 return s;
2750 }
2751
2752 static int lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
2753 {
2754 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
2755 int dirlen, count = 0, ret;
2756 struct dirent dirent, *direntp;
2757 struct lxc_snapshot *snaps =NULL, *nsnaps;
2758 DIR *dir;
2759
2760 if (!c || !lxcapi_is_defined(c))
2761 return -1;
2762 // snappath is ${lxcpath}snaps/${lxcname}/
2763 dirlen = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2764 if (dirlen < 0 || dirlen >= MAXPATHLEN) {
2765 ERROR("path name too long");
2766 return -1;
2767 }
2768 process_lock();
2769 dir = opendir(snappath);
2770 process_unlock();
2771 if (!dir) {
2772 INFO("failed to open %s - assuming no snapshots", snappath);
2773 return 0;
2774 }
2775
2776 while (!readdir_r(dir, &dirent, &direntp)) {
2777 if (!direntp)
2778 break;
2779
2780 if (!strcmp(direntp->d_name, "."))
2781 continue;
2782
2783 if (!strcmp(direntp->d_name, ".."))
2784 continue;
2785
2786 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
2787 if (ret < 0 || ret >= MAXPATHLEN) {
2788 ERROR("pathname too long");
2789 goto out_free;
2790 }
2791 if (!file_exists(path2))
2792 continue;
2793 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
2794 if (!nsnaps) {
2795 SYSERROR("Out of memory");
2796 goto out_free;
2797 }
2798 snaps = nsnaps;
2799 snaps[count].free = lxcsnap_free;
2800 snaps[count].name = strdup(direntp->d_name);
2801 if (!snaps[count].name)
2802 goto out_free;
2803 snaps[count].lxcpath = strdup(snappath);
2804 if (!snaps[count].lxcpath) {
2805 free(snaps[count].name);
2806 goto out_free;
2807 }
2808 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
2809 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
2810 count++;
2811 }
2812
2813 process_lock();
2814 if (closedir(dir))
2815 WARN("failed to close directory");
2816 process_unlock();
2817
2818 *ret_snaps = snaps;
2819 return count;
2820
2821 out_free:
2822 if (snaps) {
2823 int i;
2824 for (i=0; i<count; i++)
2825 lxcsnap_free(&snaps[i]);
2826 free(snaps);
2827 }
2828 process_lock();
2829 if (closedir(dir))
2830 WARN("failed to close directory");
2831 process_unlock();
2832 return -1;
2833 }
2834
2835 static bool lxcapi_snapshot_restore(struct lxc_container *c, char *snapname, char *newname)
2836 {
2837 char clonelxcpath[MAXPATHLEN];
2838 int ret;
2839 struct lxc_container *snap, *rest;
2840 struct bdev *bdev;
2841 bool b = false;
2842
2843 if (!c || !c->name || !c->config_path)
2844 return false;
2845
2846 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2847 if (!bdev) {
2848 ERROR("Failed to find original backing store type");
2849 return false;
2850 }
2851
2852 if (!newname)
2853 newname = c->name;
2854 if (strcmp(c->name, newname) == 0) {
2855 if (!lxcapi_destroy(c)) {
2856 ERROR("Could not destroy existing container %s", newname);
2857 bdev_put(bdev);
2858 return false;
2859 }
2860 }
2861 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2862 if (ret < 0 || ret >= MAXPATHLEN) {
2863 bdev_put(bdev);
2864 return false;
2865 }
2866 // how should we lock this?
2867
2868 snap = lxc_container_new(snapname, clonelxcpath);
2869 if (!snap || !lxcapi_is_defined(snap)) {
2870 ERROR("Could not open snapshot %s", snapname);
2871 if (snap) lxc_container_put(snap);
2872 bdev_put(bdev);
2873 return false;
2874 }
2875
2876 rest = lxcapi_clone(snap, newname, c->config_path, 0, bdev->type, NULL, 0, NULL);
2877 bdev_put(bdev);
2878 if (rest && lxcapi_is_defined(rest))
2879 b = true;
2880 if (rest)
2881 lxc_container_put(rest);
2882 lxc_container_put(snap);
2883 return b;
2884 }
2885
2886 static bool lxcapi_snapshot_destroy(struct lxc_container *c, char *snapname)
2887 {
2888 int ret;
2889 char clonelxcpath[MAXPATHLEN];
2890 struct lxc_container *snap = NULL;
2891
2892 if (!c || !c->name || !c->config_path)
2893 return false;
2894
2895 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2896 if (ret < 0 || ret >= MAXPATHLEN)
2897 goto err;
2898
2899 snap = lxc_container_new(snapname, clonelxcpath);
2900 if (!snap || !lxcapi_is_defined(snap)) {
2901 ERROR("Could not find snapshot %s", snapname);
2902 goto err;
2903 }
2904
2905 if (!lxcapi_destroy(snap)) {
2906 ERROR("Could not destroy snapshot %s", snapname);
2907 goto err;
2908 }
2909 lxc_container_put(snap);
2910
2911 return true;
2912 err:
2913 if (snap)
2914 lxc_container_put(snap);
2915 return false;
2916 }
2917
2918 static bool lxcapi_may_control(struct lxc_container *c)
2919 {
2920 return lxc_try_cmd(c->name, c->config_path) == 0;
2921 }
2922
2923 static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
2924 {
2925 va_list ap;
2926 const char **argv;
2927 int ret;
2928
2929 if (!c)
2930 return -1;
2931
2932 va_start(ap, arg);
2933 argv = lxc_va_arg_list_to_argv_const(ap, 1);
2934 va_end(ap);
2935
2936 if (!argv) {
2937 ERROR("Memory allocation error.");
2938 return -1;
2939 }
2940 argv[0] = arg;
2941
2942 ret = lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
2943 free((void*)argv);
2944 return ret;
2945 }
2946
2947 struct lxc_container *lxc_container_new(const char *name, const char *configpath)
2948 {
2949 struct lxc_container *c;
2950
2951 c = malloc(sizeof(*c));
2952 if (!c) {
2953 fprintf(stderr, "failed to malloc lxc_container\n");
2954 return NULL;
2955 }
2956 memset(c, 0, sizeof(*c));
2957
2958 if (configpath)
2959 c->config_path = strdup(configpath);
2960 else
2961 c->config_path = strdup(default_lxc_path());
2962
2963 if (!c->config_path) {
2964 fprintf(stderr, "Out of memory");
2965 goto err;
2966 }
2967
2968 remove_trailing_slashes(c->config_path);
2969 c->name = malloc(strlen(name)+1);
2970 if (!c->name) {
2971 fprintf(stderr, "Error allocating lxc_container name\n");
2972 goto err;
2973 }
2974 strcpy(c->name, name);
2975
2976 c->numthreads = 1;
2977 if (!(c->slock = lxc_newlock(c->config_path, name))) {
2978 fprintf(stderr, "failed to create lock\n");
2979 goto err;
2980 }
2981
2982 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
2983 fprintf(stderr, "failed to alloc privlock\n");
2984 goto err;
2985 }
2986
2987 if (!set_config_filename(c)) {
2988 fprintf(stderr, "Error allocating config file pathname\n");
2989 goto err;
2990 }
2991
2992 if (file_exists(c->configfile))
2993 lxcapi_load_config(c, NULL);
2994
2995 if (ongoing_create(c) == 2) {
2996 ERROR("Error: %s creation was not completed", c->name);
2997 lxcapi_destroy(c);
2998 lxc_conf_free(c->lxc_conf);
2999 c->lxc_conf = NULL;
3000 }
3001
3002 // assign the member functions
3003 c->is_defined = lxcapi_is_defined;
3004 c->state = lxcapi_state;
3005 c->is_running = lxcapi_is_running;
3006 c->freeze = lxcapi_freeze;
3007 c->unfreeze = lxcapi_unfreeze;
3008 c->console = lxcapi_console;
3009 c->console_getfd = lxcapi_console_getfd;
3010 c->init_pid = lxcapi_init_pid;
3011 c->load_config = lxcapi_load_config;
3012 c->want_daemonize = lxcapi_want_daemonize;
3013 c->want_close_all_fds = lxcapi_want_close_all_fds;
3014 c->start = lxcapi_start;
3015 c->startl = lxcapi_startl;
3016 c->stop = lxcapi_stop;
3017 c->config_file_name = lxcapi_config_file_name;
3018 c->wait = lxcapi_wait;
3019 c->set_config_item = lxcapi_set_config_item;
3020 c->destroy = lxcapi_destroy;
3021 c->save_config = lxcapi_save_config;
3022 c->get_keys = lxcapi_get_keys;
3023 c->create = lxcapi_create;
3024 c->createl = lxcapi_createl;
3025 c->shutdown = lxcapi_shutdown;
3026 c->reboot = lxcapi_reboot;
3027 c->clear_config_item = lxcapi_clear_config_item;
3028 c->get_config_item = lxcapi_get_config_item;
3029 c->get_cgroup_item = lxcapi_get_cgroup_item;
3030 c->set_cgroup_item = lxcapi_set_cgroup_item;
3031 c->get_config_path = lxcapi_get_config_path;
3032 c->set_config_path = lxcapi_set_config_path;
3033 c->clone = lxcapi_clone;
3034 c->get_interfaces = lxcapi_get_interfaces;
3035 c->get_ips = lxcapi_get_ips;
3036 c->attach = lxcapi_attach;
3037 c->attach_run_wait = lxcapi_attach_run_wait;
3038 c->attach_run_waitl = lxcapi_attach_run_waitl;
3039 c->snapshot = lxcapi_snapshot;
3040 c->snapshot_list = lxcapi_snapshot_list;
3041 c->snapshot_restore = lxcapi_snapshot_restore;
3042 c->snapshot_destroy = lxcapi_snapshot_destroy;
3043 c->may_control = lxcapi_may_control;
3044
3045 /* we'll allow the caller to update these later */
3046 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
3047 fprintf(stderr, "failed to open log\n");
3048 goto err;
3049 }
3050
3051 return c;
3052
3053 err:
3054 lxc_container_free(c);
3055 return NULL;
3056 }
3057
3058 int lxc_get_wait_states(const char **states)
3059 {
3060 int i;
3061
3062 if (states)
3063 for (i=0; i<MAX_STATE; i++)
3064 states[i] = lxc_state2str(i);
3065 return MAX_STATE;
3066 }
3067
3068 /*
3069 * These next two could probably be done smarter with reusing a common function
3070 * with different iterators and tests...
3071 */
3072 int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
3073 {
3074 DIR *dir;
3075 int i, cfound = 0, nfound = 0;
3076 struct dirent dirent, *direntp;
3077 struct lxc_container *c;
3078
3079 if (!lxcpath)
3080 lxcpath = default_lxc_path();
3081
3082 process_lock();
3083 dir = opendir(lxcpath);
3084 process_unlock();
3085
3086 if (!dir) {
3087 SYSERROR("opendir on lxcpath");
3088 return -1;
3089 }
3090
3091 if (cret)
3092 *cret = NULL;
3093 if (names)
3094 *names = NULL;
3095
3096 while (!readdir_r(dir, &dirent, &direntp)) {
3097 if (!direntp)
3098 break;
3099 if (!strcmp(direntp->d_name, "."))
3100 continue;
3101 if (!strcmp(direntp->d_name, ".."))
3102 continue;
3103
3104 if (!config_file_exists(lxcpath, direntp->d_name))
3105 continue;
3106
3107 if (names) {
3108 if (!add_to_array(names, direntp->d_name, cfound))
3109 goto free_bad;
3110 }
3111 cfound++;
3112
3113 if (!cret) {
3114 nfound++;
3115 continue;
3116 }
3117
3118 c = lxc_container_new(direntp->d_name, lxcpath);
3119 if (!c) {
3120 INFO("Container %s:%s has a config but could not be loaded",
3121 lxcpath, direntp->d_name);
3122 if (names)
3123 if(!remove_from_array(names, direntp->d_name, cfound--))
3124 goto free_bad;
3125 continue;
3126 }
3127 if (!lxcapi_is_defined(c)) {
3128 INFO("Container %s:%s has a config but is not defined",
3129 lxcpath, direntp->d_name);
3130 if (names)
3131 if(!remove_from_array(names, direntp->d_name, cfound--))
3132 goto free_bad;
3133 lxc_container_put(c);
3134 continue;
3135 }
3136
3137 if (!add_to_clist(cret, c, nfound, true)) {
3138 lxc_container_put(c);
3139 goto free_bad;
3140 }
3141 nfound++;
3142 }
3143
3144 process_lock();
3145 closedir(dir);
3146 process_unlock();
3147 return nfound;
3148
3149 free_bad:
3150 if (names && *names) {
3151 for (i=0; i<cfound; i++)
3152 free((*names)[i]);
3153 free(*names);
3154 }
3155 if (cret && *cret) {
3156 for (i=0; i<nfound; i++)
3157 lxc_container_put((*cret)[i]);
3158 free(*cret);
3159 }
3160 process_lock();
3161 closedir(dir);
3162 process_unlock();
3163 return -1;
3164 }
3165
3166 int list_active_containers(const char *lxcpath, char ***nret,
3167 struct lxc_container ***cret)
3168 {
3169 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
3170 int lxcpath_len;
3171 char *line = NULL;
3172 char **ct_name = NULL;
3173 size_t len = 0;
3174 struct lxc_container *c;
3175
3176 if (!lxcpath)
3177 lxcpath = default_lxc_path();
3178 lxcpath_len = strlen(lxcpath);
3179
3180 if (cret)
3181 *cret = NULL;
3182 if (nret)
3183 *nret = NULL;
3184
3185 process_lock();
3186 FILE *f = fopen("/proc/net/unix", "r");
3187 process_unlock();
3188 if (!f)
3189 return -1;
3190
3191 while (getline(&line, &len, f) != -1) {
3192 char *p = strrchr(line, ' '), *p2;
3193 if (!p)
3194 continue;
3195 p++;
3196 if (*p != 0x40)
3197 continue;
3198 p++;
3199 if (strncmp(p, lxcpath, lxcpath_len) != 0)
3200 continue;
3201 p += lxcpath_len;
3202 while (*p == '/')
3203 p++;
3204
3205 // Now p is the start of lxc_name
3206 p2 = index(p, '/');
3207 if (!p2 || strncmp(p2, "/command", 8) != 0)
3208 continue;
3209 *p2 = '\0';
3210
3211 if (array_contains(&ct_name, p, ct_name_cnt))
3212 continue;
3213
3214 if (!add_to_array(&ct_name, p, ct_name_cnt))
3215 goto free_cret_list;
3216
3217 ct_name_cnt++;
3218
3219 if (!cret)
3220 continue;
3221
3222 c = lxc_container_new(p, lxcpath);
3223 if (!c) {
3224 INFO("Container %s:%s is running but could not be loaded",
3225 lxcpath, p);
3226 remove_from_array(&ct_name, p, ct_name_cnt--);
3227 continue;
3228 }
3229
3230 /*
3231 * If this is an anonymous container, then is_defined *can*
3232 * return false. So we don't do that check. Count on the
3233 * fact that the command socket exists.
3234 */
3235
3236 if (!add_to_clist(cret, c, cret_cnt, true)) {
3237 lxc_container_put(c);
3238 goto free_cret_list;
3239 }
3240 cret_cnt++;
3241 }
3242
3243 assert(!nret || !cret || cret_cnt == ct_name_cnt);
3244 ret = ct_name_cnt;
3245 if (nret)
3246 *nret = ct_name;
3247 else
3248 goto free_ct_name;
3249 goto out;
3250
3251 free_cret_list:
3252 if (cret && *cret) {
3253 for (i = 0; i < cret_cnt; i++)
3254 lxc_container_put((*cret)[i]);
3255 free(*cret);
3256 }
3257
3258 free_ct_name:
3259 if (ct_name) {
3260 for (i = 0; i < ct_name_cnt; i++)
3261 free(ct_name[i]);
3262 free(ct_name);
3263 }
3264
3265 out:
3266 if (line)
3267 free(line);
3268
3269 process_lock();
3270 fclose(f);
3271 process_unlock();
3272 return ret;
3273 }
3274
3275 int list_all_containers(const char *lxcpath, char ***nret,
3276 struct lxc_container ***cret)
3277 {
3278 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
3279 char **active_name;
3280 char **ct_name;
3281 struct lxc_container **ct_list = NULL;
3282
3283 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
3284 if (ct_cnt < 0)
3285 return ct_cnt;
3286
3287 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
3288 if (active_cnt < 0) {
3289 ret = active_cnt;
3290 goto free_ct_name;
3291 }
3292
3293 for (i = 0; i < active_cnt; i++) {
3294 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
3295 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
3296 ret = -1;
3297 goto free_active_name;
3298 }
3299 ct_cnt++;
3300 }
3301 free(active_name[i]);
3302 active_name[i] = NULL;
3303 }
3304 free(active_name);
3305 active_name = NULL;
3306 active_cnt = 0;
3307
3308 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
3309 struct lxc_container *c;
3310
3311 c = lxc_container_new(ct_name[i], lxcpath);
3312 if (!c) {
3313 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
3314 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
3315 continue;
3316 }
3317
3318 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
3319 lxc_container_put(c);
3320 ret = -1;
3321 goto free_ct_list;
3322 }
3323 ct_list_cnt++;
3324 }
3325
3326 if (cret)
3327 *cret = ct_list;
3328
3329 if (nret)
3330 *nret = ct_name;
3331 else {
3332 ret = ct_cnt;
3333 goto free_ct_name;
3334 }
3335 return ct_cnt;
3336
3337 free_ct_list:
3338 for (i = 0; i < ct_list_cnt; i++) {
3339 lxc_container_put(ct_list[i]);
3340 }
3341 if (ct_list)
3342 free(ct_list);
3343
3344 free_active_name:
3345 for (i = 0; i < active_cnt; i++) {
3346 if (active_name[i])
3347 free(active_name[i]);
3348 }
3349 if (active_name)
3350 free(active_name);
3351
3352 free_ct_name:
3353 for (i = 0; i < ct_cnt; i++) {
3354 free(ct_name[i]);
3355 }
3356 free(ct_name);
3357 return ret;
3358 }