]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
add lxc.haltsignal for soft shutdown
[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 static 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 static 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 static 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 static 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 int haltsignal = SIGPWR;
1311
1312 if (!c)
1313 return false;
1314
1315 if (!timeout)
1316 timeout = -1;
1317 if (!c->is_running(c))
1318 return true;
1319 pid = c->init_pid(c);
1320 if (pid <= 0)
1321 return true;
1322 if (c->lxc_conf->haltsignal)
1323 haltsignal = c->lxc_conf->haltsignal;
1324 kill(pid, haltsignal);
1325 retv = c->wait(c, "STOPPED", timeout);
1326 if (!retv && timeout > 0) {
1327 c->stop(c);
1328 retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
1329 }
1330 return retv;
1331 }
1332
1333 static bool lxcapi_createl(struct lxc_container *c, const char *t,
1334 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
1335 {
1336 bool bret = false;
1337 char **args = NULL;
1338 va_list ap;
1339
1340 if (!c)
1341 return false;
1342
1343 /*
1344 * since we're going to wait for create to finish, I don't think we
1345 * need to get a copy of the arguments.
1346 */
1347 va_start(ap, flags);
1348 args = lxc_va_arg_list_to_argv(ap, 0, 0);
1349 va_end(ap);
1350 if (!args) {
1351 ERROR("Memory allocation error.");
1352 goto out;
1353 }
1354
1355 bret = c->create(c, t, bdevtype, specs, flags, args);
1356
1357 out:
1358 free(args);
1359 return bret;
1360 }
1361
1362 static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
1363 {
1364 int ret;
1365
1366 if (!c || !c->lxc_conf)
1367 return false;
1368 if (container_mem_lock(c))
1369 return false;
1370 ret = lxc_clear_config_item(c->lxc_conf, key);
1371 container_mem_unlock(c);
1372 return ret == 0;
1373 }
1374
1375 static inline void exit_from_ns(struct lxc_container *c, int *old_netns, int *new_netns) {
1376 /* Switch back to original netns */
1377 if (*old_netns >= 0 && setns(*old_netns, CLONE_NEWNET))
1378 SYSERROR("failed to setns");
1379 if (*new_netns >= 0)
1380 close(*new_netns);
1381 if (*old_netns >= 0)
1382 close(*old_netns);
1383 }
1384
1385 static inline bool enter_to_ns(struct lxc_container *c, int *old_netns, int *new_netns) {
1386 int ret = 0;
1387 char new_netns_path[MAXPATHLEN];
1388
1389 if (!c->is_running(c))
1390 goto out;
1391
1392 /* Save reference to old netns */
1393 *old_netns = open("/proc/self/ns/net", O_RDONLY);
1394 if (*old_netns < 0) {
1395 SYSERROR("failed to open /proc/self/ns/net");
1396 goto out;
1397 }
1398
1399 /* Switch to new netns */
1400 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", c->init_pid(c));
1401 if (ret < 0 || ret >= MAXPATHLEN)
1402 goto out;
1403
1404 *new_netns = open(new_netns_path, O_RDONLY);
1405 if (*new_netns < 0) {
1406 SYSERROR("failed to open %s", new_netns_path);
1407 goto out;
1408 }
1409
1410 if (setns(*new_netns, CLONE_NEWNET)) {
1411 SYSERROR("failed to setns");
1412 goto out;
1413 }
1414 return true;
1415 out:
1416 exit_from_ns(c, old_netns, new_netns);
1417 return false;
1418 }
1419
1420 // used by qsort and bsearch functions for comparing names
1421 static inline int string_cmp(char **first, char **second)
1422 {
1423 return strcmp(*first, *second);
1424 }
1425
1426 // used by qsort and bsearch functions for comparing container names
1427 static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1428 {
1429 return strcmp((*first)->name, (*second)->name);
1430 }
1431
1432 static bool add_to_array(char ***names, char *cname, int pos)
1433 {
1434 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1435 if (!newnames) {
1436 ERROR("Out of memory");
1437 return false;
1438 }
1439
1440 *names = newnames;
1441 newnames[pos] = strdup(cname);
1442 if (!newnames[pos])
1443 return false;
1444
1445 // sort the arrray as we will use binary search on it
1446 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1447
1448 return true;
1449 }
1450
1451 static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
1452 {
1453 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1454 if (!newlist) {
1455 ERROR("Out of memory");
1456 return false;
1457 }
1458
1459 *list = newlist;
1460 newlist[pos] = c;
1461
1462 // sort the arrray as we will use binary search on it
1463 if (sort)
1464 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
1465
1466 return true;
1467 }
1468
1469 static char** get_from_array(char ***names, char *cname, int size)
1470 {
1471 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1472 }
1473
1474
1475 static bool array_contains(char ***names, char *cname, int size) {
1476 if(get_from_array(names, cname, size) != NULL)
1477 return true;
1478 return false;
1479 }
1480
1481 static bool remove_from_array(char ***names, char *cname, int size)
1482 {
1483 char **result = get_from_array(names, cname, size);
1484 if (result != NULL) {
1485 free(result);
1486 return true;
1487 }
1488 return false;
1489 }
1490
1491 static char** lxcapi_get_interfaces(struct lxc_container *c)
1492 {
1493 int i, count = 0;
1494 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1495 char **interfaces = NULL;
1496 int old_netns = -1, new_netns = -1;
1497
1498 if (!enter_to_ns(c, &old_netns, &new_netns))
1499 goto out;
1500
1501 /* Grab the list of interfaces */
1502 if (getifaddrs(&interfaceArray)) {
1503 SYSERROR("failed to get interfaces list");
1504 goto out;
1505 }
1506
1507 /* Iterate through the interfaces */
1508 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1509 if (array_contains(&interfaces, tempIfAddr->ifa_name, count))
1510 continue;
1511
1512 if(!add_to_array(&interfaces, tempIfAddr->ifa_name, count))
1513 goto err;
1514 count++;
1515 }
1516
1517 out:
1518 if (interfaceArray)
1519 freeifaddrs(interfaceArray);
1520
1521 exit_from_ns(c, &old_netns, &new_netns);
1522
1523 /* Append NULL to the array */
1524 if(interfaces)
1525 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
1526
1527 return interfaces;
1528
1529 err:
1530 for(i=0;i<count;i++)
1531 free(interfaces[i]);
1532 free(interfaces);
1533 interfaces = NULL;
1534 goto out;
1535 }
1536
1537 static char** lxcapi_get_ips(struct lxc_container *c, const char* interface, const char* family, int scope)
1538 {
1539 int i, count = 0;
1540 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1541 char addressOutputBuffer[INET6_ADDRSTRLEN];
1542 void *tempAddrPtr = NULL;
1543 char **addresses = NULL;
1544 char *address = NULL;
1545 int old_netns = -1, new_netns = -1;
1546
1547 if (!enter_to_ns(c, &old_netns, &new_netns))
1548 goto out;
1549
1550 /* Grab the list of interfaces */
1551 if (getifaddrs(&interfaceArray)) {
1552 SYSERROR("failed to get interfaces list");
1553 goto out;
1554 }
1555
1556 /* Iterate through the interfaces */
1557 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1558 if (tempIfAddr->ifa_addr == NULL)
1559 continue;
1560
1561 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1562 if (family && strcmp(family, "inet"))
1563 continue;
1564 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1565 }
1566 else {
1567 if (family && strcmp(family, "inet6"))
1568 continue;
1569
1570 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1571 continue;
1572
1573 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1574 }
1575
1576 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1577 continue;
1578 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
1579 continue;
1580
1581 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1582 tempAddrPtr,
1583 addressOutputBuffer,
1584 sizeof(addressOutputBuffer));
1585 if (!address)
1586 continue;
1587
1588 if(!add_to_array(&addresses, address, count))
1589 goto err;
1590 count++;
1591 }
1592
1593 out:
1594 if(interfaceArray)
1595 freeifaddrs(interfaceArray);
1596
1597 exit_from_ns(c, &old_netns, &new_netns);
1598
1599 /* Append NULL to the array */
1600 if(addresses)
1601 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
1602
1603 return addresses;
1604
1605 err:
1606 for(i=0;i<count;i++)
1607 free(addresses[i]);
1608 free(addresses);
1609 addresses = NULL;
1610
1611 goto out;
1612 }
1613
1614 static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
1615 {
1616 int ret;
1617
1618 if (!c || !c->lxc_conf)
1619 return -1;
1620 if (container_mem_lock(c))
1621 return -1;
1622 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
1623 container_mem_unlock(c);
1624 return ret;
1625 }
1626
1627 static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
1628 {
1629 if (!key)
1630 return lxc_listconfigs(retv, inlen);
1631 /*
1632 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1633 * This is an intelligent result to show which keys are valid given
1634 * the type of nic it is
1635 */
1636 if (!c || !c->lxc_conf)
1637 return -1;
1638 if (container_mem_lock(c))
1639 return -1;
1640 int ret = -1;
1641 if (strncmp(key, "lxc.network.", 12) == 0)
1642 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
1643 container_mem_unlock(c);
1644 return ret;
1645 }
1646
1647 static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
1648 {
1649 FILE *fout;
1650 bool ret = false, need_disklock = false;
1651 int lret;
1652
1653 if (!alt_file)
1654 alt_file = c->configfile;
1655 if (!alt_file)
1656 return false; // should we write to stdout if no file is specified?
1657
1658 // If we haven't yet loaded a config, load the stock config
1659 if (!c->lxc_conf) {
1660 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
1661 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
1662 return false;
1663 }
1664 }
1665
1666 if (!create_container_dir(c))
1667 return false;
1668
1669 /*
1670 * If we're writing to the container's config file, take the
1671 * disk lock. Otherwise just take the memlock to protect the
1672 * struct lxc_container while we're traversing it.
1673 */
1674 if (strcmp(c->configfile, alt_file) == 0)
1675 need_disklock = true;
1676
1677 if (need_disklock)
1678 lret = container_disk_lock(c);
1679 else
1680 lret = container_mem_lock(c);
1681
1682 if (lret)
1683 return false;
1684
1685 fout = fopen(alt_file, "w");
1686 if (!fout)
1687 goto out;
1688 write_config(fout, c->lxc_conf);
1689 fclose(fout);
1690 ret = true;
1691
1692 out:
1693 if (need_disklock)
1694 container_disk_unlock(c);
1695 else
1696 container_mem_unlock(c);
1697 return ret;
1698 }
1699
1700 static bool mod_rdep(struct lxc_container *c, bool inc)
1701 {
1702 char path[MAXPATHLEN];
1703 int ret, v = 0;
1704 FILE *f;
1705 bool bret = false;
1706
1707 if (container_disk_lock(c))
1708 return false;
1709 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1710 c->name);
1711 if (ret < 0 || ret > MAXPATHLEN)
1712 goto out;
1713 f = fopen(path, "r");
1714 if (f) {
1715 ret = fscanf(f, "%d", &v);
1716 fclose(f);
1717 if (ret != 1) {
1718 ERROR("Corrupted file %s", path);
1719 goto out;
1720 }
1721 }
1722 v += inc ? 1 : -1;
1723 f = fopen(path, "w");
1724 if (!f)
1725 goto out;
1726 if (fprintf(f, "%d\n", v) < 0) {
1727 ERROR("Error writing new snapshots value");
1728 fclose(f);
1729 goto out;
1730 }
1731 ret = fclose(f);
1732 if (ret != 0) {
1733 SYSERROR("Error writing to or closing snapshots file");
1734 goto out;
1735 }
1736
1737 bret = true;
1738
1739 out:
1740 container_disk_unlock(c);
1741 return bret;
1742 }
1743
1744 static void strip_newline(char *p)
1745 {
1746 size_t len = strlen(p);
1747 if (len < 1)
1748 return;
1749 if (p[len-1] == '\n')
1750 p[len-1] = '\0';
1751 }
1752
1753 static void mod_all_rdeps(struct lxc_container *c, bool inc)
1754 {
1755 struct lxc_container *p;
1756 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
1757 size_t pathlen = 0, namelen = 0;
1758 FILE *f;
1759 int ret;
1760
1761 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
1762 c->config_path, c->name);
1763 if (ret < 0 || ret >= MAXPATHLEN) {
1764 ERROR("Path name too long");
1765 return;
1766 }
1767 f = fopen(path, "r");
1768 if (f == NULL)
1769 return;
1770 while (getline(&lxcpath, &pathlen, f) != -1) {
1771 if (getline(&lxcname, &namelen, f) == -1) {
1772 ERROR("badly formatted file %s\n", path);
1773 goto out;
1774 }
1775 strip_newline(lxcpath);
1776 strip_newline(lxcname);
1777 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
1778 ERROR("Unable to find dependent container %s:%s",
1779 lxcpath, lxcname);
1780 continue;
1781 }
1782 if (!mod_rdep(p, inc))
1783 ERROR("Failed to increase numsnapshots for %s:%s",
1784 lxcpath, lxcname);
1785 lxc_container_put(p);
1786 }
1787 out:
1788 if (lxcpath) free(lxcpath);
1789 if (lxcname) free(lxcname);
1790 fclose(f);
1791 }
1792
1793 static bool has_snapshots(struct lxc_container *c)
1794 {
1795 char path[MAXPATHLEN];
1796 int ret, v;
1797 FILE *f;
1798 bool bret = false;
1799
1800 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1801 c->name);
1802 if (ret < 0 || ret > MAXPATHLEN)
1803 goto out;
1804 f = fopen(path, "r");
1805 if (!f)
1806 goto out;
1807 ret = fscanf(f, "%d", &v);
1808 fclose(f);
1809 if (ret != 1)
1810 goto out;
1811 bret = v != 0;
1812
1813 out:
1814 return bret;
1815 }
1816
1817 static int lxc_rmdir_onedev_wrapper(void *data)
1818 {
1819 char *arg = (char *) data;
1820 return lxc_rmdir_onedev(arg);
1821 }
1822
1823 // do we want the api to support --force, or leave that to the caller?
1824 static bool lxcapi_destroy(struct lxc_container *c)
1825 {
1826 struct bdev *r = NULL;
1827 bool bret = false, am_unpriv;
1828 int ret;
1829
1830 if (!c || !lxcapi_is_defined(c))
1831 return false;
1832
1833 if (container_disk_lock(c))
1834 return false;
1835
1836 if (!is_stopped(c)) {
1837 // we should queue some sort of error - in c->error_string?
1838 ERROR("container %s is not stopped", c->name);
1839 goto out;
1840 }
1841
1842 am_unpriv = c->lxc_conf && geteuid() != 0 && !lxc_list_empty(&c->lxc_conf->id_map);
1843
1844 if (c->lxc_conf && has_snapshots(c)) {
1845 ERROR("container %s has dependent snapshots", c->name);
1846 goto out;
1847 }
1848
1849 if (!am_unpriv && c->lxc_conf->rootfs.path && c->lxc_conf->rootfs.mount) {
1850 r = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
1851 if (r) {
1852 if (r->ops->destroy(r) < 0) {
1853 bdev_put(r);
1854 ERROR("Error destroying rootfs for %s", c->name);
1855 goto out;
1856 }
1857 bdev_put(r);
1858 }
1859 }
1860
1861 mod_all_rdeps(c, false);
1862
1863 const char *p1 = lxcapi_get_config_path(c);
1864 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
1865 sprintf(path, "%s/%s", p1, c->name);
1866 if (am_unpriv)
1867 ret = userns_exec_1(c->lxc_conf, lxc_rmdir_onedev_wrapper, path);
1868 else
1869 ret = lxc_rmdir_onedev(path);
1870 if (ret < 0) {
1871 ERROR("Error destroying container directory for %s", c->name);
1872 goto out;
1873 }
1874 bret = true;
1875
1876 out:
1877 container_disk_unlock(c);
1878 return bret;
1879 }
1880
1881 static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
1882 {
1883 struct lxc_config_t *config;
1884
1885 if (!c->lxc_conf)
1886 c->lxc_conf = lxc_conf_init();
1887 if (!c->lxc_conf)
1888 return false;
1889 config = lxc_getconfig(key);
1890 if (!config)
1891 return false;
1892 return (0 == config->cb(key, v, c->lxc_conf));
1893 }
1894
1895 static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
1896 {
1897 bool b = false;
1898
1899 if (!c)
1900 return false;
1901
1902 if (container_mem_lock(c))
1903 return false;
1904
1905 b = set_config_item_locked(c, key, v);
1906
1907 container_mem_unlock(c);
1908 return b;
1909 }
1910
1911 static char *lxcapi_config_file_name(struct lxc_container *c)
1912 {
1913 if (!c || !c->configfile)
1914 return NULL;
1915 return strdup(c->configfile);
1916 }
1917
1918 static const char *lxcapi_get_config_path(struct lxc_container *c)
1919 {
1920 if (!c || !c->config_path)
1921 return NULL;
1922 return (const char *)(c->config_path);
1923 }
1924
1925 /*
1926 * not for export
1927 * Just recalculate the c->configfile based on the
1928 * c->config_path, which must be set.
1929 * The lxc_container must be locked or not yet public.
1930 */
1931 static bool set_config_filename(struct lxc_container *c)
1932 {
1933 char *newpath;
1934 int len, ret;
1935
1936 if (!c->config_path)
1937 return false;
1938
1939 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1940 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
1941 newpath = malloc(len);
1942 if (!newpath)
1943 return false;
1944
1945 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
1946 if (ret < 0 || ret >= len) {
1947 fprintf(stderr, "Error printing out config file name\n");
1948 free(newpath);
1949 return false;
1950 }
1951
1952 if (c->configfile)
1953 free(c->configfile);
1954 c->configfile = newpath;
1955
1956 return true;
1957 }
1958
1959 static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
1960 {
1961 char *p;
1962 bool b = false;
1963 char *oldpath = NULL;
1964
1965 if (!c)
1966 return b;
1967
1968 if (container_mem_lock(c))
1969 return b;
1970
1971 p = strdup(path);
1972 if (!p) {
1973 ERROR("Out of memory setting new lxc path");
1974 goto err;
1975 }
1976
1977 b = true;
1978 if (c->config_path)
1979 oldpath = c->config_path;
1980 c->config_path = p;
1981
1982 /* Since we've changed the config path, we have to change the
1983 * config file name too */
1984 if (!set_config_filename(c)) {
1985 ERROR("Out of memory setting new config filename");
1986 b = false;
1987 free(c->config_path);
1988 c->config_path = oldpath;
1989 oldpath = NULL;
1990 }
1991 err:
1992 if (oldpath)
1993 free(oldpath);
1994 container_mem_unlock(c);
1995 return b;
1996 }
1997
1998
1999 static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
2000 {
2001 int ret;
2002
2003 if (!c)
2004 return false;
2005
2006 if (is_stopped(c))
2007 return false;
2008
2009 if (container_disk_lock(c))
2010 return false;
2011
2012 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
2013
2014 container_disk_unlock(c);
2015 return ret == 0;
2016 }
2017
2018 static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
2019 {
2020 int ret;
2021
2022 if (!c)
2023 return -1;
2024
2025 if (is_stopped(c))
2026 return -1;
2027
2028 if (container_disk_lock(c))
2029 return -1;
2030
2031 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
2032
2033 container_disk_unlock(c);
2034 return ret;
2035 }
2036
2037 const char *lxc_get_default_config_path(void)
2038 {
2039 return default_lxc_path();
2040 }
2041
2042 const char *lxc_get_default_lvm_vg(void)
2043 {
2044 return default_lvm_vg();
2045 }
2046
2047 const char *lxc_get_default_lvm_thin_pool(void)
2048 {
2049 return default_lvm_thin_pool();
2050 }
2051
2052 const char *lxc_get_default_zfs_root(void)
2053 {
2054 return default_zfs_root();
2055 }
2056
2057 const char *lxc_get_version(void)
2058 {
2059 return LXC_VERSION;
2060 }
2061
2062 static int copy_file(const char *old, const char *new)
2063 {
2064 int in, out;
2065 ssize_t len, ret;
2066 char buf[8096];
2067 struct stat sbuf;
2068
2069 if (file_exists(new)) {
2070 ERROR("copy destination %s exists", new);
2071 return -1;
2072 }
2073 ret = stat(old, &sbuf);
2074 if (ret < 0) {
2075 INFO("Error stat'ing %s", old);
2076 return -1;
2077 }
2078
2079 in = open(old, O_RDONLY);
2080 if (in < 0) {
2081 SYSERROR("Error opening original file %s", old);
2082 return -1;
2083 }
2084 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
2085 if (out < 0) {
2086 SYSERROR("Error opening new file %s", new);
2087 close(in);
2088 return -1;
2089 }
2090
2091 while (1) {
2092 len = read(in, buf, 8096);
2093 if (len < 0) {
2094 SYSERROR("Error reading old file %s", old);
2095 goto err;
2096 }
2097 if (len == 0)
2098 break;
2099 ret = write(out, buf, len);
2100 if (ret < len) { // should we retry?
2101 SYSERROR("Error: write to new file %s was interrupted", new);
2102 goto err;
2103 }
2104 }
2105 close(in);
2106 close(out);
2107
2108 // we set mode, but not owner/group
2109 ret = chmod(new, sbuf.st_mode);
2110 if (ret) {
2111 SYSERROR("Error setting mode on %s", new);
2112 return -1;
2113 }
2114
2115 return 0;
2116
2117 err:
2118 close(in);
2119 close(out);
2120 return -1;
2121 }
2122
2123 static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2124 {
2125 int i, len, ret;
2126 struct lxc_list *it;
2127 char *cpath;
2128
2129 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
2130 cpath = alloca(len);
2131 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
2132 if (ret < 0 || ret >= len)
2133 return -1;
2134
2135 for (i=0; i<NUM_LXC_HOOKS; i++) {
2136 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2137 char *hookname = it->elem;
2138 char *fname = strrchr(hookname, '/');
2139 char tmppath[MAXPATHLEN];
2140 if (!fname) // relative path - we don't support, but maybe we should
2141 return 0;
2142 if (strncmp(hookname, cpath, len - 1) != 0) {
2143 // this hook is public - ignore
2144 continue;
2145 }
2146 // copy the script, and change the entry in confile
2147 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2148 c->config_path, c->name, fname+1);
2149 if (ret < 0 || ret >= MAXPATHLEN)
2150 return -1;
2151 ret = copy_file(it->elem, tmppath);
2152 if (ret < 0)
2153 return -1;
2154 free(it->elem);
2155 it->elem = strdup(tmppath);
2156 if (!it->elem) {
2157 ERROR("out of memory copying hook path");
2158 return -1;
2159 }
2160 }
2161 }
2162
2163 c->save_config(c, NULL);
2164 return 0;
2165 }
2166
2167 static void new_hwaddr(char *hwaddr)
2168 {
2169 FILE *f;
2170 f = fopen("/dev/urandom", "r");
2171 if (f) {
2172 unsigned int seed;
2173 int ret = fread(&seed, sizeof(seed), 1, f);
2174 if (ret != 1)
2175 seed = time(NULL);
2176 fclose(f);
2177 srand(seed);
2178 } else
2179 srand(time(NULL));
2180 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
2181 rand() % 255, rand() % 255, rand() % 255);
2182 }
2183
2184 static void network_new_hwaddrs(struct lxc_container *c)
2185 {
2186 struct lxc_list *it;
2187
2188 lxc_list_for_each(it, &c->lxc_conf->network) {
2189 struct lxc_netdev *n = it->elem;
2190 if (n->hwaddr)
2191 new_hwaddr(n->hwaddr);
2192 }
2193 }
2194
2195 static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2196 {
2197 char newpath[MAXPATHLEN];
2198 char *oldpath = oldc->lxc_conf->fstab;
2199 int ret;
2200
2201 if (!oldpath)
2202 return 0;
2203
2204 char *p = strrchr(oldpath, '/');
2205 if (!p)
2206 return -1;
2207 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2208 c->config_path, c->name, p);
2209 if (ret < 0 || ret >= MAXPATHLEN) {
2210 ERROR("error printing new path for %s", oldpath);
2211 return -1;
2212 }
2213 if (file_exists(newpath)) {
2214 ERROR("error: fstab file %s exists", newpath);
2215 return -1;
2216 }
2217
2218 if (copy_file(oldpath, newpath) < 0) {
2219 ERROR("error: copying %s to %s", oldpath, newpath);
2220 return -1;
2221 }
2222 free(c->lxc_conf->fstab);
2223 c->lxc_conf->fstab = strdup(newpath);
2224 if (!c->lxc_conf->fstab) {
2225 ERROR("error: allocating pathname");
2226 return -1;
2227 }
2228
2229 return 0;
2230 }
2231
2232 static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2233 {
2234 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2235 int ret;
2236
2237 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2238 c0->name);
2239 if (ret < 0 || ret >= MAXPATHLEN) {
2240 WARN("Error copying reverse dependencies");
2241 return;
2242 }
2243 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2244 c->name);
2245 if (ret < 0 || ret >= MAXPATHLEN) {
2246 WARN("Error copying reverse dependencies");
2247 return;
2248 }
2249 if (copy_file(path0, path1) < 0) {
2250 INFO("Error copying reverse dependencies");
2251 return;
2252 }
2253 }
2254
2255 static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2256 {
2257 int ret;
2258 char path[MAXPATHLEN];
2259 FILE *f;
2260 bool bret;
2261
2262 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2263 c->name);
2264 if (ret < 0 || ret >= MAXPATHLEN)
2265 return false;
2266 f = fopen(path, "a");
2267 if (!f)
2268 return false;
2269 bret = true;
2270 // if anything goes wrong, just return an error
2271 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2272 bret = false;
2273 if (fclose(f) != 0)
2274 bret = false;
2275 return bret;
2276 }
2277
2278 static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
2279 const char *newtype, int flags, const char *bdevdata, unsigned long newsize)
2280 {
2281 struct bdev *bdev;
2282 int need_rdep;
2283
2284 bdev = bdev_copy(c0->lxc_conf->rootfs.path, c0->name, c->name,
2285 c0->config_path, c->config_path, newtype, flags,
2286 bdevdata, newsize, &need_rdep);
2287 if (!bdev) {
2288 ERROR("Error copying storage");
2289 return -1;
2290 }
2291 free(c->lxc_conf->rootfs.path);
2292 c->lxc_conf->rootfs.path = strdup(bdev->src);
2293 bdev_put(bdev);
2294 if (!c->lxc_conf->rootfs.path) {
2295 ERROR("Out of memory while setting storage path");
2296 return -1;
2297 }
2298 if (flags & LXC_CLONE_SNAPSHOT)
2299 copy_rdepends(c, c0);
2300 if (need_rdep) {
2301 if (!add_rdepends(c, c0))
2302 WARN("Error adding reverse dependency from %s to %s",
2303 c->name, c0->name);
2304 }
2305
2306 mod_all_rdeps(c, true);
2307
2308 return 0;
2309 }
2310
2311 static int clone_update_rootfs(struct lxc_container *c0,
2312 struct lxc_container *c, int flags,
2313 char **hookargs)
2314 {
2315 int ret = -1;
2316 char path[MAXPATHLEN];
2317 struct bdev *bdev;
2318 FILE *fout;
2319 pid_t pid;
2320 struct lxc_conf *conf = c->lxc_conf;
2321
2322 /* update hostname in rootfs */
2323 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2324
2325 pid = fork();
2326 if (pid < 0)
2327 return -1;
2328 if (pid > 0)
2329 return wait_for_pid(pid);
2330
2331 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2332 if (!bdev)
2333 exit(1);
2334 if (strcmp(bdev->type, "dir") != 0) {
2335 if (unshare(CLONE_NEWNS) < 0) {
2336 ERROR("error unsharing mounts");
2337 exit(1);
2338 }
2339 if (bdev->ops->mount(bdev) < 0)
2340 exit(1);
2341 } else { // TODO come up with a better way
2342 if (bdev->dest)
2343 free(bdev->dest);
2344 bdev->dest = strdup(bdev->src);
2345 }
2346
2347 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2348 /* Start of environment variable setup for hooks */
2349 if (setenv("LXC_SRC_NAME", c0->name, 1)) {
2350 SYSERROR("failed to set environment variable for source container name");
2351 }
2352 if (setenv("LXC_NAME", c->name, 1)) {
2353 SYSERROR("failed to set environment variable for container name");
2354 }
2355 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
2356 SYSERROR("failed to set environment variable for config path");
2357 }
2358 if (setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1)) {
2359 SYSERROR("failed to set environment variable for rootfs mount");
2360 }
2361 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
2362 SYSERROR("failed to set environment variable for rootfs mount");
2363 }
2364
2365 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
2366 ERROR("Error executing clone hook for %s", c->name);
2367 exit(1);
2368 }
2369 }
2370
2371 if (!(flags & LXC_CLONE_KEEPNAME)) {
2372 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
2373 if (ret < 0 || ret >= MAXPATHLEN)
2374 exit(1);
2375 if (!file_exists(path))
2376 exit(0);
2377 if (!(fout = fopen(path, "w"))) {
2378 SYSERROR("unable to open %s: ignoring\n", path);
2379 exit(0);
2380 }
2381 if (fprintf(fout, "%s", c->name) < 0)
2382 exit(1);
2383 if (fclose(fout) < 0)
2384 exit(1);
2385 }
2386 exit(0);
2387 }
2388
2389 /*
2390 * We want to support:
2391 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2392 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2393
2394 -s [ implies overlayfs]
2395 -s -B overlayfs
2396 -s -B aufs
2397
2398 only rootfs gets converted (copied/snapshotted) on clone.
2399 */
2400
2401 static int create_file_dirname(char *path)
2402 {
2403 char *p = strrchr(path, '/');
2404 int ret;
2405
2406 if (!p)
2407 return -1;
2408 *p = '\0';
2409 ret = mkdir(path, 0755);
2410 if (ret && errno != EEXIST)
2411 SYSERROR("creating container path %s\n", path);
2412 *p = '/';
2413 return ret;
2414 }
2415
2416 static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
2417 const char *lxcpath, int flags,
2418 const char *bdevtype, const char *bdevdata, unsigned long newsize,
2419 char **hookargs)
2420 {
2421 struct lxc_container *c2 = NULL;
2422 char newpath[MAXPATHLEN];
2423 int ret, storage_copied = 0;
2424 const char *n, *l;
2425 FILE *fout;
2426
2427 if (!c || !c->is_defined(c))
2428 return NULL;
2429
2430 if (container_mem_lock(c))
2431 return NULL;
2432
2433 if (!is_stopped(c)) {
2434 ERROR("error: Original container (%s) is running", c->name);
2435 goto out;
2436 }
2437
2438 // Make sure the container doesn't yet exist.
2439 n = newname ? newname : c->name;
2440 l = lxcpath ? lxcpath : c->get_config_path(c);
2441 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
2442 if (ret < 0 || ret >= MAXPATHLEN) {
2443 SYSERROR("clone: failed making config pathname");
2444 goto out;
2445 }
2446 if (file_exists(newpath)) {
2447 ERROR("error: clone: %s exists", newpath);
2448 goto out;
2449 }
2450
2451 ret = create_file_dirname(newpath);
2452 if (ret < 0 && errno != EEXIST) {
2453 ERROR("Error creating container dir for %s", newpath);
2454 goto out;
2455 }
2456
2457 // copy the configuration, tweak it as needed,
2458 fout = fopen(newpath, "w");
2459 if (!fout) {
2460 SYSERROR("open %s", newpath);
2461 goto out;
2462 }
2463 write_config(fout, c->lxc_conf);
2464 fclose(fout);
2465
2466 sprintf(newpath, "%s/%s/rootfs", l, n);
2467 if (mkdir(newpath, 0755) < 0) {
2468 SYSERROR("error creating %s", newpath);
2469 goto out;
2470 }
2471
2472 c2 = lxc_container_new(n, l);
2473 if (!c2) {
2474 ERROR("clone: failed to create new container (%s %s)", n, l);
2475 goto out;
2476 }
2477
2478 // update utsname
2479 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
2480 ERROR("Error setting new hostname");
2481 goto out;
2482 }
2483
2484 // copy hooks
2485 ret = copyhooks(c, c2);
2486 if (ret < 0) {
2487 ERROR("error copying hooks");
2488 goto out;
2489 }
2490
2491 if (copy_fstab(c, c2) < 0) {
2492 ERROR("error copying fstab");
2493 goto out;
2494 }
2495
2496 // update macaddrs
2497 if (!(flags & LXC_CLONE_KEEPMACADDR))
2498 network_new_hwaddrs(c2);
2499
2500 // copy/snapshot rootfs's
2501 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
2502 if (ret < 0)
2503 goto out;
2504
2505 // We've now successfully created c2's storage, so clear it out if we
2506 // fail after this
2507 storage_copied = 1;
2508
2509 if (!c2->save_config(c2, NULL))
2510 goto out;
2511
2512 if (clone_update_rootfs(c, c2, flags, hookargs) < 0)
2513 goto out;
2514
2515 // TODO: update c's lxc.snapshot = count
2516 container_mem_unlock(c);
2517 return c2;
2518
2519 out:
2520 container_mem_unlock(c);
2521 if (c2) {
2522 if (!storage_copied)
2523 c2->lxc_conf->rootfs.path = NULL;
2524 c2->destroy(c2);
2525 lxc_container_put(c2);
2526 }
2527
2528 return NULL;
2529 }
2530
2531 static bool lxcapi_rename(struct lxc_container *c, const char *newname)
2532 {
2533 struct bdev *bdev;
2534 struct lxc_container *newc;
2535
2536 if (!c || !c->name || !c->config_path)
2537 return false;
2538
2539 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2540 if (!bdev) {
2541 ERROR("Failed to find original backing store type");
2542 return false;
2543 }
2544
2545 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
2546 bdev_put(bdev);
2547 if (!newc) {
2548 lxc_container_put(newc);
2549 return false;
2550 }
2551
2552 if (newc && lxcapi_is_defined(newc))
2553 lxc_container_put(newc);
2554
2555 if (!lxcapi_destroy(c)) {
2556 ERROR("Could not destroy existing container %s", c->name);
2557 return false;
2558 }
2559 return true;
2560 }
2561
2562 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)
2563 {
2564 if (!c)
2565 return -1;
2566
2567 return lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
2568 }
2569
2570 static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
2571 {
2572 lxc_attach_command_t command;
2573 pid_t pid;
2574 int r;
2575
2576 if (!c)
2577 return -1;
2578
2579 command.program = (char*)program;
2580 command.argv = (char**)argv;
2581 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
2582 if (r < 0) {
2583 ERROR("ups");
2584 return r;
2585 }
2586 return lxc_wait_for_pid_status(pid);
2587 }
2588
2589 static int get_next_index(const char *lxcpath, char *cname)
2590 {
2591 char *fname;
2592 struct stat sb;
2593 int i = 0, ret;
2594
2595 fname = alloca(strlen(lxcpath) + 20);
2596 while (1) {
2597 sprintf(fname, "%s/snap%d", lxcpath, i);
2598 ret = stat(fname, &sb);
2599 if (ret != 0)
2600 return i;
2601 i++;
2602 }
2603 }
2604
2605 static int lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
2606 {
2607 int i, flags, ret;
2608 struct lxc_container *c2;
2609 char snappath[MAXPATHLEN], newname[20];
2610
2611 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2612 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2613 if (ret < 0 || ret >= MAXPATHLEN)
2614 return -1;
2615 i = get_next_index(snappath, c->name);
2616
2617 if (mkdir_p(snappath, 0755) < 0) {
2618 ERROR("Failed to create snapshot directory %s", snappath);
2619 return -1;
2620 }
2621
2622 ret = snprintf(newname, 20, "snap%d", i);
2623 if (ret < 0 || ret >= 20)
2624 return -1;
2625
2626 /*
2627 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2628 * created in the original container
2629 */
2630 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
2631 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
2632 c2 = c->clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
2633 if (!c2) {
2634 ERROR("clone of %s:%s failed\n", c->config_path, c->name);
2635 return -1;
2636 }
2637
2638 lxc_container_put(c2);
2639
2640 // Now write down the creation time
2641 time_t timer;
2642 char buffer[25];
2643 struct tm* tm_info;
2644 FILE *f;
2645
2646 time(&timer);
2647 tm_info = localtime(&timer);
2648
2649 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
2650
2651 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
2652 sprintf(dfnam, "%s/%s/ts", snappath, newname);
2653 f = fopen(dfnam, "w");
2654 if (!f) {
2655 ERROR("Failed to open %s\n", dfnam);
2656 return -1;
2657 }
2658 if (fprintf(f, "%s", buffer) < 0) {
2659 SYSERROR("Writing timestamp");
2660 fclose(f);
2661 return -1;
2662 }
2663 ret = fclose(f);
2664 if (ret != 0) {
2665 SYSERROR("Writing timestamp");
2666 return -1;
2667 }
2668
2669 if (commentfile) {
2670 // $p / $name / comment \0
2671 int len = strlen(snappath) + strlen(newname) + 10;
2672 char *path = alloca(len);
2673 sprintf(path, "%s/%s/comment", snappath, newname);
2674 return copy_file(commentfile, path) < 0 ? -1 : i;
2675 }
2676
2677 return i;
2678 }
2679
2680 static void lxcsnap_free(struct lxc_snapshot *s)
2681 {
2682 if (s->name)
2683 free(s->name);
2684 if (s->comment_pathname)
2685 free(s->comment_pathname);
2686 if (s->timestamp)
2687 free(s->timestamp);
2688 if (s->lxcpath)
2689 free(s->lxcpath);
2690 }
2691
2692 static char *get_snapcomment_path(char* snappath, char *name)
2693 {
2694 // $snappath/$name/comment
2695 int ret, len = strlen(snappath) + strlen(name) + 10;
2696 char *s = malloc(len);
2697
2698 if (s) {
2699 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
2700 if (ret < 0 || ret >= len) {
2701 free(s);
2702 s = NULL;
2703 }
2704 }
2705 return s;
2706 }
2707
2708 static char *get_timestamp(char* snappath, char *name)
2709 {
2710 char path[MAXPATHLEN], *s = NULL;
2711 int ret, len;
2712 FILE *fin;
2713
2714 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
2715 if (ret < 0 || ret >= MAXPATHLEN)
2716 return NULL;
2717 fin = fopen(path, "r");
2718 if (!fin)
2719 return NULL;
2720 (void) fseek(fin, 0, SEEK_END);
2721 len = ftell(fin);
2722 (void) fseek(fin, 0, SEEK_SET);
2723 if (len > 0) {
2724 s = malloc(len+1);
2725 if (s) {
2726 s[len] = '\0';
2727 if (fread(s, 1, len, fin) != len) {
2728 SYSERROR("reading timestamp");
2729 free(s);
2730 s = NULL;
2731 }
2732 }
2733 }
2734 fclose(fin);
2735 return s;
2736 }
2737
2738 static int lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
2739 {
2740 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
2741 int dirlen, count = 0, ret;
2742 struct dirent dirent, *direntp;
2743 struct lxc_snapshot *snaps =NULL, *nsnaps;
2744 DIR *dir;
2745
2746 if (!c || !lxcapi_is_defined(c))
2747 return -1;
2748 // snappath is ${lxcpath}snaps/${lxcname}/
2749 dirlen = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2750 if (dirlen < 0 || dirlen >= MAXPATHLEN) {
2751 ERROR("path name too long");
2752 return -1;
2753 }
2754 dir = opendir(snappath);
2755 if (!dir) {
2756 INFO("failed to open %s - assuming no snapshots", snappath);
2757 return 0;
2758 }
2759
2760 while (!readdir_r(dir, &dirent, &direntp)) {
2761 if (!direntp)
2762 break;
2763
2764 if (!strcmp(direntp->d_name, "."))
2765 continue;
2766
2767 if (!strcmp(direntp->d_name, ".."))
2768 continue;
2769
2770 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
2771 if (ret < 0 || ret >= MAXPATHLEN) {
2772 ERROR("pathname too long");
2773 goto out_free;
2774 }
2775 if (!file_exists(path2))
2776 continue;
2777 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
2778 if (!nsnaps) {
2779 SYSERROR("Out of memory");
2780 goto out_free;
2781 }
2782 snaps = nsnaps;
2783 snaps[count].free = lxcsnap_free;
2784 snaps[count].name = strdup(direntp->d_name);
2785 if (!snaps[count].name)
2786 goto out_free;
2787 snaps[count].lxcpath = strdup(snappath);
2788 if (!snaps[count].lxcpath) {
2789 free(snaps[count].name);
2790 goto out_free;
2791 }
2792 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
2793 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
2794 count++;
2795 }
2796
2797 if (closedir(dir))
2798 WARN("failed to close directory");
2799
2800 *ret_snaps = snaps;
2801 return count;
2802
2803 out_free:
2804 if (snaps) {
2805 int i;
2806 for (i=0; i<count; i++)
2807 lxcsnap_free(&snaps[i]);
2808 free(snaps);
2809 }
2810 if (closedir(dir))
2811 WARN("failed to close directory");
2812 return -1;
2813 }
2814
2815 static bool lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
2816 {
2817 char clonelxcpath[MAXPATHLEN];
2818 int ret;
2819 struct lxc_container *snap, *rest;
2820 struct bdev *bdev;
2821 bool b = false;
2822
2823 if (!c || !c->name || !c->config_path)
2824 return false;
2825
2826 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2827 if (!bdev) {
2828 ERROR("Failed to find original backing store type");
2829 return false;
2830 }
2831
2832 if (!newname)
2833 newname = c->name;
2834 if (strcmp(c->name, newname) == 0) {
2835 if (!lxcapi_destroy(c)) {
2836 ERROR("Could not destroy existing container %s", newname);
2837 bdev_put(bdev);
2838 return false;
2839 }
2840 }
2841 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2842 if (ret < 0 || ret >= MAXPATHLEN) {
2843 bdev_put(bdev);
2844 return false;
2845 }
2846 // how should we lock this?
2847
2848 snap = lxc_container_new(snapname, clonelxcpath);
2849 if (!snap || !lxcapi_is_defined(snap)) {
2850 ERROR("Could not open snapshot %s", snapname);
2851 if (snap) lxc_container_put(snap);
2852 bdev_put(bdev);
2853 return false;
2854 }
2855
2856 rest = lxcapi_clone(snap, newname, c->config_path, 0, bdev->type, NULL, 0, NULL);
2857 bdev_put(bdev);
2858 if (rest && lxcapi_is_defined(rest))
2859 b = true;
2860 if (rest)
2861 lxc_container_put(rest);
2862 lxc_container_put(snap);
2863 return b;
2864 }
2865
2866 static bool lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
2867 {
2868 int ret;
2869 char clonelxcpath[MAXPATHLEN];
2870 struct lxc_container *snap = NULL;
2871
2872 if (!c || !c->name || !c->config_path)
2873 return false;
2874
2875 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2876 if (ret < 0 || ret >= MAXPATHLEN)
2877 goto err;
2878
2879 snap = lxc_container_new(snapname, clonelxcpath);
2880 if (!snap || !lxcapi_is_defined(snap)) {
2881 ERROR("Could not find snapshot %s", snapname);
2882 goto err;
2883 }
2884
2885 if (!lxcapi_destroy(snap)) {
2886 ERROR("Could not destroy snapshot %s", snapname);
2887 goto err;
2888 }
2889 lxc_container_put(snap);
2890
2891 return true;
2892 err:
2893 if (snap)
2894 lxc_container_put(snap);
2895 return false;
2896 }
2897
2898 static bool lxcapi_may_control(struct lxc_container *c)
2899 {
2900 return lxc_try_cmd(c->name, c->config_path) == 0;
2901 }
2902
2903 static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
2904 {
2905 int ret;
2906 struct stat st;
2907 char path[MAXPATHLEN];
2908 char value[MAX_BUFFER];
2909 char *directory_path = NULL;
2910 const char *p;
2911
2912 /* make sure container is running */
2913 if (!c->is_running(c)) {
2914 ERROR("container is not running");
2915 goto out;
2916 }
2917
2918 /* use src_path if dest_path is NULL otherwise use dest_path */
2919 p = dest_path ? dest_path : src_path;
2920
2921 /* prepare the path */
2922 ret = snprintf(path, MAXPATHLEN, "/proc/%d/root/%s", c->init_pid(c), p);
2923 if (ret < 0 || ret >= MAXPATHLEN)
2924 goto out;
2925 remove_trailing_slashes(path);
2926
2927 p = add ? src_path : path;
2928 /* make sure we can access p */
2929 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
2930 goto out;
2931
2932 /* continue if path is character device or block device */
2933 if (S_ISCHR(st.st_mode))
2934 ret = snprintf(value, MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
2935 else if (S_ISBLK(st.st_mode))
2936 ret = snprintf(value, MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
2937 else
2938 goto out;
2939
2940 /* check snprintf return code */
2941 if (ret < 0 || ret >= MAX_BUFFER)
2942 goto out;
2943
2944 directory_path = dirname(strdup(path));
2945 /* remove path and directory_path (if empty) */
2946 if(access(path, F_OK) == 0) {
2947 if (unlink(path) < 0) {
2948 ERROR("unlink failed");
2949 goto out;
2950 }
2951 if (rmdir(directory_path) < 0 && errno != ENOTEMPTY) {
2952 ERROR("rmdir failed");
2953 goto out;
2954 }
2955 }
2956
2957 if (add) {
2958 /* create the missing directories */
2959 if (mkdir_p(directory_path, 0755) < 0) {
2960 ERROR("failed to create directory");
2961 goto out;
2962 }
2963
2964 /* create the device node */
2965 if (mknod(path, st.st_mode, st.st_rdev) < 0) {
2966 ERROR("mknod failed");
2967 goto out;
2968 }
2969
2970 /* add device node to device list */
2971 if (!c->set_cgroup_item(c, "devices.allow", value)) {
2972 ERROR("set_cgroup_item failed while adding the device node");
2973 goto out;
2974 }
2975 } else {
2976 /* remove device node from device list */
2977 if (!c->set_cgroup_item(c, "devices.deny", value)) {
2978 ERROR("set_cgroup_item failed while removing the device node");
2979 goto out;
2980 }
2981 }
2982 return true;
2983 out:
2984 if (directory_path)
2985 free(directory_path);
2986 return false;
2987 }
2988
2989 static bool lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
2990 {
2991 return add_remove_device_node(c, src_path, dest_path, true);
2992 }
2993
2994 static bool lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
2995 {
2996 return add_remove_device_node(c, src_path, dest_path, false);
2997 }
2998
2999 static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
3000 {
3001 va_list ap;
3002 const char **argv;
3003 int ret;
3004
3005 if (!c)
3006 return -1;
3007
3008 va_start(ap, arg);
3009 argv = lxc_va_arg_list_to_argv_const(ap, 1);
3010 va_end(ap);
3011
3012 if (!argv) {
3013 ERROR("Memory allocation error.");
3014 return -1;
3015 }
3016 argv[0] = arg;
3017
3018 ret = lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
3019 free((void*)argv);
3020 return ret;
3021 }
3022
3023 struct lxc_container *lxc_container_new(const char *name, const char *configpath)
3024 {
3025 struct lxc_container *c;
3026
3027 c = malloc(sizeof(*c));
3028 if (!c) {
3029 fprintf(stderr, "failed to malloc lxc_container\n");
3030 return NULL;
3031 }
3032 memset(c, 0, sizeof(*c));
3033
3034 if (configpath)
3035 c->config_path = strdup(configpath);
3036 else
3037 c->config_path = strdup(default_lxc_path());
3038
3039 if (!c->config_path) {
3040 fprintf(stderr, "Out of memory");
3041 goto err;
3042 }
3043
3044 remove_trailing_slashes(c->config_path);
3045 c->name = malloc(strlen(name)+1);
3046 if (!c->name) {
3047 fprintf(stderr, "Error allocating lxc_container name\n");
3048 goto err;
3049 }
3050 strcpy(c->name, name);
3051
3052 c->numthreads = 1;
3053 if (!(c->slock = lxc_newlock(c->config_path, name))) {
3054 fprintf(stderr, "failed to create lock\n");
3055 goto err;
3056 }
3057
3058 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
3059 fprintf(stderr, "failed to alloc privlock\n");
3060 goto err;
3061 }
3062
3063 if (!set_config_filename(c)) {
3064 fprintf(stderr, "Error allocating config file pathname\n");
3065 goto err;
3066 }
3067
3068 if (file_exists(c->configfile))
3069 lxcapi_load_config(c, NULL);
3070
3071 if (ongoing_create(c) == 2) {
3072 ERROR("Error: %s creation was not completed", c->name);
3073 lxcapi_destroy(c);
3074 lxcapi_clear_config(c);
3075 }
3076
3077 // assign the member functions
3078 c->is_defined = lxcapi_is_defined;
3079 c->state = lxcapi_state;
3080 c->is_running = lxcapi_is_running;
3081 c->freeze = lxcapi_freeze;
3082 c->unfreeze = lxcapi_unfreeze;
3083 c->console = lxcapi_console;
3084 c->console_getfd = lxcapi_console_getfd;
3085 c->init_pid = lxcapi_init_pid;
3086 c->load_config = lxcapi_load_config;
3087 c->want_daemonize = lxcapi_want_daemonize;
3088 c->want_close_all_fds = lxcapi_want_close_all_fds;
3089 c->start = lxcapi_start;
3090 c->startl = lxcapi_startl;
3091 c->stop = lxcapi_stop;
3092 c->config_file_name = lxcapi_config_file_name;
3093 c->wait = lxcapi_wait;
3094 c->set_config_item = lxcapi_set_config_item;
3095 c->destroy = lxcapi_destroy;
3096 c->rename = lxcapi_rename;
3097 c->save_config = lxcapi_save_config;
3098 c->get_keys = lxcapi_get_keys;
3099 c->create = lxcapi_create;
3100 c->createl = lxcapi_createl;
3101 c->shutdown = lxcapi_shutdown;
3102 c->reboot = lxcapi_reboot;
3103 c->clear_config = lxcapi_clear_config;
3104 c->clear_config_item = lxcapi_clear_config_item;
3105 c->get_config_item = lxcapi_get_config_item;
3106 c->get_cgroup_item = lxcapi_get_cgroup_item;
3107 c->set_cgroup_item = lxcapi_set_cgroup_item;
3108 c->get_config_path = lxcapi_get_config_path;
3109 c->set_config_path = lxcapi_set_config_path;
3110 c->clone = lxcapi_clone;
3111 c->get_interfaces = lxcapi_get_interfaces;
3112 c->get_ips = lxcapi_get_ips;
3113 c->attach = lxcapi_attach;
3114 c->attach_run_wait = lxcapi_attach_run_wait;
3115 c->attach_run_waitl = lxcapi_attach_run_waitl;
3116 c->snapshot = lxcapi_snapshot;
3117 c->snapshot_list = lxcapi_snapshot_list;
3118 c->snapshot_restore = lxcapi_snapshot_restore;
3119 c->snapshot_destroy = lxcapi_snapshot_destroy;
3120 c->may_control = lxcapi_may_control;
3121 c->add_device_node = lxcapi_add_device_node;
3122 c->remove_device_node = lxcapi_remove_device_node;
3123
3124 /* we'll allow the caller to update these later */
3125 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
3126 fprintf(stderr, "failed to open log\n");
3127 goto err;
3128 }
3129
3130 return c;
3131
3132 err:
3133 lxc_container_free(c);
3134 return NULL;
3135 }
3136
3137 int lxc_get_wait_states(const char **states)
3138 {
3139 int i;
3140
3141 if (states)
3142 for (i=0; i<MAX_STATE; i++)
3143 states[i] = lxc_state2str(i);
3144 return MAX_STATE;
3145 }
3146
3147 /*
3148 * These next two could probably be done smarter with reusing a common function
3149 * with different iterators and tests...
3150 */
3151 int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
3152 {
3153 DIR *dir;
3154 int i, cfound = 0, nfound = 0;
3155 struct dirent dirent, *direntp;
3156 struct lxc_container *c;
3157
3158 if (!lxcpath)
3159 lxcpath = default_lxc_path();
3160
3161 dir = opendir(lxcpath);
3162 if (!dir) {
3163 SYSERROR("opendir on lxcpath");
3164 return -1;
3165 }
3166
3167 if (cret)
3168 *cret = NULL;
3169 if (names)
3170 *names = NULL;
3171
3172 while (!readdir_r(dir, &dirent, &direntp)) {
3173 if (!direntp)
3174 break;
3175 if (!strcmp(direntp->d_name, "."))
3176 continue;
3177 if (!strcmp(direntp->d_name, ".."))
3178 continue;
3179
3180 if (!config_file_exists(lxcpath, direntp->d_name))
3181 continue;
3182
3183 if (names) {
3184 if (!add_to_array(names, direntp->d_name, cfound))
3185 goto free_bad;
3186 }
3187 cfound++;
3188
3189 if (!cret) {
3190 nfound++;
3191 continue;
3192 }
3193
3194 c = lxc_container_new(direntp->d_name, lxcpath);
3195 if (!c) {
3196 INFO("Container %s:%s has a config but could not be loaded",
3197 lxcpath, direntp->d_name);
3198 if (names)
3199 if(!remove_from_array(names, direntp->d_name, cfound--))
3200 goto free_bad;
3201 continue;
3202 }
3203 if (!lxcapi_is_defined(c)) {
3204 INFO("Container %s:%s has a config but is not defined",
3205 lxcpath, direntp->d_name);
3206 if (names)
3207 if(!remove_from_array(names, direntp->d_name, cfound--))
3208 goto free_bad;
3209 lxc_container_put(c);
3210 continue;
3211 }
3212
3213 if (!add_to_clist(cret, c, nfound, true)) {
3214 lxc_container_put(c);
3215 goto free_bad;
3216 }
3217 nfound++;
3218 }
3219
3220 closedir(dir);
3221 return nfound;
3222
3223 free_bad:
3224 if (names && *names) {
3225 for (i=0; i<cfound; i++)
3226 free((*names)[i]);
3227 free(*names);
3228 }
3229 if (cret && *cret) {
3230 for (i=0; i<nfound; i++)
3231 lxc_container_put((*cret)[i]);
3232 free(*cret);
3233 }
3234 closedir(dir);
3235 return -1;
3236 }
3237
3238 int list_active_containers(const char *lxcpath, char ***nret,
3239 struct lxc_container ***cret)
3240 {
3241 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
3242 int lxcpath_len;
3243 char *line = NULL;
3244 char **ct_name = NULL;
3245 size_t len = 0;
3246 struct lxc_container *c;
3247
3248 if (!lxcpath)
3249 lxcpath = default_lxc_path();
3250 lxcpath_len = strlen(lxcpath);
3251
3252 if (cret)
3253 *cret = NULL;
3254 if (nret)
3255 *nret = NULL;
3256
3257 FILE *f = fopen("/proc/net/unix", "r");
3258 if (!f)
3259 return -1;
3260
3261 while (getline(&line, &len, f) != -1) {
3262 char *p = strrchr(line, ' '), *p2;
3263 if (!p)
3264 continue;
3265 p++;
3266 if (*p != 0x40)
3267 continue;
3268 p++;
3269 if (strncmp(p, lxcpath, lxcpath_len) != 0)
3270 continue;
3271 p += lxcpath_len;
3272 while (*p == '/')
3273 p++;
3274
3275 // Now p is the start of lxc_name
3276 p2 = index(p, '/');
3277 if (!p2 || strncmp(p2, "/command", 8) != 0)
3278 continue;
3279 *p2 = '\0';
3280
3281 if (array_contains(&ct_name, p, ct_name_cnt))
3282 continue;
3283
3284 if (!add_to_array(&ct_name, p, ct_name_cnt))
3285 goto free_cret_list;
3286
3287 ct_name_cnt++;
3288
3289 if (!cret)
3290 continue;
3291
3292 c = lxc_container_new(p, lxcpath);
3293 if (!c) {
3294 INFO("Container %s:%s is running but could not be loaded",
3295 lxcpath, p);
3296 remove_from_array(&ct_name, p, ct_name_cnt--);
3297 continue;
3298 }
3299
3300 /*
3301 * If this is an anonymous container, then is_defined *can*
3302 * return false. So we don't do that check. Count on the
3303 * fact that the command socket exists.
3304 */
3305
3306 if (!add_to_clist(cret, c, cret_cnt, true)) {
3307 lxc_container_put(c);
3308 goto free_cret_list;
3309 }
3310 cret_cnt++;
3311 }
3312
3313 assert(!nret || !cret || cret_cnt == ct_name_cnt);
3314 ret = ct_name_cnt;
3315 if (nret)
3316 *nret = ct_name;
3317 else
3318 goto free_ct_name;
3319 goto out;
3320
3321 free_cret_list:
3322 if (cret && *cret) {
3323 for (i = 0; i < cret_cnt; i++)
3324 lxc_container_put((*cret)[i]);
3325 free(*cret);
3326 }
3327
3328 free_ct_name:
3329 if (ct_name) {
3330 for (i = 0; i < ct_name_cnt; i++)
3331 free(ct_name[i]);
3332 free(ct_name);
3333 }
3334
3335 out:
3336 if (line)
3337 free(line);
3338
3339 fclose(f);
3340 return ret;
3341 }
3342
3343 int list_all_containers(const char *lxcpath, char ***nret,
3344 struct lxc_container ***cret)
3345 {
3346 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
3347 char **active_name;
3348 char **ct_name;
3349 struct lxc_container **ct_list = NULL;
3350
3351 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
3352 if (ct_cnt < 0)
3353 return ct_cnt;
3354
3355 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
3356 if (active_cnt < 0) {
3357 ret = active_cnt;
3358 goto free_ct_name;
3359 }
3360
3361 for (i = 0; i < active_cnt; i++) {
3362 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
3363 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
3364 ret = -1;
3365 goto free_active_name;
3366 }
3367 ct_cnt++;
3368 }
3369 free(active_name[i]);
3370 active_name[i] = NULL;
3371 }
3372 free(active_name);
3373 active_name = NULL;
3374 active_cnt = 0;
3375
3376 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
3377 struct lxc_container *c;
3378
3379 c = lxc_container_new(ct_name[i], lxcpath);
3380 if (!c) {
3381 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
3382 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
3383 continue;
3384 }
3385
3386 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
3387 lxc_container_put(c);
3388 ret = -1;
3389 goto free_ct_list;
3390 }
3391 ct_list_cnt++;
3392 }
3393
3394 if (cret)
3395 *cret = ct_list;
3396
3397 if (nret)
3398 *nret = ct_name;
3399 else {
3400 ret = ct_cnt;
3401 goto free_ct_name;
3402 }
3403 return ct_cnt;
3404
3405 free_ct_list:
3406 for (i = 0; i < ct_list_cnt; i++) {
3407 lxc_container_put(ct_list[i]);
3408 }
3409 if (ct_list)
3410 free(ct_list);
3411
3412 free_active_name:
3413 for (i = 0; i < active_cnt; i++) {
3414 if (active_name[i])
3415 free(active_name[i]);
3416 }
3417 if (active_name)
3418 free(active_name);
3419
3420 free_ct_name:
3421 for (i = 0; i < ct_cnt; i++) {
3422 free(ct_name[i]);
3423 }
3424 free(ct_name);
3425 return ret;
3426 }