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