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