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