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