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