]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
lxccontainer: s/strtok_r()/lxc_iterate_parts()/g
[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(pipe(pipefd) < 0) {
2303 SYSERROR("pipe failed");
2304 return NULL;
2305 }
2306
2307 pid = fork();
2308 if (pid < 0) {
2309 SYSERROR("failed to fork task to get interfaces information");
2310 close(pipefd[0]);
2311 close(pipefd[1]);
2312 return NULL;
2313 }
2314
2315 if (pid == 0) { /* child */
2316 int ret = 1, nbytes;
2317 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
2318
2319 /* close the read-end of the pipe */
2320 close(pipefd[0]);
2321
2322 if (!enter_net_ns(c)) {
2323 SYSERROR("failed to enter namespace");
2324 goto out;
2325 }
2326
2327 /* Grab the list of interfaces */
2328 if (getifaddrs(&interfaceArray)) {
2329 SYSERROR("failed to get interfaces list");
2330 goto out;
2331 }
2332
2333 /* Iterate through the interfaces */
2334 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
2335 nbytes = write(pipefd[1], tempIfAddr->ifa_name, IFNAMSIZ);
2336 if (nbytes < 0) {
2337 ERROR("write failed");
2338 goto out;
2339 }
2340 count++;
2341 }
2342
2343 ret = 0;
2344
2345 out:
2346 if (interfaceArray)
2347 freeifaddrs(interfaceArray);
2348
2349 /* close the write-end of the pipe, thus sending EOF to the reader */
2350 close(pipefd[1]);
2351 _exit(ret);
2352 }
2353
2354 /* close the write-end of the pipe */
2355 close(pipefd[1]);
2356
2357 while (read(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
2358 interface[IFNAMSIZ - 1] = '\0';
2359
2360 if (array_contains(&interfaces, interface, count))
2361 continue;
2362
2363 if(!add_to_array(&interfaces, interface, count))
2364 ERROR("Failed to add \"%s\" to array", interface);
2365
2366 count++;
2367 }
2368
2369 if (wait_for_pid(pid) != 0) {
2370 for(i=0;i<count;i++)
2371 free(interfaces[i]);
2372
2373 free(interfaces);
2374 interfaces = NULL;
2375 }
2376
2377 /* close the read-end of the pipe */
2378 close(pipefd[0]);
2379
2380 /* Append NULL to the array */
2381 if(interfaces)
2382 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
2383
2384 return interfaces;
2385 }
2386
2387 WRAP_API(char **, lxcapi_get_interfaces)
2388
2389 static char **do_lxcapi_get_ips(struct lxc_container *c, const char *interface,
2390 const char *family, int scope)
2391 {
2392 int i, ret;
2393 pid_t pid;
2394 int pipefd[2];
2395 char address[INET6_ADDRSTRLEN];
2396 int count = 0;
2397 char **addresses = NULL;
2398
2399 ret = pipe(pipefd);
2400 if (ret < 0) {
2401 SYSERROR("Failed to create pipe");
2402 return NULL;
2403 }
2404
2405 pid = fork();
2406 if (pid < 0) {
2407 SYSERROR("Failed to create new process");
2408 close(pipefd[0]);
2409 close(pipefd[1]);
2410 return NULL;
2411 }
2412
2413 if (pid == 0) {
2414 ssize_t nbytes;
2415 char addressOutputBuffer[INET6_ADDRSTRLEN];
2416 int ret = 1;
2417 char *address = NULL;
2418 void *tempAddrPtr = NULL;
2419 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
2420
2421 /* close the read-end of the pipe */
2422 close(pipefd[0]);
2423
2424 if (!enter_net_ns(c)) {
2425 SYSERROR("Failed to attach to network namespace");
2426 goto out;
2427 }
2428
2429 /* Grab the list of interfaces */
2430 if (getifaddrs(&interfaceArray)) {
2431 SYSERROR("Failed to get interfaces list");
2432 goto out;
2433 }
2434
2435 /* Iterate through the interfaces */
2436 for (tempIfAddr = interfaceArray; tempIfAddr;
2437 tempIfAddr = tempIfAddr->ifa_next) {
2438 if (tempIfAddr->ifa_addr == NULL)
2439 continue;
2440
2441 if (tempIfAddr->ifa_addr->sa_family == AF_INET) {
2442 if (family && strcmp(family, "inet"))
2443 continue;
2444
2445 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
2446 } else {
2447 if (family && strcmp(family, "inet6"))
2448 continue;
2449
2450 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
2451 continue;
2452
2453 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
2454 }
2455
2456 if (interface && strcmp(interface, tempIfAddr->ifa_name))
2457 continue;
2458 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
2459 continue;
2460
2461 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
2462 tempAddrPtr, addressOutputBuffer,
2463 sizeof(addressOutputBuffer));
2464 if (!address)
2465 continue;
2466
2467 nbytes = lxc_write_nointr(pipefd[1], address, INET6_ADDRSTRLEN);
2468 if (nbytes != INET6_ADDRSTRLEN) {
2469 SYSERROR("Failed to send ipv6 address \"%s\"",
2470 address);
2471 goto out;
2472 }
2473
2474 count++;
2475 }
2476
2477 ret = 0;
2478
2479 out:
2480 if (interfaceArray)
2481 freeifaddrs(interfaceArray);
2482
2483 /* close the write-end of the pipe, thus sending EOF to the reader */
2484 close(pipefd[1]);
2485 _exit(ret);
2486 }
2487
2488 /* close the write-end of the pipe */
2489 close(pipefd[1]);
2490
2491 while (lxc_read_nointr(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
2492 address[INET6_ADDRSTRLEN - 1] = '\0';
2493
2494 if (!add_to_array(&addresses, address, count))
2495 ERROR("PARENT: add_to_array failed");
2496
2497 count++;
2498 }
2499
2500 if (wait_for_pid(pid) != 0) {
2501 for (i = 0; i < count; i++)
2502 free(addresses[i]);
2503
2504 free(addresses);
2505 addresses = NULL;
2506 }
2507
2508 /* close the read-end of the pipe */
2509 close(pipefd[0]);
2510
2511 /* Append NULL to the array */
2512 if (addresses)
2513 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
2514
2515 return addresses;
2516 }
2517
2518 WRAP_API_3(char **, lxcapi_get_ips, const char *, const char *, int)
2519
2520 static int do_lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
2521 {
2522 int ret = -1;
2523 struct lxc_config_t *config;
2524
2525 if (!c || !c->lxc_conf)
2526 return -1;
2527
2528 if (container_mem_lock(c))
2529 return -1;
2530
2531 config = lxc_get_config(key);
2532 /* Verify that the config key exists and that it has a callback
2533 * implemented.
2534 */
2535 if (config && config->get)
2536 ret = config->get(key, retv, inlen, c->lxc_conf, NULL);
2537
2538 container_mem_unlock(c);
2539 return ret;
2540 }
2541
2542 WRAP_API_3(int, lxcapi_get_config_item, const char *, char *, int)
2543
2544 static char* do_lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
2545 {
2546 char *ret;
2547
2548 if (!c || !c->lxc_conf)
2549 return NULL;
2550
2551 if (container_mem_lock(c))
2552 return NULL;
2553
2554 ret = lxc_cmd_get_config_item(c->name, key, do_lxcapi_get_config_path(c));
2555 container_mem_unlock(c);
2556 return ret;
2557 }
2558
2559 WRAP_API_1(char *, lxcapi_get_running_config_item, const char *)
2560
2561 static int do_lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
2562 {
2563 int ret = -1;
2564
2565 /* List all config items. */
2566 if (!key)
2567 return lxc_list_config_items(retv, inlen);
2568
2569 if (!c || !c->lxc_conf)
2570 return -1;
2571
2572 if (container_mem_lock(c))
2573 return -1;
2574
2575 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2576 * This is an intelligent result to show which keys are valid given the
2577 * type of nic it is.
2578 */
2579 if (strncmp(key, "lxc.net.", 8) == 0)
2580 ret = lxc_list_net(c->lxc_conf, key, retv, inlen);
2581 else
2582 ret = lxc_list_subkeys(c->lxc_conf, key, retv, inlen);
2583
2584 container_mem_unlock(c);
2585 return ret;
2586 }
2587
2588 WRAP_API_3(int, lxcapi_get_keys, const char *, char *, int)
2589
2590 static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file)
2591 {
2592 int fd, lret;
2593 bool ret = false, need_disklock = false;
2594
2595 if (!alt_file)
2596 alt_file = c->configfile;
2597
2598 if (!alt_file)
2599 return false;
2600
2601 /* If we haven't yet loaded a config, load the stock config. */
2602 if (!c->lxc_conf) {
2603 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
2604 ERROR("Error loading default configuration file %s "
2605 "while saving %s",
2606 lxc_global_config_value("lxc.default_config"),
2607 c->name);
2608 return false;
2609 }
2610 }
2611
2612 if (!create_container_dir(c))
2613 return false;
2614
2615 /* If we're writing to the container's config file, take the disk lock.
2616 * Otherwise just take the memlock to protect the struct lxc_container
2617 * while we're traversing it.
2618 */
2619 if (strcmp(c->configfile, alt_file) == 0)
2620 need_disklock = true;
2621
2622 if (need_disklock)
2623 lret = container_disk_lock(c);
2624 else
2625 lret = container_mem_lock(c);
2626 if (lret)
2627 return false;
2628
2629 fd = open(alt_file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
2630 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
2631 if (fd < 0)
2632 goto on_error;
2633
2634 lret = write_config(fd, c->lxc_conf);
2635 close(fd);
2636 if (lret < 0)
2637 goto on_error;
2638
2639 ret = true;
2640
2641 on_error:
2642 if (need_disklock)
2643 container_disk_unlock(c);
2644 else
2645 container_mem_unlock(c);
2646
2647 return ret;
2648 }
2649
2650 WRAP_API_1(bool, lxcapi_save_config, const char *)
2651
2652
2653 static bool mod_rdep(struct lxc_container *c0, struct lxc_container *c, bool inc)
2654 {
2655 FILE *f1;
2656 struct stat fbuf;
2657 void *buf = NULL;
2658 char *del = NULL;
2659 char path[MAXPATHLEN];
2660 char newpath[MAXPATHLEN];
2661 int fd, ret, n = 0, v = 0;
2662 bool bret = false;
2663 size_t len = 0, bytes = 0;
2664
2665 if (container_disk_lock(c0))
2666 return false;
2667
2668 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c0->config_path, c0->name);
2669 if (ret < 0 || ret > MAXPATHLEN)
2670 goto out;
2671
2672 ret = snprintf(newpath, MAXPATHLEN, "%s\n%s\n", c->config_path, c->name);
2673 if (ret < 0 || ret > MAXPATHLEN)
2674 goto out;
2675
2676 /* If we find an lxc-snapshot file using the old format only listing the
2677 * number of snapshots we will keep using it. */
2678 f1 = fopen(path, "r");
2679 if (f1) {
2680 n = fscanf(f1, "%d", &v);
2681 fclose(f1);
2682 if (n == 1 && v == 0) {
2683 ret = remove(path);
2684 if (ret < 0)
2685 SYSERROR("Failed to remove \"%s\"", path);
2686
2687 n = 0;
2688 }
2689 }
2690
2691 if (n == 1) {
2692 v += inc ? 1 : -1;
2693 f1 = fopen(path, "w");
2694 if (!f1)
2695 goto out;
2696
2697 if (fprintf(f1, "%d\n", v) < 0) {
2698 ERROR("Error writing new snapshots value");
2699 fclose(f1);
2700 goto out;
2701 }
2702
2703 ret = fclose(f1);
2704 if (ret != 0) {
2705 SYSERROR("Error writing to or closing snapshots file");
2706 goto out;
2707 }
2708 } else {
2709 /* Here we know that we have or can use an lxc-snapshot file
2710 * using the new format. */
2711 if (inc) {
2712 f1 = fopen(path, "a");
2713 if (!f1)
2714 goto out;
2715
2716 if (fprintf(f1, "%s", newpath) < 0) {
2717 ERROR("Error writing new snapshots entry");
2718 ret = fclose(f1);
2719 if (ret != 0)
2720 SYSERROR("Error writing to or closing snapshots file");
2721 goto out;
2722 }
2723
2724 ret = fclose(f1);
2725 if (ret != 0) {
2726 SYSERROR("Error writing to or closing snapshots file");
2727 goto out;
2728 }
2729 } else if (!inc) {
2730 if ((fd = open(path, O_RDWR | O_CLOEXEC)) < 0)
2731 goto out;
2732
2733 if (fstat(fd, &fbuf) < 0) {
2734 close(fd);
2735 goto out;
2736 }
2737
2738 if (fbuf.st_size != 0) {
2739 buf = lxc_strmmap(NULL, fbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2740 if (buf == MAP_FAILED) {
2741 SYSERROR("Failed to create mapping %s", path);
2742 close(fd);
2743 goto out;
2744 }
2745
2746 len = strlen(newpath);
2747 while ((del = strstr((char *)buf, newpath))) {
2748 memmove(del, del + len, strlen(del) - len + 1);
2749 bytes += len;
2750 }
2751
2752 lxc_strmunmap(buf, fbuf.st_size);
2753 if (ftruncate(fd, fbuf.st_size - bytes) < 0) {
2754 SYSERROR("Failed to truncate file %s", path);
2755 close(fd);
2756 goto out;
2757 }
2758 }
2759
2760 close(fd);
2761 }
2762
2763 /* If the lxc-snapshot file is empty, remove it. */
2764 if (stat(path, &fbuf) < 0)
2765 goto out;
2766
2767 if (!fbuf.st_size) {
2768 ret = remove(path);
2769 if (ret < 0)
2770 SYSERROR("Failed to remove \"%s\"", path);
2771 }
2772 }
2773
2774 bret = true;
2775
2776 out:
2777 container_disk_unlock(c0);
2778 return bret;
2779 }
2780
2781 void mod_all_rdeps(struct lxc_container *c, bool inc)
2782 {
2783 struct lxc_container *p;
2784 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
2785 size_t pathlen = 0, namelen = 0;
2786 FILE *f;
2787 int ret;
2788
2789 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
2790 c->config_path, c->name);
2791 if (ret < 0 || ret >= MAXPATHLEN) {
2792 ERROR("Path name too long");
2793 return;
2794 }
2795
2796 f = fopen(path, "r");
2797 if (f == NULL)
2798 return;
2799
2800 while (getline(&lxcpath, &pathlen, f) != -1) {
2801 if (getline(&lxcname, &namelen, f) == -1) {
2802 ERROR("badly formatted file %s", path);
2803 goto out;
2804 }
2805
2806 remove_trailing_newlines(lxcpath);
2807 remove_trailing_newlines(lxcname);
2808
2809 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
2810 ERROR("Unable to find dependent container %s:%s",
2811 lxcpath, lxcname);
2812 continue;
2813 }
2814
2815 if (!mod_rdep(p, c, inc))
2816 ERROR("Failed to update snapshots file for %s:%s",
2817 lxcpath, lxcname);
2818
2819 lxc_container_put(p);
2820 }
2821
2822 out:
2823 free(lxcpath);
2824 free(lxcname);
2825 fclose(f);
2826 }
2827
2828 static bool has_fs_snapshots(struct lxc_container *c)
2829 {
2830 FILE *f;
2831 char path[MAXPATHLEN];
2832 int ret, v;
2833 struct stat fbuf;
2834 bool bret = false;
2835
2836 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
2837 c->name);
2838 if (ret < 0 || ret > MAXPATHLEN)
2839 goto out;
2840
2841 /* If the file doesn't exist there are no snapshots. */
2842 if (stat(path, &fbuf) < 0)
2843 goto out;
2844
2845 v = fbuf.st_size;
2846 if (v != 0) {
2847 f = fopen(path, "r");
2848 if (!f)
2849 goto out;
2850
2851 ret = fscanf(f, "%d", &v);
2852 fclose(f);
2853 /* TODO: Figure out what to do with the return value of fscanf. */
2854 if (ret != 1)
2855 INFO("Container uses new lxc-snapshots format %s", path);
2856 }
2857
2858 bret = v != 0;
2859
2860 out:
2861 return bret;
2862 }
2863
2864 static bool has_snapshots(struct lxc_container *c)
2865 {
2866 char path[MAXPATHLEN];
2867 struct dirent *direntp;
2868 int count=0;
2869 DIR *dir;
2870
2871 if (!get_snappath_dir(c, path))
2872 return false;
2873
2874 dir = opendir(path);
2875 if (!dir)
2876 return false;
2877
2878 while ((direntp = readdir(dir))) {
2879 if (!strcmp(direntp->d_name, "."))
2880 continue;
2881
2882 if (!strcmp(direntp->d_name, ".."))
2883 continue;
2884 count++;
2885 break;
2886 }
2887
2888 closedir(dir);
2889 return count > 0;
2890 }
2891
2892 static bool do_destroy_container(struct lxc_conf *conf) {
2893 int ret;
2894
2895 if (am_guest_unpriv()) {
2896 ret = userns_exec_full(conf, storage_destroy_wrapper, conf,
2897 "storage_destroy_wrapper");
2898 if (ret < 0)
2899 return false;
2900
2901 return true;
2902 }
2903
2904 return storage_destroy(conf);
2905 }
2906
2907 static int lxc_rmdir_onedev_wrapper(void *data)
2908 {
2909 char *arg = (char *) data;
2910 return lxc_rmdir_onedev(arg, "snaps");
2911 }
2912
2913 static int lxc_unlink_exec_wrapper(void *data)
2914 {
2915 char *arg = data;
2916 return unlink(arg);
2917 }
2918
2919 static bool container_destroy(struct lxc_container *c,
2920 struct lxc_storage *storage)
2921 {
2922 const char *p1;
2923 size_t len;
2924 struct lxc_conf *conf;
2925 char *path = NULL;
2926 bool bret = false;
2927 int ret = 0;
2928
2929 if (!c || !do_lxcapi_is_defined(c))
2930 return false;
2931
2932 conf = c->lxc_conf;
2933 if (container_disk_lock(c))
2934 return false;
2935
2936 if (!is_stopped(c)) {
2937 /* We should queue some sort of error - in c->error_string? */
2938 ERROR("container %s is not stopped", c->name);
2939 goto out;
2940 }
2941
2942 if (conf && !lxc_list_empty(&conf->hooks[LXCHOOK_DESTROY])) {
2943 /* Start of environment variable setup for hooks */
2944 if (setenv("LXC_NAME", c->name, 1))
2945 SYSERROR("Failed to set environment variable for container name");
2946
2947 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
2948 SYSERROR("Failed to set environment variable for config path");
2949
2950 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
2951 SYSERROR("Failed to set environment variable for rootfs mount");
2952
2953 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
2954 SYSERROR("Failed to set environment variable for rootfs mount");
2955
2956 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
2957 SYSERROR("Failed to set environment variable for console path");
2958
2959 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
2960 SYSERROR("Failed to set environment variable for console log");
2961 /* End of environment variable setup for hooks */
2962
2963 if (run_lxc_hooks(c->name, "destroy", conf, NULL)) {
2964 ERROR("Failed to execute clone hook for \"%s\"", c->name);
2965 goto out;
2966 }
2967 }
2968
2969 if (current_config && conf == current_config) {
2970 current_config = NULL;
2971
2972 if (conf->logfd != -1) {
2973 close(conf->logfd);
2974 conf->logfd = -1;
2975 }
2976 }
2977
2978 if (conf && conf->rootfs.path && conf->rootfs.mount) {
2979 if (!do_destroy_container(conf)) {
2980 ERROR("Error destroying rootfs for %s", c->name);
2981 goto out;
2982 }
2983 INFO("Destroyed rootfs for %s", c->name);
2984 }
2985
2986 mod_all_rdeps(c, false);
2987
2988 p1 = do_lxcapi_get_config_path(c);
2989 /* strlen(p1)
2990 * +
2991 * /
2992 * +
2993 * strlen(c->name)
2994 * +
2995 * /
2996 * +
2997 * strlen("config") = 6
2998 * +
2999 * \0
3000 */
3001 len = strlen(p1) + 1 + strlen(c->name) + 1 + 6 + 1;
3002 path = malloc(len);
3003 if (!path) {
3004 ERROR("Failed to allocate memory");
3005 goto out;
3006 }
3007
3008 /* For an overlay container the rootfs is considered immutable and
3009 * cannot be removed when restoring from a snapshot.
3010 */
3011 if (storage && (!strcmp(storage->type, "overlay") ||
3012 !strcmp(storage->type, "overlayfs")) &&
3013 (storage->flags & LXC_STORAGE_INTERNAL_OVERLAY_RESTORE)) {
3014 ret = snprintf(path, len, "%s/%s/config", p1, c->name);
3015 if (ret < 0 || (size_t)ret >= len)
3016 goto out;
3017
3018 if (am_guest_unpriv())
3019 ret = userns_exec_1(conf, lxc_unlink_exec_wrapper, path,
3020 "lxc_unlink_exec_wrapper");
3021 else
3022 ret = unlink(path);
3023 if (ret < 0) {
3024 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3025 path, c->name);
3026 goto out;
3027 }
3028 INFO("Destroyed config file \"%s\" for \"%s\"", path, c->name);
3029
3030 bret = true;
3031 goto out;
3032 }
3033
3034 ret = snprintf(path, len, "%s/%s", p1, c->name);
3035 if (ret < 0 || (size_t)ret >= len)
3036 goto out;
3037
3038 if (am_guest_unpriv())
3039 ret = userns_exec_full(conf, lxc_rmdir_onedev_wrapper, path,
3040 "lxc_rmdir_onedev_wrapper");
3041 else
3042 ret = lxc_rmdir_onedev(path, "snaps");
3043 if (ret < 0) {
3044 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path,
3045 c->name);
3046 goto out;
3047 }
3048 INFO("Destroyed directory \"%s\" for \"%s\"", path, c->name);
3049
3050 bret = true;
3051
3052 out:
3053 if (path)
3054 free(path);
3055
3056 container_disk_unlock(c);
3057 return bret;
3058 }
3059
3060 static bool do_lxcapi_destroy(struct lxc_container *c)
3061 {
3062 if (!c || !lxcapi_is_defined(c))
3063 return false;
3064
3065 if (has_snapshots(c)) {
3066 ERROR("Container %s has snapshots; not removing", c->name);
3067 return false;
3068 }
3069
3070 if (has_fs_snapshots(c)) {
3071 ERROR("container %s has snapshots on its rootfs", c->name);
3072 return false;
3073 }
3074
3075 return container_destroy(c, NULL);
3076 }
3077
3078 WRAP_API(bool, lxcapi_destroy)
3079
3080 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container *c)
3081 {
3082 if (!c || !lxcapi_is_defined(c))
3083 return false;
3084
3085 if (!lxcapi_snapshot_destroy_all(c)) {
3086 ERROR("Error deleting all snapshots");
3087 return false;
3088 }
3089
3090 return lxcapi_destroy(c);
3091 }
3092
3093 WRAP_API(bool, lxcapi_destroy_with_snapshots)
3094
3095 int lxc_set_config_item_locked(struct lxc_conf *conf, const char *key,
3096 const char *v)
3097 {
3098 int ret;
3099 struct lxc_config_t *config;
3100 bool bret = true;
3101
3102 config = lxc_get_config(key);
3103 if (!config)
3104 return -EINVAL;
3105
3106 ret = config->set(key, v, conf, NULL);
3107 if (ret < 0)
3108 return -EINVAL;
3109
3110 if (lxc_config_value_empty(v))
3111 do_clear_unexp_config_line(conf, key);
3112 else
3113 bret = do_append_unexp_config_line(conf, key, v);
3114 if (!bret)
3115 return -ENOMEM;
3116
3117 return 0;
3118 }
3119
3120 static bool do_set_config_item_locked(struct lxc_container *c, const char *key,
3121 const char *v)
3122 {
3123 int ret;
3124
3125 if (!c->lxc_conf)
3126 c->lxc_conf = lxc_conf_init();
3127
3128 if (!c->lxc_conf)
3129 return false;
3130
3131 ret = lxc_set_config_item_locked(c->lxc_conf, key, v);
3132 if (ret < 0)
3133 return false;
3134
3135 return true;
3136 }
3137
3138 static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
3139 {
3140 bool b = false;
3141
3142 if (!c)
3143 return false;
3144
3145 if (container_mem_lock(c))
3146 return false;
3147
3148 b = do_set_config_item_locked(c, key, v);
3149
3150 container_mem_unlock(c);
3151 return b;
3152 }
3153
3154 WRAP_API_2(bool, lxcapi_set_config_item, const char *, const char *)
3155
3156 static char *lxcapi_config_file_name(struct lxc_container *c)
3157 {
3158 if (!c || !c->configfile)
3159 return NULL;
3160
3161 return strdup(c->configfile);
3162 }
3163
3164 static const char *lxcapi_get_config_path(struct lxc_container *c)
3165 {
3166 if (!c || !c->config_path)
3167 return NULL;
3168
3169 return (const char *)(c->config_path);
3170 }
3171
3172 /*
3173 * not for export
3174 * Just recalculate the c->configfile based on the
3175 * c->config_path, which must be set.
3176 * The lxc_container must be locked or not yet public.
3177 */
3178 static bool set_config_filename(struct lxc_container *c)
3179 {
3180 char *newpath;
3181 int len, ret;
3182
3183 if (!c->config_path)
3184 return false;
3185
3186 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3187 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
3188 newpath = malloc(len);
3189 if (!newpath)
3190 return false;
3191
3192 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
3193 if (ret < 0 || ret >= len) {
3194 fprintf(stderr, "Error printing out config file name\n");
3195 free(newpath);
3196 return false;
3197 }
3198
3199 free(c->configfile);
3200 c->configfile = newpath;
3201
3202 return true;
3203 }
3204
3205 static bool do_lxcapi_set_config_path(struct lxc_container *c, const char *path)
3206 {
3207 char *p;
3208 bool b = false;
3209 char *oldpath = NULL;
3210
3211 if (!c)
3212 return b;
3213
3214 if (container_mem_lock(c))
3215 return b;
3216
3217 p = strdup(path);
3218 if (!p) {
3219 ERROR("Out of memory setting new lxc path");
3220 goto err;
3221 }
3222
3223 b = true;
3224 if (c->config_path)
3225 oldpath = c->config_path;
3226 c->config_path = p;
3227
3228 /* Since we've changed the config path, we have to change the
3229 * config file name too */
3230 if (!set_config_filename(c)) {
3231 ERROR("Out of memory setting new config filename");
3232 b = false;
3233 free(c->config_path);
3234 c->config_path = oldpath;
3235 oldpath = NULL;
3236 }
3237
3238 err:
3239 free(oldpath);
3240 container_mem_unlock(c);
3241 return b;
3242 }
3243
3244 WRAP_API_1(bool, lxcapi_set_config_path, const char *)
3245
3246 static bool do_lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
3247 {
3248 int ret;
3249 struct cgroup_ops *cgroup_ops;
3250
3251 if (!c)
3252 return false;
3253
3254 if (is_stopped(c))
3255 return false;
3256
3257 cgroup_ops = cgroup_init(NULL);
3258 if (!cgroup_ops)
3259 return false;
3260
3261 if (container_disk_lock(c))
3262 return false;
3263
3264 ret = cgroup_ops->set(cgroup_ops, subsys, value, c->name, c->config_path);
3265
3266 container_disk_unlock(c);
3267
3268 cgroup_exit(cgroup_ops);
3269
3270 return ret == 0;
3271 }
3272
3273 WRAP_API_2(bool, lxcapi_set_cgroup_item, const char *, const char *)
3274
3275 static int do_lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
3276 {
3277 int ret;
3278 struct cgroup_ops *cgroup_ops;
3279
3280 if (!c)
3281 return -1;
3282
3283 if (is_stopped(c))
3284 return -1;
3285
3286 cgroup_ops = cgroup_init(NULL);
3287 if (!cgroup_ops)
3288 return -1;
3289
3290 if (container_disk_lock(c))
3291 return -1;
3292
3293 ret = cgroup_ops->get(cgroup_ops, subsys, retv, inlen, c->name,
3294 c->config_path);
3295
3296 container_disk_unlock(c);
3297
3298 cgroup_exit(cgroup_ops);
3299
3300 return ret;
3301 }
3302
3303 WRAP_API_3(int, lxcapi_get_cgroup_item, const char *, char *, int)
3304
3305 const char *lxc_get_global_config_item(const char *key)
3306 {
3307 return lxc_global_config_value(key);
3308 }
3309
3310 const char *lxc_get_version(void)
3311 {
3312 return LXC_VERSION;
3313 }
3314
3315 static int copy_file(const char *old, const char *new)
3316 {
3317 int in, out;
3318 ssize_t len, ret;
3319 char buf[8096];
3320 struct stat sbuf;
3321
3322 if (file_exists(new)) {
3323 ERROR("copy destination %s exists", new);
3324 return -1;
3325 }
3326
3327 ret = stat(old, &sbuf);
3328 if (ret < 0) {
3329 INFO("Error stat'ing %s", old);
3330 return -1;
3331 }
3332
3333 in = open(old, O_RDONLY);
3334 if (in < 0) {
3335 SYSERROR("Error opening original file %s", old);
3336 return -1;
3337 }
3338
3339 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
3340 if (out < 0) {
3341 SYSERROR("Error opening new file %s", new);
3342 close(in);
3343 return -1;
3344 }
3345
3346 while (1) {
3347 len = read(in, buf, 8096);
3348 if (len < 0) {
3349 SYSERROR("Error reading old file %s", old);
3350 goto err;
3351 }
3352
3353 if (len == 0)
3354 break;
3355
3356 ret = write(out, buf, len);
3357 if (ret < len) { /* should we retry? */
3358 SYSERROR("Error: write to new file %s was interrupted", new);
3359 goto err;
3360 }
3361 }
3362
3363 close(in);
3364 close(out);
3365
3366 /* We set mode, but not owner/group. */
3367 ret = chmod(new, sbuf.st_mode);
3368 if (ret) {
3369 SYSERROR("Error setting mode on %s", new);
3370 return -1;
3371 }
3372
3373 return 0;
3374
3375 err:
3376 close(in);
3377 close(out);
3378 return -1;
3379 }
3380
3381 static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
3382 {
3383 int i, len, ret;
3384 struct lxc_list *it;
3385 char *cpath;
3386
3387 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
3388 cpath = alloca(len);
3389 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
3390 if (ret < 0 || ret >= len)
3391 return -1;
3392
3393 for (i=0; i<NUM_LXC_HOOKS; i++) {
3394 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
3395 char *hookname = it->elem;
3396 char *fname = strrchr(hookname, '/');
3397 char tmppath[MAXPATHLEN];
3398 if (!fname) /* relative path - we don't support, but maybe we should */
3399 return 0;
3400
3401 if (strncmp(hookname, cpath, len - 1) != 0) {
3402 /* this hook is public - ignore */
3403 continue;
3404 }
3405
3406 /* copy the script, and change the entry in confile */
3407 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
3408 c->config_path, c->name, fname+1);
3409 if (ret < 0 || ret >= MAXPATHLEN)
3410 return -1;
3411
3412 ret = copy_file(it->elem, tmppath);
3413 if (ret < 0)
3414 return -1;
3415
3416 free(it->elem);
3417
3418 it->elem = strdup(tmppath);
3419 if (!it->elem) {
3420 ERROR("out of memory copying hook path");
3421 return -1;
3422 }
3423 }
3424 }
3425
3426 if (!clone_update_unexp_hooks(c->lxc_conf, oldc->config_path,
3427 c->config_path, oldc->name, c->name)) {
3428 ERROR("Error saving new hooks in clone");
3429 return -1;
3430 }
3431
3432 do_lxcapi_save_config(c, NULL);
3433 return 0;
3434 }
3435
3436
3437 static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
3438 {
3439 char newpath[MAXPATHLEN];
3440 char *oldpath = oldc->lxc_conf->fstab;
3441 int ret;
3442
3443 if (!oldpath)
3444 return 0;
3445
3446 clear_unexp_config_line(c->lxc_conf, "lxc.mount.fstab", false);
3447
3448 char *p = strrchr(oldpath, '/');
3449 if (!p)
3450 return -1;
3451
3452 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
3453 c->config_path, c->name, p);
3454 if (ret < 0 || ret >= MAXPATHLEN) {
3455 ERROR("error printing new path for %s", oldpath);
3456 return -1;
3457 }
3458
3459 if (file_exists(newpath)) {
3460 ERROR("error: fstab file %s exists", newpath);
3461 return -1;
3462 }
3463
3464 if (copy_file(oldpath, newpath) < 0) {
3465 ERROR("error: copying %s to %s", oldpath, newpath);
3466 return -1;
3467 }
3468
3469 free(c->lxc_conf->fstab);
3470
3471 c->lxc_conf->fstab = strdup(newpath);
3472 if (!c->lxc_conf->fstab) {
3473 ERROR("error: allocating pathname");
3474 return -1;
3475 }
3476
3477 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.mount.fstab", newpath)) {
3478 ERROR("error saving new lxctab");
3479 return -1;
3480 }
3481
3482 return 0;
3483 }
3484
3485 static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
3486 {
3487 char path0[MAXPATHLEN], path1[MAXPATHLEN];
3488 int ret;
3489
3490 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
3491 c0->name);
3492 if (ret < 0 || ret >= MAXPATHLEN) {
3493 WARN("Error copying reverse dependencies");
3494 return;
3495 }
3496
3497 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
3498 c->name);
3499 if (ret < 0 || ret >= MAXPATHLEN) {
3500 WARN("Error copying reverse dependencies");
3501 return;
3502 }
3503
3504 if (copy_file(path0, path1) < 0) {
3505 INFO("Error copying reverse dependencies");
3506 return;
3507 }
3508 }
3509
3510 static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
3511 {
3512 int ret;
3513 char path[MAXPATHLEN];
3514 FILE *f;
3515 bool bret;
3516
3517 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
3518 c->name);
3519 if (ret < 0 || ret >= MAXPATHLEN)
3520 return false;
3521
3522 f = fopen(path, "a");
3523 if (!f)
3524 return false;
3525
3526 bret = true;
3527
3528 /* If anything goes wrong, just return an error. */
3529 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
3530 bret = false;
3531
3532 if (fclose(f) != 0)
3533 bret = false;
3534
3535 return bret;
3536 }
3537
3538 /*
3539 * If the fs natively supports snapshot clones with no penalty,
3540 * then default to those even if not requested.
3541 * Currently we only do this for btrfs.
3542 */
3543 bool should_default_to_snapshot(struct lxc_container *c0,
3544 struct lxc_container *c1)
3545 {
3546 int ret;
3547 size_t l0 = strlen(c0->config_path) + strlen(c0->name) + 2;
3548 size_t l1 = strlen(c1->config_path) + strlen(c1->name) + 2;
3549 char *p0 = alloca(l0 + 1);
3550 char *p1 = alloca(l1 + 1);
3551 char *rootfs = c0->lxc_conf->rootfs.path;
3552
3553 ret = snprintf(p0, l0, "%s/%s", c0->config_path, c0->name);
3554 if (ret < 0 || ret >= l0)
3555 return false;
3556
3557 ret = snprintf(p1, l1, "%s/%s", c1->config_path, c1->name);
3558 if (ret < 0 || ret >= l1)
3559 return false;
3560
3561 if (!is_btrfs_fs(p0) || !is_btrfs_fs(p1))
3562 return false;
3563
3564 if (is_btrfs_subvol(rootfs) <= 0)
3565 return false;
3566
3567 return btrfs_same_fs(p0, p1) == 0;
3568 }
3569
3570 static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
3571 const char *newtype, int flags, const char *bdevdata,
3572 uint64_t newsize)
3573 {
3574 struct lxc_storage *bdev;
3575 bool need_rdep;
3576
3577 if (should_default_to_snapshot(c0, c))
3578 flags |= LXC_CLONE_SNAPSHOT;
3579
3580 bdev = storage_copy(c0, c->name, c->config_path, newtype, flags,
3581 bdevdata, newsize, &need_rdep);
3582 if (!bdev) {
3583 ERROR("Error copying storage.");
3584 return -1;
3585 }
3586
3587 /* Set new rootfs. */
3588 free(c->lxc_conf->rootfs.path);
3589 c->lxc_conf->rootfs.path = strdup(bdev->src);
3590 storage_put(bdev);
3591
3592 if (!c->lxc_conf->rootfs.path) {
3593 ERROR("Out of memory while setting storage path.");
3594 return -1;
3595 }
3596
3597 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3598 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.path", false);
3599 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs.path",
3600 c->lxc_conf->rootfs.path)) {
3601 ERROR("Error saving new rootfs to cloned config.");
3602 return -1;
3603 }
3604
3605 if (flags & LXC_CLONE_SNAPSHOT)
3606 copy_rdepends(c, c0);
3607
3608 if (need_rdep) {
3609 if (!add_rdepends(c, c0))
3610 WARN("Error adding reverse dependency from %s to %s",
3611 c->name, c0->name);
3612 }
3613
3614 mod_all_rdeps(c, true);
3615
3616 return 0;
3617 }
3618
3619 struct clone_update_data {
3620 struct lxc_container *c0;
3621 struct lxc_container *c1;
3622 int flags;
3623 char **hookargs;
3624 };
3625
3626 static int clone_update_rootfs(struct clone_update_data *data)
3627 {
3628 struct lxc_container *c0 = data->c0;
3629 struct lxc_container *c = data->c1;
3630 int flags = data->flags;
3631 char **hookargs = data->hookargs;
3632 int ret = -1;
3633 char path[MAXPATHLEN];
3634 struct lxc_storage *bdev;
3635 FILE *fout;
3636 struct lxc_conf *conf = c->lxc_conf;
3637
3638 /* update hostname in rootfs */
3639 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3640
3641 if (setgid(0) < 0) {
3642 ERROR("Failed to setgid to 0");
3643 return -1;
3644 }
3645
3646 if (setuid(0) < 0) {
3647 ERROR("Failed to setuid to 0");
3648 return -1;
3649 }
3650
3651 if (setgroups(0, NULL) < 0)
3652 WARN("Failed to clear groups");
3653
3654 if (unshare(CLONE_NEWNS) < 0)
3655 return -1;
3656
3657 bdev = storage_init(c->lxc_conf);
3658 if (!bdev)
3659 return -1;
3660
3661 if (strcmp(bdev->type, "dir") != 0) {
3662 if (unshare(CLONE_NEWNS) < 0) {
3663 ERROR("error unsharing mounts");
3664 storage_put(bdev);
3665 return -1;
3666 }
3667
3668 if (detect_shared_rootfs()) {
3669 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
3670 SYSERROR("Failed to make / rslave");
3671 ERROR("Continuing...");
3672 }
3673 }
3674
3675 if (bdev->ops->mount(bdev) < 0) {
3676 storage_put(bdev);
3677 return -1;
3678 }
3679 } else { /* TODO come up with a better way */
3680 free(bdev->dest);
3681 bdev->dest = strdup(bdev->src);
3682 }
3683
3684 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
3685 /* Start of environment variable setup for hooks */
3686 if (c0->name && setenv("LXC_SRC_NAME", c0->name, 1))
3687 SYSERROR("failed to set environment variable for source container name");
3688
3689 if (setenv("LXC_NAME", c->name, 1))
3690 SYSERROR("failed to set environment variable for container name");
3691
3692 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
3693 SYSERROR("failed to set environment variable for config path");
3694
3695 if (bdev->dest && setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1))
3696 SYSERROR("failed to set environment variable for rootfs mount");
3697
3698 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
3699 SYSERROR("failed to set environment variable for rootfs mount");
3700
3701 if (run_lxc_hooks(c->name, "clone", conf, hookargs)) {
3702 ERROR("Error executing clone hook for %s", c->name);
3703 storage_put(bdev);
3704 return -1;
3705 }
3706 }
3707
3708 if (!(flags & LXC_CLONE_KEEPNAME)) {
3709 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
3710 storage_put(bdev);
3711
3712 if (ret < 0 || ret >= MAXPATHLEN)
3713 return -1;
3714
3715 if (!file_exists(path))
3716 return 0;
3717
3718 if (!(fout = fopen(path, "w"))) {
3719 SYSERROR("unable to open %s: ignoring", path);
3720 return 0;
3721 }
3722
3723 if (fprintf(fout, "%s", c->name) < 0) {
3724 fclose(fout);
3725 return -1;
3726 }
3727
3728 if (fclose(fout) < 0)
3729 return -1;
3730 } else {
3731 storage_put(bdev);
3732 }
3733
3734 return 0;
3735 }
3736
3737 static int clone_update_rootfs_wrapper(void *data)
3738 {
3739 struct clone_update_data *arg = (struct clone_update_data *) data;
3740 return clone_update_rootfs(arg);
3741 }
3742
3743 /*
3744 * We want to support:
3745 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3746 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3747
3748 -s [ implies overlay]
3749 -s -B overlay
3750
3751 only rootfs gets converted (copied/snapshotted) on clone.
3752 */
3753
3754 static int create_file_dirname(char *path, struct lxc_conf *conf)
3755 {
3756 char *p = strrchr(path, '/');
3757 int ret = -1;
3758
3759 if (!p)
3760 return -1;
3761
3762 *p = '\0';
3763 ret = do_create_container_dir(path, conf);
3764 *p = '/';
3765
3766 return ret;
3767 }
3768
3769 static struct lxc_container *do_lxcapi_clone(struct lxc_container *c, const char *newname,
3770 const char *lxcpath, int flags,
3771 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3772 char **hookargs)
3773 {
3774 char newpath[MAXPATHLEN];
3775 int fd, ret;
3776 struct clone_update_data data;
3777 size_t saved_unexp_len;
3778 pid_t pid;
3779 int storage_copied = 0;
3780 char *origroot = NULL, *saved_unexp_conf = NULL;
3781 struct lxc_container *c2 = NULL;
3782
3783 if (!c || !do_lxcapi_is_defined(c))
3784 return NULL;
3785
3786 if (container_mem_lock(c))
3787 return NULL;
3788
3789 if (!is_stopped(c)) {
3790 ERROR("error: Original container (%s) is running", c->name);
3791 goto out;
3792 }
3793
3794 /* Make sure the container doesn't yet exist. */
3795 if (!newname)
3796 newname = c->name;
3797
3798 if (!lxcpath)
3799 lxcpath = do_lxcapi_get_config_path(c);
3800
3801 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", lxcpath, newname);
3802 if (ret < 0 || ret >= MAXPATHLEN) {
3803 SYSERROR("clone: failed making config pathname");
3804 goto out;
3805 }
3806
3807 if (file_exists(newpath)) {
3808 ERROR("error: clone: %s exists", newpath);
3809 goto out;
3810 }
3811
3812 ret = create_file_dirname(newpath, c->lxc_conf);
3813 if (ret < 0 && errno != EEXIST) {
3814 ERROR("Error creating container dir for %s", newpath);
3815 goto out;
3816 }
3817
3818 /* Copy the configuration. Tweak it as needed. */
3819 if (c->lxc_conf->rootfs.path) {
3820 origroot = c->lxc_conf->rootfs.path;
3821 c->lxc_conf->rootfs.path = NULL;
3822 }
3823
3824 fd = open(newpath, O_WRONLY | O_CREAT | O_CLOEXEC,
3825 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
3826 if (fd < 0) {
3827 SYSERROR("Failed to open \"%s\"", newpath);
3828 goto out;
3829 }
3830
3831 saved_unexp_conf = c->lxc_conf->unexpanded_config;
3832 saved_unexp_len = c->lxc_conf->unexpanded_len;
3833 c->lxc_conf->unexpanded_config = strdup(saved_unexp_conf);
3834 if (!c->lxc_conf->unexpanded_config) {
3835 close(fd);
3836 goto out;
3837 }
3838
3839 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.path", false);
3840 write_config(fd, c->lxc_conf);
3841 close(fd);
3842
3843 c->lxc_conf->rootfs.path = origroot;
3844
3845 free(c->lxc_conf->unexpanded_config);
3846 c->lxc_conf->unexpanded_config = saved_unexp_conf;
3847 saved_unexp_conf = NULL;
3848 c->lxc_conf->unexpanded_len = saved_unexp_len;
3849
3850 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/rootfs", lxcpath, newname);
3851 if (ret < 0 || ret >= MAXPATHLEN) {
3852 SYSERROR("clone: failed making rootfs pathname");
3853 goto out;
3854 }
3855
3856 ret = mkdir(newpath, 0755);
3857 if (ret < 0) {
3858 /* For an overlay container the rootfs is considered immutable
3859 * and will not have been removed when restoring from a
3860 * snapshot.
3861 */
3862 if (errno != ENOENT &&
3863 !(flags & LXC_STORAGE_INTERNAL_OVERLAY_RESTORE)) {
3864 SYSERROR("Failed to create directory \"%s\"", newpath);
3865 goto out;
3866 }
3867 }
3868
3869 if (am_guest_unpriv()) {
3870 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
3871 ERROR("Error chowning %s to container root", newpath);
3872 goto out;
3873 }
3874 }
3875
3876 c2 = lxc_container_new(newname, lxcpath);
3877 if (!c2) {
3878 ERROR("clone: failed to create new container (%s %s)", newname,
3879 lxcpath);
3880 goto out;
3881 }
3882
3883 /* copy/snapshot rootfs's */
3884 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
3885 if (ret < 0)
3886 goto out;
3887
3888 /* update utsname */
3889 if (!(flags & LXC_CLONE_KEEPNAME)) {
3890 clear_unexp_config_line(c2->lxc_conf, "lxc.utsname", false);
3891 clear_unexp_config_line(c2->lxc_conf, "lxc.uts.name", false);
3892
3893 if (!do_set_config_item_locked(c2, "lxc.uts.name", newname)) {
3894 ERROR("Error setting new hostname");
3895 goto out;
3896 }
3897 }
3898
3899 /* copy hooks */
3900 ret = copyhooks(c, c2);
3901 if (ret < 0) {
3902 ERROR("error copying hooks");
3903 goto out;
3904 }
3905
3906 if (copy_fstab(c, c2) < 0) {
3907 ERROR("error copying fstab");
3908 goto out;
3909 }
3910
3911 /* update macaddrs */
3912 if (!(flags & LXC_CLONE_KEEPMACADDR)) {
3913 if (!network_new_hwaddrs(c2->lxc_conf)) {
3914 ERROR("Error updating mac addresses");
3915 goto out;
3916 }
3917 }
3918
3919 /* Update absolute paths for overlay mount directories. */
3920 if (ovl_update_abs_paths(c2->lxc_conf, c->config_path, c->name, lxcpath, newname) < 0)
3921 goto out;
3922
3923 /* We've now successfully created c2's storage, so clear it out if we
3924 * fail after this.
3925 */
3926 storage_copied = 1;
3927
3928 if (!c2->save_config(c2, NULL))
3929 goto out;
3930
3931 if ((pid = fork()) < 0) {
3932 SYSERROR("fork");
3933 goto out;
3934 }
3935
3936 if (pid > 0) {
3937 ret = wait_for_pid(pid);
3938 if (ret)
3939 goto out;
3940
3941 container_mem_unlock(c);
3942 return c2;
3943 }
3944
3945 data.c0 = c;
3946 data.c1 = c2;
3947 data.flags = flags;
3948 data.hookargs = hookargs;
3949
3950 if (am_guest_unpriv())
3951 ret = userns_exec_full(c->lxc_conf, clone_update_rootfs_wrapper,
3952 &data, "clone_update_rootfs_wrapper");
3953 else
3954 ret = clone_update_rootfs(&data);
3955 if (ret < 0)
3956 _exit(EXIT_FAILURE);
3957
3958 container_mem_unlock(c);
3959 _exit(EXIT_SUCCESS);
3960
3961 out:
3962 container_mem_unlock(c);
3963 if (c2) {
3964 if (!storage_copied)
3965 c2->lxc_conf->rootfs.path = NULL;
3966
3967 c2->destroy(c2);
3968 lxc_container_put(c2);
3969 }
3970
3971 return NULL;
3972 }
3973
3974 static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
3975 const char *lxcpath, int flags,
3976 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3977 char **hookargs)
3978 {
3979 struct lxc_container * ret;
3980
3981 current_config = c ? c->lxc_conf : NULL;
3982 ret = do_lxcapi_clone(c, newname, lxcpath, flags, bdevtype, bdevdata, newsize, hookargs);
3983 current_config = NULL;
3984
3985 return ret;
3986 }
3987
3988 static bool do_lxcapi_rename(struct lxc_container *c, const char *newname)
3989 {
3990 struct lxc_storage *bdev;
3991 struct lxc_container *newc;
3992
3993 if (!c || !c->name || !c->config_path || !c->lxc_conf)
3994 return false;
3995
3996 if (has_fs_snapshots(c) || has_snapshots(c)) {
3997 ERROR("Renaming a container with snapshots is not supported");
3998 return false;
3999 }
4000
4001 bdev = storage_init(c->lxc_conf);
4002 if (!bdev) {
4003 ERROR("Failed to find original backing store type");
4004 return false;
4005 }
4006
4007 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
4008 storage_put(bdev);
4009 if (!newc) {
4010 lxc_container_put(newc);
4011 return false;
4012 }
4013
4014 if (newc && lxcapi_is_defined(newc))
4015 lxc_container_put(newc);
4016
4017 if (!container_destroy(c, NULL)) {
4018 ERROR("Could not destroy existing container %s", c->name);
4019 return false;
4020 }
4021
4022 return true;
4023 }
4024
4025 WRAP_API_1(bool, lxcapi_rename, const char *)
4026
4027 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)
4028 {
4029 int ret;
4030
4031 if (!c)
4032 return -1;
4033
4034 current_config = c->lxc_conf;
4035
4036 ret = lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
4037 current_config = NULL;
4038 return ret;
4039 }
4040
4041 static int do_lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
4042 {
4043 lxc_attach_command_t command;
4044 pid_t pid;
4045 int r;
4046
4047 if (!c)
4048 return -1;
4049
4050 command.program = (char*)program;
4051 command.argv = (char**)argv;
4052
4053 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
4054 if (r < 0) {
4055 ERROR("ups");
4056 return r;
4057 }
4058
4059 return lxc_wait_for_pid_status(pid);
4060 }
4061
4062 static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
4063 {
4064 int ret;
4065
4066 current_config = c ? c->lxc_conf : NULL;
4067 ret = do_lxcapi_attach_run_wait(c, options, program, argv);
4068 current_config = NULL;
4069
4070 return ret;
4071 }
4072
4073 static int get_next_index(const char *lxcpath, char *cname)
4074 {
4075 char *fname;
4076 struct stat sb;
4077 int i = 0, ret;
4078
4079 fname = alloca(strlen(lxcpath) + 20);
4080
4081 while (1) {
4082 sprintf(fname, "%s/snap%d", lxcpath, i);
4083
4084 ret = stat(fname, &sb);
4085 if (ret != 0)
4086 return i;
4087
4088 i++;
4089 }
4090 }
4091
4092 static bool get_snappath_dir(struct lxc_container *c, char *snappath)
4093 {
4094 int ret;
4095
4096 /*
4097 * If the old style snapshot path exists, use it
4098 * /var/lib/lxc -> /var/lib/lxcsnaps
4099 */
4100 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps", c->config_path);
4101 if (ret < 0 || ret >= MAXPATHLEN)
4102 return false;
4103
4104 if (dir_exists(snappath)) {
4105 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
4106 if (ret < 0 || ret >= MAXPATHLEN)
4107 return false;
4108
4109 return true;
4110 }
4111
4112 /*
4113 * Use the new style path
4114 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4115 */
4116 ret = snprintf(snappath, MAXPATHLEN, "%s/%s/snaps", c->config_path, c->name);
4117 if (ret < 0 || ret >= MAXPATHLEN)
4118 return false;
4119
4120 return true;
4121 }
4122
4123 static int do_lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
4124 {
4125 int i, flags, ret;
4126 struct lxc_container *c2;
4127 char snappath[MAXPATHLEN], newname[20];
4128
4129 if (!c || !lxcapi_is_defined(c))
4130 return -1;
4131
4132 if (!storage_can_backup(c->lxc_conf)) {
4133 ERROR("%s's backing store cannot be backed up.", c->name);
4134 ERROR("Your container must use another backing store type.");
4135 return -1;
4136 }
4137
4138 if (!get_snappath_dir(c, snappath))
4139 return -1;
4140
4141 i = get_next_index(snappath, c->name);
4142
4143 if (mkdir_p(snappath, 0755) < 0) {
4144 ERROR("Failed to create snapshot directory %s", snappath);
4145 return -1;
4146 }
4147
4148 ret = snprintf(newname, 20, "snap%d", i);
4149 if (ret < 0 || ret >= 20)
4150 return -1;
4151
4152 /*
4153 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4154 * created in the original container
4155 */
4156 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
4157 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
4158 if (storage_is_dir(c->lxc_conf)) {
4159 ERROR("Snapshot of directory-backed container requested.");
4160 ERROR("Making a copy-clone. If you do want snapshots, then");
4161 ERROR("please create overlay clone first, snapshot that");
4162 ERROR("and keep the original container pristine.");
4163 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
4164 }
4165
4166 c2 = do_lxcapi_clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
4167 if (!c2) {
4168 ERROR("clone of %s:%s failed", c->config_path, c->name);
4169 return -1;
4170 }
4171
4172 lxc_container_put(c2);
4173
4174 /* Now write down the creation time. */
4175 time_t timer;
4176 char buffer[25];
4177 struct tm* tm_info;
4178 FILE *f;
4179
4180 time(&timer);
4181 tm_info = localtime(&timer);
4182
4183 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
4184
4185 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
4186 sprintf(dfnam, "%s/%s/ts", snappath, newname);
4187 f = fopen(dfnam, "w");
4188 if (!f) {
4189 ERROR("Failed to open %s", dfnam);
4190 return -1;
4191 }
4192
4193 if (fprintf(f, "%s", buffer) < 0) {
4194 SYSERROR("Writing timestamp");
4195 fclose(f);
4196 return -1;
4197 }
4198
4199 ret = fclose(f);
4200 if (ret != 0) {
4201 SYSERROR("Writing timestamp");
4202 return -1;
4203 }
4204
4205 if (commentfile) {
4206 /* $p / $name / comment \0 */
4207 int len = strlen(snappath) + strlen(newname) + 10;
4208 char *path = alloca(len);
4209
4210 sprintf(path, "%s/%s/comment", snappath, newname);
4211 return copy_file(commentfile, path) < 0 ? -1 : i;
4212 }
4213
4214 return i;
4215 }
4216
4217 WRAP_API_1(int, lxcapi_snapshot, const char *)
4218
4219 static void lxcsnap_free(struct lxc_snapshot *s)
4220 {
4221 free(s->name);
4222 free(s->comment_pathname);
4223 free(s->timestamp);
4224 free(s->lxcpath);
4225 }
4226
4227 static char *get_snapcomment_path(char* snappath, char *name)
4228 {
4229 /* $snappath/$name/comment */
4230 int ret, len = strlen(snappath) + strlen(name) + 10;
4231 char *s = malloc(len);
4232
4233 if (s) {
4234 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
4235 if (ret < 0 || ret >= len) {
4236 free(s);
4237 s = NULL;
4238 }
4239 }
4240
4241 return s;
4242 }
4243
4244 static char *get_timestamp(char* snappath, char *name)
4245 {
4246 char path[MAXPATHLEN], *s = NULL;
4247 int ret, len;
4248 FILE *fin;
4249
4250 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
4251 if (ret < 0 || ret >= MAXPATHLEN)
4252 return NULL;
4253
4254 fin = fopen(path, "r");
4255 if (!fin)
4256 return NULL;
4257
4258 (void) fseek(fin, 0, SEEK_END);
4259 len = ftell(fin);
4260 (void) fseek(fin, 0, SEEK_SET);
4261 if (len > 0) {
4262 s = malloc(len+1);
4263 if (s) {
4264 s[len] = '\0';
4265 if (fread(s, 1, len, fin) != len) {
4266 SYSERROR("reading timestamp");
4267 free(s);
4268 s = NULL;
4269 }
4270 }
4271 }
4272
4273 fclose(fin);
4274 return s;
4275 }
4276
4277 static int do_lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
4278 {
4279 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
4280 int count = 0, ret;
4281 struct dirent *direntp;
4282 struct lxc_snapshot *snaps =NULL, *nsnaps;
4283 DIR *dir;
4284
4285 if (!c || !lxcapi_is_defined(c))
4286 return -1;
4287
4288 if (!get_snappath_dir(c, snappath)) {
4289 ERROR("path name too long");
4290 return -1;
4291 }
4292
4293 dir = opendir(snappath);
4294 if (!dir) {
4295 INFO("Failed to open %s - assuming no snapshots", snappath);
4296 return 0;
4297 }
4298
4299 while ((direntp = readdir(dir))) {
4300 if (!strcmp(direntp->d_name, "."))
4301 continue;
4302
4303 if (!strcmp(direntp->d_name, ".."))
4304 continue;
4305
4306 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
4307 if (ret < 0 || ret >= MAXPATHLEN) {
4308 ERROR("pathname too long");
4309 goto out_free;
4310 }
4311
4312 if (!file_exists(path2))
4313 continue;
4314
4315 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
4316 if (!nsnaps) {
4317 SYSERROR("Out of memory");
4318 goto out_free;
4319 }
4320
4321 snaps = nsnaps;
4322 snaps[count].free = lxcsnap_free;
4323 snaps[count].name = strdup(direntp->d_name);
4324 if (!snaps[count].name)
4325 goto out_free;
4326
4327 snaps[count].lxcpath = strdup(snappath);
4328 if (!snaps[count].lxcpath) {
4329 free(snaps[count].name);
4330 goto out_free;
4331 }
4332
4333 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
4334 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
4335 count++;
4336 }
4337
4338 if (closedir(dir))
4339 WARN("Failed to close directory");
4340
4341 *ret_snaps = snaps;
4342 return count;
4343
4344 out_free:
4345 if (snaps) {
4346 int i;
4347
4348 for (i=0; i<count; i++)
4349 lxcsnap_free(&snaps[i]);
4350
4351 free(snaps);
4352 }
4353
4354 if (closedir(dir))
4355 WARN("Failed to close directory");
4356
4357 return -1;
4358 }
4359
4360 WRAP_API_1(int, lxcapi_snapshot_list, struct lxc_snapshot **)
4361
4362 static bool do_lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
4363 {
4364 char clonelxcpath[MAXPATHLEN];
4365 int flags = 0;
4366 struct lxc_container *snap, *rest;
4367 struct lxc_storage *bdev;
4368 bool b = false;
4369
4370 if (!c || !c->name || !c->config_path)
4371 return false;
4372
4373 if (has_fs_snapshots(c)) {
4374 ERROR("container rootfs has dependent snapshots");
4375 return false;
4376 }
4377
4378 bdev = storage_init(c->lxc_conf);
4379 if (!bdev) {
4380 ERROR("Failed to find original backing store type");
4381 return false;
4382 }
4383
4384 /* For an overlay container the rootfs is considered immutable
4385 * and cannot be removed when restoring from a snapshot. We pass this
4386 * internal flag along to communicate this to various parts of the
4387 * codebase.
4388 */
4389 if (!strcmp(bdev->type, "overlay") || !strcmp(bdev->type, "overlayfs"))
4390 bdev->flags |= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE;
4391
4392 if (!newname)
4393 newname = c->name;
4394
4395 if (!get_snappath_dir(c, clonelxcpath)) {
4396 storage_put(bdev);
4397 return false;
4398 }
4399 /* how should we lock this? */
4400
4401 snap = lxc_container_new(snapname, clonelxcpath);
4402 if (!snap || !lxcapi_is_defined(snap)) {
4403 ERROR("Could not open snapshot %s", snapname);
4404
4405 if (snap)
4406 lxc_container_put(snap);
4407
4408 storage_put(bdev);
4409 return false;
4410 }
4411
4412 if (!strcmp(c->name, newname)) {
4413 if (!container_destroy(c, bdev)) {
4414 ERROR("Could not destroy existing container %s", newname);
4415 lxc_container_put(snap);
4416 storage_put(bdev);
4417 return false;
4418 }
4419 }
4420
4421 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
4422 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
4423
4424 if (!strcmp(bdev->type, "overlay") || !strcmp(bdev->type, "overlayfs"))
4425 flags |= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE;
4426
4427 rest = lxcapi_clone(snap, newname, c->config_path, flags, bdev->type,
4428 NULL, 0, NULL);
4429 storage_put(bdev);
4430 if (rest && lxcapi_is_defined(rest))
4431 b = true;
4432
4433 if (rest)
4434 lxc_container_put(rest);
4435
4436 lxc_container_put(snap);
4437 return b;
4438 }
4439
4440 WRAP_API_2(bool, lxcapi_snapshot_restore, const char *, const char *)
4441
4442 static bool do_snapshot_destroy(const char *snapname, const char *clonelxcpath)
4443 {
4444 struct lxc_container *snap = NULL;
4445 bool bret = false;
4446
4447 snap = lxc_container_new(snapname, clonelxcpath);
4448 if (!snap) {
4449 ERROR("Could not find snapshot %s", snapname);
4450 goto err;
4451 }
4452
4453 if (!do_lxcapi_destroy(snap)) {
4454 ERROR("Could not destroy snapshot %s", snapname);
4455 goto err;
4456 }
4457
4458 bret = true;
4459
4460 err:
4461 if (snap)
4462 lxc_container_put(snap);
4463
4464 return bret;
4465 }
4466
4467 static bool remove_all_snapshots(const char *path)
4468 {
4469 DIR *dir;
4470 struct dirent *direntp;
4471 bool bret = true;
4472
4473 dir = opendir(path);
4474 if (!dir) {
4475 SYSERROR("opendir on snapshot path %s", path);
4476 return false;
4477 }
4478
4479 while ((direntp = readdir(dir))) {
4480 if (!strcmp(direntp->d_name, "."))
4481 continue;
4482
4483 if (!strcmp(direntp->d_name, ".."))
4484 continue;
4485
4486 if (!do_snapshot_destroy(direntp->d_name, path)) {
4487 bret = false;
4488 continue;
4489 }
4490 }
4491
4492 closedir(dir);
4493
4494 if (rmdir(path))
4495 SYSERROR("Error removing directory %s", path);
4496
4497 return bret;
4498 }
4499
4500 static bool do_lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
4501 {
4502 char clonelxcpath[MAXPATHLEN];
4503
4504 if (!c || !c->name || !c->config_path || !snapname)
4505 return false;
4506
4507 if (!get_snappath_dir(c, clonelxcpath))
4508 return false;
4509
4510 return do_snapshot_destroy(snapname, clonelxcpath);
4511 }
4512
4513 WRAP_API_1(bool, lxcapi_snapshot_destroy, const char *)
4514
4515 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container *c)
4516 {
4517 char clonelxcpath[MAXPATHLEN];
4518
4519 if (!c || !c->name || !c->config_path)
4520 return false;
4521
4522 if (!get_snappath_dir(c, clonelxcpath))
4523 return false;
4524
4525 return remove_all_snapshots(clonelxcpath);
4526 }
4527
4528 WRAP_API(bool, lxcapi_snapshot_destroy_all)
4529
4530 static bool do_lxcapi_may_control(struct lxc_container *c)
4531 {
4532 return lxc_try_cmd(c->name, c->config_path) == 0;
4533 }
4534
4535 WRAP_API(bool, lxcapi_may_control)
4536
4537 static bool do_add_remove_node(pid_t init_pid, const char *path, bool add,
4538 struct stat *st)
4539 {
4540 int ret;
4541 char *tmp;
4542 pid_t pid;
4543 char chrootpath[MAXPATHLEN];
4544 char *directory_path = NULL;
4545
4546 pid = fork();
4547 if (pid < 0) {
4548 SYSERROR("Failed to fork()");
4549 return false;
4550 }
4551
4552 if (pid) {
4553 ret = wait_for_pid(pid);
4554 if (ret != 0) {
4555 ERROR("Failed to create device node");
4556 return false;
4557 }
4558
4559 return true;
4560 }
4561
4562 /* prepare the path */
4563 ret = snprintf(chrootpath, MAXPATHLEN, "/proc/%d/root", init_pid);
4564 if (ret < 0 || ret >= MAXPATHLEN)
4565 return false;
4566
4567 ret = chroot(chrootpath);
4568 if (ret < 0)
4569 _exit(EXIT_FAILURE);
4570
4571 ret = chdir("/");
4572 if (ret < 0)
4573 _exit(EXIT_FAILURE);
4574
4575 /* remove path if it exists */
4576 ret = faccessat(AT_FDCWD, path, F_OK, AT_SYMLINK_NOFOLLOW);
4577 if(ret == 0) {
4578 ret = unlink(path);
4579 if (ret < 0) {
4580 SYSERROR("Failed to remove \"%s\"", path);
4581 _exit(EXIT_FAILURE);
4582 }
4583 }
4584
4585 if (!add)
4586 _exit(EXIT_SUCCESS);
4587
4588 /* create any missing directories */
4589 tmp = strdup(path);
4590 if (!tmp)
4591 _exit(EXIT_FAILURE);
4592
4593 directory_path = dirname(tmp);
4594 ret = mkdir_p(directory_path, 0755);
4595 if (ret < 0 && errno != EEXIST) {
4596 SYSERROR("Failed to create path \"%s\"", directory_path);
4597 free(tmp);
4598 _exit(EXIT_FAILURE);
4599 }
4600
4601 /* create the device node */
4602 ret = mknod(path, st->st_mode, st->st_rdev);
4603 free(tmp);
4604 if (ret < 0) {
4605 SYSERROR("Failed to create device node at \"%s\"", path);
4606 _exit(EXIT_FAILURE);
4607 }
4608
4609 _exit(EXIT_SUCCESS);
4610 }
4611
4612 static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
4613 {
4614 int ret;
4615 struct stat st;
4616 char value[LXC_MAX_BUFFER];
4617 const char *p;
4618
4619 /* make sure container is running */
4620 if (!do_lxcapi_is_running(c)) {
4621 ERROR("container is not running");
4622 return false;
4623 }
4624
4625 /* use src_path if dest_path is NULL otherwise use dest_path */
4626 p = dest_path ? dest_path : src_path;
4627
4628 /* make sure we can access p */
4629 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
4630 return false;
4631
4632 /* continue if path is character device or block device */
4633 if (S_ISCHR(st.st_mode))
4634 ret = snprintf(value, LXC_MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
4635 else if (S_ISBLK(st.st_mode))
4636 ret = snprintf(value, LXC_MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
4637 else
4638 return false;
4639
4640 /* check snprintf return code */
4641 if (ret < 0 || ret >= LXC_MAX_BUFFER)
4642 return false;
4643
4644 if (!do_add_remove_node(do_lxcapi_init_pid(c), p, add, &st))
4645 return false;
4646
4647 /* add or remove device to/from cgroup access list */
4648 if (add) {
4649 if (!do_lxcapi_set_cgroup_item(c, "devices.allow", value)) {
4650 ERROR("set_cgroup_item failed while adding the device node");
4651 return false;
4652 }
4653 } else {
4654 if (!do_lxcapi_set_cgroup_item(c, "devices.deny", value)) {
4655 ERROR("set_cgroup_item failed while removing the device node");
4656 return false;
4657 }
4658 }
4659
4660 return true;
4661 }
4662
4663 static bool do_lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
4664 {
4665 // cannot mknod if we're not privileged wrt init_user_ns
4666 if (am_host_unpriv()) {
4667 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
4668 return false;
4669 }
4670
4671 return add_remove_device_node(c, src_path, dest_path, true);
4672 }
4673
4674 WRAP_API_2(bool, lxcapi_add_device_node, const char *, const char *)
4675
4676 static bool do_lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
4677 {
4678 if (am_guest_unpriv()) {
4679 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
4680 return false;
4681 }
4682
4683 return add_remove_device_node(c, src_path, dest_path, false);
4684 }
4685
4686 WRAP_API_2(bool, lxcapi_remove_device_node, const char *, const char *)
4687
4688 static bool do_lxcapi_attach_interface(struct lxc_container *c,
4689 const char *ifname,
4690 const char *dst_ifname)
4691 {
4692 pid_t init_pid;
4693 int ret = 0;
4694
4695 if (am_guest_unpriv()) {
4696 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
4697 return false;
4698 }
4699
4700 if (!ifname) {
4701 ERROR("No source interface name given");
4702 return false;
4703 }
4704
4705 ret = lxc_netdev_isup(ifname);
4706 if (ret > 0) {
4707 /* netdev of ifname is up. */
4708 ret = lxc_netdev_down(ifname);
4709 if (ret)
4710 goto err;
4711 }
4712
4713 init_pid = do_lxcapi_init_pid(c);
4714 ret = lxc_netdev_move_by_name(ifname, init_pid, dst_ifname);
4715 if (ret)
4716 goto err;
4717
4718 INFO("Moved network device \"%s\" to network namespace of %d", ifname, init_pid);
4719 return true;
4720
4721 err:
4722 return false;
4723 }
4724
4725 WRAP_API_2(bool, lxcapi_attach_interface, const char *, const char *)
4726
4727 static bool do_lxcapi_detach_interface(struct lxc_container *c,
4728 const char *ifname,
4729 const char *dst_ifname)
4730 {
4731 int ret;
4732 pid_t pid, pid_outside;
4733
4734 /*
4735 * TODO - if this is a physical device, then we need am_host_unpriv.
4736 * But for other types guest privilege suffices.
4737 */
4738 if (am_guest_unpriv()) {
4739 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
4740 return false;
4741 }
4742
4743 if (!ifname) {
4744 ERROR("No source interface name given");
4745 return false;
4746 }
4747
4748 pid_outside = lxc_raw_getpid();
4749 pid = fork();
4750 if (pid < 0) {
4751 ERROR("Failed to fork");
4752 return false;
4753 }
4754
4755 if (pid == 0) { /* child */
4756 pid_t init_pid;
4757
4758 init_pid = do_lxcapi_init_pid(c);
4759 if (!switch_to_ns(init_pid, "net")) {
4760 ERROR("Failed to enter network namespace");
4761 _exit(EXIT_FAILURE);
4762 }
4763
4764 ret = lxc_netdev_isup(ifname);
4765 if (ret < 0) {
4766 ERROR("Failed to determine whether network device \"%s\" is up", ifname);
4767 _exit(EXIT_FAILURE);
4768 }
4769
4770 /* netdev of ifname is up. */
4771 if (ret) {
4772 ret = lxc_netdev_down(ifname);
4773 if (ret) {
4774 ERROR("Failed to set network device \"%s\" down", ifname);
4775 _exit(EXIT_FAILURE);
4776 }
4777 }
4778
4779 ret = lxc_netdev_move_by_name(ifname, pid_outside, dst_ifname);
4780 /* -EINVAL means there is no netdev named as ifname. */
4781 if (ret < 0) {
4782 if (ret == -EINVAL)
4783 ERROR("Network device \"%s\" not found", ifname);
4784 else
4785 ERROR("Failed to remove network device \"%s\"", ifname);
4786
4787 _exit(EXIT_FAILURE);
4788 }
4789
4790 _exit(EXIT_SUCCESS);
4791 }
4792
4793 ret = wait_for_pid(pid);
4794 if (ret != 0)
4795 return false;
4796
4797 INFO("Moved network device \"%s\" to network namespace of %d", ifname, pid_outside);
4798 return true;
4799 }
4800
4801 WRAP_API_2(bool, lxcapi_detach_interface, const char *, const char *)
4802
4803 static int do_lxcapi_migrate(struct lxc_container *c, unsigned int cmd,
4804 struct migrate_opts *opts, unsigned int size)
4805 {
4806 int ret = -1;
4807 struct migrate_opts *valid_opts = opts;
4808 uint64_t features_to_check = 0;
4809
4810 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4811 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4812 * to do anything special.
4813 */
4814 if (size > sizeof(*opts)) {
4815 unsigned char *addr;
4816 unsigned char *end;
4817
4818 addr = (void *)opts + sizeof(*opts);
4819 end = (void *)opts + size;
4820
4821 for (; addr < end; addr++)
4822 if (*addr)
4823 return -E2BIG;
4824 }
4825
4826 /* If the caller has a smaller struct, let's zero out the end for them
4827 * so we don't accidentally use bits of it that they didn't know about
4828 * to initialize.
4829 */
4830 if (size < sizeof(*opts)) {
4831 valid_opts = malloc(sizeof(*opts));
4832 if (!valid_opts)
4833 return -ENOMEM;
4834
4835 memset(valid_opts, 0, sizeof(*opts));
4836 memcpy(valid_opts, opts, size);
4837 }
4838
4839 switch (cmd) {
4840 case MIGRATE_PRE_DUMP:
4841 if (!do_lxcapi_is_running(c)) {
4842 ERROR("container is not running");
4843 goto on_error;
4844 }
4845
4846 ret = !__criu_pre_dump(c, valid_opts);
4847 break;
4848 case MIGRATE_DUMP:
4849 if (!do_lxcapi_is_running(c)) {
4850 ERROR("container is not running");
4851 goto on_error;
4852 }
4853
4854 ret = !__criu_dump(c, valid_opts);
4855 break;
4856 case MIGRATE_RESTORE:
4857 if (do_lxcapi_is_running(c)) {
4858 ERROR("container is already running");
4859 goto on_error;
4860 }
4861
4862 ret = !__criu_restore(c, valid_opts);
4863 break;
4864 case MIGRATE_FEATURE_CHECK:
4865 features_to_check = valid_opts->features_to_check;
4866 ret = !__criu_check_feature(&features_to_check);
4867 if (ret) {
4868 /* Something went wrong. Let's let the caller
4869 * know which feature checks failed. */
4870 valid_opts->features_to_check = features_to_check;
4871 }
4872 break;
4873 default:
4874 ERROR("invalid migrate command %u", cmd);
4875 ret = -EINVAL;
4876 }
4877
4878 on_error:
4879 if (size < sizeof(*opts))
4880 free(valid_opts);
4881
4882 return ret;
4883 }
4884
4885 WRAP_API_3(int, lxcapi_migrate, unsigned int, struct migrate_opts *, unsigned int)
4886
4887 static bool do_lxcapi_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose)
4888 {
4889 struct migrate_opts opts;
4890
4891 memset(&opts, 0, sizeof(opts));
4892
4893 opts.directory = directory;
4894 opts.stop = stop;
4895 opts.verbose = verbose;
4896
4897 return !do_lxcapi_migrate(c, MIGRATE_DUMP, &opts, sizeof(opts));
4898 }
4899
4900 WRAP_API_3(bool, lxcapi_checkpoint, char *, bool, bool)
4901
4902 static bool do_lxcapi_restore(struct lxc_container *c, char *directory, bool verbose)
4903 {
4904 struct migrate_opts opts;
4905
4906 memset(&opts, 0, sizeof(opts));
4907
4908 opts.directory = directory;
4909 opts.verbose = verbose;
4910
4911 return !do_lxcapi_migrate(c, MIGRATE_RESTORE, &opts, sizeof(opts));
4912 }
4913
4914 WRAP_API_2(bool, lxcapi_restore, char *, bool)
4915
4916 /* @st_mode is the st_mode field of the stat(source) return struct */
4917 static int create_mount_target(const char *dest, mode_t st_mode)
4918 {
4919 char *dirdup, *destdirname;
4920 int ret;
4921
4922 dirdup = strdup(dest);
4923 if (!dirdup) {
4924 SYSERROR("Failed to duplicate target name \"%s\"", dest);
4925 return -1;
4926 }
4927 destdirname = dirname(dirdup);
4928
4929 ret = mkdir_p(destdirname, 0755);
4930 if (ret < 0) {
4931 SYSERROR("Failed to create \"%s\"", destdirname);
4932 free(dirdup);
4933 return ret;
4934 }
4935 free(dirdup);
4936
4937 (void)remove(dest);
4938
4939 if (S_ISDIR(st_mode))
4940 ret = mkdir(dest, 0000);
4941 else
4942 ret = mknod(dest, S_IFREG | 0000, 0);
4943 if (ret < 0) {
4944 SYSERROR("Failed to create mount target \"%s\"", dest);
4945 return -1;
4946 }
4947
4948 return 0;
4949 }
4950
4951 static int do_lxcapi_mount(struct lxc_container *c, const char *source,
4952 const char *target, const char *filesystemtype,
4953 unsigned long mountflags, const void *data,
4954 struct lxc_mount *mnt)
4955 {
4956 char *suff, *sret;
4957 char template[MAXPATHLEN], path[MAXPATHLEN];
4958 pid_t pid, init_pid;
4959 struct stat sb;
4960 int ret = -1, fd = -EBADF;
4961
4962 if (!c || !c->lxc_conf) {
4963 ERROR("Container or configuration is NULL");
4964 return -EINVAL;
4965 }
4966
4967 if (!c->lxc_conf->shmount.path_host) {
4968 ERROR("Host path to shared mountpoint must be specified in the config\n");
4969 return -EINVAL;
4970 }
4971
4972 ret = snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c->lxc_conf->shmount.path_host);
4973 if (ret < 0 || (size_t)ret >= sizeof(template)) {
4974 SYSERROR("Error writing shmounts tempdir name");
4975 goto out;
4976 }
4977
4978 /* Create a temporary file / dir under the shared mountpoint */
4979 if (!source || strcmp(source, "") == 0) {
4980 /* If source is not specified, maybe we want to mount a filesystem? */
4981 sb.st_mode = S_IFDIR;
4982 } else {
4983 ret = stat(source, &sb);
4984 if (ret < 0) {
4985 SYSERROR("Error getting stat info about the source \"%s\"", source);
4986 goto out;
4987 }
4988 }
4989
4990 if (S_ISDIR(sb.st_mode)) {
4991 sret = mkdtemp(template);
4992 if (!sret) {
4993 SYSERROR("Could not create shmounts temporary dir");
4994 goto out;
4995 }
4996 } else {
4997 fd = lxc_make_tmpfile(template, false);
4998 if (fd < 0) {
4999 SYSERROR("Could not create shmounts temporary file");
5000 goto out;
5001 }
5002 }
5003
5004 /* Do the fork */
5005 pid = fork();
5006 if (pid < 0) {
5007 SYSERROR("Could not fork");
5008 goto out;
5009 }
5010
5011 if (pid == 0) {
5012 /* Do the mount */
5013 ret = mount(source, template, filesystemtype, mountflags, data);
5014 if (ret < 0) {
5015 SYSERROR("Failed to mount onto \"%s\"", template);
5016 _exit(EXIT_FAILURE);
5017 }
5018 TRACE("Mounted \"%s\" onto \"%s\"", source, template);
5019
5020 init_pid = do_lxcapi_init_pid(c);
5021 if (init_pid < 0) {
5022 ERROR("Failed to obtain container's init pid");
5023 _exit(EXIT_FAILURE);
5024 }
5025
5026 /* Enter the container namespaces */
5027 if (!lxc_list_empty(&c->lxc_conf->id_map)) {
5028 if (!switch_to_ns(init_pid, "user")){
5029 ERROR("Failed to enter user namespace");
5030 _exit(EXIT_FAILURE);
5031 }
5032 }
5033
5034 if (!switch_to_ns(init_pid, "mnt")) {
5035 ERROR("Failed to enter mount namespace");
5036 _exit(EXIT_FAILURE);
5037 }
5038
5039 ret = create_mount_target(target, sb.st_mode);
5040 if (ret < 0)
5041 _exit(EXIT_FAILURE);
5042 TRACE("Created mount target \"%s\"", target);
5043
5044 suff = strrchr(template, '/');
5045 if (!suff)
5046 _exit(EXIT_FAILURE);
5047
5048 ret = snprintf(path, sizeof(path), "%s%s", c->lxc_conf->shmount.path_cont, suff);
5049 if (ret < 0 || (size_t)ret >= sizeof(path)) {
5050 SYSERROR("Error writing container mountpoint name");
5051 _exit(EXIT_FAILURE);
5052 }
5053
5054 ret = mount(path, target, NULL, MS_MOVE | MS_REC, NULL);
5055 if (ret < 0) {
5056 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path, target);
5057 _exit(EXIT_FAILURE);
5058 }
5059 TRACE("Moved mount from \"%s\" to \"%s\"", path, target);
5060
5061 _exit(EXIT_SUCCESS);
5062 }
5063
5064 ret = wait_for_pid(pid);
5065 if (ret < 0) {
5066 SYSERROR("Wait for the child with pid %ld failed", (long) pid);
5067 goto out;
5068 }
5069
5070 ret = 0;
5071
5072 (void)umount2(template, MNT_DETACH);
5073 (void)unlink(template);
5074
5075 out:
5076 if (fd >= 0)
5077 close(fd);
5078
5079 return ret;
5080 }
5081
5082 WRAP_API_6(int, lxcapi_mount, const char *, const char *, const char *,
5083 unsigned long, const void *, struct lxc_mount *)
5084
5085 static int do_lxcapi_umount(struct lxc_container *c, const char *target,
5086 unsigned long flags, struct lxc_mount *mnt)
5087 {
5088 pid_t pid, init_pid;
5089 int ret = -1;
5090
5091 if (!c || !c->lxc_conf) {
5092 ERROR("Container or configuration is NULL");
5093 return -EINVAL;
5094 }
5095
5096 /* Do the fork */
5097 pid = fork();
5098 if (pid < 0) {
5099 SYSERROR("Could not fork");
5100 return -1;
5101 }
5102
5103 if (pid == 0) {
5104 init_pid = do_lxcapi_init_pid(c);
5105 if (init_pid < 0) {
5106 ERROR("Failed to obtain container's init pid");
5107 _exit(EXIT_FAILURE);
5108 }
5109
5110 /* Enter the container namespaces */
5111 if (!lxc_list_empty(&c->lxc_conf->id_map)) {
5112 if (!switch_to_ns(init_pid, "user")) {
5113 ERROR("Failed to enter user namespace");
5114 _exit(EXIT_FAILURE);
5115 }
5116 }
5117
5118 if (!switch_to_ns(init_pid, "mnt")) {
5119 ERROR("Failed to enter mount namespace");
5120 _exit(EXIT_FAILURE);
5121 }
5122
5123 /* Do the unmount */
5124 ret = umount2(target, flags);
5125 if (ret < 0) {
5126 SYSERROR("Failed to umount \"%s\"", target);
5127 _exit(EXIT_FAILURE);
5128 }
5129
5130 _exit(EXIT_SUCCESS);
5131 }
5132
5133 ret = wait_for_pid(pid);
5134 if (ret < 0) {
5135 SYSERROR("Wait for the child with pid %ld failed", (long)pid);
5136 return -ret;
5137 }
5138
5139 return 0;
5140 }
5141
5142 WRAP_API_3(int, lxcapi_umount, const char *, unsigned long, struct lxc_mount*)
5143
5144 static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
5145 {
5146 va_list ap;
5147 const char **argv;
5148 int ret;
5149
5150 if (!c)
5151 return -1;
5152
5153 current_config = c->lxc_conf;
5154
5155 va_start(ap, arg);
5156 argv = lxc_va_arg_list_to_argv_const(ap, 1);
5157 va_end(ap);
5158
5159 if (!argv) {
5160 ERROR("Memory allocation error.");
5161 ret = -1;
5162 goto out;
5163 }
5164 argv[0] = arg;
5165
5166 ret = do_lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
5167 free((void*)argv);
5168
5169 out:
5170 current_config = NULL;
5171 return ret;
5172 }
5173
5174 struct lxc_container *lxc_container_new(const char *name, const char *configpath)
5175 {
5176 struct lxc_container *c;
5177 size_t len;
5178
5179 if (!name)
5180 return NULL;
5181
5182 c = malloc(sizeof(*c));
5183 if (!c) {
5184 fprintf(stderr, "Failed to allocate memory for %s\n", name);
5185 return NULL;
5186 }
5187 memset(c, 0, sizeof(*c));
5188
5189 if (configpath)
5190 c->config_path = strdup(configpath);
5191 else
5192 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
5193 if (!c->config_path) {
5194 fprintf(stderr, "Failed to allocate memory for %s\n", name);
5195 goto err;
5196 }
5197
5198 remove_trailing_slashes(c->config_path);
5199
5200 len = strlen(name);
5201 c->name = malloc(len + 1);
5202 if (!c->name) {
5203 fprintf(stderr, "Failed to allocate memory for %s\n", name);
5204 goto err;
5205 }
5206 (void)strlcpy(c->name, name, len + 1);
5207
5208 c->numthreads = 1;
5209 c->slock = lxc_newlock(c->config_path, name);
5210 if (!c->slock) {
5211 fprintf(stderr, "Failed to create lock for %s\n", name);
5212 goto err;
5213 }
5214
5215 c->privlock = lxc_newlock(NULL, NULL);
5216 if (!c->privlock) {
5217 fprintf(stderr, "Failed to create private lock for %s\n", name);
5218 goto err;
5219 }
5220
5221 if (!set_config_filename(c)) {
5222 fprintf(stderr, "Failed to create config file name for %s\n", name);
5223 goto err;
5224 }
5225
5226 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL)) {
5227 fprintf(stderr, "Failed to load config for %s\n", name);
5228 goto err;
5229 }
5230
5231 if (ongoing_create(c) == 2) {
5232 ERROR("Failed to complete container creation for %s", c->name);
5233 container_destroy(c, NULL);
5234 lxcapi_clear_config(c);
5235 }
5236
5237 c->daemonize = true;
5238 c->pidfile = NULL;
5239
5240 /* Assign the member functions. */
5241 c->is_defined = lxcapi_is_defined;
5242 c->state = lxcapi_state;
5243 c->is_running = lxcapi_is_running;
5244 c->freeze = lxcapi_freeze;
5245 c->unfreeze = lxcapi_unfreeze;
5246 c->console = lxcapi_console;
5247 c->console_getfd = lxcapi_console_getfd;
5248 c->init_pid = lxcapi_init_pid;
5249 c->load_config = lxcapi_load_config;
5250 c->want_daemonize = lxcapi_want_daemonize;
5251 c->want_close_all_fds = lxcapi_want_close_all_fds;
5252 c->start = lxcapi_start;
5253 c->startl = lxcapi_startl;
5254 c->stop = lxcapi_stop;
5255 c->config_file_name = lxcapi_config_file_name;
5256 c->wait = lxcapi_wait;
5257 c->set_config_item = lxcapi_set_config_item;
5258 c->destroy = lxcapi_destroy;
5259 c->destroy_with_snapshots = lxcapi_destroy_with_snapshots;
5260 c->rename = lxcapi_rename;
5261 c->save_config = lxcapi_save_config;
5262 c->get_keys = lxcapi_get_keys;
5263 c->create = lxcapi_create;
5264 c->createl = lxcapi_createl;
5265 c->shutdown = lxcapi_shutdown;
5266 c->reboot = lxcapi_reboot;
5267 c->reboot2 = lxcapi_reboot2;
5268 c->clear_config = lxcapi_clear_config;
5269 c->clear_config_item = lxcapi_clear_config_item;
5270 c->get_config_item = lxcapi_get_config_item;
5271 c->get_running_config_item = lxcapi_get_running_config_item;
5272 c->get_cgroup_item = lxcapi_get_cgroup_item;
5273 c->set_cgroup_item = lxcapi_set_cgroup_item;
5274 c->get_config_path = lxcapi_get_config_path;
5275 c->set_config_path = lxcapi_set_config_path;
5276 c->clone = lxcapi_clone;
5277 c->get_interfaces = lxcapi_get_interfaces;
5278 c->get_ips = lxcapi_get_ips;
5279 c->attach = lxcapi_attach;
5280 c->attach_run_wait = lxcapi_attach_run_wait;
5281 c->attach_run_waitl = lxcapi_attach_run_waitl;
5282 c->snapshot = lxcapi_snapshot;
5283 c->snapshot_list = lxcapi_snapshot_list;
5284 c->snapshot_restore = lxcapi_snapshot_restore;
5285 c->snapshot_destroy = lxcapi_snapshot_destroy;
5286 c->snapshot_destroy_all = lxcapi_snapshot_destroy_all;
5287 c->may_control = lxcapi_may_control;
5288 c->add_device_node = lxcapi_add_device_node;
5289 c->remove_device_node = lxcapi_remove_device_node;
5290 c->attach_interface = lxcapi_attach_interface;
5291 c->detach_interface = lxcapi_detach_interface;
5292 c->checkpoint = lxcapi_checkpoint;
5293 c->restore = lxcapi_restore;
5294 c->migrate = lxcapi_migrate;
5295 c->console_log = lxcapi_console_log;
5296 c->mount = lxcapi_mount;
5297 c->umount = lxcapi_umount;
5298
5299 return c;
5300
5301 err:
5302 lxc_container_free(c);
5303 return NULL;
5304 }
5305
5306 int lxc_get_wait_states(const char **states)
5307 {
5308 int i;
5309
5310 if (states)
5311 for (i=0; i<MAX_STATE; i++)
5312 states[i] = lxc_state2str(i);
5313
5314 return MAX_STATE;
5315 }
5316
5317 /*
5318 * These next two could probably be done smarter with reusing a common function
5319 * with different iterators and tests...
5320 */
5321 int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
5322 {
5323 DIR *dir;
5324 int i, cfound = 0, nfound = 0;
5325 struct dirent *direntp;
5326 struct lxc_container *c;
5327
5328 if (!lxcpath)
5329 lxcpath = lxc_global_config_value("lxc.lxcpath");
5330
5331 dir = opendir(lxcpath);
5332 if (!dir) {
5333 SYSERROR("opendir on lxcpath");
5334 return -1;
5335 }
5336
5337 if (cret)
5338 *cret = NULL;
5339
5340 if (names)
5341 *names = NULL;
5342
5343 while ((direntp = readdir(dir))) {
5344 /* Ignore '.', '..' and any hidden directory. */
5345 if (!strncmp(direntp->d_name, ".", 1))
5346 continue;
5347
5348 if (!config_file_exists(lxcpath, direntp->d_name))
5349 continue;
5350
5351 if (names)
5352 if (!add_to_array(names, direntp->d_name, cfound))
5353 goto free_bad;
5354
5355 cfound++;
5356
5357 if (!cret) {
5358 nfound++;
5359 continue;
5360 }
5361
5362 c = lxc_container_new(direntp->d_name, lxcpath);
5363 if (!c) {
5364 INFO("Container %s:%s has a config but could not be loaded",
5365 lxcpath, direntp->d_name);
5366
5367 if (names)
5368 if(!remove_from_array(names, direntp->d_name, cfound--))
5369 goto free_bad;
5370
5371 continue;
5372 }
5373
5374 if (!do_lxcapi_is_defined(c)) {
5375 INFO("Container %s:%s has a config but is not defined",
5376 lxcpath, direntp->d_name);
5377
5378 if (names)
5379 if(!remove_from_array(names, direntp->d_name, cfound--))
5380 goto free_bad;
5381
5382 lxc_container_put(c);
5383 continue;
5384 }
5385
5386 if (!add_to_clist(cret, c, nfound, true)) {
5387 lxc_container_put(c);
5388 goto free_bad;
5389 }
5390
5391 nfound++;
5392 }
5393
5394 closedir(dir);
5395 return nfound;
5396
5397 free_bad:
5398 if (names && *names) {
5399 for (i=0; i<cfound; i++)
5400 free((*names)[i]);
5401 free(*names);
5402 }
5403
5404 if (cret && *cret) {
5405 for (i=0; i<nfound; i++)
5406 lxc_container_put((*cret)[i]);
5407 free(*cret);
5408 }
5409
5410 closedir(dir);
5411 return -1;
5412 }
5413
5414 int list_active_containers(const char *lxcpath, char ***nret,
5415 struct lxc_container ***cret)
5416 {
5417 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
5418 int lxcpath_len;
5419 char *line = NULL;
5420 char **ct_name = NULL;
5421 size_t len = 0;
5422 struct lxc_container *c = NULL;
5423 bool is_hashed;
5424
5425 if (!lxcpath)
5426 lxcpath = lxc_global_config_value("lxc.lxcpath");
5427 lxcpath_len = strlen(lxcpath);
5428
5429 if (cret)
5430 *cret = NULL;
5431
5432 if (nret)
5433 *nret = NULL;
5434
5435 FILE *f = fopen("/proc/net/unix", "r");
5436 if (!f)
5437 return -1;
5438
5439 while (getline(&line, &len, f) != -1) {
5440 char *p = strrchr(line, ' '), *p2;
5441 if (!p)
5442 continue;
5443 p++;
5444
5445 if (*p != 0x40)
5446 continue;
5447 p++;
5448
5449 is_hashed = false;
5450
5451 if (strncmp(p, lxcpath, lxcpath_len) == 0) {
5452 p += lxcpath_len;
5453 } else if (strncmp(p, "lxc/", 4) == 0) {
5454 p += 4;
5455 is_hashed = true;
5456 } else {
5457 continue;
5458 }
5459
5460 while (*p == '/')
5461 p++;
5462
5463 /* Now p is the start of lxc_name. */
5464 p2 = strchr(p, '/');
5465 if (!p2 || strncmp(p2, "/command", 8) != 0)
5466 continue;
5467 *p2 = '\0';
5468
5469 if (is_hashed) {
5470 char *recvpath = lxc_cmd_get_lxcpath(p);
5471 if (!recvpath)
5472 continue;
5473
5474 if (strncmp(lxcpath, recvpath, lxcpath_len) != 0) {
5475 free(recvpath);
5476 continue;
5477 }
5478 free(recvpath);
5479
5480 p = lxc_cmd_get_name(p);
5481 if (!p)
5482 continue;
5483 }
5484
5485 if (array_contains(&ct_name, p, ct_name_cnt)) {
5486 if (is_hashed)
5487 free(p);
5488 continue;
5489 }
5490
5491 if (!add_to_array(&ct_name, p, ct_name_cnt)) {
5492 if (is_hashed)
5493 free(p);
5494 goto free_cret_list;
5495 }
5496
5497 ct_name_cnt++;
5498
5499 if (!cret) {
5500 if (is_hashed)
5501 free(p);
5502 continue;
5503 }
5504
5505 c = lxc_container_new(p, lxcpath);
5506 if (!c) {
5507 INFO("Container %s:%s is running but could not be loaded",
5508 lxcpath, p);
5509
5510 remove_from_array(&ct_name, p, ct_name_cnt--);
5511 if (is_hashed)
5512 free(p);
5513
5514 continue;
5515 }
5516
5517 if (is_hashed)
5518 free(p);
5519
5520 /*
5521 * If this is an anonymous container, then is_defined *can*
5522 * return false. So we don't do that check. Count on the
5523 * fact that the command socket exists.
5524 */
5525
5526 if (!add_to_clist(cret, c, cret_cnt, true)) {
5527 lxc_container_put(c);
5528 goto free_cret_list;
5529 }
5530
5531 cret_cnt++;
5532 }
5533
5534 if (nret && cret && cret_cnt != ct_name_cnt) {
5535 if (c)
5536 lxc_container_put(c);
5537 goto free_cret_list;
5538 }
5539
5540 ret = ct_name_cnt;
5541 if (nret)
5542 *nret = ct_name;
5543 else
5544 goto free_ct_name;
5545
5546 goto out;
5547
5548 free_cret_list:
5549 if (cret && *cret) {
5550 for (i = 0; i < cret_cnt; i++)
5551 lxc_container_put((*cret)[i]);
5552 free(*cret);
5553 }
5554
5555 free_ct_name:
5556 if (ct_name) {
5557 for (i = 0; i < ct_name_cnt; i++)
5558 free(ct_name[i]);
5559 free(ct_name);
5560 }
5561
5562 out:
5563 free(line);
5564 fclose(f);
5565 return ret;
5566 }
5567
5568 int list_all_containers(const char *lxcpath, char ***nret,
5569 struct lxc_container ***cret)
5570 {
5571 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
5572 char **active_name;
5573 char **ct_name;
5574 struct lxc_container **ct_list = NULL;
5575
5576 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
5577 if (ct_cnt < 0)
5578 return ct_cnt;
5579
5580 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
5581 if (active_cnt < 0) {
5582 ret = active_cnt;
5583 goto free_ct_name;
5584 }
5585
5586 for (i = 0; i < active_cnt; i++) {
5587 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
5588 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
5589 ret = -1;
5590 goto free_active_name;
5591 }
5592
5593 ct_cnt++;
5594 }
5595
5596 free(active_name[i]);
5597 active_name[i] = NULL;
5598 }
5599
5600 free(active_name);
5601 active_name = NULL;
5602 active_cnt = 0;
5603
5604 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
5605 struct lxc_container *c;
5606
5607 c = lxc_container_new(ct_name[i], lxcpath);
5608 if (!c) {
5609 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
5610 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
5611 continue;
5612 }
5613
5614 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
5615 lxc_container_put(c);
5616 ret = -1;
5617 goto free_ct_list;
5618 }
5619
5620 ct_list_cnt++;
5621 }
5622
5623 if (cret)
5624 *cret = ct_list;
5625
5626 if (nret) {
5627 *nret = ct_name;
5628 } else {
5629 ret = ct_cnt;
5630 goto free_ct_name;
5631 }
5632
5633 return ct_cnt;
5634
5635 free_ct_list:
5636 for (i = 0; i < ct_list_cnt; i++) {
5637 lxc_container_put(ct_list[i]);
5638 }
5639 free(ct_list);
5640
5641 free_active_name:
5642 for (i = 0; i < active_cnt; i++) {
5643 free(active_name[i]);
5644 }
5645 free(active_name);
5646
5647 free_ct_name:
5648 for (i = 0; i < ct_cnt; i++) {
5649 free(ct_name[i]);
5650 }
5651 free(ct_name);
5652 return ret;
5653 }
5654
5655 bool lxc_config_item_is_supported(const char *key)
5656 {
5657 return !!lxc_get_config(key);
5658 }