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