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