1 /* SPDX-License-Identifier: LGPL-2.1+ */
20 #include <sys/mount.h>
22 #include <sys/syscall.h>
23 #include <sys/sysmacros.h>
24 #include <sys/types.h>
30 #include "netns_ifaddrs.h"
32 #include "api_extensions.h"
37 #include "commands_utils.h"
41 #include "confile_utils.h"
44 #include "initutils.h"
48 #include "memory_utils.h"
50 #include "namespace.h"
53 #include "process_utils.h"
57 #include "storage/btrfs.h"
58 #include "storage/overlay.h"
59 #include "storage_utils.h"
61 #include "syscall_wrappers.h"
67 #include <openssl/evp.h>
72 #include <sys/mkdev.h>
76 #include <../include/lxcmntent.h>
82 #include "include/strlcpy.h"
85 lxc_log_define(lxccontainer
, lxc
);
87 static bool do_lxcapi_destroy(struct lxc_container
*c
);
88 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
89 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
90 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
91 static bool container_destroy(struct lxc_container
*c
,
92 struct lxc_storage
*storage
);
93 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
94 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
95 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
97 static bool config_file_exists(const char *lxcpath
, const char *cname
)
99 __do_free
char *fname
= NULL
;
103 /* $lxcpath + '/' + $cname + '/config' + \0 */
104 len
= strlen(lxcpath
) + 1 + strlen(cname
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
105 fname
= must_realloc(NULL
, len
);
106 ret
= strnprintf(fname
, len
, "%s/%s/%s", lxcpath
, cname
, LXC_CONFIG_FNAME
);
110 return file_exists(fname
);
114 * A few functions to help detect when a container creation failed. If a
115 * container creation was killed partway through, then trying to actually start
116 * that container could harm the host. We detect this by creating a 'partial'
117 * file under the container directory, and keeping an advisory lock. When
118 * container creation completes, we remove that file. When we load or try to
119 * start a container, if we find that file, without a flock, we remove the
123 LXC_CREATE_FAILED
= -1,
124 LXC_CREATE_SUCCESS
= 0,
125 LXC_CREATE_ONGOING
= 1,
126 LXC_CREATE_INCOMPLETE
= 2,
129 static int ongoing_create(struct lxc_container
*c
)
131 __do_close
int fd
= -EBADF
;
132 __do_free
char *path
= NULL
;
133 struct flock lk
= {0};
137 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
138 path
= must_realloc(NULL
, len
);
139 ret
= strnprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
141 return LXC_CREATE_FAILED
;
143 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
146 return LXC_CREATE_FAILED
;
148 return LXC_CREATE_SUCCESS
;
152 lk
.l_whence
= SEEK_SET
;
154 * F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
159 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
160 if (ret
< 0 && errno
== EINVAL
) {
161 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
162 if (ret
< 0 && errno
== EWOULDBLOCK
)
166 /* F_OFD_GETLK will not send us back a pid so don't check it. */
168 /* Create is still ongoing. */
169 return LXC_CREATE_ONGOING
;
171 /* Create completed but partial is still there. */
172 return LXC_CREATE_INCOMPLETE
;
175 static int create_partial(struct lxc_container
*c
)
177 __do_free
char *path
= NULL
;
180 struct flock lk
= {0};
182 /* $lxcpath + '/' + $name + '/partial' + \0 */
183 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
184 path
= must_realloc(NULL
, len
);
185 ret
= strnprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
189 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
194 lk
.l_whence
= SEEK_SET
;
196 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
198 if (errno
== EINVAL
) {
199 ret
= flock(fd
, LOCK_EX
);
204 SYSERROR("Failed to lock partial file %s", path
);
212 static void remove_partial(struct lxc_container
*c
, int fd
)
214 __do_free
char *path
= NULL
;
220 /* $lxcpath + '/' + $name + '/partial' + \0 */
221 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
222 path
= must_realloc(NULL
, len
);
223 ret
= strnprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
229 SYSERROR("Failed to remove partial file %s", path
);
233 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
234 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
235 * container configuration file.
236 * The container_disk_lock also takes the container_mem_lock.
237 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
238 * NOTHING mutexes two independent programs with their own struct
239 * lxc_container for the same c->name, between API calls. For instance,
240 * c->config_read(); c->start(); Between those calls, data on disk
241 * could change (which shouldn't bother the caller unless for instance
242 * the rootfs get moved). c->config_read(); update; c->config_write();
243 * Two such updaters could race. The callers should therefore check their
244 * results. Trying to prevent that would necessarily expose us to deadlocks
245 * due to hung callers. So I prefer to keep the locks only within our own
246 * functions, not across functions.
248 * If you're going to clone while holding a lxccontainer, increment
249 * c->numthreads (under privlock) before forking. When deleting,
250 * decrement numthreads under privlock, then if it hits 0 you can delete.
251 * Do not ever use a lxccontainer whose numthreads you did not bump.
253 static void lxc_container_free(struct lxc_container
*c
)
259 c
->configfile
= NULL
;
261 free(c
->error_string
);
262 c
->error_string
= NULL
;
265 lxc_putlock(c
->slock
);
270 lxc_putlock(c
->privlock
);
278 lxc_conf_free(c
->lxc_conf
);
282 free(c
->config_path
);
283 c
->config_path
= NULL
;
288 /* Consider the following case:
290 * |====================================================================|
291 * | freer | racing get()er |
292 * |====================================================================|
293 * | lxc_container_put() | lxc_container_get() |
294 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
295 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
296 * | \ lxcunlock() | \ |
297 * | \ lxc_container_free() | \ lxclock() returns |
298 * | | \ c->numthreads < 1 -> return 0 |
299 * | \ \ (free stuff) | |
300 * | \ \ sem_destroy(privlock) | |
301 * |_______________________________|____________________________________|
303 * When the get()er checks numthreads the first time, one of the following
305 * 1. freer has set numthreads = 0. get() returns 0
306 * 2. freer is between lxclock and setting numthreads to 0. get()er will
307 * sem_wait on privlock, get lxclock after freer() drops it, then see
308 * numthreads is 0 and exit without touching lxclock again..
309 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
310 * will see --numthreads = 1 and not call lxc_container_free().
313 int lxc_container_get(struct lxc_container
*c
)
318 /* If someone else has already started freeing the container, don't try
319 * to take the lock, which may be invalid.
321 if (c
->numthreads
< 1)
324 if (container_mem_lock(c
))
327 /* Bail without trying to unlock, bc the privlock is now probably in
330 if (c
->numthreads
< 1)
334 container_mem_unlock(c
);
339 int lxc_container_put(struct lxc_container
*c
)
344 if (container_mem_lock(c
))
349 if (c
->numthreads
< 1) {
350 container_mem_unlock(c
);
351 lxc_container_free(c
);
355 container_mem_unlock(c
);
359 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
368 if (container_mem_lock(c
))
374 statret
= stat(c
->configfile
, &statbuf
);
381 container_mem_unlock(c
);
385 #define WRAP_API(rettype, fnname) \
386 static rettype fnname(struct lxc_container *c) \
389 bool reset_config = false; \
391 if (!current_config && c && c->lxc_conf) { \
392 current_config = c->lxc_conf; \
393 reset_config = true; \
396 ret = do_##fnname(c); \
398 current_config = NULL; \
403 #define WRAP_API_1(rettype, fnname, t1) \
404 static rettype fnname(struct lxc_container *c, t1 a1) \
407 bool reset_config = false; \
409 if (!current_config && c && c->lxc_conf) { \
410 current_config = c->lxc_conf; \
411 reset_config = true; \
414 ret = do_##fnname(c, a1); \
416 current_config = NULL; \
421 #define WRAP_API_2(rettype, fnname, t1, t2) \
422 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
425 bool reset_config = false; \
427 if (!current_config && c && c->lxc_conf) { \
428 current_config = c->lxc_conf; \
429 reset_config = true; \
432 ret = do_##fnname(c, a1, a2); \
434 current_config = NULL; \
439 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
440 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
443 bool reset_config = false; \
445 if (!current_config && c && c->lxc_conf) { \
446 current_config = c->lxc_conf; \
447 reset_config = true; \
450 ret = do_##fnname(c, a1, a2, a3); \
452 current_config = NULL; \
457 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
458 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
459 t4 a4, t5 a5, t6 a6) \
462 bool reset_config = false; \
464 if (!current_config && c && c->lxc_conf) { \
465 current_config = c->lxc_conf; \
466 reset_config = true; \
469 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
471 current_config = NULL; \
476 WRAP_API(bool, lxcapi_is_defined
)
478 static const char *do_lxcapi_state(struct lxc_container
*c
)
485 s
= lxc_getstate(c
->name
, c
->config_path
);
486 return lxc_state2str(s
);
489 WRAP_API(const char *, lxcapi_state
)
491 static bool is_stopped(struct lxc_container
*c
)
495 s
= lxc_getstate(c
->name
, c
->config_path
);
496 return (s
== STOPPED
);
499 static bool do_lxcapi_is_running(struct lxc_container
*c
)
504 return !is_stopped(c
);
507 WRAP_API(bool, lxcapi_is_running
)
509 static bool do_lxcapi_freeze(struct lxc_container
*c
)
514 if (!c
|| !c
->lxc_conf
)
517 s
= lxc_getstate(c
->name
, c
->config_path
);
519 ret
= cgroup_freeze(c
->name
, c
->config_path
, -1);
520 if (ret
== -ENOCGROUP2
)
521 ret
= lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
);
527 WRAP_API(bool, lxcapi_freeze
)
529 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
534 if (!c
|| !c
->lxc_conf
)
537 s
= lxc_getstate(c
->name
, c
->config_path
);
539 ret
= cgroup_unfreeze(c
->name
, c
->config_path
, -1);
540 if (ret
== -ENOCGROUP2
)
541 ret
= lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
);
548 WRAP_API(bool, lxcapi_unfreeze
)
550 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *ptxfd
)
555 return lxc_terminal_getfd(c
, ttynum
, ptxfd
);
558 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
560 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
561 int stdoutfd
, int stderrfd
, int escape
)
568 current_config
= c
->lxc_conf
;
569 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
570 current_config
= NULL
;
575 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
582 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
585 NOTICE("The console log is empty");
586 else if (ret
== -EFAULT
)
587 NOTICE("The container does not keep a console log");
588 else if (ret
== -ENOENT
)
589 NOTICE("The container does not keep a console log file");
590 else if (ret
== -EIO
)
591 NOTICE("Failed to write console log to log file");
593 ERROR("Failed to retrieve console log");
599 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
601 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
606 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
609 WRAP_API(pid_t
, lxcapi_init_pid
)
611 static int do_lxcapi_init_pidfd(struct lxc_container
*c
)
614 return ret_errno(EBADF
);
616 return lxc_cmd_get_init_pidfd(c
->name
, c
->config_path
);
619 WRAP_API(int, lxcapi_init_pidfd
)
621 static int do_lxcapi_devpts_fd(struct lxc_container
*c
)
624 return ret_errno(EBADF
);
626 return lxc_cmd_get_devpts_fd(c
->name
, c
->config_path
);
629 WRAP_API(int, lxcapi_devpts_fd
)
631 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
634 c
->lxc_conf
= lxc_conf_init();
639 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
642 c
->lxc_conf
->name
= c
->name
;
646 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
650 bool need_disklock
= false, ret
= false;
655 fname
= c
->configfile
;
663 /* If we're reading something other than the container's config, we only
664 * need to lock the in-memory container. If loading the container's
665 * config file, take the disk lock.
667 if (strequal(fname
, c
->configfile
))
668 need_disklock
= true;
671 lret
= container_disk_lock(c
);
673 lret
= container_mem_lock(c
);
677 ret
= load_config_locked(c
, fname
);
680 container_disk_unlock(c
);
682 container_mem_unlock(c
);
687 WRAP_API_1(bool, lxcapi_load_config
, const char *)
689 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
691 if (!c
|| !c
->lxc_conf
)
694 if (container_mem_lock(c
))
697 c
->daemonize
= state
;
699 container_mem_unlock(c
);
704 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
706 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
708 if (!c
|| !c
->lxc_conf
)
711 if (container_mem_lock(c
))
714 c
->lxc_conf
->close_all_fds
= state
;
716 container_mem_unlock(c
);
721 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
723 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
731 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
735 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
737 static bool am_single_threaded(void)
739 __do_closedir
DIR *dir
= NULL
;
740 struct dirent
*direntp
;
743 dir
= opendir("/proc/self/task");
747 while ((direntp
= readdir(dir
))) {
748 if (strequal(direntp
->d_name
, "."))
751 if (strequal(direntp
->d_name
, ".."))
762 static void push_arg(char ***argp
, char *arg
, int *nargs
)
767 copy
= must_copy_string(arg
);
770 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
779 static char **split_init_cmd(const char *incmd
)
781 __do_free
char *copy
= NULL
;
789 copy
= must_copy_string(incmd
);
792 argv
= malloc(sizeof(char *));
796 lxc_iterate_parts (p
, copy
, " ")
797 push_arg(&argv
, p
, &nargs
);
807 static void free_init_cmd(char **argv
)
820 static int lxc_rcv_status(int state_socket
)
826 /* Receive container state. */
827 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
832 TRACE("Caught EINTR; retrying");
839 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
843 /* The first child is going to fork() again and then exits. So we reap
844 * the first child here.
846 ret
= wait_for_pid(pid
);
848 DEBUG("Failed waiting on first child %d", pid
);
850 DEBUG("First child %d exited", pid
);
852 /* Close write end of the socket pair. */
853 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
855 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
857 /* Close read end of the socket pair. */
858 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
861 SYSERROR("Failed to receive the container state");
865 /* If we receive anything else then running we know that the container
868 if (state
!= RUNNING
) {
869 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
870 lxc_state2str(state
));
874 TRACE("Container is in \"RUNNING\" state");
878 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
881 struct lxc_handler
*handler
;
882 struct lxc_conf
*conf
;
883 char *default_args
[] = {
887 char **init_cmd
= NULL
;
889 /* container does exist */
893 /* If anything fails before we set error_num, we want an error in there.
897 /* Container has not been setup. */
901 ret
= ongoing_create(c
);
903 case LXC_CREATE_FAILED
:
904 ERROR("Failed checking for incomplete container creation");
906 case LXC_CREATE_ONGOING
:
907 ERROR("Ongoing container creation detected");
909 case LXC_CREATE_INCOMPLETE
:
910 ERROR("Failed to create container");
911 do_lxcapi_destroy(c
);
915 if (container_mem_lock(c
))
920 /* initialize handler */
921 handler
= lxc_init_handler(NULL
, c
->name
, conf
, c
->config_path
, c
->daemonize
);
923 container_mem_unlock(c
);
928 if (useinit
&& conf
->execute_cmd
)
929 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
931 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
934 /* ... otherwise use default_args. */
937 ERROR("No valid init detected");
938 lxc_put_handler(handler
);
944 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
945 * here to protect the on disk container? We don't want to exclude
946 * things like lxc_info while the container is running.
951 pid_t pid_first
, pid_second
;
955 free_init_cmd(init_cmd
);
956 lxc_put_handler(handler
);
961 if (pid_first
!= 0) {
962 /* Set to NULL because we don't want father unlink
963 * the PID file, child will do the free and unlink.
967 /* Wait for container to tell us whether it started
970 started
= wait_on_daemonized_start(handler
, pid_first
);
972 free_init_cmd(init_cmd
);
973 lxc_put_handler(handler
);
979 /* We don't really care if this doesn't print all the
980 * characters. All that it means is that the proctitle will be
981 * ugly. Similarly, we also don't care if setproctitle() fails.
983 ret
= strnprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
985 ret
= setproctitle(title
);
987 INFO("Failed to set process title to %s", title
);
989 INFO("Set process title to %s", title
);
992 /* We fork() a second time to be reparented to init. Like
993 * POSIX's daemon() function we change to "/" and redirect
994 * std{in,out,err} to /dev/null.
997 if (pid_second
< 0) {
998 SYSERROR("Failed to fork first child process");
1003 if (pid_second
!= 0) {
1004 free_init_cmd(init_cmd
);
1005 lxc_put_handler(handler
);
1006 _exit(EXIT_SUCCESS
);
1011 /* change to / directory */
1014 SYSERROR("Failed to change to \"/\" directory");
1015 _exit(EXIT_FAILURE
);
1018 ret
= inherit_fds(handler
, true);
1020 _exit(EXIT_FAILURE
);
1022 /* redirect std{in,out,err} to /dev/null */
1023 ret
= null_stdfds();
1025 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1026 _exit(EXIT_FAILURE
);
1029 /* become session leader */
1032 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1033 } else if (!am_single_threaded()) {
1034 ERROR("Cannot start non-daemonized container when threaded");
1035 free_init_cmd(init_cmd
);
1036 lxc_put_handler(handler
);
1040 /* We need to write PID file after daemonize, so we always write the
1045 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1047 w
= strnprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1049 free_init_cmd(init_cmd
);
1050 lxc_put_handler(handler
);
1052 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1055 _exit(EXIT_FAILURE
);
1060 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1062 free_init_cmd(init_cmd
);
1063 lxc_put_handler(handler
);
1065 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1068 _exit(EXIT_FAILURE
);
1074 conf
->reboot
= REBOOT_NONE
;
1076 /* Unshare the mount namespace if requested */
1077 if (conf
->monitor_unshare
) {
1078 ret
= unshare(CLONE_NEWNS
);
1080 SYSERROR("Failed to unshare mount namespace");
1081 lxc_put_handler(handler
);
1086 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1088 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
1089 lxc_put_handler(handler
);
1096 if (conf
->reboot
== REBOOT_INIT
) {
1097 /* initialize handler */
1098 handler
= lxc_init_handler(handler
, c
->name
, conf
, c
->config_path
, c
->daemonize
);
1105 ret
= inherit_fds(handler
, c
->daemonize
);
1107 lxc_put_handler(handler
);
1113 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1114 c
->daemonize
, &c
->error_num
);
1116 ret
= lxc_start(argv
, handler
, c
->config_path
, c
->daemonize
,
1119 if (conf
->reboot
== REBOOT_REQ
) {
1120 INFO("Container requested reboot");
1121 conf
->reboot
= REBOOT_INIT
;
1131 free_init_cmd(init_cmd
);
1133 if (c
->daemonize
&& ret
!= 0)
1134 _exit(EXIT_FAILURE
);
1135 else if (c
->daemonize
)
1136 _exit(EXIT_SUCCESS
);
1144 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1149 current_config
= c
? c
->lxc_conf
: NULL
;
1150 ret
= do_lxcapi_start(c
, useinit
, argv
);
1151 current_config
= NULL
;
1156 /* Note, there MUST be an ending NULL. */
1157 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1160 char **inargs
= NULL
;
1163 /* container exists */
1167 current_config
= c
->lxc_conf
;
1169 va_start(ap
, useinit
);
1170 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1175 /* pass NULL if no arguments were supplied */
1176 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1182 for (arg
= inargs
; *arg
; arg
++)
1187 current_config
= NULL
;
1192 static bool do_lxcapi_stop(struct lxc_container
*c
)
1199 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1204 WRAP_API(bool, lxcapi_stop
)
1206 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1211 mode_t mask
= umask(0002);
1212 ret
= mkdir(path
, 0770);
1217 if (errno
!= EEXIST
)
1223 if (!list_empty(&conf
->id_map
)) {
1224 ret
= chown_mapped_root(path
, conf
);
1232 /* Create the standard expected container dir. */
1233 static bool create_container_dir(struct lxc_container
*c
)
1235 __do_free
char *s
= NULL
;
1239 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1244 ret
= strnprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1248 return do_create_container_dir(s
, c
->lxc_conf
) == 0;
1251 /* do_storage_create: thin wrapper around storage_create(). Like
1252 * storage_create(), it returns a mounted bdev on success, NULL on error.
1254 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1256 struct bdev_specs
*specs
)
1258 __do_free
char *dest
= NULL
;
1261 struct lxc_storage
*bdev
;
1263 /* rootfs.path or lxcpath/lxcname/rootfs */
1264 if (c
->lxc_conf
->rootfs
.path
&&
1265 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1266 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1267 len
= strlen(rpath
) + 1;
1268 dest
= must_realloc(NULL
, len
);
1269 ret
= strnprintf(dest
, len
, "%s", rpath
);
1271 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1272 len
= strlen(c
->name
) + 1 + strlen(lxcpath
) + 1 + strlen(LXC_ROOTFS_DNAME
) + 1;
1273 dest
= must_realloc(NULL
, len
);
1274 ret
= strnprintf(dest
, len
, "%s/%s/%s", lxcpath
, c
->name
, LXC_ROOTFS_DNAME
);
1279 bdev
= storage_create(dest
, type
, c
->name
, specs
, c
->lxc_conf
);
1281 ERROR("Failed to create \"%s\" storage", type
);
1285 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1286 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1291 /* If we are not root, chown the rootfs dir to root in the target user
1294 if (am_guest_unpriv() || !list_empty(&c
->lxc_conf
->id_map
)) {
1295 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1297 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1298 suggest_default_idmap();
1307 /* Strip path and return name of file for argv[0] passed to execvp */
1308 static char *lxctemplatefilename(char *tpath
)
1312 p
= tpath
+ strlen(tpath
) - 1;
1313 while ( (p
-1) >= tpath
&& *(p
-1) != '/')
1319 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1320 bool need_null_stdfds
, char *const argv
[])
1330 SYSERROR("Failed to fork task for container creation template");
1334 if (pid
== 0) { /* child */
1336 char *namearg
, *patharg
, *rootfsarg
;
1339 struct lxc_storage
*bdev
= NULL
;
1340 struct lxc_conf
*conf
= c
->lxc_conf
;
1343 if (need_null_stdfds
) {
1344 ret
= null_stdfds();
1346 _exit(EXIT_FAILURE
);
1349 ret
= lxc_storage_prepare(conf
);
1351 ERROR("Failed to initialize storage");
1352 _exit(EXIT_FAILURE
);
1354 bdev
= conf
->rootfs
.storage
;
1358 ret
= unshare(CLONE_NEWNS
);
1360 ERROR("Failed to unshare CLONE_NEWNS");
1361 _exit(EXIT_FAILURE
);
1364 if (detect_shared_rootfs() && mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
))
1365 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
1368 if (!strequal(bdev
->type
, "dir") && !strequal(bdev
->type
, "btrfs")) {
1370 ERROR("Unprivileged users can only create "
1371 "btrfs and directory-backed containers");
1372 _exit(EXIT_FAILURE
);
1375 if (strequal(bdev
->type
, "overlay") ||
1376 strequal(bdev
->type
, "overlayfs")) {
1377 /* If we create an overlay container we need to
1378 * rsync the contents into
1379 * <container-path>/<container-name>/rootfs.
1380 * However, the overlay mount function will
1382 * <container-path>/<container-name>/delta0
1384 * <container-path>/<container-name>/rootfs
1385 * which means we would rsync the rootfs into
1386 * the delta directory. That doesn't make sense
1387 * since the delta directory only exists to
1388 * record the differences to
1389 * <container-path>/<container-name>/rootfs. So
1390 * let's simply bind-mount here and then rsync
1392 * <container-path>/<container-name>/rootfs.
1396 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1398 ERROR("Failed to get rootfs");
1399 _exit(EXIT_FAILURE
);
1402 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1404 ERROR("Failed to mount rootfs");
1405 _exit(EXIT_FAILURE
);
1408 ret
= bdev
->ops
->mount(bdev
);
1410 ERROR("Failed to mount rootfs");
1411 _exit(EXIT_FAILURE
);
1414 } else { /* TODO come up with a better way here! */
1417 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1418 bdev
->dest
= strdup(src
);
1421 /* Create our new array, pre-pend the template name and base
1425 for (nargs
= 0; argv
[nargs
]; nargs
++)
1428 /* template, path, rootfs and name args */
1431 newargv
= malloc(nargs
* sizeof(*newargv
));
1433 _exit(EXIT_FAILURE
);
1434 newargv
[0] = lxctemplatefilename(tpath
);
1437 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1438 patharg
= malloc(len
);
1440 _exit(EXIT_FAILURE
);
1442 ret
= strnprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1444 _exit(EXIT_FAILURE
);
1445 newargv
[1] = patharg
;
1448 len
= strlen("--name=") + strlen(c
->name
) + 1;
1449 namearg
= malloc(len
);
1451 _exit(EXIT_FAILURE
);
1453 ret
= strnprintf(namearg
, len
, "--name=%s", c
->name
);
1455 _exit(EXIT_FAILURE
);
1456 newargv
[2] = namearg
;
1459 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1460 rootfsarg
= malloc(len
);
1462 _exit(EXIT_FAILURE
);
1464 ret
= strnprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1466 _exit(EXIT_FAILURE
);
1467 newargv
[3] = rootfsarg
;
1469 /* add passed-in args */
1471 for (i
= 4; i
< nargs
; i
++)
1472 newargv
[i
] = argv
[i
- 4];
1474 /* add trailing NULL */
1476 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1478 _exit(EXIT_FAILURE
);
1479 newargv
[nargs
- 1] = NULL
;
1481 /* If we're running the template in a mapped userns, then we
1482 * prepend the template command with: lxc-usernsexec <-m map1>
1483 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1484 * the mapped uid for our geteuid()
1486 if (!list_empty(&conf
->id_map
)) {
1487 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1489 char txtuid
[20], txtgid
[20];
1493 n2
= malloc(n2args
* sizeof(*n2
));
1495 _exit(EXIT_FAILURE
);
1498 tpath
= "lxc-usernsexec";
1499 n2
[0] = "lxc-usernsexec";
1501 list_for_each_entry(map
, &conf
->id_map
, head
) {
1503 n2
= realloc(n2
, n2args
* sizeof(char *));
1505 _exit(EXIT_FAILURE
);
1507 n2
[n2args
- 2] = "-m";
1508 n2
[n2args
- 1] = malloc(200);
1509 if (!n2
[n2args
- 1])
1510 _exit(EXIT_FAILURE
);
1512 ret
= strnprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1513 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1514 map
->nsid
, map
->hostid
, map
->range
);
1516 _exit(EXIT_FAILURE
);
1519 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1520 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1522 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1524 _exit(EXIT_FAILURE
);
1526 if (hostuid_mapped
< 0) {
1527 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1528 n2
[n2args
++] = "-m";
1529 if (hostuid_mapped
< 0) {
1530 ERROR("Failed to find free uid to map");
1531 _exit(EXIT_FAILURE
);
1534 n2
[n2args
++] = malloc(200);
1535 if (!n2
[n2args
- 1]) {
1536 SYSERROR("out of memory");
1537 _exit(EXIT_FAILURE
);
1540 ret
= strnprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1541 hostuid_mapped
, geteuid());
1543 _exit(EXIT_FAILURE
);
1546 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1547 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1549 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1551 _exit(EXIT_FAILURE
);
1553 if (hostgid_mapped
< 0) {
1554 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1555 n2
[n2args
++] = "-m";
1556 if (hostgid_mapped
< 0) {
1557 ERROR("Failed to find free gid to map");
1558 _exit(EXIT_FAILURE
);
1561 n2
[n2args
++] = malloc(200);
1562 if (!n2
[n2args
- 1]) {
1563 SYSERROR("out of memory");
1564 _exit(EXIT_FAILURE
);
1567 ret
= strnprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1568 hostgid_mapped
, getegid());
1570 _exit(EXIT_FAILURE
);
1573 n2
[n2args
++] = "--";
1575 for (i
= 0; i
< nargs
; i
++)
1576 n2
[i
+ n2args
] = newargv
[i
];
1579 /* Finally add "--mapped-uid $uid" to tell template what
1580 * to chown cached images to.
1583 n2
= realloc(n2
, n2args
* sizeof(char *));
1585 _exit(EXIT_FAILURE
);
1587 /* note n2[n2args-1] is NULL */
1588 n2
[n2args
- 5] = "--mapped-uid";
1590 ret
= strnprintf(txtuid
, 20, "%d", hostuid_mapped
);
1594 _exit(EXIT_FAILURE
);
1597 n2
[n2args
- 4] = txtuid
;
1598 n2
[n2args
- 3] = "--mapped-gid";
1600 ret
= strnprintf(txtgid
, 20, "%d", hostgid_mapped
);
1604 _exit(EXIT_FAILURE
);
1607 n2
[n2args
- 2] = txtgid
;
1608 n2
[n2args
- 1] = NULL
;
1613 execvp(tpath
, newargv
);
1614 SYSERROR("Failed to execute template %s", tpath
);
1615 _exit(EXIT_FAILURE
);
1618 ret
= wait_for_pid(pid
);
1620 ERROR("Failed to create container from template");
1627 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1635 unsigned int md_len
= 0;
1636 unsigned char md_value
[EVP_MAX_MD_SIZE
];
1640 f
= fopen(path
, "re");
1644 ret
= fseek(f
, 0, SEEK_END
);
1653 ret
= fseek(f
, 0, SEEK_SET
);
1657 ret
= fseek(f
, 0, SEEK_SET
);
1662 contents
= malloc(flen
+ 1);
1666 len
= fread(contents
, 1, flen
, f
);
1668 goto out_free_contents
;
1670 contents
[flen
] = '\0';
1675 goto out_free_contents
;
1678 tpath
= get_template_path(t
);
1680 ERROR("Invalid template \"%s\" specified", t
);
1681 goto out_free_contents
;
1684 ret
= sha1sum_file(tpath
, md_value
, &md_len
);
1686 ERROR("Failed to get sha1sum of %s", tpath
);
1688 goto out_free_contents
;
1693 f
= fopen(path
, "we");
1695 SYSERROR("Reopening config for writing");
1700 fprintf(f
, "# Template used to create this container: %s\n", t
);
1702 fprintf(f
, "# Parameters passed to the template:");
1704 fprintf(f
, " %s", *argv
);
1711 fprintf(f
, "# Template script checksum (SHA-1): ");
1712 for (size_t i
= 0; i
< md_len
; i
++)
1713 fprintf(f
, "%02x", md_value
[i
]);
1716 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1717 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1718 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1719 fprintf(f
, "# (Be aware this has security implications)\n\n");
1720 nbytes
= fwrite(contents
, 1, flen
, f
);
1721 if (nbytes
< 0 || nbytes
!= flen
) {
1722 SYSERROR("Writing original contents");
1742 SYSERROR("Error prepending header");
1749 static void lxcapi_clear_config(struct lxc_container
*c
)
1751 if (!c
|| !c
->lxc_conf
)
1754 lxc_conf_free(c
->lxc_conf
);
1758 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1762 * create a container with the given parameters.
1763 * @c: container to be created. It has the lxcpath, name, and a starting
1764 * configuration already set
1765 * @t: the template to execute to instantiate the root filesystem and
1766 * adjust the configuration.
1767 * @bdevtype: backing store type to use. If NULL, dir will be used.
1768 * @specs: additional parameters for the backing store, i.e. LVM vg to
1771 * @argv: the arguments to pass to the template, terminated by NULL. If no
1772 * arguments, you can just pass NULL.
1774 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1775 const char *bdevtype
, struct bdev_specs
*specs
,
1776 int flags
, char *const argv
[])
1778 __do_free
char *path_template
= NULL
;
1782 bool ret
= false, rootfs_managed
= true;
1788 path_template
= get_template_path(t
);
1790 return syserror_set(ENOENT
, "Template \"%s\" not found", t
);
1793 /* If a template is passed in, and the rootfs already is defined in the
1794 * container config and exists, then the caller is trying to create an
1795 * existing container. Return an error, but do NOT delete the container.
1797 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1798 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && path_template
)
1799 return syserror_set(EEXIST
, "Container \"%s\" already exists in \"%s\"", c
->name
, c
->config_path
);
1802 !do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config")))
1803 return syserror_set(EINVAL
, "Failed to load default configuration file %s",
1804 lxc_global_config_value("lxc.default_config"));
1806 if (!create_container_dir(c
))
1807 return syserror_set(EINVAL
, "Failed to create container %s", c
->name
);
1809 if (c
->lxc_conf
->rootfs
.path
)
1810 rootfs_managed
= false;
1812 /* If both template and rootfs.path are set, template is setup as
1813 * rootfs.path. The container is already created if we have a config and
1814 * rootfs.path is accessible
1816 if (!c
->lxc_conf
->rootfs
.path
&& !path_template
) {
1817 /* No template passed in and rootfs does not exist. */
1818 if (!c
->save_config(c
, NULL
)) {
1819 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1826 /* Rootfs passed into configuration, but does not exist. */
1827 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1830 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !path_template
) {
1831 /* Rootfs already existed, user just wanted to save the loaded
1834 if (!c
->save_config(c
, NULL
))
1835 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1841 /* Mark that this container is being created */
1842 partial_fd
= create_partial(c
);
1846 /* No need to get disk lock bc we have the partial lock. */
1850 /* Create the storage.
1851 * Note we can't do this in the same task as we use to execute the
1852 * template because of the way zfs works.
1853 * After you 'zfs create', zfs mounts the fs only in the initial
1858 SYSERROR("Failed to fork task for container creation template");
1862 if (pid
== 0) { /* child */
1863 struct lxc_storage
*bdev
= NULL
;
1865 bdev
= do_storage_create(c
, bdevtype
, specs
);
1867 ERROR("Failed to create %s storage for %s",
1868 bdevtype
? bdevtype
: "(none)", c
->name
);
1869 _exit(EXIT_FAILURE
);
1872 /* Save config file again to store the new rootfs location. */
1873 if (!do_lxcapi_save_config(c
, NULL
)) {
1874 ERROR("Failed to save initial config for %s", c
->name
);
1875 /* Parent task won't see the storage driver in the
1876 * config so we delete it.
1878 bdev
->ops
->umount(bdev
);
1879 bdev
->ops
->destroy(bdev
);
1880 _exit(EXIT_FAILURE
);
1883 _exit(EXIT_SUCCESS
);
1886 if (wait_for_pid(pid
) != 0)
1889 /* Reload config to get the rootfs. */
1890 lxc_conf_free(c
->lxc_conf
);
1893 if (!load_config_locked(c
, c
->configfile
))
1896 if (!create_run_template(c
, path_template
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1899 /* Now clear out the lxc_conf we have, reload from the created
1902 do_lxcapi_clear_config(c
);
1905 if (!prepend_lxc_header(c
->configfile
, path_template
, argv
)) {
1906 ERROR("Failed to prepend header to config file");
1911 ret
= load_config_locked(c
, c
->configfile
);
1915 remove_partial(c
, partial_fd
);
1919 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1922 * Ensure that we don't destroy storage we didn't create
1925 if (!rootfs_managed
)
1926 c
->lxc_conf
->rootfs
.managed
= false;
1927 container_destroy(c
, NULL
);
1928 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1934 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1935 const char *bdevtype
, struct bdev_specs
*specs
,
1936 int flags
, char *const argv
[])
1940 current_config
= c
? c
->lxc_conf
: NULL
;
1942 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1943 current_config
= NULL
;
1947 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1949 __do_close
int pidfd
= -EBADF
;
1952 int rebootsignal
= SIGINT
;
1957 if (!do_lxcapi_is_running(c
))
1960 pidfd
= do_lxcapi_init_pidfd(c
);
1962 pid
= do_lxcapi_init_pid(c
);
1967 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1968 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1971 ret
= lxc_raw_pidfd_send_signal(pidfd
, rebootsignal
, NULL
, 0);
1973 ret
= kill(pid
, rebootsignal
);
1975 return log_warn(false, "Failed to send signal %d to pid %d",
1981 WRAP_API(bool, lxcapi_reboot
)
1983 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1985 __do_close
int pidfd
= -EBADF
, state_client_fd
= -EBADF
;
1986 int rebootsignal
= SIGINT
;
1988 lxc_state_t states
[MAX_STATE
] = {0};
1994 if (!do_lxcapi_is_running(c
))
1997 pidfd
= do_lxcapi_init_pidfd(c
);
1999 pid
= do_lxcapi_init_pid(c
);
2004 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2005 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2007 /* Add a new state client before sending the shutdown signal so that we
2008 * don't miss a state.
2011 states
[RUNNING
] = 2;
2012 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2017 if (state_client_fd
< 0)
2023 if (ret
< MAX_STATE
)
2027 /* Send reboot signal to container. */
2029 killret
= lxc_raw_pidfd_send_signal(pidfd
, rebootsignal
, NULL
, 0);
2031 killret
= kill(pid
, rebootsignal
);
2033 return log_warn(false, "Failed to send signal %d to pidfd(%d)/pid(%d)", rebootsignal
, pidfd
, pid
);
2034 TRACE("Sent signal %d to pidfd(%d)/pid(%d)", rebootsignal
, pidfd
, pid
);
2039 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2043 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2050 WRAP_API_1(bool, lxcapi_reboot2
, int)
2052 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2054 __do_close
int pidfd
= -EBADF
, state_client_fd
= -EBADF
;
2055 int haltsignal
= SIGPWR
;
2057 lxc_state_t states
[MAX_STATE
] = {0};
2063 if (!do_lxcapi_is_running(c
))
2066 pidfd
= do_lxcapi_init_pidfd(c
);
2067 pid
= do_lxcapi_init_pid(c
);
2071 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2072 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2073 haltsignal
= c
->lxc_conf
->haltsignal
;
2074 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2075 haltsignal
= (SIGRTMIN
+ 3);
2079 * Add a new state client before sending the shutdown signal so
2080 * that we don't miss a state.
2083 states
[STOPPED
] = 1;
2084 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2089 if (state_client_fd
< 0)
2095 if (ret
< MAX_STATE
)
2100 struct pollfd pidfd_poll
= {
2105 killret
= lxc_raw_pidfd_send_signal(pidfd
, haltsignal
,
2108 return log_warn(false, "Failed to send signal %d to pidfd %d",
2111 TRACE("Sent signal %d to pidfd %d", haltsignal
, pidfd
);
2114 * No need for going through all of the state server
2115 * complications anymore. We can just poll on pidfds. :)
2119 ret
= poll(&pidfd_poll
, 1, timeout
* 1000);
2120 if (ret
< 0 || !(pidfd_poll
.revents
& POLLIN
))
2123 TRACE("Pidfd polling detected container exit");
2126 killret
= kill(pid
, haltsignal
);
2128 return log_warn(false, "Failed to send signal %d to pid %d",
2131 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2137 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2141 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2148 WRAP_API_1(bool, lxcapi_shutdown
, int)
2150 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2151 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2160 current_config
= c
->lxc_conf
;
2163 * since we're going to wait for create to finish, I don't think we
2164 * need to get a copy of the arguments.
2166 va_start(ap
, flags
);
2167 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2170 ERROR("Failed to allocate memory");
2174 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2178 current_config
= NULL
;
2182 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2184 if (strequal(key
, "lxc.cgroup"))
2185 return clear_unexp_config_line(conf
, key
, true);
2187 if (strequal(key
, "lxc.network"))
2188 return clear_unexp_config_line(conf
, key
, true);
2190 if (strequal(key
, "lxc.net"))
2191 return clear_unexp_config_line(conf
, key
, true);
2193 /* Clear a network with a specific index. */
2194 if (strnequal(key
, "lxc.net.", 8)) {
2199 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2201 return clear_unexp_config_line(conf
, key
, true);
2204 if (strequal(key
, "lxc.hook"))
2205 return clear_unexp_config_line(conf
, key
, true);
2207 return clear_unexp_config_line(conf
, key
, false);
2210 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2214 struct lxc_config_t
*config
;
2216 if (!c
|| !c
->lxc_conf
)
2219 if (container_mem_lock(c
))
2222 config
= lxc_get_config(key
);
2224 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2226 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2228 container_mem_unlock(c
);
2232 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2234 static inline bool enter_net_ns(struct lxc_container
*c
)
2236 pid_t pid
= do_lxcapi_init_pid(c
);
2241 if ((geteuid() != 0 || (c
->lxc_conf
&& !list_empty(&c
->lxc_conf
->id_map
))) &&
2242 (access("/proc/self/ns/user", F_OK
) == 0))
2243 if (!switch_to_ns(pid
, "user"))
2246 return switch_to_ns(pid
, "net");
2249 /* Used by qsort and bsearch functions for comparing names. */
2250 static inline int string_cmp(char **first
, char **second
)
2252 return strcmp(*first
, *second
);
2255 /* Used by qsort and bsearch functions for comparing container names. */
2256 static inline int container_cmp(struct lxc_container
**first
,
2257 struct lxc_container
**second
)
2259 return strcmp((*first
)->name
, (*second
)->name
);
2262 static bool add_to_array(char ***names
, char *cname
, int pos
)
2264 __do_free
char *dup_cname
= NULL
;
2267 dup_cname
= strdup(cname
);
2271 newnames
= realloc(*names
, (pos
+ 1) * sizeof(char *));
2273 return ret_set_errno(false, ENOMEM
);
2275 newnames
[pos
] = move_ptr(dup_cname
);
2277 /* Sort the array as we will use binary search on it. */
2278 qsort(newnames
, pos
+ 1, sizeof(char *),
2279 (int (*)(const void *, const void *))string_cmp
);
2285 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2288 struct lxc_container
**newlist
;
2290 newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2292 return ret_set_errno(false, ENOMEM
);
2296 /* Sort the array as we will use binary search on it. */
2298 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2299 (int (*)(const void *, const void *))container_cmp
);
2305 static char **get_from_array(char ***names
, char *cname
, int size
)
2310 return bsearch(&cname
, *names
, size
, sizeof(char *),
2311 (int (*)(const void *, const void *))string_cmp
);
2314 static bool array_contains(char ***names
, char *cname
, int size
)
2316 if (get_from_array(names
, cname
, size
))
2322 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2325 int i
, count
= 0, pipefd
[2];
2326 char **interfaces
= NULL
;
2327 char interface
[IFNAMSIZ
];
2329 if (pipe2(pipefd
, O_CLOEXEC
))
2330 return log_error_errno(NULL
, errno
, "Failed to create pipe");
2336 return log_error_errno(NULL
, errno
, "Failed to fork task to get interfaces information");
2340 call_cleaner(netns_freeifaddrs
) struct netns_ifaddrs
*ifaddrs
= NULL
;
2341 struct netns_ifaddrs
*ifa
= NULL
;
2345 /* close the read-end of the pipe */
2348 if (!enter_net_ns(c
)) {
2349 SYSERROR("Failed to enter network namespace");
2353 /* Grab the list of interfaces */
2354 if (netns_getifaddrs(&ifaddrs
, -1, &(bool){false})) {
2355 SYSERROR("Failed to get interfaces list");
2359 /* Iterate through the interfaces */
2360 for (ifa
= ifaddrs
; ifa
!= NULL
;
2361 ifa
= ifa
->ifa_next
) {
2362 nbytes
= lxc_write_nointr(pipefd
[1], ifa
->ifa_name
, IFNAMSIZ
);
2372 /* close the write-end of the pipe, thus sending EOF to the reader */
2377 /* close the write-end of the pipe */
2380 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2381 interface
[IFNAMSIZ
- 1] = '\0';
2383 if (array_contains(&interfaces
, interface
, count
))
2386 if (!add_to_array(&interfaces
, interface
, count
))
2387 ERROR("Failed to add \"%s\" to array", interface
);
2392 if (wait_for_pid(pid
)) {
2393 for (i
= 0; i
< count
; i
++)
2394 free(interfaces
[i
]);
2400 /* close the read-end of the pipe */
2403 /* Append NULL to the array */
2405 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2410 WRAP_API(char **, lxcapi_get_interfaces
)
2412 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2413 const char *family
, int scope
)
2418 char address
[INET6_ADDRSTRLEN
];
2420 char **addresses
= NULL
;
2422 ret
= pipe2(pipefd
, O_CLOEXEC
);
2424 return log_error_errno(NULL
, errno
, "Failed to create pipe");
2428 SYSERROR("Failed to create new process");
2435 call_cleaner(netns_freeifaddrs
) struct netns_ifaddrs
*ifaddrs
= NULL
;
2436 struct netns_ifaddrs
*ifa
= NULL
;
2438 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2439 char *address_ptr
= NULL
;
2440 void *address_ptr_tmp
= NULL
;
2442 /* close the read-end of the pipe */
2445 if (!enter_net_ns(c
)) {
2446 SYSERROR("Failed to attach to network namespace");
2450 /* Grab the list of interfaces */
2451 if (netns_getifaddrs(&ifaddrs
, -1, &(bool){false})) {
2452 SYSERROR("Failed to get interfaces list");
2456 /* Iterate through the interfaces */
2457 for (ifa
= ifaddrs
; ifa
; ifa
= ifa
->ifa_next
) {
2458 if (ifa
->ifa_addr
== NULL
)
2461 #pragma GCC diagnostic push
2462 #pragma GCC diagnostic ignored "-Wcast-align"
2464 if (ifa
->ifa_addr
->sa_family
== AF_INET
) {
2465 if (family
&& !strequal(family
, "inet"))
2468 address_ptr_tmp
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2470 if (family
&& !strequal(family
, "inet6"))
2473 if (((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_scope_id
!= (uint32_t)scope
)
2476 address_ptr_tmp
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2479 #pragma GCC diagnostic pop
2481 if (interface
&& !strequal(interface
, ifa
->ifa_name
))
2483 else if (!interface
&& strequal("lo", ifa
->ifa_name
))
2486 address_ptr
= (char *)inet_ntop(ifa
->ifa_addr
->sa_family
, address_ptr_tmp
,
2487 addressOutputBuffer
,
2488 sizeof(addressOutputBuffer
));
2492 nbytes
= lxc_write_nointr(pipefd
[1], address_ptr
, INET6_ADDRSTRLEN
);
2493 if (nbytes
!= INET6_ADDRSTRLEN
) {
2494 SYSERROR("Failed to send ipv6 address \"%s\"", address_ptr
);
2504 /* close the write-end of the pipe, thus sending EOF to the reader */
2509 /* close the write-end of the pipe */
2512 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2513 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2515 if (!add_to_array(&addresses
, address
, count
))
2516 ERROR("PARENT: add_to_array failed");
2521 if (wait_for_pid(pid
)) {
2522 for (i
= 0; i
< count
; i
++)
2529 /* close the read-end of the pipe */
2532 /* Append NULL to the array */
2534 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2539 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2541 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2544 struct lxc_config_t
*config
;
2546 if (!c
|| !c
->lxc_conf
)
2549 if (container_mem_lock(c
))
2552 config
= lxc_get_config(key
);
2554 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2556 container_mem_unlock(c
);
2560 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2562 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2566 if (!c
|| !c
->lxc_conf
)
2569 if (container_mem_lock(c
))
2572 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2573 container_mem_unlock(c
);
2577 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2579 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2583 /* List all config items. */
2585 return lxc_list_config_items(retv
, inlen
);
2587 if (!c
|| !c
->lxc_conf
)
2590 if (container_mem_lock(c
))
2593 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2594 * This is an intelligent result to show which keys are valid given the
2595 * type of nic it is.
2597 if (strnequal(key
, "lxc.net.", 8))
2598 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2600 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2602 container_mem_unlock(c
);
2606 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2608 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2611 bool ret
= false, need_disklock
= false;
2614 alt_file
= c
->configfile
;
2619 /* If we haven't yet loaded a config, load the stock config. */
2621 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2622 ERROR("Error loading default configuration file %s "
2624 lxc_global_config_value("lxc.default_config"),
2630 if (!create_container_dir(c
))
2633 /* If we're writing to the container's config file, take the disk lock.
2634 * Otherwise just take the memlock to protect the struct lxc_container
2635 * while we're traversing it.
2637 if (strequal(c
->configfile
, alt_file
))
2638 need_disklock
= true;
2641 lret
= container_disk_lock(c
);
2643 lret
= container_mem_lock(c
);
2647 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2648 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2652 lret
= write_config(fd
, c
->lxc_conf
);
2661 container_disk_unlock(c
);
2663 container_mem_unlock(c
);
2668 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2671 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2677 char path
[PATH_MAX
];
2678 char newpath
[PATH_MAX
];
2679 int fd
, ret
, n
= 0, v
= 0;
2681 size_t len
= 0, bytes
= 0;
2683 if (container_disk_lock(c0
))
2686 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2690 ret
= strnprintf(newpath
, sizeof(newpath
), "%s\n%s\n", c
->config_path
, c
->name
);
2694 /* If we find an lxc-snapshot file using the old format only listing the
2695 * number of snapshots we will keep using it. */
2696 f1
= fopen(path
, "re");
2698 n
= fscanf(f1
, "%d", &v
);
2700 if (n
== 1 && v
== 0) {
2703 SYSERROR("Failed to remove \"%s\"", path
);
2711 f1
= fopen(path
, "we");
2715 if (fprintf(f1
, "%d\n", v
) < 0) {
2716 ERROR("Error writing new snapshots value");
2723 SYSERROR("Error writing to or closing snapshots file");
2727 /* Here we know that we have or can use an lxc-snapshot file
2728 * using the new format. */
2730 f1
= fopen(path
, "ae");
2734 if (fprintf(f1
, "%s", newpath
) < 0) {
2735 ERROR("Error writing new snapshots entry");
2738 SYSERROR("Error writing to or closing snapshots file");
2744 SYSERROR("Error writing to or closing snapshots file");
2748 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2751 if (fstat(fd
, &fbuf
) < 0) {
2756 if (fbuf
.st_size
!= 0) {
2757 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2758 if (buf
== MAP_FAILED
) {
2759 SYSERROR("Failed to create mapping %s", path
);
2764 len
= strlen(newpath
);
2765 while ((del
= strstr((char *)buf
, newpath
))) {
2766 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2770 lxc_strmunmap(buf
, fbuf
.st_size
);
2771 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2772 SYSERROR("Failed to truncate file %s", path
);
2781 /* If the lxc-snapshot file is empty, remove it. */
2782 if (stat(path
, &fbuf
) < 0)
2785 if (!fbuf
.st_size
) {
2788 SYSERROR("Failed to remove \"%s\"", path
);
2795 container_disk_unlock(c0
);
2799 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2801 __do_free
char *lxcpath
= NULL
, *lxcname
= NULL
;
2802 __do_fclose
FILE *f
= NULL
;
2803 size_t pathlen
= 0, namelen
= 0;
2804 struct lxc_container
*p
;
2805 char path
[PATH_MAX
];
2808 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_rdepends",
2809 c
->config_path
, c
->name
);
2811 ERROR("Path name too long");
2815 f
= fopen(path
, "re");
2819 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2820 if (getline(&lxcname
, &namelen
, f
) == -1) {
2821 ERROR("badly formatted file %s", path
);
2825 remove_trailing_newlines(lxcpath
);
2826 remove_trailing_newlines(lxcname
);
2828 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2829 ERROR("Unable to find dependent container %s:%s",
2834 if (!mod_rdep(p
, c
, inc
))
2835 ERROR("Failed to update snapshots file for %s:%s",
2838 lxc_container_put(p
);
2842 static bool has_fs_snapshots(struct lxc_container
*c
)
2844 __do_fclose
FILE *f
= NULL
;
2845 char path
[PATH_MAX
];
2849 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_snapshots", c
->config_path
,
2854 /* If the file doesn't exist there are no snapshots. */
2855 if (stat(path
, &fbuf
) < 0)
2860 f
= fopen(path
, "re");
2864 ret
= fscanf(f
, "%d", &v
);
2866 INFO("Container uses new lxc-snapshots format %s", path
);
2872 static bool has_snapshots(struct lxc_container
*c
)
2874 __do_closedir
DIR *dir
= NULL
;
2875 char path
[PATH_MAX
];
2876 struct dirent
*direntp
;
2879 if (!get_snappath_dir(c
, path
))
2882 dir
= opendir(path
);
2886 while ((direntp
= readdir(dir
))) {
2887 if (strequal(direntp
->d_name
, "."))
2890 if (strequal(direntp
->d_name
, ".."))
2899 static bool do_destroy_container(struct lxc_conf
*conf
) {
2902 if (am_guest_unpriv()) {
2903 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2904 "storage_destroy_wrapper");
2911 return storage_destroy(conf
);
2914 static int lxc_rmdir_onedev_wrapper(void *data
)
2916 char *arg
= (char *) data
;
2917 return lxc_rmdir_onedev(arg
, "snaps");
2920 static int lxc_unlink_exec_wrapper(void *data
)
2926 static bool container_destroy(struct lxc_container
*c
,
2927 struct lxc_storage
*storage
)
2931 struct lxc_conf
*conf
;
2936 if (!c
|| !do_lxcapi_is_defined(c
))
2940 if (container_disk_lock(c
))
2943 if (!is_stopped(c
)) {
2944 /* We should queue some sort of error - in c->error_string? */
2945 ERROR("container %s is not stopped", c
->name
);
2949 if (conf
&& !list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2950 /* Start of environment variable setup for hooks */
2951 if (setenv("LXC_NAME", c
->name
, 1))
2952 SYSERROR("Failed to set environment variable for container name");
2954 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2955 SYSERROR("Failed to set environment variable for config path");
2957 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2958 SYSERROR("Failed to set environment variable for rootfs mount");
2960 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2961 SYSERROR("Failed to set environment variable for rootfs mount");
2963 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2964 SYSERROR("Failed to set environment variable for console path");
2966 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2967 SYSERROR("Failed to set environment variable for console log");
2968 /* End of environment variable setup for hooks */
2970 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2971 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2976 if (current_config
&& conf
== current_config
) {
2977 current_config
= NULL
;
2979 if (conf
->logfd
!= -1) {
2985 /* LXC is not managing the storage of the container. */
2986 if (conf
&& !conf
->rootfs
.managed
)
2989 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2990 if (!do_destroy_container(conf
)) {
2991 ERROR("Error destroying rootfs for %s", c
->name
);
2994 INFO("Destroyed rootfs for %s", c
->name
);
2997 mod_all_rdeps(c
, false);
2999 p1
= do_lxcapi_get_config_path(c
);
3008 * strlen("config") = 6
3012 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
3015 ERROR("Failed to allocate memory");
3019 /* For an overlay container the rootfs is considered immutable and
3020 * cannot be removed when restoring from a snapshot.
3022 if (storage
&& (strequal(storage
->type
, "overlay") ||
3023 strequal(storage
->type
, "overlayfs")) &&
3024 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3025 ret
= strnprintf(path
, len
, "%s/%s/%s", p1
, c
->name
, LXC_CONFIG_FNAME
);
3029 if (am_guest_unpriv())
3030 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3031 "lxc_unlink_exec_wrapper");
3035 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3039 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3045 ret
= strnprintf(path
, len
, "%s/%s", p1
, c
->name
);
3049 if (am_guest_unpriv())
3050 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3051 "lxc_rmdir_onedev_wrapper");
3053 ret
= lxc_rmdir_onedev(path
, "snaps");
3055 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3059 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3068 container_disk_unlock(c
);
3072 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3074 if (!c
|| !lxcapi_is_defined(c
))
3077 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3078 if (has_snapshots(c
)) {
3079 ERROR("Container %s has snapshots; not removing", c
->name
);
3083 if (has_fs_snapshots(c
)) {
3084 ERROR("container %s has snapshots on its rootfs", c
->name
);
3089 return container_destroy(c
, NULL
);
3092 WRAP_API(bool, lxcapi_destroy
)
3094 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3096 if (!c
|| !lxcapi_is_defined(c
))
3099 if (!lxcapi_snapshot_destroy_all(c
)) {
3100 ERROR("Error deleting all snapshots");
3104 return lxcapi_destroy(c
);
3107 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3109 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3113 struct lxc_config_t
*config
;
3116 config
= lxc_get_config(key
);
3118 ret
= config
->set(key
, v
, conf
, NULL
);
3122 if (lxc_config_value_empty(v
))
3123 do_clear_unexp_config_line(conf
, key
);
3125 bret
= do_append_unexp_config_line(conf
, key
, v
);
3132 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3138 c
->lxc_conf
= lxc_conf_init();
3143 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3150 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3157 if (container_mem_lock(c
))
3160 b
= do_set_config_item_locked(c
, key
, v
);
3162 container_mem_unlock(c
);
3166 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3168 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3170 if (!c
|| !c
->configfile
)
3173 return strdup(c
->configfile
);
3176 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3178 if (!c
|| !c
->config_path
)
3181 return (const char *)(c
->config_path
);
3186 * Just recalculate the c->configfile based on the
3187 * c->config_path, which must be set.
3188 * The lxc_container must be locked or not yet public.
3190 static bool set_config_filename(struct lxc_container
*c
)
3195 if (!c
->config_path
)
3198 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3199 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
3200 newpath
= malloc(len
);
3204 ret
= strnprintf(newpath
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_CONFIG_FNAME
);
3206 fprintf(stderr
, "Error printing out config file name\n");
3211 free(c
->configfile
);
3212 c
->configfile
= newpath
;
3217 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3221 char *oldpath
= NULL
;
3226 if (container_mem_lock(c
))
3231 ERROR("Out of memory setting new lxc path");
3237 oldpath
= c
->config_path
;
3240 /* Since we've changed the config path, we have to change the
3241 * config file name too */
3242 if (!set_config_filename(c
)) {
3243 ERROR("Out of memory setting new config filename");
3245 free(c
->config_path
);
3246 c
->config_path
= oldpath
;
3252 container_mem_unlock(c
);
3256 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3258 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3260 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
3269 ret
= cgroup_set(c
->name
, c
->config_path
, subsys
, value
);
3270 if (ret
< 0 && ERRNO_IS_NOT_SUPPORTED(ret
)) {
3271 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3275 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3281 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3283 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3285 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
3294 ret
= cgroup_get(c
->name
, c
->config_path
, subsys
, retv
, inlen
);
3295 if (ret
< 0 && ERRNO_IS_NOT_SUPPORTED(ret
)) {
3296 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3300 return cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
, c
->config_path
);
3306 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3308 const char *lxc_get_global_config_item(const char *key
)
3310 return lxc_global_config_value(key
);
3313 const char *lxc_get_version(void)
3318 static int copy_file(const char *old
, const char *new)
3325 if (file_exists(new)) {
3326 ERROR("copy destination %s exists", new);
3330 ret
= stat(old
, &sbuf
);
3332 INFO("Error stat'ing %s", old
);
3336 in
= open(old
, O_RDONLY
);
3338 SYSERROR("Error opening original file %s", old
);
3342 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3344 SYSERROR("Error opening new file %s", new);
3350 len
= lxc_read_nointr(in
, buf
, 8096);
3352 SYSERROR("Error reading old file %s", old
);
3359 ret
= lxc_write_nointr(out
, buf
, len
);
3360 if (ret
< len
) { /* should we retry? */
3361 SYSERROR("Error: write to new file %s was interrupted", new);
3369 /* We set mode, but not owner/group. */
3370 ret
= chmod(new, sbuf
.st_mode
);
3372 SYSERROR("Error setting mode on %s", new);
3384 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3386 __do_free
char *cpath
= NULL
;
3388 struct string_entry
*entry
;
3390 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3391 cpath
= malloc(len
);
3393 return ret_errno(ENOMEM
);
3395 ret
= strnprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3399 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3400 list_for_each_entry(entry
, &c
->lxc_conf
->hooks
[i
], head
) {
3401 __do_free
char *hookname
= NULL
;
3402 char *fname
, *new_hook
;
3403 char tmppath
[PATH_MAX
];
3405 fname
= strrchr(entry
->val
, '/');
3409 /* If this hook is public - ignore. */
3410 if (!strnequal(entry
->val
, cpath
, len
- 1))
3413 /* copy the script, and change the entry in confile */
3414 ret
= strnprintf(tmppath
, sizeof(tmppath
), "%s/%s/%s",
3415 c
->config_path
, c
->name
, fname
+1);
3419 ret
= copy_file(entry
->val
, tmppath
);
3423 new_hook
= strdup(tmppath
);
3425 return syserror("out of memory copying hook path");
3427 hookname
= move_ptr(entry
->val
);
3428 entry
->val
= move_ptr(new_hook
);
3432 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3433 c
->config_path
, oldc
->name
, c
->name
)) {
3434 return syserror_ret(-1, "Error saving new hooks in clone");
3437 do_lxcapi_save_config(c
, NULL
);
3441 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3443 char newpath
[PATH_MAX
];
3444 char *oldpath
= oldc
->lxc_conf
->fstab
;
3450 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3452 char *p
= strrchr(oldpath
, '/');
3456 ret
= strnprintf(newpath
, sizeof(newpath
), "%s/%s%s",
3457 c
->config_path
, c
->name
, p
);
3459 ERROR("error printing new path for %s", oldpath
);
3463 if (file_exists(newpath
)) {
3464 ERROR("error: fstab file %s exists", newpath
);
3468 if (copy_file(oldpath
, newpath
) < 0) {
3469 ERROR("error: copying %s to %s", oldpath
, newpath
);
3473 free(c
->lxc_conf
->fstab
);
3475 c
->lxc_conf
->fstab
= strdup(newpath
);
3476 if (!c
->lxc_conf
->fstab
) {
3477 ERROR("error: allocating pathname");
3481 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3482 ERROR("error saving new lxctab");
3489 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3491 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3494 ret
= strnprintf(path0
, sizeof(path0
), "%s/%s/lxc_rdepends", c0
->config_path
,
3497 WARN("Error copying reverse dependencies");
3501 ret
= strnprintf(path1
, sizeof(path1
), "%s/%s/lxc_rdepends", c
->config_path
,
3504 WARN("Error copying reverse dependencies");
3508 if (copy_file(path0
, path1
) < 0) {
3509 INFO("Error copying reverse dependencies");
3514 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3516 __do_fclose
FILE *f
= NULL
;
3518 char path
[PATH_MAX
];
3520 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_rdepends", c
->config_path
, c
->name
);
3524 f
= fopen(path
, "ae");
3528 /* If anything goes wrong, just return an error. */
3529 return fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) > 0;
3533 * If the fs natively supports snapshot clones with no penalty,
3534 * then default to those even if not requested.
3535 * Currently we only do this for btrfs.
3537 static bool should_default_to_snapshot(struct lxc_container
*c0
,
3538 struct lxc_container
*c1
)
3540 __do_free
char *p0
= NULL
, *p1
= NULL
;
3542 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3543 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3544 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3546 p0
= must_realloc(NULL
, l0
+ 1);
3547 p1
= must_realloc(NULL
, l1
+ 1);
3548 ret
= strnprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3552 ret
= strnprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3556 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3559 if (is_btrfs_subvol(rootfs
) <= 0)
3562 return btrfs_same_fs(p0
, p1
) == 0;
3565 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3566 const char *newtype
, int flags
, const char *bdevdata
,
3569 struct lxc_storage
*bdev
;
3572 if (should_default_to_snapshot(c0
, c
))
3573 flags
|= LXC_CLONE_SNAPSHOT
;
3575 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3576 bdevdata
, newsize
, &need_rdep
);
3578 ERROR("Error copying storage.");
3582 /* Set new rootfs. */
3583 free(c
->lxc_conf
->rootfs
.path
);
3584 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3587 if (!c
->lxc_conf
->rootfs
.path
) {
3588 ERROR("Out of memory while setting storage path.");
3592 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3593 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3594 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3595 c
->lxc_conf
->rootfs
.path
)) {
3596 ERROR("Error saving new rootfs to cloned config.");
3600 if (flags
& LXC_CLONE_SNAPSHOT
)
3601 copy_rdepends(c
, c0
);
3604 if (!add_rdepends(c
, c0
))
3605 WARN("Error adding reverse dependency from %s to %s",
3609 mod_all_rdeps(c
, true);
3614 struct clone_update_data
{
3615 struct lxc_container
*c0
;
3616 struct lxc_container
*c1
;
3621 static int clone_update_rootfs(struct clone_update_data
*data
)
3623 struct lxc_container
*c0
= data
->c0
;
3624 struct lxc_container
*c
= data
->c1
;
3625 int flags
= data
->flags
;
3626 char **hookargs
= data
->hookargs
;
3628 char path
[PATH_MAX
];
3629 struct lxc_storage
*bdev
;
3631 struct lxc_conf
*conf
= c
->lxc_conf
;
3633 /* update hostname in rootfs */
3634 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3636 (void)lxc_drop_groups();
3638 if (setgid(0) < 0) {
3639 ERROR("Failed to setgid to 0");
3643 if (setuid(0) < 0) {
3644 ERROR("Failed to setuid to 0");
3648 if (unshare(CLONE_NEWNS
) < 0)
3651 ret
= lxc_storage_prepare(conf
);
3654 bdev
= conf
->rootfs
.storage
;
3656 if (!strequal(bdev
->type
, "dir")) {
3657 if (unshare(CLONE_NEWNS
) < 0) {
3658 ERROR("error unsharing mounts");
3659 lxc_storage_put(conf
);
3663 if (detect_shared_rootfs() && mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
))
3664 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
3666 if (bdev
->ops
->mount(bdev
) < 0) {
3667 lxc_storage_put(conf
);
3670 } else { /* TODO come up with a better way */
3672 bdev
->dest
= strdup(lxc_storage_get_path(bdev
->src
, bdev
->type
));
3675 if (!list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3676 /* Start of environment variable setup for hooks */
3677 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3678 SYSERROR("failed to set environment variable for source container name");
3680 if (setenv("LXC_NAME", c
->name
, 1))
3681 SYSERROR("failed to set environment variable for container name");
3683 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3684 SYSERROR("failed to set environment variable for config path");
3686 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3687 SYSERROR("failed to set environment variable for rootfs mount");
3689 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3690 SYSERROR("failed to set environment variable for rootfs mount");
3692 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3693 ERROR("Error executing clone hook for %s", c
->name
);
3694 lxc_storage_put(conf
);
3699 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3700 ret
= strnprintf(path
, sizeof(path
), "%s/etc/hostname", bdev
->dest
);
3701 lxc_storage_put(conf
);
3706 if (!file_exists(path
))
3709 if (!(fout
= fopen(path
, "we"))) {
3710 SYSERROR("unable to open %s: ignoring", path
);
3714 if (fprintf(fout
, "%s", c
->name
) < 0) {
3719 if (fclose(fout
) < 0)
3722 lxc_storage_put(conf
);
3728 static int clone_update_rootfs_wrapper(void *data
)
3730 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3731 return clone_update_rootfs(arg
);
3735 * We want to support:
3736 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3737 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3739 -s [ implies overlay]
3742 only rootfs gets converted (copied/snapshotted) on clone.
3745 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3747 char *p
= strrchr(path
, '/');
3754 ret
= do_create_container_dir(path
, conf
);
3760 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3761 const char *lxcpath
, int flags
,
3762 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3765 char newpath
[PATH_MAX
];
3767 struct clone_update_data data
;
3768 size_t saved_unexp_len
;
3770 int storage_copied
= 0;
3771 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3772 struct lxc_container
*c2
= NULL
;
3774 if (!c
|| !do_lxcapi_is_defined(c
))
3777 if (container_mem_lock(c
))
3779 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3780 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3784 /* Make sure the container doesn't yet exist. */
3789 lxcpath
= do_lxcapi_get_config_path(c
);
3791 ret
= strnprintf(newpath
, sizeof(newpath
), "%s/%s/%s", lxcpath
, newname
, LXC_CONFIG_FNAME
);
3793 SYSERROR("clone: failed making config pathname");
3797 if (file_exists(newpath
)) {
3798 ERROR("error: clone: %s exists", newpath
);
3802 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3803 if (ret
< 0 && errno
!= EEXIST
) {
3804 ERROR("Error creating container dir for %s", newpath
);
3808 /* Copy the configuration. Tweak it as needed. */
3809 if (c
->lxc_conf
->rootfs
.path
) {
3810 origroot
= c
->lxc_conf
->rootfs
.path
;
3811 c
->lxc_conf
->rootfs
.path
= NULL
;
3814 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3815 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3817 SYSERROR("Failed to open \"%s\"", newpath
);
3821 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3822 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3823 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3824 if (!c
->lxc_conf
->unexpanded_config
) {
3829 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3830 write_config(fd
, c
->lxc_conf
);
3833 c
->lxc_conf
->rootfs
.path
= origroot
;
3835 free(c
->lxc_conf
->unexpanded_config
);
3836 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3837 saved_unexp_conf
= NULL
;
3838 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3840 ret
= strnprintf(newpath
, sizeof(newpath
), "%s/%s/%s", lxcpath
, newname
, LXC_ROOTFS_DNAME
);
3842 SYSERROR("clone: failed making rootfs pathname");
3846 ret
= mkdir(newpath
, 0755);
3848 /* For an overlay container the rootfs is considered immutable
3849 * and will not have been removed when restoring from a
3852 if (errno
!= ENOENT
&&
3853 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3854 SYSERROR("Failed to create directory \"%s\"", newpath
);
3859 if (am_guest_unpriv()) {
3860 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3861 ERROR("Error chowning %s to container root", newpath
);
3866 c2
= lxc_container_new(newname
, lxcpath
);
3868 ERROR("clone: failed to create new container (%s %s)", newname
,
3873 /* copy/snapshot rootfs's */
3874 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3878 /* update utsname */
3879 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3880 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3881 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3883 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3884 ERROR("Error setting new hostname");
3890 ret
= copyhooks(c
, c2
);
3892 ERROR("error copying hooks");
3896 if (copy_fstab(c
, c2
) < 0) {
3897 ERROR("error copying fstab");
3901 /* update macaddrs */
3902 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3903 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3904 ERROR("Error updating mac addresses");
3909 /* Update absolute paths for overlay mount directories. */
3910 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3913 /* We've now successfully created c2's storage, so clear it out if we
3918 if (!c2
->save_config(c2
, NULL
))
3921 if ((pid
= fork()) < 0) {
3927 ret
= wait_for_pid(pid
);
3931 container_mem_unlock(c
);
3938 data
.hookargs
= hookargs
;
3940 if (am_guest_unpriv())
3941 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3942 &data
, "clone_update_rootfs_wrapper");
3944 ret
= clone_update_rootfs(&data
);
3946 _exit(EXIT_FAILURE
);
3948 container_mem_unlock(c
);
3949 _exit(EXIT_SUCCESS
);
3952 container_mem_unlock(c
);
3954 if (!storage_copied
)
3955 c2
->lxc_conf
->rootfs
.path
= NULL
;
3958 lxc_container_put(c2
);
3964 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3965 const char *lxcpath
, int flags
,
3966 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3969 struct lxc_container
* ret
;
3971 current_config
= c
? c
->lxc_conf
: NULL
;
3972 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3973 current_config
= NULL
;
3978 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3980 struct lxc_storage
*bdev
;
3981 struct lxc_container
*newc
;
3983 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3986 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3987 ERROR("Renaming a container with snapshots is not supported");
3991 if (lxc_storage_prepare(c
->lxc_conf
)) {
3992 ERROR("Failed to find original backing store type");
3995 bdev
= c
->lxc_conf
->rootfs
.storage
;
3997 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3998 lxc_storage_put(c
->lxc_conf
);
4000 lxc_container_put(newc
);
4004 if (newc
&& lxcapi_is_defined(newc
))
4005 lxc_container_put(newc
);
4007 if (!container_destroy(c
, NULL
)) {
4008 ERROR("Could not destroy existing container %s", c
->name
);
4015 WRAP_API_1(bool, lxcapi_rename
, const char *)
4017 static int lxcapi_attach(struct lxc_container
*c
,
4018 lxc_attach_exec_t exec_function
, void *exec_payload
,
4019 lxc_attach_options_t
*options
, pid_t
*attached_process
)
4026 current_config
= c
->lxc_conf
;
4028 ret
= lxc_attach(c
, exec_function
, exec_payload
, options
,
4030 current_config
= NULL
;
4034 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
,
4035 lxc_attach_options_t
*options
,
4036 const char *program
,
4037 const char *const argv
[])
4039 lxc_attach_command_t command
;
4046 command
.program
= (char *)program
;
4047 command
.argv
= (char **)argv
;
4049 ret
= lxc_attach(c
, lxc_attach_run_command
, &command
, options
, &pid
);
4053 return lxc_wait_for_pid_status(pid
);
4056 static int lxcapi_attach_run_wait(struct lxc_container
*c
,
4057 lxc_attach_options_t
*options
,
4058 const char *program
, const char *const argv
[])
4062 current_config
= c
? c
->lxc_conf
: NULL
;
4063 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4064 current_config
= NULL
;
4069 static int get_next_index(const char *lxcpath
, char *cname
)
4071 __do_free
char *fname
= NULL
;
4075 fname
= must_realloc(NULL
, strlen(lxcpath
) + 20);
4078 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4080 ret
= stat(fname
, &sb
);
4088 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4093 * If the old style snapshot path exists, use it
4094 * /var/lib/lxc -> /var/lib/lxcsnaps
4096 ret
= strnprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4100 if (dir_exists(snappath
)) {
4101 ret
= strnprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4109 * Use the new style path
4110 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4112 ret
= strnprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4119 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4121 __do_free
char *dfnam
= NULL
;
4126 struct lxc_container
*c2
;
4127 char snappath
[PATH_MAX
], newname
[20];
4131 if (!c
|| !lxcapi_is_defined(c
))
4134 if (!storage_can_backup(c
->lxc_conf
)) {
4135 ERROR("%s's backing store cannot be backed up", c
->name
);
4136 ERROR("Your container must use another backing store type");
4140 if (!get_snappath_dir(c
, snappath
))
4143 i
= get_next_index(snappath
, c
->name
);
4145 if (mkdir_p(snappath
, 0755) < 0) {
4146 ERROR("Failed to create snapshot directory %s", snappath
);
4150 ret
= strnprintf(newname
, 20, "snap%d", i
);
4155 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4156 * created in the original container
4158 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4159 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4160 if (storage_is_dir(c
->lxc_conf
)) {
4161 ERROR("Snapshot of directory-backed container requested");
4162 ERROR("Making a copy-clone. If you do want snapshots, then");
4163 ERROR("please create overlay clone first, snapshot that");
4164 ERROR("and keep the original container pristine");
4165 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4168 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4170 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4174 lxc_container_put(c2
);
4176 /* Now write down the creation time. */
4179 if (!localtime_r(&timer
, &tm_info
)) {
4180 ERROR("Failed to get localtime");
4184 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4186 len
= strlen(snappath
) + 1 + strlen(newname
) + 1 + strlen(LXC_TIMESTAMP_FNAME
) + 1;
4187 dfnam
= must_realloc(NULL
, len
);
4188 ret
= strnprintf(dfnam
, len
, "%s/%s/%s", snappath
, newname
, LXC_TIMESTAMP_FNAME
);
4191 f
= fopen(dfnam
, "we");
4193 ERROR("Failed to open %s", dfnam
);
4197 if (fprintf(f
, "%s", buffer
) < 0) {
4198 SYSERROR("Writing timestamp");
4205 SYSERROR("Writing timestamp");
4210 __do_free
char *path
= NULL
;
4211 /* $p / $name / comment \0 */
4212 len
= strlen(snappath
) + 1 + strlen(newname
) + 1 + strlen(LXC_COMMENT_FNAME
) + 1;
4214 path
= must_realloc(NULL
, len
);
4215 ret
= strnprintf(path
, len
, "%s/%s/%s", snappath
, newname
, LXC_COMMENT_FNAME
);
4218 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4224 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4226 static void lxcsnap_free(struct lxc_snapshot
*s
)
4229 free(s
->comment_pathname
);
4234 static char *get_snapcomment_path(char *snappath
, char *name
)
4236 __do_free
char *s
= NULL
;
4237 /* $snappath/$name/comment */
4238 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4244 ret
= strnprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4251 static char *get_timestamp(char* snappath
, char *name
)
4253 __do_free
char *s
= NULL
;
4254 __do_fclose
FILE *fin
= NULL
;
4255 char path
[PATH_MAX
];
4258 ret
= strnprintf(path
, sizeof(path
), "%s/%s/ts", snappath
, name
);
4262 fin
= fopen(path
, "re");
4266 (void) fseek(fin
, 0, SEEK_END
);
4268 (void) fseek(fin
, 0, SEEK_SET
);
4275 nbytes
= fread(s
, 1, len
, fin
);
4276 if (nbytes
< 0 || nbytes
!= (ssize_t
)len
)
4277 return log_error_errno(NULL
, errno
, "reading timestamp");
4284 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4286 __do_closedir
DIR *dir
= NULL
;
4287 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4289 struct dirent
*direntp
;
4290 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4292 if (!c
|| !lxcapi_is_defined(c
))
4295 if (!get_snappath_dir(c
, snappath
)) {
4296 ERROR("path name too long");
4300 dir
= opendir(snappath
);
4302 INFO("Failed to open %s - assuming no snapshots", snappath
);
4306 while ((direntp
= readdir(dir
))) {
4307 if (strequal(direntp
->d_name
, "."))
4310 if (strequal(direntp
->d_name
, ".."))
4313 ret
= strnprintf(path2
, sizeof(path2
), "%s/%s/%s", snappath
, direntp
->d_name
, LXC_CONFIG_FNAME
);
4315 ERROR("pathname too long");
4319 if (!file_exists(path2
))
4322 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4324 SYSERROR("Out of memory");
4329 snaps
[count
].free
= lxcsnap_free
;
4330 snaps
[count
].name
= strdup(direntp
->d_name
);
4331 if (!snaps
[count
].name
)
4334 snaps
[count
].lxcpath
= strdup(snappath
);
4335 if (!snaps
[count
].lxcpath
) {
4336 free(snaps
[count
].name
);
4340 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4341 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4350 for (int i
= 0; i
< count
; i
++)
4351 lxcsnap_free(&snaps
[i
]);
4359 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4361 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4363 char clonelxcpath
[PATH_MAX
];
4365 struct lxc_container
*snap
, *rest
;
4366 struct lxc_storage
*bdev
;
4369 if (!c
|| !c
->name
|| !c
->config_path
)
4372 if (has_fs_snapshots(c
)) {
4373 ERROR("container rootfs has dependent snapshots");
4377 if (lxc_storage_prepare(c
->lxc_conf
)) {
4378 ERROR("Failed to find original backing store type");
4381 bdev
= c
->lxc_conf
->rootfs
.storage
;
4383 /* For an overlay container the rootfs is considered immutable
4384 * and cannot be removed when restoring from a snapshot. We pass this
4385 * internal flag along to communicate this to various parts of the
4388 if (strequal(bdev
->type
, "overlay") || strequal(bdev
->type
, "overlayfs"))
4389 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4394 if (!get_snappath_dir(c
, clonelxcpath
)) {
4395 lxc_storage_put(c
->lxc_conf
);
4398 /* how should we lock this? */
4400 snap
= lxc_container_new(snapname
, clonelxcpath
);
4401 if (!snap
|| !lxcapi_is_defined(snap
)) {
4402 ERROR("Could not open snapshot %s", snapname
);
4405 lxc_container_put(snap
);
4407 lxc_storage_put(c
->lxc_conf
);
4411 if (strequal(c
->name
, newname
)) {
4412 if (!container_destroy(c
, bdev
)) {
4413 ERROR("Could not destroy existing container %s", newname
);
4414 lxc_container_put(snap
);
4415 lxc_storage_put(c
->lxc_conf
);
4420 if (!strequal(bdev
->type
, "dir") && !strequal(bdev
->type
, "loop"))
4421 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4423 if (strequal(bdev
->type
, "overlay") || strequal(bdev
->type
, "overlayfs"))
4424 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4426 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4428 lxc_storage_put(c
->lxc_conf
);
4429 if (rest
&& lxcapi_is_defined(rest
))
4433 lxc_container_put(rest
);
4435 lxc_container_put(snap
);
4439 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4441 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4443 struct lxc_container
*snap
= NULL
;
4446 snap
= lxc_container_new(snapname
, clonelxcpath
);
4448 ERROR("Could not find snapshot %s", snapname
);
4452 if (!do_lxcapi_destroy(snap
)) {
4453 ERROR("Could not destroy snapshot %s", snapname
);
4461 lxc_container_put(snap
);
4466 static bool remove_all_snapshots(const char *path
)
4468 __do_closedir
DIR *dir
= NULL
;
4469 struct dirent
*direntp
;
4472 dir
= opendir(path
);
4474 SYSERROR("opendir on snapshot path %s", path
);
4478 while ((direntp
= readdir(dir
))) {
4479 if (strequal(direntp
->d_name
, "."))
4482 if (strequal(direntp
->d_name
, ".."))
4485 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4492 SYSERROR("Error removing directory %s", path
);
4497 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4499 char clonelxcpath
[PATH_MAX
];
4501 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4504 if (!get_snappath_dir(c
, clonelxcpath
))
4507 return do_snapshot_destroy(snapname
, clonelxcpath
);
4510 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4512 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4514 char clonelxcpath
[PATH_MAX
];
4516 if (!c
|| !c
->name
|| !c
->config_path
)
4519 if (!get_snappath_dir(c
, clonelxcpath
))
4522 return remove_all_snapshots(clonelxcpath
);
4525 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4527 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4532 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4535 WRAP_API(bool, lxcapi_may_control
)
4537 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4543 char chrootpath
[PATH_MAX
];
4544 char *directory_path
= NULL
;
4548 SYSERROR("Failed to fork()");
4553 ret
= wait_for_pid(pid
);
4555 ERROR("Failed to create device node");
4562 /* prepare the path */
4563 ret
= strnprintf(chrootpath
, sizeof(chrootpath
), "/proc/%d/root", init_pid
);
4567 ret
= chroot(chrootpath
);
4569 _exit(EXIT_FAILURE
);
4573 _exit(EXIT_FAILURE
);
4575 /* remove path if it exists */
4576 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4580 SYSERROR("Failed to remove \"%s\"", path
);
4581 _exit(EXIT_FAILURE
);
4586 _exit(EXIT_SUCCESS
);
4588 /* create any missing directories */
4591 _exit(EXIT_FAILURE
);
4593 directory_path
= dirname(tmp
);
4594 ret
= mkdir_p(directory_path
, 0755);
4595 if (ret
< 0 && errno
!= EEXIST
) {
4596 SYSERROR("Failed to create path \"%s\"", directory_path
);
4598 _exit(EXIT_FAILURE
);
4601 /* create the device node */
4602 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4605 SYSERROR("Failed to create device node at \"%s\"", path
);
4606 _exit(EXIT_FAILURE
);
4609 _exit(EXIT_SUCCESS
);
4612 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4616 char value
[LXC_MAX_BUFFER
];
4620 /* make sure container is running */
4621 if (!do_lxcapi_is_running(c
)) {
4622 ERROR("container is not running");
4626 /* use src_path if dest_path is NULL otherwise use dest_path */
4627 p
= dest_path
? dest_path
: src_path
;
4629 /* make sure we can access p */
4630 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4633 /* continue if path is character device or block device */
4634 if (S_ISCHR(st
.st_mode
))
4635 ret
= strnprintf(value
, sizeof(value
), "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4636 else if (S_ISBLK(st
.st_mode
))
4637 ret
= strnprintf(value
, sizeof(value
), "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4643 init_pid
= do_lxcapi_init_pid(c
);
4645 ERROR("Failed to get init pid");
4649 if (!do_add_remove_node(init_pid
, p
, add
, &st
))
4652 /* add or remove device to/from cgroup access list */
4654 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4655 ERROR("set_cgroup_item failed while adding the device node");
4659 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4660 ERROR("set_cgroup_item failed while removing the device node");
4668 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4670 // cannot mknod if we're not privileged wrt init_user_ns
4671 if (am_host_unpriv()) {
4672 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4676 return add_remove_device_node(c
, src_path
, dest_path
, true);
4679 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4681 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4683 if (am_guest_unpriv()) {
4684 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4688 return add_remove_device_node(c
, src_path
, dest_path
, false);
4691 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4693 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4695 const char *dst_ifname
)
4700 if (am_guest_unpriv()) {
4701 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4706 ERROR("No source interface name given");
4710 ret
= lxc_netdev_isup(ifname
);
4712 /* netdev of ifname is up. */
4713 ret
= lxc_netdev_down(ifname
);
4718 init_pid
= do_lxcapi_init_pid(c
);
4720 ERROR("Failed to get init pid");
4724 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4728 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4735 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4737 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4739 const char *dst_ifname
)
4742 pid_t pid
, pid_outside
;
4743 __do_free
char *physname
= NULL
;
4746 * TODO - if this is a physical device, then we need am_host_unpriv.
4747 * But for other types guest privilege suffices.
4749 if (am_guest_unpriv()) {
4750 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4755 ERROR("No source interface name given");
4759 pid_outside
= lxc_raw_getpid();
4762 ERROR("Failed to fork");
4766 if (pid
== 0) { /* child */
4769 init_pid
= do_lxcapi_init_pid(c
);
4771 ERROR("Failed to get init pid");
4772 _exit(EXIT_FAILURE
);
4774 if (!switch_to_ns(init_pid
, "net")) {
4775 ERROR("Failed to enter network namespace");
4776 _exit(EXIT_FAILURE
);
4779 /* create new mount namespace for use with remounting /sys and is_wlan() below. */
4780 ret
= unshare(CLONE_NEWNS
);
4782 ERROR("Failed to unshare mount namespace");
4783 _exit(EXIT_FAILURE
);
4786 /* set / recursively as private so that mount propagation doesn't affect us. */
4787 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4788 ERROR("Failed to recursively set / as private in mount namespace");
4789 _exit(EXIT_FAILURE
);
4792 ret
= lxc_netdev_isup(ifname
);
4794 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4795 _exit(EXIT_FAILURE
);
4798 /* netdev of ifname is up. */
4800 ret
= lxc_netdev_down(ifname
);
4802 ERROR("Failed to set network device \"%s\" down", ifname
);
4803 _exit(EXIT_FAILURE
);
4807 /* remount /sys so is_wlan() can check if this device is a wlan device. */
4808 lxc_attach_remount_sys_proc();
4809 physname
= is_wlan(ifname
);
4811 ret
= lxc_netdev_move_wlan(physname
, ifname
, pid_outside
, dst_ifname
);
4813 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4815 /* -EINVAL means there is no netdev named as ifname. */
4818 ERROR("Network device \"%s\" not found", ifname
);
4820 ERROR("Failed to remove network device \"%s\"", ifname
);
4822 _exit(EXIT_FAILURE
);
4825 _exit(EXIT_SUCCESS
);
4828 ret
= wait_for_pid(pid
);
4832 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4836 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4838 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4839 struct migrate_opts
*opts
, unsigned int size
)
4842 struct migrate_opts
*valid_opts
= opts
;
4843 uint64_t features_to_check
= 0;
4845 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4846 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4847 * to do anything special.
4849 if (size
> sizeof(*opts
)) {
4850 unsigned char *addr
;
4853 addr
= (void *)opts
+ sizeof(*opts
);
4854 end
= (void *)opts
+ size
;
4856 for (; addr
< end
; addr
++)
4861 /* If the caller has a smaller struct, let's zero out the end for them
4862 * so we don't accidentally use bits of it that they didn't know about
4865 if (size
< sizeof(*opts
)) {
4866 valid_opts
= malloc(sizeof(*opts
));
4870 memset(valid_opts
, 0, sizeof(*opts
));
4871 memcpy(valid_opts
, opts
, size
);
4875 case MIGRATE_PRE_DUMP
:
4876 if (!do_lxcapi_is_running(c
)) {
4877 ERROR("container is not running");
4881 ret
= !__criu_pre_dump(c
, valid_opts
);
4884 if (!do_lxcapi_is_running(c
)) {
4885 ERROR("container is not running");
4889 ret
= !__criu_dump(c
, valid_opts
);
4891 case MIGRATE_RESTORE
:
4892 if (do_lxcapi_is_running(c
)) {
4893 ERROR("container is already running");
4897 ret
= !__criu_restore(c
, valid_opts
);
4899 case MIGRATE_FEATURE_CHECK
:
4900 features_to_check
= valid_opts
->features_to_check
;
4901 ret
= !__criu_check_feature(&features_to_check
);
4903 /* Something went wrong. Let's let the caller
4904 * know which feature checks failed. */
4905 valid_opts
->features_to_check
= features_to_check
;
4909 ERROR("invalid migrate command %u", cmd
);
4914 if (size
< sizeof(*opts
))
4920 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4922 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4924 struct migrate_opts opts
;
4926 memset(&opts
, 0, sizeof(opts
));
4928 opts
.directory
= directory
;
4930 opts
.verbose
= verbose
;
4932 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4935 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4937 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4939 struct migrate_opts opts
;
4941 memset(&opts
, 0, sizeof(opts
));
4943 opts
.directory
= directory
;
4944 opts
.verbose
= verbose
;
4946 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4949 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4951 /* @st_mode is the st_mode field of the stat(source) return struct */
4952 static int create_mount_target(const char *dest
, mode_t st_mode
)
4954 char *dirdup
, *destdirname
;
4957 dirdup
= strdup(dest
);
4959 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4962 destdirname
= dirname(dirdup
);
4964 ret
= mkdir_p(destdirname
, 0755);
4966 SYSERROR("Failed to create \"%s\"", destdirname
);
4974 if (S_ISDIR(st_mode
))
4975 ret
= mkdir(dest
, 0000);
4977 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4980 TRACE("Created mount target \"%s\"", dest
);
4981 else if (ret
< 0 && errno
!= EEXIST
) {
4982 SYSERROR("Failed to create mount target \"%s\"", dest
);
4989 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4990 const char *target
, const char *filesystemtype
,
4991 unsigned long mountflags
, const void *data
,
4992 struct lxc_mount
*mnt
)
4995 char template[PATH_MAX
], path
[PATH_MAX
];
4996 pid_t pid
, init_pid
;
4999 int ret
= -1, fd
= -EBADF
;
5001 if (!c
|| !c
->lxc_conf
) {
5002 ERROR("Container or configuration is NULL");
5006 if (!c
->lxc_conf
->shmount
.path_host
) {
5007 ERROR("Host path to shared mountpoint must be specified in the config\n");
5011 ret
= strnprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5013 SYSERROR("Error writing shmounts tempdir name");
5017 /* Create a temporary file / dir under the shared mountpoint */
5018 if (!source
|| strequal(source
, "")) {
5019 /* If source is not specified, maybe we want to mount a filesystem? */
5020 sb
.st_mode
= S_IFDIR
;
5022 ret
= stat(source
, &sb
);
5024 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5029 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5031 sret
= mkdtemp(template);
5033 SYSERROR("Could not create shmounts temporary dir");
5037 fd
= lxc_make_tmpfile(template, false);
5039 SYSERROR("Could not create shmounts temporary file");
5047 SYSERROR("Could not fork");
5053 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5055 SYSERROR("Failed to mount onto \"%s\"", template);
5056 _exit(EXIT_FAILURE
);
5058 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5060 init_pid
= do_lxcapi_init_pid(c
);
5062 ERROR("Failed to obtain container's init pid");
5063 _exit(EXIT_FAILURE
);
5066 /* Enter the container namespaces */
5067 if (!list_empty(&c
->lxc_conf
->id_map
)) {
5068 if (!switch_to_ns(init_pid
, "user")) {
5069 ERROR("Failed to enter user namespace");
5070 _exit(EXIT_FAILURE
);
5073 if (!lxc_switch_uid_gid(0, 0))
5074 _exit(EXIT_FAILURE
);
5077 if (!switch_to_ns(init_pid
, "mnt")) {
5078 ERROR("Failed to enter mount namespace");
5079 _exit(EXIT_FAILURE
);
5082 ret
= create_mount_target(target
, sb
.st_mode
);
5084 _exit(EXIT_FAILURE
);
5086 suff
= strrchr(template, '/');
5088 goto cleanup_target_in_child
;
5090 ret
= strnprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5092 SYSERROR("Error writing container mountpoint name");
5093 goto cleanup_target_in_child
;
5096 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5098 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5099 goto cleanup_target_in_child
;
5101 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5103 _exit(EXIT_SUCCESS
);
5105 cleanup_target_in_child
:
5106 (void)remove(target
);
5107 _exit(EXIT_FAILURE
);
5110 ret
= wait_for_pid(pid
);
5112 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5116 if (umount2(template, MNT_DETACH
))
5117 SYSWARN("Failed to remove temporary mount \"%s\"", template);
5120 (void)rmdir(template);
5122 (void)unlink(template);
5131 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5132 unsigned long, const void *, struct lxc_mount
*)
5134 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5135 unsigned long flags
, struct lxc_mount
*mnt
)
5137 pid_t pid
, init_pid
;
5140 if (!c
|| !c
->lxc_conf
) {
5141 ERROR("Container or configuration is NULL");
5148 SYSERROR("Could not fork");
5153 init_pid
= do_lxcapi_init_pid(c
);
5155 ERROR("Failed to obtain container's init pid");
5156 _exit(EXIT_FAILURE
);
5159 /* Enter the container namespaces */
5160 if (!list_empty(&c
->lxc_conf
->id_map
)) {
5161 if (!switch_to_ns(init_pid
, "user")) {
5162 ERROR("Failed to enter user namespace");
5163 _exit(EXIT_FAILURE
);
5167 if (!switch_to_ns(init_pid
, "mnt")) {
5168 ERROR("Failed to enter mount namespace");
5169 _exit(EXIT_FAILURE
);
5172 /* Do the unmount */
5173 ret
= umount2(target
, flags
);
5175 SYSERROR("Failed to umount \"%s\"", target
);
5176 _exit(EXIT_FAILURE
);
5179 _exit(EXIT_SUCCESS
);
5182 ret
= wait_for_pid(pid
);
5184 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5191 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5193 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5202 current_config
= c
->lxc_conf
;
5205 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5209 ERROR("Memory allocation error.");
5215 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5219 current_config
= NULL
;
5223 static int do_lxcapi_seccomp_notify_fd(struct lxc_container
*c
)
5225 if (!c
|| !c
->lxc_conf
)
5226 return ret_set_errno(-1, -EINVAL
);
5228 return lxc_seccomp_get_notify_fd(&c
->lxc_conf
->seccomp
);
5231 WRAP_API(int, lxcapi_seccomp_notify_fd
)
5233 static int do_lxcapi_seccomp_notify_fd_active(struct lxc_container
*c
)
5235 if (!c
|| !c
->lxc_conf
)
5236 return ret_set_errno(-1, -EINVAL
);
5238 return lxc_cmd_get_seccomp_notify_fd(c
->name
, c
->config_path
);
5241 WRAP_API(int, lxcapi_seccomp_notify_fd_active
)
5243 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5245 struct lxc_container
*c
;
5252 c
= malloc(sizeof(*c
));
5254 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5257 memset(c
, 0, sizeof(*c
));
5260 c
->config_path
= strdup(configpath
);
5262 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5263 if (!c
->config_path
) {
5264 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5268 remove_trailing_slashes(c
->config_path
);
5271 c
->name
= malloc(len
+ 1);
5273 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5276 (void)strlcpy(c
->name
, name
, len
+ 1);
5279 c
->slock
= lxc_newlock(c
->config_path
, name
);
5281 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5285 c
->privlock
= lxc_newlock(NULL
, NULL
);
5287 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5291 if (!set_config_filename(c
)) {
5292 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5296 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5297 fprintf(stderr
, "Failed to load config for %s\n", name
);
5301 rc
= ongoing_create(c
);
5303 case LXC_CREATE_INCOMPLETE
:
5304 SYSERROR("Failed to complete container creation for %s", c
->name
);
5305 container_destroy(c
, NULL
);
5306 lxcapi_clear_config(c
);
5308 case LXC_CREATE_ONGOING
:
5309 /* container creation going on */
5311 case LXC_CREATE_FAILED
:
5312 /* container creation failed */
5313 if (errno
!= EACCES
&& errno
!= EPERM
) {
5314 /* insufficient privileges */
5315 SYSERROR("Failed checking for incomplete container %s creation", c
->name
);
5321 c
->daemonize
= true;
5324 /* Assign the member functions. */
5325 c
->is_defined
= lxcapi_is_defined
;
5326 c
->state
= lxcapi_state
;
5327 c
->is_running
= lxcapi_is_running
;
5328 c
->freeze
= lxcapi_freeze
;
5329 c
->unfreeze
= lxcapi_unfreeze
;
5330 c
->console
= lxcapi_console
;
5331 c
->console_getfd
= lxcapi_console_getfd
;
5332 c
->devpts_fd
= lxcapi_devpts_fd
;
5333 c
->init_pid
= lxcapi_init_pid
;
5334 c
->init_pidfd
= lxcapi_init_pidfd
;
5335 c
->load_config
= lxcapi_load_config
;
5336 c
->want_daemonize
= lxcapi_want_daemonize
;
5337 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5338 c
->start
= lxcapi_start
;
5339 c
->startl
= lxcapi_startl
;
5340 c
->stop
= lxcapi_stop
;
5341 c
->config_file_name
= lxcapi_config_file_name
;
5342 c
->wait
= lxcapi_wait
;
5343 c
->set_config_item
= lxcapi_set_config_item
;
5344 c
->destroy
= lxcapi_destroy
;
5345 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5346 c
->rename
= lxcapi_rename
;
5347 c
->save_config
= lxcapi_save_config
;
5348 c
->get_keys
= lxcapi_get_keys
;
5349 c
->create
= lxcapi_create
;
5350 c
->createl
= lxcapi_createl
;
5351 c
->shutdown
= lxcapi_shutdown
;
5352 c
->reboot
= lxcapi_reboot
;
5353 c
->reboot2
= lxcapi_reboot2
;
5354 c
->clear_config
= lxcapi_clear_config
;
5355 c
->clear_config_item
= lxcapi_clear_config_item
;
5356 c
->get_config_item
= lxcapi_get_config_item
;
5357 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5358 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5359 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5360 c
->get_config_path
= lxcapi_get_config_path
;
5361 c
->set_config_path
= lxcapi_set_config_path
;
5362 c
->clone
= lxcapi_clone
;
5363 c
->get_interfaces
= lxcapi_get_interfaces
;
5364 c
->get_ips
= lxcapi_get_ips
;
5365 c
->attach
= lxcapi_attach
;
5366 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5367 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5368 c
->snapshot
= lxcapi_snapshot
;
5369 c
->snapshot_list
= lxcapi_snapshot_list
;
5370 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5371 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5372 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5373 c
->may_control
= lxcapi_may_control
;
5374 c
->add_device_node
= lxcapi_add_device_node
;
5375 c
->remove_device_node
= lxcapi_remove_device_node
;
5376 c
->attach_interface
= lxcapi_attach_interface
;
5377 c
->detach_interface
= lxcapi_detach_interface
;
5378 c
->checkpoint
= lxcapi_checkpoint
;
5379 c
->restore
= lxcapi_restore
;
5380 c
->migrate
= lxcapi_migrate
;
5381 c
->console_log
= lxcapi_console_log
;
5382 c
->mount
= lxcapi_mount
;
5383 c
->umount
= lxcapi_umount
;
5384 c
->seccomp_notify_fd
= lxcapi_seccomp_notify_fd
;
5385 c
->seccomp_notify_fd_active
= lxcapi_seccomp_notify_fd_active
;
5390 lxc_container_free(c
);
5394 int lxc_get_wait_states(const char **states
)
5399 for (i
=0; i
<MAX_STATE
; i
++)
5400 states
[i
] = lxc_state2str(i
);
5406 * These next two could probably be done smarter with reusing a common function
5407 * with different iterators and tests...
5409 int list_defined_containers(const char *lxcpath
, char ***names
,
5410 struct lxc_container
***cret
)
5412 __do_closedir
DIR *dir
= NULL
;
5413 size_t array_len
= 0, name_array_len
= 0, ct_array_len
= 0;
5414 struct dirent
*direntp
;
5415 struct lxc_container
*c
;
5418 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5420 dir
= opendir(lxcpath
);
5422 SYSERROR("opendir on lxcpath");
5432 while ((direntp
= readdir(dir
))) {
5433 /* Ignore '.', '..' and any hidden directory. */
5434 if (strnequal(direntp
->d_name
, ".", 1))
5437 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5441 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5443 INFO("Container %s:%s has a config but could not be loaded",
5444 lxcpath
, direntp
->d_name
);
5448 if (!do_lxcapi_is_defined(c
)) {
5449 INFO("Container %s:%s has a config but is not defined",
5450 lxcpath
, direntp
->d_name
);
5452 lxc_container_put(c
);
5458 if (!add_to_array(names
, direntp
->d_name
, array_len
))
5464 if (!add_to_clist(cret
, c
, array_len
, true)) {
5465 lxc_container_put(c
);
5477 if (names
&& *names
) {
5478 for (size_t i
= 0; i
< name_array_len
; i
++)
5483 if (cret
&& *cret
) {
5484 for (size_t i
= 0; i
< ct_array_len
; i
++)
5485 lxc_container_put((*cret
)[i
]);
5492 int list_active_containers(const char *lxcpath
, char ***nret
,
5493 struct lxc_container
***cret
)
5495 __do_free
char *line
= NULL
;
5496 __do_fclose
FILE *f
= NULL
;
5497 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5499 char **ct_name
= NULL
;
5501 struct lxc_container
*c
= NULL
;
5505 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5506 lxcpath_len
= strlen(lxcpath
);
5514 f
= fopen("/proc/net/unix", "re");
5518 while (getline(&line
, &len
, f
) != -1) {
5519 char *p
= strrchr(line
, ' '), *p2
;
5530 if (strnequal(p
, lxcpath
, lxcpath_len
)) {
5532 } else if (strnequal(p
, "lxc/", 4)) {
5542 /* Now p is the start of lxc_name. */
5543 p2
= strchr(p
, '/');
5544 if (!p2
|| !strnequal(p2
, "/command", 8))
5549 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5553 if (!strnequal(lxcpath
, recvpath
, lxcpath_len
)) {
5559 p
= lxc_cmd_get_name(p
);
5564 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5570 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5573 goto free_cret_list
;
5584 c
= lxc_container_new(p
, lxcpath
);
5586 INFO("Container %s:%s is running but could not be loaded", lxcpath
, p
);
5590 goto free_cret_list
;
5597 * If this is an anonymous container, then is_defined *can*
5598 * return false. So we don't do that check. Count on the
5599 * fact that the command socket exists.
5602 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5603 lxc_container_put(c
);
5604 goto free_cret_list
;
5610 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5612 lxc_container_put(c
);
5613 goto free_cret_list
;
5625 if (cret
&& *cret
) {
5626 for (i
= 0; i
< cret_cnt
; i
++)
5627 lxc_container_put((*cret
)[i
]);
5633 for (i
= 0; i
< ct_name_cnt
; i
++)
5642 int list_all_containers(const char *lxcpath
, char ***nret
,
5643 struct lxc_container
***cret
)
5645 int active_cnt
, ct_cnt
, ct_list_cnt
, ret
;
5646 char **active_name
= NULL
, **ct_name
= NULL
;
5647 struct lxc_container
**ct_list
= NULL
;
5649 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5653 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5654 if (active_cnt
< 0) {
5660 for (int i
= 0; i
< active_cnt
; i
++) {
5661 if (array_contains(&ct_name
, active_name
[i
], ct_cnt
))
5664 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
))
5665 goto free_active_name
;
5672 for (int i
= 0; i
< ct_cnt
; i
++) {
5673 __put_lxc_container
struct lxc_container
*c
= NULL
;
5675 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5677 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5681 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false))
5691 for (int i
= 0; i
< active_cnt
; i
++)
5692 free(active_name
[i
]);
5698 for (int i
= 0; i
< ct_cnt
; i
++)
5706 for (int i
= 0; i
< ct_list_cnt
; i
++)
5707 lxc_container_put(ct_list
[i
]);
5711 for (int i
= 0; i
< active_cnt
; i
++)
5712 free(active_name
[i
]);
5716 for (int i
= 0; i
< ct_cnt
; i
++)
5723 bool lxc_config_item_is_supported(const char *key
)
5725 return !!lxc_get_config_exact(key
);
5728 bool lxc_has_api_extension(const char *extension
)
5730 /* The NULL API extension is always present. :) */
5734 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5735 if (strequal(api_extensions
[i
], extension
))