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