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