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