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