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