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>
28 #include "netns_ifaddrs.h"
30 #include "api_extensions.h"
35 #include "commands_utils.h"
39 #include "confile_utils.h"
42 #include "initutils.h"
45 #include "lxccontainer.h"
47 #include "memory_utils.h"
49 #include "namespace.h"
52 #include "process_utils.h"
56 #include "storage/btrfs.h"
57 #include "storage/overlay.h"
58 #include "storage_utils.h"
60 #include "syscall_wrappers.h"
66 #include <openssl/evp.h>
71 #include <sys/mkdev.h>
75 #include <../include/lxcmntent.h>
81 #include "include/strlcpy.h"
84 lxc_log_define(lxccontainer
, lxc
);
86 static bool do_lxcapi_destroy(struct lxc_container
*c
);
87 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
88 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
89 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
90 static bool container_destroy(struct lxc_container
*c
,
91 struct lxc_storage
*storage
);
92 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
93 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
94 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
96 static bool config_file_exists(const char *lxcpath
, const char *cname
)
98 __do_free
char *fname
= NULL
;
102 /* $lxcpath + '/' + $cname + '/config' + \0 */
103 len
= strlen(lxcpath
) + 1 + strlen(cname
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
104 fname
= must_realloc(NULL
, len
);
105 ret
= strnprintf(fname
, len
, "%s/%s/%s", lxcpath
, cname
, LXC_CONFIG_FNAME
);
109 return file_exists(fname
);
113 * A few functions to help detect when a container creation failed. If a
114 * container creation was killed partway through, then trying to actually start
115 * that container could harm the host. We detect this by creating a 'partial'
116 * file under the container directory, and keeping an advisory lock. When
117 * container creation completes, we remove that file. When we load or try to
118 * start a container, if we find that file, without a flock, we remove the
122 LXC_CREATE_FAILED
= -1,
123 LXC_CREATE_SUCCESS
= 0,
124 LXC_CREATE_ONGOING
= 1,
125 LXC_CREATE_INCOMPLETE
= 2,
128 static int ongoing_create(struct lxc_container
*c
)
130 __do_close
int fd
= -EBADF
;
131 __do_free
char *path
= NULL
;
132 struct flock lk
= {0};
136 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
137 path
= must_realloc(NULL
, len
);
138 ret
= strnprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
140 return LXC_CREATE_FAILED
;
142 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
145 return LXC_CREATE_FAILED
;
147 return LXC_CREATE_SUCCESS
;
151 lk
.l_whence
= SEEK_SET
;
153 * F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
158 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
159 if (ret
< 0 && errno
== EINVAL
) {
160 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
161 if (ret
< 0 && errno
== EWOULDBLOCK
)
165 /* F_OFD_GETLK will not send us back a pid so don't check it. */
167 /* Create is still ongoing. */
168 return LXC_CREATE_ONGOING
;
170 /* Create completed but partial is still there. */
171 return LXC_CREATE_INCOMPLETE
;
174 static int create_partial(struct lxc_container
*c
)
176 __do_free
char *path
= NULL
;
179 struct flock lk
= {0};
181 /* $lxcpath + '/' + $name + '/partial' + \0 */
182 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
183 path
= must_realloc(NULL
, len
);
184 ret
= strnprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
188 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
193 lk
.l_whence
= SEEK_SET
;
195 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
197 if (errno
== EINVAL
) {
198 ret
= flock(fd
, LOCK_EX
);
203 SYSERROR("Failed to lock partial file %s", path
);
211 static void remove_partial(struct lxc_container
*c
, int fd
)
213 __do_free
char *path
= NULL
;
219 /* $lxcpath + '/' + $name + '/partial' + \0 */
220 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
221 path
= must_realloc(NULL
, len
);
222 ret
= strnprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
228 SYSERROR("Failed to remove partial file %s", path
);
232 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
233 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
234 * container configuration file.
235 * The container_disk_lock also takes the container_mem_lock.
236 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
237 * NOTHING mutexes two independent programs with their own struct
238 * lxc_container for the same c->name, between API calls. For instance,
239 * c->config_read(); c->start(); Between those calls, data on disk
240 * could change (which shouldn't bother the caller unless for instance
241 * the rootfs get moved). c->config_read(); update; c->config_write();
242 * Two such updaters could race. The callers should therefore check their
243 * results. Trying to prevent that would necessarily expose us to deadlocks
244 * due to hung callers. So I prefer to keep the locks only within our own
245 * functions, not across functions.
247 * If you're going to clone while holding a lxccontainer, increment
248 * c->numthreads (under privlock) before forking. When deleting,
249 * decrement numthreads under privlock, then if it hits 0 you can delete.
250 * Do not ever use a lxccontainer whose numthreads you did not bump.
252 static void lxc_container_free(struct lxc_container
*c
)
258 c
->configfile
= NULL
;
260 free(c
->error_string
);
261 c
->error_string
= NULL
;
264 lxc_putlock(c
->slock
);
269 lxc_putlock(c
->privlock
);
277 lxc_conf_free(c
->lxc_conf
);
281 free(c
->config_path
);
282 c
->config_path
= NULL
;
287 /* Consider the following case:
289 * |====================================================================|
290 * | freer | racing get()er |
291 * |====================================================================|
292 * | lxc_container_put() | lxc_container_get() |
293 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
294 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
295 * | \ lxcunlock() | \ |
296 * | \ lxc_container_free() | \ lxclock() returns |
297 * | | \ c->numthreads < 1 -> return 0 |
298 * | \ \ (free stuff) | |
299 * | \ \ sem_destroy(privlock) | |
300 * |_______________________________|____________________________________|
302 * When the get()er checks numthreads the first time, one of the following
304 * 1. freer has set numthreads = 0. get() returns 0
305 * 2. freer is between lxclock and setting numthreads to 0. get()er will
306 * sem_wait on privlock, get lxclock after freer() drops it, then see
307 * numthreads is 0 and exit without touching lxclock again..
308 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
309 * will see --numthreads = 1 and not call lxc_container_free().
312 int lxc_container_get(struct lxc_container
*c
)
317 /* If someone else has already started freeing the container, don't try
318 * to take the lock, which may be invalid.
320 if (c
->numthreads
< 1)
323 if (container_mem_lock(c
))
326 /* Bail without trying to unlock, bc the privlock is now probably in
329 if (c
->numthreads
< 1)
333 container_mem_unlock(c
);
338 int lxc_container_put(struct lxc_container
*c
)
343 if (container_mem_lock(c
))
348 if (c
->numthreads
< 1) {
349 container_mem_unlock(c
);
350 lxc_container_free(c
);
354 container_mem_unlock(c
);
358 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
367 if (container_mem_lock(c
))
373 statret
= stat(c
->configfile
, &statbuf
);
380 container_mem_unlock(c
);
384 #define WRAP_API(rettype, fnname) \
385 static rettype fnname(struct lxc_container *c) \
388 bool reset_config = false; \
390 if (!current_config && c && c->lxc_conf) { \
391 current_config = c->lxc_conf; \
392 reset_config = true; \
395 ret = do_##fnname(c); \
397 current_config = NULL; \
402 #define WRAP_API_1(rettype, fnname, t1) \
403 static rettype fnname(struct lxc_container *c, t1 a1) \
406 bool reset_config = false; \
408 if (!current_config && c && c->lxc_conf) { \
409 current_config = c->lxc_conf; \
410 reset_config = true; \
413 ret = do_##fnname(c, a1); \
415 current_config = NULL; \
420 #define WRAP_API_2(rettype, fnname, t1, t2) \
421 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
424 bool reset_config = false; \
426 if (!current_config && c && c->lxc_conf) { \
427 current_config = c->lxc_conf; \
428 reset_config = true; \
431 ret = do_##fnname(c, a1, a2); \
433 current_config = NULL; \
438 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
439 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
442 bool reset_config = false; \
444 if (!current_config && c && c->lxc_conf) { \
445 current_config = c->lxc_conf; \
446 reset_config = true; \
449 ret = do_##fnname(c, a1, a2, a3); \
451 current_config = NULL; \
456 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
457 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
458 t4 a4, t5 a5, t6 a6) \
461 bool reset_config = false; \
463 if (!current_config && c && c->lxc_conf) { \
464 current_config = c->lxc_conf; \
465 reset_config = true; \
468 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
470 current_config = NULL; \
475 WRAP_API(bool, lxcapi_is_defined
)
477 static const char *do_lxcapi_state(struct lxc_container
*c
)
484 s
= lxc_getstate(c
->name
, c
->config_path
);
485 return lxc_state2str(s
);
488 WRAP_API(const char *, lxcapi_state
)
490 static bool is_stopped(struct lxc_container
*c
)
494 s
= lxc_getstate(c
->name
, c
->config_path
);
495 return (s
== STOPPED
);
498 static bool do_lxcapi_is_running(struct lxc_container
*c
)
503 return !is_stopped(c
);
506 WRAP_API(bool, lxcapi_is_running
)
508 static bool do_lxcapi_freeze(struct lxc_container
*c
)
513 if (!c
|| !c
->lxc_conf
)
516 s
= lxc_getstate(c
->name
, c
->config_path
);
518 ret
= cgroup_freeze(c
->name
, c
->config_path
, -1);
519 if (ret
== -ENOCGROUP2
)
520 ret
= lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
);
526 WRAP_API(bool, lxcapi_freeze
)
528 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
533 if (!c
|| !c
->lxc_conf
)
536 s
= lxc_getstate(c
->name
, c
->config_path
);
538 ret
= cgroup_unfreeze(c
->name
, c
->config_path
, -1);
539 if (ret
== -ENOCGROUP2
)
540 ret
= lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
);
547 WRAP_API(bool, lxcapi_unfreeze
)
549 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *ptxfd
)
554 return lxc_terminal_getfd(c
, ttynum
, ptxfd
);
557 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
559 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
560 int stdoutfd
, int stderrfd
, int escape
)
567 current_config
= c
->lxc_conf
;
568 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
569 current_config
= NULL
;
574 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
581 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
584 NOTICE("The console log is empty");
585 else if (ret
== -EFAULT
)
586 NOTICE("The container does not keep a console log");
587 else if (ret
== -ENOENT
)
588 NOTICE("The container does not keep a console log file");
589 else if (ret
== -EIO
)
590 NOTICE("Failed to write console log to log file");
592 ERROR("Failed to retrieve console log");
598 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
600 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
605 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
608 WRAP_API(pid_t
, lxcapi_init_pid
)
610 static int do_lxcapi_init_pidfd(struct lxc_container
*c
)
613 return ret_errno(EBADF
);
615 return lxc_cmd_get_init_pidfd(c
->name
, c
->config_path
);
618 WRAP_API(int, lxcapi_init_pidfd
)
620 static int do_lxcapi_devpts_fd(struct lxc_container
*c
)
623 return ret_errno(EBADF
);
625 return lxc_cmd_get_devpts_fd(c
->name
, c
->config_path
);
628 WRAP_API(int, lxcapi_devpts_fd
)
630 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
633 c
->lxc_conf
= lxc_conf_init();
638 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
641 c
->lxc_conf
->name
= c
->name
;
645 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
649 bool need_disklock
= false, ret
= false;
654 fname
= c
->configfile
;
662 /* If we're reading something other than the container's config, we only
663 * need to lock the in-memory container. If loading the container's
664 * config file, take the disk lock.
666 if (strequal(fname
, c
->configfile
))
667 need_disklock
= true;
670 lret
= container_disk_lock(c
);
672 lret
= container_mem_lock(c
);
676 ret
= load_config_locked(c
, fname
);
679 container_disk_unlock(c
);
681 container_mem_unlock(c
);
686 WRAP_API_1(bool, lxcapi_load_config
, const char *)
688 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
690 if (!c
|| !c
->lxc_conf
)
693 if (container_mem_lock(c
))
696 c
->daemonize
= state
;
698 container_mem_unlock(c
);
703 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
705 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
707 if (!c
|| !c
->lxc_conf
)
710 if (container_mem_lock(c
))
713 c
->lxc_conf
->close_all_fds
= state
;
715 container_mem_unlock(c
);
720 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
722 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
730 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
734 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
736 static bool am_single_threaded(void)
738 __do_closedir
DIR *dir
= NULL
;
739 struct dirent
*direntp
;
742 dir
= opendir("/proc/self/task");
746 while ((direntp
= readdir(dir
))) {
747 if (strequal(direntp
->d_name
, "."))
750 if (strequal(direntp
->d_name
, ".."))
761 static void push_arg(char ***argp
, char *arg
, int *nargs
)
766 copy
= must_copy_string(arg
);
769 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
778 static char **split_init_cmd(const char *incmd
)
780 __do_free
char *copy
= NULL
;
788 copy
= must_copy_string(incmd
);
791 argv
= malloc(sizeof(char *));
795 lxc_iterate_parts (p
, copy
, " ")
796 push_arg(&argv
, p
, &nargs
);
806 static void free_init_cmd(char **argv
)
819 static int lxc_rcv_status(int state_socket
)
825 /* Receive container state. */
826 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
831 TRACE("Caught EINTR; retrying");
838 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
842 /* The first child is going to fork() again and then exits. So we reap
843 * the first child here.
845 ret
= wait_for_pid(pid
);
847 DEBUG("Failed waiting on first child %d", pid
);
849 DEBUG("First child %d exited", pid
);
851 /* Close write end of the socket pair. */
852 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
854 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
856 /* Close read end of the socket pair. */
857 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
860 SYSERROR("Failed to receive the container state");
864 /* If we receive anything else then running we know that the container
867 if (state
!= RUNNING
) {
868 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
869 lxc_state2str(state
));
873 TRACE("Container is in \"RUNNING\" state");
877 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
880 struct lxc_handler
*handler
;
881 struct lxc_conf
*conf
;
882 char *default_args
[] = {
886 char **init_cmd
= NULL
;
888 /* container does exist */
892 /* If anything fails before we set error_num, we want an error in there.
896 /* Container has not been setup. */
900 ret
= ongoing_create(c
);
902 case LXC_CREATE_FAILED
:
903 ERROR("Failed checking for incomplete container creation");
905 case LXC_CREATE_ONGOING
:
906 ERROR("Ongoing container creation detected");
908 case LXC_CREATE_INCOMPLETE
:
909 ERROR("Failed to create container");
910 do_lxcapi_destroy(c
);
914 if (container_mem_lock(c
))
919 /* initialize handler */
920 handler
= lxc_init_handler(NULL
, c
->name
, conf
, c
->config_path
, c
->daemonize
);
922 container_mem_unlock(c
);
927 if (useinit
&& conf
->execute_cmd
)
928 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
930 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
933 /* ... otherwise use default_args. */
936 ERROR("No valid init detected");
937 lxc_put_handler(handler
);
943 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
944 * here to protect the on disk container? We don't want to exclude
945 * things like lxc_info while the container is running.
950 pid_t pid_first
, pid_second
;
954 free_init_cmd(init_cmd
);
955 lxc_put_handler(handler
);
960 if (pid_first
!= 0) {
961 /* Set to NULL because we don't want father unlink
962 * the PID file, child will do the free and unlink.
966 /* Wait for container to tell us whether it started
969 started
= wait_on_daemonized_start(handler
, pid_first
);
971 free_init_cmd(init_cmd
);
972 lxc_put_handler(handler
);
978 /* We don't really care if this doesn't print all the
979 * characters. All that it means is that the proctitle will be
980 * ugly. Similarly, we also don't care if setproctitle() fails.
982 ret
= strnprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
984 ret
= setproctitle(title
);
986 INFO("Failed to set process title to %s", title
);
988 INFO("Set process title to %s", title
);
991 /* We fork() a second time to be reparented to init. Like
992 * POSIX's daemon() function we change to "/" and redirect
993 * std{in,out,err} to /dev/null.
996 if (pid_second
< 0) {
997 SYSERROR("Failed to fork first child process");
1002 if (pid_second
!= 0) {
1003 free_init_cmd(init_cmd
);
1004 lxc_put_handler(handler
);
1005 _exit(EXIT_SUCCESS
);
1010 /* change to / directory */
1013 SYSERROR("Failed to change to \"/\" directory");
1014 _exit(EXIT_FAILURE
);
1017 ret
= inherit_fds(handler
, true);
1019 _exit(EXIT_FAILURE
);
1021 /* redirect std{in,out,err} to /dev/null */
1022 ret
= null_stdfds();
1024 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1025 _exit(EXIT_FAILURE
);
1028 /* become session leader */
1031 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1032 } else if (!am_single_threaded()) {
1033 ERROR("Cannot start non-daemonized container when threaded");
1034 free_init_cmd(init_cmd
);
1035 lxc_put_handler(handler
);
1039 /* We need to write PID file after daemonize, so we always write the
1044 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1046 w
= strnprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1048 free_init_cmd(init_cmd
);
1049 lxc_put_handler(handler
);
1051 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1054 _exit(EXIT_FAILURE
);
1059 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1061 free_init_cmd(init_cmd
);
1062 lxc_put_handler(handler
);
1064 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1067 _exit(EXIT_FAILURE
);
1073 conf
->reboot
= REBOOT_NONE
;
1075 /* Unshare the mount namespace if requested */
1076 if (conf
->monitor_unshare
) {
1077 ret
= unshare(CLONE_NEWNS
);
1079 SYSERROR("Failed to unshare mount namespace");
1080 lxc_put_handler(handler
);
1085 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1087 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
1088 lxc_put_handler(handler
);
1095 if (conf
->reboot
== REBOOT_INIT
) {
1096 /* initialize handler */
1097 handler
= lxc_init_handler(handler
, c
->name
, conf
, c
->config_path
, c
->daemonize
);
1104 ret
= inherit_fds(handler
, c
->daemonize
);
1106 lxc_put_handler(handler
);
1112 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1113 c
->daemonize
, &c
->error_num
);
1115 ret
= lxc_start(argv
, handler
, c
->config_path
, c
->daemonize
,
1118 if (conf
->reboot
== REBOOT_REQ
) {
1119 INFO("Container requested reboot");
1120 conf
->reboot
= REBOOT_INIT
;
1130 free_init_cmd(init_cmd
);
1132 if (c
->daemonize
&& ret
!= 0)
1133 _exit(EXIT_FAILURE
);
1134 else if (c
->daemonize
)
1135 _exit(EXIT_SUCCESS
);
1143 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1148 current_config
= c
? c
->lxc_conf
: NULL
;
1149 ret
= do_lxcapi_start(c
, useinit
, argv
);
1150 current_config
= NULL
;
1155 /* Note, there MUST be an ending NULL. */
1156 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1159 char **inargs
= NULL
;
1162 /* container exists */
1166 current_config
= c
->lxc_conf
;
1168 va_start(ap
, useinit
);
1169 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1174 /* pass NULL if no arguments were supplied */
1175 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1181 for (arg
= inargs
; *arg
; arg
++)
1186 current_config
= NULL
;
1191 static bool do_lxcapi_stop(struct lxc_container
*c
)
1198 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1203 WRAP_API(bool, lxcapi_stop
)
1205 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1210 mode_t mask
= umask(0002);
1211 ret
= mkdir(path
, 0770);
1216 if (errno
!= EEXIST
)
1222 if (!list_empty(&conf
->id_map
)) {
1223 ret
= chown_mapped_root(path
, conf
);
1231 /* Create the standard expected container dir. */
1232 static bool create_container_dir(struct lxc_container
*c
)
1234 __do_free
char *s
= NULL
;
1238 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1243 ret
= strnprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1247 return do_create_container_dir(s
, c
->lxc_conf
) == 0;
1250 /* do_storage_create: thin wrapper around storage_create(). Like
1251 * storage_create(), it returns a mounted bdev on success, NULL on error.
1253 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1255 struct bdev_specs
*specs
)
1257 __do_free
char *dest
= NULL
;
1260 struct lxc_storage
*bdev
;
1262 /* rootfs.path or lxcpath/lxcname/rootfs */
1263 if (c
->lxc_conf
->rootfs
.path
&&
1264 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1265 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1266 len
= strlen(rpath
) + 1;
1267 dest
= must_realloc(NULL
, len
);
1268 ret
= strnprintf(dest
, len
, "%s", rpath
);
1270 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1271 len
= strlen(c
->name
) + 1 + strlen(lxcpath
) + 1 + strlen(LXC_ROOTFS_DNAME
) + 1;
1272 dest
= must_realloc(NULL
, len
);
1273 ret
= strnprintf(dest
, len
, "%s/%s/%s", lxcpath
, c
->name
, LXC_ROOTFS_DNAME
);
1278 bdev
= storage_create(dest
, type
, c
->name
, specs
, c
->lxc_conf
);
1280 ERROR("Failed to create \"%s\" storage", type
);
1284 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1285 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1290 /* If we are not root, chown the rootfs dir to root in the target user
1293 if (am_guest_unpriv() || !list_empty(&c
->lxc_conf
->id_map
)) {
1294 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1296 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1297 suggest_default_idmap();
1306 /* Strip path and return name of file for argv[0] passed to execvp */
1307 static char *lxctemplatefilename(char *tpath
)
1311 p
= tpath
+ strlen(tpath
) - 1;
1312 while ( (p
-1) >= tpath
&& *(p
-1) != '/')
1318 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1319 bool need_null_stdfds
, char *const argv
[])
1329 SYSERROR("Failed to fork task for container creation template");
1333 if (pid
== 0) { /* child */
1335 char *namearg
, *patharg
, *rootfsarg
;
1338 struct lxc_storage
*bdev
= NULL
;
1339 struct lxc_conf
*conf
= c
->lxc_conf
;
1342 if (need_null_stdfds
) {
1343 ret
= null_stdfds();
1345 _exit(EXIT_FAILURE
);
1348 ret
= lxc_storage_prepare(conf
);
1350 ERROR("Failed to initialize storage");
1351 _exit(EXIT_FAILURE
);
1353 bdev
= conf
->rootfs
.storage
;
1357 ret
= unshare(CLONE_NEWNS
);
1359 ERROR("Failed to unshare CLONE_NEWNS");
1360 _exit(EXIT_FAILURE
);
1363 if (detect_shared_rootfs() && mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
))
1364 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
1367 if (!strequal(bdev
->type
, "dir") && !strequal(bdev
->type
, "btrfs")) {
1369 ERROR("Unprivileged users can only create "
1370 "btrfs and directory-backed containers");
1371 _exit(EXIT_FAILURE
);
1374 if (strequal(bdev
->type
, "overlay") ||
1375 strequal(bdev
->type
, "overlayfs")) {
1376 /* If we create an overlay container we need to
1377 * rsync the contents into
1378 * <container-path>/<container-name>/rootfs.
1379 * However, the overlay mount function will
1381 * <container-path>/<container-name>/delta0
1383 * <container-path>/<container-name>/rootfs
1384 * which means we would rsync the rootfs into
1385 * the delta directory. That doesn't make sense
1386 * since the delta directory only exists to
1387 * record the differences to
1388 * <container-path>/<container-name>/rootfs. So
1389 * let's simply bind-mount here and then rsync
1391 * <container-path>/<container-name>/rootfs.
1395 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1397 ERROR("Failed to get rootfs");
1398 _exit(EXIT_FAILURE
);
1401 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1403 ERROR("Failed to mount rootfs");
1404 _exit(EXIT_FAILURE
);
1407 ret
= bdev
->ops
->mount(bdev
);
1409 ERROR("Failed to mount rootfs");
1410 _exit(EXIT_FAILURE
);
1413 } else { /* TODO come up with a better way here! */
1416 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1417 bdev
->dest
= strdup(src
);
1420 /* Create our new array, pre-pend the template name and base
1424 for (nargs
= 0; argv
[nargs
]; nargs
++)
1427 /* template, path, rootfs and name args */
1430 newargv
= malloc(nargs
* sizeof(*newargv
));
1432 _exit(EXIT_FAILURE
);
1433 newargv
[0] = lxctemplatefilename(tpath
);
1436 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1437 patharg
= malloc(len
);
1439 _exit(EXIT_FAILURE
);
1441 ret
= strnprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1443 _exit(EXIT_FAILURE
);
1444 newargv
[1] = patharg
;
1447 len
= strlen("--name=") + strlen(c
->name
) + 1;
1448 namearg
= malloc(len
);
1450 _exit(EXIT_FAILURE
);
1452 ret
= strnprintf(namearg
, len
, "--name=%s", c
->name
);
1454 _exit(EXIT_FAILURE
);
1455 newargv
[2] = namearg
;
1458 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1459 rootfsarg
= malloc(len
);
1461 _exit(EXIT_FAILURE
);
1463 ret
= strnprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1465 _exit(EXIT_FAILURE
);
1466 newargv
[3] = rootfsarg
;
1468 /* add passed-in args */
1470 for (i
= 4; i
< nargs
; i
++)
1471 newargv
[i
] = argv
[i
- 4];
1473 /* add trailing NULL */
1475 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1477 _exit(EXIT_FAILURE
);
1478 newargv
[nargs
- 1] = NULL
;
1480 /* If we're running the template in a mapped userns, then we
1481 * prepend the template command with: lxc-usernsexec <-m map1>
1482 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1483 * the mapped uid for our geteuid()
1485 if (!list_empty(&conf
->id_map
)) {
1486 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1488 char txtuid
[20], txtgid
[20];
1492 n2
= malloc(n2args
* sizeof(*n2
));
1494 _exit(EXIT_FAILURE
);
1497 tpath
= "lxc-usernsexec";
1498 n2
[0] = "lxc-usernsexec";
1500 list_for_each_entry(map
, &conf
->id_map
, head
) {
1502 n2
= realloc(n2
, n2args
* sizeof(char *));
1504 _exit(EXIT_FAILURE
);
1506 n2
[n2args
- 2] = "-m";
1507 n2
[n2args
- 1] = malloc(200);
1508 if (!n2
[n2args
- 1])
1509 _exit(EXIT_FAILURE
);
1511 ret
= strnprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1512 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1513 map
->nsid
, map
->hostid
, map
->range
);
1515 _exit(EXIT_FAILURE
);
1518 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1519 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1521 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1523 _exit(EXIT_FAILURE
);
1525 if (hostuid_mapped
< 0) {
1526 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1527 n2
[n2args
++] = "-m";
1528 if (hostuid_mapped
< 0) {
1529 ERROR("Failed to find free uid to map");
1530 _exit(EXIT_FAILURE
);
1533 n2
[n2args
++] = malloc(200);
1534 if (!n2
[n2args
- 1]) {
1535 SYSERROR("out of memory");
1536 _exit(EXIT_FAILURE
);
1539 ret
= strnprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1540 hostuid_mapped
, geteuid());
1542 _exit(EXIT_FAILURE
);
1545 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1546 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1548 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1550 _exit(EXIT_FAILURE
);
1552 if (hostgid_mapped
< 0) {
1553 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1554 n2
[n2args
++] = "-m";
1555 if (hostgid_mapped
< 0) {
1556 ERROR("Failed to find free gid to map");
1557 _exit(EXIT_FAILURE
);
1560 n2
[n2args
++] = malloc(200);
1561 if (!n2
[n2args
- 1]) {
1562 SYSERROR("out of memory");
1563 _exit(EXIT_FAILURE
);
1566 ret
= strnprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1567 hostgid_mapped
, getegid());
1569 _exit(EXIT_FAILURE
);
1572 n2
[n2args
++] = "--";
1574 for (i
= 0; i
< nargs
; i
++)
1575 n2
[i
+ n2args
] = newargv
[i
];
1578 /* Finally add "--mapped-uid $uid" to tell template what
1579 * to chown cached images to.
1582 n2
= realloc(n2
, n2args
* sizeof(char *));
1584 _exit(EXIT_FAILURE
);
1586 /* note n2[n2args-1] is NULL */
1587 n2
[n2args
- 5] = "--mapped-uid";
1589 ret
= strnprintf(txtuid
, 20, "%d", hostuid_mapped
);
1593 _exit(EXIT_FAILURE
);
1596 n2
[n2args
- 4] = txtuid
;
1597 n2
[n2args
- 3] = "--mapped-gid";
1599 ret
= strnprintf(txtgid
, 20, "%d", hostgid_mapped
);
1603 _exit(EXIT_FAILURE
);
1606 n2
[n2args
- 2] = txtgid
;
1607 n2
[n2args
- 1] = NULL
;
1612 execvp(tpath
, newargv
);
1613 SYSERROR("Failed to execute template %s", tpath
);
1614 _exit(EXIT_FAILURE
);
1617 ret
= wait_for_pid(pid
);
1619 ERROR("Failed to create container from template");
1626 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1634 unsigned int md_len
= 0;
1635 unsigned char md_value
[EVP_MAX_MD_SIZE
];
1639 f
= fopen(path
, "re");
1643 ret
= fseek(f
, 0, SEEK_END
);
1652 ret
= fseek(f
, 0, SEEK_SET
);
1656 ret
= fseek(f
, 0, SEEK_SET
);
1661 contents
= malloc(flen
+ 1);
1665 len
= fread(contents
, 1, flen
, f
);
1667 goto out_free_contents
;
1669 contents
[flen
] = '\0';
1674 goto out_free_contents
;
1677 tpath
= get_template_path(t
);
1679 ERROR("Invalid template \"%s\" specified", t
);
1680 goto out_free_contents
;
1683 ret
= sha1sum_file(tpath
, md_value
, &md_len
);
1685 ERROR("Failed to get sha1sum of %s", tpath
);
1687 goto out_free_contents
;
1692 f
= fopen(path
, "we");
1694 SYSERROR("Reopening config for writing");
1699 fprintf(f
, "# Template used to create this container: %s\n", t
);
1701 fprintf(f
, "# Parameters passed to the template:");
1703 fprintf(f
, " %s", *argv
);
1710 fprintf(f
, "# Template script checksum (SHA-1): ");
1711 for (size_t i
= 0; i
< md_len
; i
++)
1712 fprintf(f
, "%02x", md_value
[i
]);
1715 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1716 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1717 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1718 fprintf(f
, "# (Be aware this has security implications)\n\n");
1719 nbytes
= fwrite(contents
, 1, flen
, f
);
1720 if (nbytes
< 0 || nbytes
!= flen
) {
1721 SYSERROR("Writing original contents");
1741 SYSERROR("Error prepending header");
1748 static void lxcapi_clear_config(struct lxc_container
*c
)
1750 if (!c
|| !c
->lxc_conf
)
1753 lxc_conf_free(c
->lxc_conf
);
1757 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1761 * create a container with the given parameters.
1762 * @c: container to be created. It has the lxcpath, name, and a starting
1763 * configuration already set
1764 * @t: the template to execute to instantiate the root filesystem and
1765 * adjust the configuration.
1766 * @bdevtype: backing store type to use. If NULL, dir will be used.
1767 * @specs: additional parameters for the backing store, i.e. LVM vg to
1770 * @argv: the arguments to pass to the template, terminated by NULL. If no
1771 * arguments, you can just pass NULL.
1773 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1774 const char *bdevtype
, struct bdev_specs
*specs
,
1775 int flags
, char *const argv
[])
1777 __do_free
char *path_template
= NULL
;
1781 bool ret
= false, rootfs_managed
= true;
1787 path_template
= get_template_path(t
);
1789 return syserror_set(ENOENT
, "Template \"%s\" not found", t
);
1792 /* If a template is passed in, and the rootfs already is defined in the
1793 * container config and exists, then the caller is trying to create an
1794 * existing container. Return an error, but do NOT delete the container.
1796 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1797 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && path_template
)
1798 return syserror_set(EEXIST
, "Container \"%s\" already exists in \"%s\"", c
->name
, c
->config_path
);
1801 !do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config")))
1802 return syserror_set(EINVAL
, "Failed to load default configuration file %s",
1803 lxc_global_config_value("lxc.default_config"));
1805 if (!create_container_dir(c
))
1806 return syserror_set(EINVAL
, "Failed to create container %s", c
->name
);
1808 if (c
->lxc_conf
->rootfs
.path
)
1809 rootfs_managed
= false;
1811 /* If both template and rootfs.path are set, template is setup as
1812 * rootfs.path. The container is already created if we have a config and
1813 * rootfs.path is accessible
1815 if (!c
->lxc_conf
->rootfs
.path
&& !path_template
) {
1816 /* No template passed in and rootfs does not exist. */
1817 if (!c
->save_config(c
, NULL
)) {
1818 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1825 /* Rootfs passed into configuration, but does not exist. */
1826 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1829 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !path_template
) {
1830 /* Rootfs already existed, user just wanted to save the loaded
1833 if (!c
->save_config(c
, NULL
))
1834 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1840 /* Mark that this container is being created */
1841 partial_fd
= create_partial(c
);
1845 /* No need to get disk lock bc we have the partial lock. */
1849 /* Create the storage.
1850 * Note we can't do this in the same task as we use to execute the
1851 * template because of the way zfs works.
1852 * After you 'zfs create', zfs mounts the fs only in the initial
1857 SYSERROR("Failed to fork task for container creation template");
1861 if (pid
== 0) { /* child */
1862 struct lxc_storage
*bdev
= NULL
;
1864 bdev
= do_storage_create(c
, bdevtype
, specs
);
1866 ERROR("Failed to create %s storage for %s",
1867 bdevtype
? bdevtype
: "(none)", c
->name
);
1868 _exit(EXIT_FAILURE
);
1871 /* Save config file again to store the new rootfs location. */
1872 if (!do_lxcapi_save_config(c
, NULL
)) {
1873 ERROR("Failed to save initial config for %s", c
->name
);
1874 /* Parent task won't see the storage driver in the
1875 * config so we delete it.
1877 bdev
->ops
->umount(bdev
);
1878 bdev
->ops
->destroy(bdev
);
1879 _exit(EXIT_FAILURE
);
1882 _exit(EXIT_SUCCESS
);
1885 if (wait_for_pid(pid
) != 0)
1888 /* Reload config to get the rootfs. */
1889 lxc_conf_free(c
->lxc_conf
);
1892 if (!load_config_locked(c
, c
->configfile
))
1895 if (!create_run_template(c
, path_template
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1898 /* Now clear out the lxc_conf we have, reload from the created
1901 do_lxcapi_clear_config(c
);
1904 if (!prepend_lxc_header(c
->configfile
, path_template
, argv
)) {
1905 ERROR("Failed to prepend header to config file");
1910 ret
= load_config_locked(c
, c
->configfile
);
1914 remove_partial(c
, partial_fd
);
1918 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1921 * Ensure that we don't destroy storage we didn't create
1924 if (!rootfs_managed
)
1925 c
->lxc_conf
->rootfs
.managed
= false;
1926 container_destroy(c
, NULL
);
1927 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1933 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1934 const char *bdevtype
, struct bdev_specs
*specs
,
1935 int flags
, char *const argv
[])
1939 current_config
= c
? c
->lxc_conf
: NULL
;
1941 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1942 current_config
= NULL
;
1946 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1948 __do_close
int pidfd
= -EBADF
;
1951 int rebootsignal
= SIGINT
;
1956 if (!do_lxcapi_is_running(c
))
1959 pidfd
= do_lxcapi_init_pidfd(c
);
1961 pid
= do_lxcapi_init_pid(c
);
1966 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1967 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1970 ret
= lxc_raw_pidfd_send_signal(pidfd
, rebootsignal
, NULL
, 0);
1972 ret
= kill(pid
, rebootsignal
);
1974 return log_warn(false, "Failed to send signal %d to pid %d",
1980 WRAP_API(bool, lxcapi_reboot
)
1982 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1984 __do_close
int pidfd
= -EBADF
, state_client_fd
= -EBADF
;
1985 int rebootsignal
= SIGINT
;
1987 lxc_state_t states
[MAX_STATE
] = {0};
1993 if (!do_lxcapi_is_running(c
))
1996 pidfd
= do_lxcapi_init_pidfd(c
);
1998 pid
= do_lxcapi_init_pid(c
);
2003 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2004 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2006 /* Add a new state client before sending the shutdown signal so that we
2007 * don't miss a state.
2010 states
[RUNNING
] = 2;
2011 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2016 if (state_client_fd
< 0)
2022 if (ret
< MAX_STATE
)
2026 /* Send reboot signal to container. */
2028 killret
= lxc_raw_pidfd_send_signal(pidfd
, rebootsignal
, NULL
, 0);
2030 killret
= kill(pid
, rebootsignal
);
2032 return log_warn(false, "Failed to send signal %d to pidfd(%d)/pid(%d)", rebootsignal
, pidfd
, pid
);
2033 TRACE("Sent signal %d to pidfd(%d)/pid(%d)", rebootsignal
, pidfd
, pid
);
2038 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2042 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2049 WRAP_API_1(bool, lxcapi_reboot2
, int)
2051 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2053 __do_close
int pidfd
= -EBADF
, state_client_fd
= -EBADF
;
2054 int haltsignal
= SIGPWR
;
2056 lxc_state_t states
[MAX_STATE
] = {0};
2062 if (!do_lxcapi_is_running(c
))
2065 pidfd
= do_lxcapi_init_pidfd(c
);
2066 pid
= do_lxcapi_init_pid(c
);
2070 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2071 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2072 haltsignal
= c
->lxc_conf
->haltsignal
;
2073 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2074 haltsignal
= (SIGRTMIN
+ 3);
2078 * Add a new state client before sending the shutdown signal so
2079 * that we don't miss a state.
2082 states
[STOPPED
] = 1;
2083 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2088 if (state_client_fd
< 0)
2094 if (ret
< MAX_STATE
)
2099 struct pollfd pidfd_poll
= {
2104 killret
= lxc_raw_pidfd_send_signal(pidfd
, haltsignal
,
2107 return log_warn(false, "Failed to send signal %d to pidfd %d",
2110 TRACE("Sent signal %d to pidfd %d", haltsignal
, pidfd
);
2113 * No need for going through all of the state server
2114 * complications anymore. We can just poll on pidfds. :)
2118 ret
= poll(&pidfd_poll
, 1, timeout
* 1000);
2119 if (ret
< 0 || !(pidfd_poll
.revents
& POLLIN
))
2122 TRACE("Pidfd polling detected container exit");
2125 killret
= kill(pid
, haltsignal
);
2127 return log_warn(false, "Failed to send signal %d to pid %d",
2130 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2136 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2140 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2147 WRAP_API_1(bool, lxcapi_shutdown
, int)
2149 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2150 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2159 current_config
= c
->lxc_conf
;
2162 * since we're going to wait for create to finish, I don't think we
2163 * need to get a copy of the arguments.
2165 va_start(ap
, flags
);
2166 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2169 ERROR("Failed to allocate memory");
2173 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2177 current_config
= NULL
;
2181 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2183 if (strequal(key
, "lxc.cgroup"))
2184 return clear_unexp_config_line(conf
, key
, true);
2186 if (strequal(key
, "lxc.network"))
2187 return clear_unexp_config_line(conf
, key
, true);
2189 if (strequal(key
, "lxc.net"))
2190 return clear_unexp_config_line(conf
, key
, true);
2192 /* Clear a network with a specific index. */
2193 if (strnequal(key
, "lxc.net.", 8)) {
2198 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2200 return clear_unexp_config_line(conf
, key
, true);
2203 if (strequal(key
, "lxc.hook"))
2204 return clear_unexp_config_line(conf
, key
, true);
2206 return clear_unexp_config_line(conf
, key
, false);
2209 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2213 struct lxc_config_t
*config
;
2215 if (!c
|| !c
->lxc_conf
)
2218 if (container_mem_lock(c
))
2221 config
= lxc_get_config(key
);
2223 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2225 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2227 container_mem_unlock(c
);
2231 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2233 static inline bool enter_net_ns(struct lxc_container
*c
)
2235 pid_t pid
= do_lxcapi_init_pid(c
);
2240 if ((geteuid() != 0 || (c
->lxc_conf
&& !list_empty(&c
->lxc_conf
->id_map
))) &&
2241 (access("/proc/self/ns/user", F_OK
) == 0))
2242 if (!switch_to_ns(pid
, "user"))
2245 return switch_to_ns(pid
, "net");
2248 /* Used by qsort and bsearch functions for comparing names. */
2249 static inline int string_cmp(char **first
, char **second
)
2251 return strcmp(*first
, *second
);
2254 /* Used by qsort and bsearch functions for comparing container names. */
2255 static inline int container_cmp(struct lxc_container
**first
,
2256 struct lxc_container
**second
)
2258 return strcmp((*first
)->name
, (*second
)->name
);
2261 static bool add_to_array(char ***names
, char *cname
, int pos
)
2263 __do_free
char *dup_cname
= NULL
;
2266 dup_cname
= strdup(cname
);
2270 newnames
= realloc(*names
, (pos
+ 1) * sizeof(char *));
2272 return ret_set_errno(false, ENOMEM
);
2274 newnames
[pos
] = move_ptr(dup_cname
);
2276 /* Sort the array as we will use binary search on it. */
2277 qsort(newnames
, pos
+ 1, sizeof(char *),
2278 (int (*)(const void *, const void *))string_cmp
);
2284 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2287 struct lxc_container
**newlist
;
2289 newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2291 return ret_set_errno(false, ENOMEM
);
2295 /* Sort the array as we will use binary search on it. */
2297 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2298 (int (*)(const void *, const void *))container_cmp
);
2304 static char **get_from_array(char ***names
, char *cname
, int size
)
2309 return bsearch(&cname
, *names
, size
, sizeof(char *),
2310 (int (*)(const void *, const void *))string_cmp
);
2313 static bool array_contains(char ***names
, char *cname
, int size
)
2315 if (get_from_array(names
, cname
, size
))
2321 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2324 int i
, count
= 0, pipefd
[2];
2325 char **interfaces
= NULL
;
2326 char interface
[IFNAMSIZ
];
2328 if (pipe2(pipefd
, O_CLOEXEC
))
2329 return log_error_errno(NULL
, errno
, "Failed to create pipe");
2335 return log_error_errno(NULL
, errno
, "Failed to fork task to get interfaces information");
2339 call_cleaner(netns_freeifaddrs
) struct netns_ifaddrs
*ifaddrs
= NULL
;
2340 struct netns_ifaddrs
*ifa
= NULL
;
2344 /* close the read-end of the pipe */
2347 if (!enter_net_ns(c
)) {
2348 SYSERROR("Failed to enter network namespace");
2352 /* Grab the list of interfaces */
2353 if (netns_getifaddrs(&ifaddrs
, -1, &(bool){false})) {
2354 SYSERROR("Failed to get interfaces list");
2358 /* Iterate through the interfaces */
2359 for (ifa
= ifaddrs
; ifa
!= NULL
;
2360 ifa
= ifa
->ifa_next
) {
2361 nbytes
= lxc_write_nointr(pipefd
[1], ifa
->ifa_name
, IFNAMSIZ
);
2371 /* close the write-end of the pipe, thus sending EOF to the reader */
2376 /* close the write-end of the pipe */
2379 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2380 interface
[IFNAMSIZ
- 1] = '\0';
2382 if (array_contains(&interfaces
, interface
, count
))
2385 if (!add_to_array(&interfaces
, interface
, count
))
2386 ERROR("Failed to add \"%s\" to array", interface
);
2391 if (wait_for_pid(pid
)) {
2392 for (i
= 0; i
< count
; i
++)
2393 free(interfaces
[i
]);
2399 /* close the read-end of the pipe */
2402 /* Append NULL to the array */
2404 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2409 WRAP_API(char **, lxcapi_get_interfaces
)
2411 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2412 const char *family
, int scope
)
2417 char address
[INET6_ADDRSTRLEN
];
2419 char **addresses
= NULL
;
2421 ret
= pipe2(pipefd
, O_CLOEXEC
);
2423 return log_error_errno(NULL
, errno
, "Failed to create pipe");
2427 SYSERROR("Failed to create new process");
2434 call_cleaner(netns_freeifaddrs
) struct netns_ifaddrs
*ifaddrs
= NULL
;
2435 struct netns_ifaddrs
*ifa
= NULL
;
2437 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2438 char *address_ptr
= NULL
;
2439 void *address_ptr_tmp
= NULL
;
2441 /* close the read-end of the pipe */
2444 if (!enter_net_ns(c
)) {
2445 SYSERROR("Failed to attach to network namespace");
2449 /* Grab the list of interfaces */
2450 if (netns_getifaddrs(&ifaddrs
, -1, &(bool){false})) {
2451 SYSERROR("Failed to get interfaces list");
2455 /* Iterate through the interfaces */
2456 for (ifa
= ifaddrs
; ifa
; ifa
= ifa
->ifa_next
) {
2457 if (ifa
->ifa_addr
== NULL
)
2460 #pragma GCC diagnostic push
2461 #pragma GCC diagnostic ignored "-Wcast-align"
2463 if (ifa
->ifa_addr
->sa_family
== AF_INET
) {
2464 if (family
&& !strequal(family
, "inet"))
2467 address_ptr_tmp
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2469 if (family
&& !strequal(family
, "inet6"))
2472 if (((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_scope_id
!= (uint32_t)scope
)
2475 address_ptr_tmp
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2478 #pragma GCC diagnostic pop
2480 if (interface
&& !strequal(interface
, ifa
->ifa_name
))
2482 else if (!interface
&& strequal("lo", ifa
->ifa_name
))
2485 address_ptr
= (char *)inet_ntop(ifa
->ifa_addr
->sa_family
, address_ptr_tmp
,
2486 addressOutputBuffer
,
2487 sizeof(addressOutputBuffer
));
2491 nbytes
= lxc_write_nointr(pipefd
[1], address_ptr
, INET6_ADDRSTRLEN
);
2492 if (nbytes
!= INET6_ADDRSTRLEN
) {
2493 SYSERROR("Failed to send ipv6 address \"%s\"", address_ptr
);
2503 /* close the write-end of the pipe, thus sending EOF to the reader */
2508 /* close the write-end of the pipe */
2511 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2512 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2514 if (!add_to_array(&addresses
, address
, count
))
2515 ERROR("PARENT: add_to_array failed");
2520 if (wait_for_pid(pid
)) {
2521 for (i
= 0; i
< count
; i
++)
2528 /* close the read-end of the pipe */
2531 /* Append NULL to the array */
2533 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2538 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2540 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2543 struct lxc_config_t
*config
;
2545 if (!c
|| !c
->lxc_conf
)
2548 if (container_mem_lock(c
))
2551 config
= lxc_get_config(key
);
2553 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2555 container_mem_unlock(c
);
2559 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2561 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2565 if (!c
|| !c
->lxc_conf
)
2568 if (container_mem_lock(c
))
2571 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2572 container_mem_unlock(c
);
2576 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2578 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2582 /* List all config items. */
2584 return lxc_list_config_items(retv
, inlen
);
2586 if (!c
|| !c
->lxc_conf
)
2589 if (container_mem_lock(c
))
2592 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2593 * This is an intelligent result to show which keys are valid given the
2594 * type of nic it is.
2596 if (strnequal(key
, "lxc.net.", 8))
2597 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2599 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2601 container_mem_unlock(c
);
2605 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2607 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2610 bool ret
= false, need_disklock
= false;
2613 alt_file
= c
->configfile
;
2618 /* If we haven't yet loaded a config, load the stock config. */
2620 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2621 ERROR("Error loading default configuration file %s "
2623 lxc_global_config_value("lxc.default_config"),
2629 if (!create_container_dir(c
))
2632 /* If we're writing to the container's config file, take the disk lock.
2633 * Otherwise just take the memlock to protect the struct lxc_container
2634 * while we're traversing it.
2636 if (strequal(c
->configfile
, alt_file
))
2637 need_disklock
= true;
2640 lret
= container_disk_lock(c
);
2642 lret
= container_mem_lock(c
);
2646 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2647 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2651 lret
= write_config(fd
, c
->lxc_conf
);
2660 container_disk_unlock(c
);
2662 container_mem_unlock(c
);
2667 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2670 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2676 char path
[PATH_MAX
];
2677 char newpath
[PATH_MAX
];
2678 int fd
, ret
, n
= 0, v
= 0;
2680 size_t len
= 0, bytes
= 0;
2682 if (container_disk_lock(c0
))
2685 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2689 ret
= strnprintf(newpath
, sizeof(newpath
), "%s\n%s\n", c
->config_path
, c
->name
);
2693 /* If we find an lxc-snapshot file using the old format only listing the
2694 * number of snapshots we will keep using it. */
2695 f1
= fopen(path
, "re");
2697 n
= fscanf(f1
, "%d", &v
);
2699 if (n
== 1 && v
== 0) {
2702 SYSERROR("Failed to remove \"%s\"", path
);
2710 f1
= fopen(path
, "we");
2714 if (fprintf(f1
, "%d\n", v
) < 0) {
2715 ERROR("Error writing new snapshots value");
2722 SYSERROR("Error writing to or closing snapshots file");
2726 /* Here we know that we have or can use an lxc-snapshot file
2727 * using the new format. */
2729 f1
= fopen(path
, "ae");
2733 if (fprintf(f1
, "%s", newpath
) < 0) {
2734 ERROR("Error writing new snapshots entry");
2737 SYSERROR("Error writing to or closing snapshots file");
2743 SYSERROR("Error writing to or closing snapshots file");
2747 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2750 if (fstat(fd
, &fbuf
) < 0) {
2755 if (fbuf
.st_size
!= 0) {
2756 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2757 if (buf
== MAP_FAILED
) {
2758 SYSERROR("Failed to create mapping %s", path
);
2763 len
= strlen(newpath
);
2764 while ((del
= strstr((char *)buf
, newpath
))) {
2765 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2769 lxc_strmunmap(buf
, fbuf
.st_size
);
2770 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2771 SYSERROR("Failed to truncate file %s", path
);
2780 /* If the lxc-snapshot file is empty, remove it. */
2781 if (stat(path
, &fbuf
) < 0)
2784 if (!fbuf
.st_size
) {
2787 SYSERROR("Failed to remove \"%s\"", path
);
2794 container_disk_unlock(c0
);
2798 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2800 __do_free
char *lxcpath
= NULL
, *lxcname
= NULL
;
2801 __do_fclose
FILE *f
= NULL
;
2802 size_t pathlen
= 0, namelen
= 0;
2803 struct lxc_container
*p
;
2804 char path
[PATH_MAX
];
2807 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_rdepends",
2808 c
->config_path
, c
->name
);
2810 ERROR("Path name too long");
2814 f
= fopen(path
, "re");
2818 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2819 if (getline(&lxcname
, &namelen
, f
) == -1) {
2820 ERROR("badly formatted file %s", path
);
2824 remove_trailing_newlines(lxcpath
);
2825 remove_trailing_newlines(lxcname
);
2827 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2828 ERROR("Unable to find dependent container %s:%s",
2833 if (!mod_rdep(p
, c
, inc
))
2834 ERROR("Failed to update snapshots file for %s:%s",
2837 lxc_container_put(p
);
2841 static bool has_fs_snapshots(struct lxc_container
*c
)
2843 __do_fclose
FILE *f
= NULL
;
2844 char path
[PATH_MAX
];
2848 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_snapshots", c
->config_path
,
2853 /* If the file doesn't exist there are no snapshots. */
2854 if (stat(path
, &fbuf
) < 0)
2859 f
= fopen(path
, "re");
2863 ret
= fscanf(f
, "%d", &v
);
2865 INFO("Container uses new lxc-snapshots format %s", path
);
2871 static bool has_snapshots(struct lxc_container
*c
)
2873 __do_closedir
DIR *dir
= NULL
;
2874 char path
[PATH_MAX
];
2875 struct dirent
*direntp
;
2878 if (!get_snappath_dir(c
, path
))
2881 dir
= opendir(path
);
2885 while ((direntp
= readdir(dir
))) {
2886 if (strequal(direntp
->d_name
, "."))
2889 if (strequal(direntp
->d_name
, ".."))
2898 static bool do_destroy_container(struct lxc_conf
*conf
) {
2901 if (am_guest_unpriv()) {
2902 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2903 "storage_destroy_wrapper");
2910 return storage_destroy(conf
);
2913 static int lxc_rmdir_onedev_wrapper(void *data
)
2915 char *arg
= (char *) data
;
2916 return lxc_rmdir_onedev(arg
, "snaps");
2919 static int lxc_unlink_exec_wrapper(void *data
)
2925 static bool container_destroy(struct lxc_container
*c
,
2926 struct lxc_storage
*storage
)
2930 struct lxc_conf
*conf
;
2935 if (!c
|| !do_lxcapi_is_defined(c
))
2939 if (container_disk_lock(c
))
2942 if (!is_stopped(c
)) {
2943 /* We should queue some sort of error - in c->error_string? */
2944 ERROR("container %s is not stopped", c
->name
);
2948 if (conf
&& !list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2949 /* Start of environment variable setup for hooks */
2950 if (setenv("LXC_NAME", c
->name
, 1))
2951 SYSERROR("Failed to set environment variable for container name");
2953 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2954 SYSERROR("Failed to set environment variable for config path");
2956 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2957 SYSERROR("Failed to set environment variable for rootfs mount");
2959 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2960 SYSERROR("Failed to set environment variable for rootfs mount");
2962 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2963 SYSERROR("Failed to set environment variable for console path");
2965 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2966 SYSERROR("Failed to set environment variable for console log");
2967 /* End of environment variable setup for hooks */
2969 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2970 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2975 if (current_config
&& conf
== current_config
) {
2976 current_config
= NULL
;
2978 if (conf
->logfd
!= -1) {
2984 /* LXC is not managing the storage of the container. */
2985 if (conf
&& !conf
->rootfs
.managed
)
2988 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2989 if (!do_destroy_container(conf
)) {
2990 ERROR("Error destroying rootfs for %s", c
->name
);
2993 INFO("Destroyed rootfs for %s", c
->name
);
2996 mod_all_rdeps(c
, false);
2998 p1
= do_lxcapi_get_config_path(c
);
3007 * strlen("config") = 6
3011 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
3014 ERROR("Failed to allocate memory");
3018 /* For an overlay container the rootfs is considered immutable and
3019 * cannot be removed when restoring from a snapshot.
3021 if (storage
&& (strequal(storage
->type
, "overlay") ||
3022 strequal(storage
->type
, "overlayfs")) &&
3023 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3024 ret
= strnprintf(path
, len
, "%s/%s/%s", p1
, c
->name
, LXC_CONFIG_FNAME
);
3028 if (am_guest_unpriv())
3029 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3030 "lxc_unlink_exec_wrapper");
3034 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3038 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3044 ret
= strnprintf(path
, len
, "%s/%s", p1
, c
->name
);
3048 if (am_guest_unpriv())
3049 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3050 "lxc_rmdir_onedev_wrapper");
3052 ret
= lxc_rmdir_onedev(path
, "snaps");
3054 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3058 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3067 container_disk_unlock(c
);
3071 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3073 if (!c
|| !lxcapi_is_defined(c
))
3076 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3077 if (has_snapshots(c
)) {
3078 ERROR("Container %s has snapshots; not removing", c
->name
);
3082 if (has_fs_snapshots(c
)) {
3083 ERROR("container %s has snapshots on its rootfs", c
->name
);
3088 return container_destroy(c
, NULL
);
3091 WRAP_API(bool, lxcapi_destroy
)
3093 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3095 if (!c
|| !lxcapi_is_defined(c
))
3098 if (!lxcapi_snapshot_destroy_all(c
)) {
3099 ERROR("Error deleting all snapshots");
3103 return lxcapi_destroy(c
);
3106 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3108 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3112 struct lxc_config_t
*config
;
3115 config
= lxc_get_config(key
);
3117 ret
= config
->set(key
, v
, conf
, NULL
);
3121 if (lxc_config_value_empty(v
))
3122 do_clear_unexp_config_line(conf
, key
);
3124 bret
= do_append_unexp_config_line(conf
, key
, v
);
3131 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3137 c
->lxc_conf
= lxc_conf_init();
3142 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3149 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3156 if (container_mem_lock(c
))
3159 b
= do_set_config_item_locked(c
, key
, v
);
3161 container_mem_unlock(c
);
3165 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3167 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3169 if (!c
|| !c
->configfile
)
3172 return strdup(c
->configfile
);
3175 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3177 if (!c
|| !c
->config_path
)
3180 return (const char *)(c
->config_path
);
3185 * Just recalculate the c->configfile based on the
3186 * c->config_path, which must be set.
3187 * The lxc_container must be locked or not yet public.
3189 static bool set_config_filename(struct lxc_container
*c
)
3194 if (!c
->config_path
)
3197 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3198 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
3199 newpath
= malloc(len
);
3203 ret
= strnprintf(newpath
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_CONFIG_FNAME
);
3205 fprintf(stderr
, "Error printing out config file name\n");
3210 free(c
->configfile
);
3211 c
->configfile
= newpath
;
3216 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3220 char *oldpath
= NULL
;
3225 if (container_mem_lock(c
))
3230 ERROR("Out of memory setting new lxc path");
3236 oldpath
= c
->config_path
;
3239 /* Since we've changed the config path, we have to change the
3240 * config file name too */
3241 if (!set_config_filename(c
)) {
3242 ERROR("Out of memory setting new config filename");
3244 free(c
->config_path
);
3245 c
->config_path
= oldpath
;
3251 container_mem_unlock(c
);
3255 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3257 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3259 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
3268 ret
= cgroup_set(c
->name
, c
->config_path
, subsys
, value
);
3269 if (ret
< 0 && ERRNO_IS_NOT_SUPPORTED(ret
)) {
3270 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3274 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3280 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3282 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3284 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
3293 ret
= cgroup_get(c
->name
, c
->config_path
, subsys
, retv
, inlen
);
3294 if (ret
< 0 && ERRNO_IS_NOT_SUPPORTED(ret
)) {
3295 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3299 return cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
, c
->config_path
);
3305 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3307 const char *lxc_get_global_config_item(const char *key
)
3309 return lxc_global_config_value(key
);
3312 const char *lxc_get_version(void)
3317 static int copy_file(const char *old
, const char *new)
3324 if (file_exists(new)) {
3325 ERROR("copy destination %s exists", new);
3329 ret
= stat(old
, &sbuf
);
3331 INFO("Error stat'ing %s", old
);
3335 in
= open(old
, O_RDONLY
);
3337 SYSERROR("Error opening original file %s", old
);
3341 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3343 SYSERROR("Error opening new file %s", new);
3349 len
= lxc_read_nointr(in
, buf
, 8096);
3351 SYSERROR("Error reading old file %s", old
);
3358 ret
= lxc_write_nointr(out
, buf
, len
);
3359 if (ret
< len
) { /* should we retry? */
3360 SYSERROR("Error: write to new file %s was interrupted", new);
3368 /* We set mode, but not owner/group. */
3369 ret
= chmod(new, sbuf
.st_mode
);
3371 SYSERROR("Error setting mode on %s", new);
3383 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3385 __do_free
char *cpath
= NULL
;
3387 struct string_entry
*entry
;
3389 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3390 cpath
= malloc(len
);
3392 return ret_errno(ENOMEM
);
3394 ret
= strnprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3398 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3399 list_for_each_entry(entry
, &c
->lxc_conf
->hooks
[i
], head
) {
3400 __do_free
char *hookname
= NULL
;
3401 char *fname
, *new_hook
;
3402 char tmppath
[PATH_MAX
];
3404 fname
= strrchr(entry
->val
, '/');
3408 /* If this hook is public - ignore. */
3409 if (!strnequal(entry
->val
, cpath
, len
- 1))
3412 /* copy the script, and change the entry in confile */
3413 ret
= strnprintf(tmppath
, sizeof(tmppath
), "%s/%s/%s",
3414 c
->config_path
, c
->name
, fname
+1);
3418 ret
= copy_file(entry
->val
, tmppath
);
3422 new_hook
= strdup(tmppath
);
3424 return syserror("out of memory copying hook path");
3426 hookname
= move_ptr(entry
->val
);
3427 entry
->val
= move_ptr(new_hook
);
3431 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3432 c
->config_path
, oldc
->name
, c
->name
)) {
3433 return syserror_ret(-1, "Error saving new hooks in clone");
3436 do_lxcapi_save_config(c
, NULL
);
3440 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3442 char newpath
[PATH_MAX
];
3443 char *oldpath
= oldc
->lxc_conf
->fstab
;
3449 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3451 char *p
= strrchr(oldpath
, '/');
3455 ret
= strnprintf(newpath
, sizeof(newpath
), "%s/%s%s",
3456 c
->config_path
, c
->name
, p
);
3458 ERROR("error printing new path for %s", oldpath
);
3462 if (file_exists(newpath
)) {
3463 ERROR("error: fstab file %s exists", newpath
);
3467 if (copy_file(oldpath
, newpath
) < 0) {
3468 ERROR("error: copying %s to %s", oldpath
, newpath
);
3472 free(c
->lxc_conf
->fstab
);
3474 c
->lxc_conf
->fstab
= strdup(newpath
);
3475 if (!c
->lxc_conf
->fstab
) {
3476 ERROR("error: allocating pathname");
3480 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3481 ERROR("error saving new lxctab");
3488 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3490 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3493 ret
= strnprintf(path0
, sizeof(path0
), "%s/%s/lxc_rdepends", c0
->config_path
,
3496 WARN("Error copying reverse dependencies");
3500 ret
= strnprintf(path1
, sizeof(path1
), "%s/%s/lxc_rdepends", c
->config_path
,
3503 WARN("Error copying reverse dependencies");
3507 if (copy_file(path0
, path1
) < 0) {
3508 INFO("Error copying reverse dependencies");
3513 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3515 __do_fclose
FILE *f
= NULL
;
3517 char path
[PATH_MAX
];
3519 ret
= strnprintf(path
, sizeof(path
), "%s/%s/lxc_rdepends", c
->config_path
, c
->name
);
3523 f
= fopen(path
, "ae");
3527 /* If anything goes wrong, just return an error. */
3528 return fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) > 0;
3532 * If the fs natively supports snapshot clones with no penalty,
3533 * then default to those even if not requested.
3534 * Currently we only do this for btrfs.
3536 static bool should_default_to_snapshot(struct lxc_container
*c0
,
3537 struct lxc_container
*c1
)
3539 __do_free
char *p0
= NULL
, *p1
= NULL
;
3541 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3542 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3543 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3545 p0
= must_realloc(NULL
, l0
+ 1);
3546 p1
= must_realloc(NULL
, l1
+ 1);
3547 ret
= strnprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3551 ret
= strnprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3555 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3558 if (is_btrfs_subvol(rootfs
) <= 0)
3561 return btrfs_same_fs(p0
, p1
) == 0;
3564 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3565 const char *newtype
, int flags
, const char *bdevdata
,
3568 struct lxc_storage
*bdev
;
3571 if (should_default_to_snapshot(c0
, c
))
3572 flags
|= LXC_CLONE_SNAPSHOT
;
3574 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3575 bdevdata
, newsize
, &need_rdep
);
3577 ERROR("Error copying storage.");
3581 /* Set new rootfs. */
3582 free(c
->lxc_conf
->rootfs
.path
);
3583 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3586 if (!c
->lxc_conf
->rootfs
.path
) {
3587 ERROR("Out of memory while setting storage path.");
3591 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3592 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3593 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3594 c
->lxc_conf
->rootfs
.path
)) {
3595 ERROR("Error saving new rootfs to cloned config.");
3599 if (flags
& LXC_CLONE_SNAPSHOT
)
3600 copy_rdepends(c
, c0
);
3603 if (!add_rdepends(c
, c0
))
3604 WARN("Error adding reverse dependency from %s to %s",
3608 mod_all_rdeps(c
, true);
3613 struct clone_update_data
{
3614 struct lxc_container
*c0
;
3615 struct lxc_container
*c1
;
3620 static int clone_update_rootfs(struct clone_update_data
*data
)
3622 struct lxc_container
*c0
= data
->c0
;
3623 struct lxc_container
*c
= data
->c1
;
3624 int flags
= data
->flags
;
3625 char **hookargs
= data
->hookargs
;
3627 char path
[PATH_MAX
];
3628 struct lxc_storage
*bdev
;
3630 struct lxc_conf
*conf
= c
->lxc_conf
;
3632 /* update hostname in rootfs */
3633 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3635 (void)lxc_drop_groups();
3637 if (setgid(0) < 0) {
3638 ERROR("Failed to setgid to 0");
3642 if (setuid(0) < 0) {
3643 ERROR("Failed to setuid to 0");
3647 if (unshare(CLONE_NEWNS
) < 0)
3650 ret
= lxc_storage_prepare(conf
);
3653 bdev
= conf
->rootfs
.storage
;
3655 if (!strequal(bdev
->type
, "dir")) {
3656 if (unshare(CLONE_NEWNS
) < 0) {
3657 ERROR("error unsharing mounts");
3658 lxc_storage_put(conf
);
3662 if (detect_shared_rootfs() && mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
))
3663 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
3665 if (bdev
->ops
->mount(bdev
) < 0) {
3666 lxc_storage_put(conf
);
3669 } else { /* TODO come up with a better way */
3671 bdev
->dest
= strdup(lxc_storage_get_path(bdev
->src
, bdev
->type
));
3674 if (!list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3675 /* Start of environment variable setup for hooks */
3676 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3677 SYSERROR("failed to set environment variable for source container name");
3679 if (setenv("LXC_NAME", c
->name
, 1))
3680 SYSERROR("failed to set environment variable for container name");
3682 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3683 SYSERROR("failed to set environment variable for config path");
3685 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3686 SYSERROR("failed to set environment variable for rootfs mount");
3688 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3689 SYSERROR("failed to set environment variable for rootfs mount");
3691 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3692 ERROR("Error executing clone hook for %s", c
->name
);
3693 lxc_storage_put(conf
);
3698 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3699 ret
= strnprintf(path
, sizeof(path
), "%s/etc/hostname", bdev
->dest
);
3700 lxc_storage_put(conf
);
3705 if (!file_exists(path
))
3708 if (!(fout
= fopen(path
, "we"))) {
3709 SYSERROR("unable to open %s: ignoring", path
);
3713 if (fprintf(fout
, "%s", c
->name
) < 0) {
3718 if (fclose(fout
) < 0)
3721 lxc_storage_put(conf
);
3727 static int clone_update_rootfs_wrapper(void *data
)
3729 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3730 return clone_update_rootfs(arg
);
3734 * We want to support:
3735 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3736 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3738 -s [ implies overlay]
3741 only rootfs gets converted (copied/snapshotted) on clone.
3744 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3746 char *p
= strrchr(path
, '/');
3753 ret
= do_create_container_dir(path
, conf
);
3759 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3760 const char *lxcpath
, int flags
,
3761 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3764 char newpath
[PATH_MAX
];
3766 struct clone_update_data data
;
3767 size_t saved_unexp_len
;
3769 int storage_copied
= 0;
3770 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3771 struct lxc_container
*c2
= NULL
;
3773 if (!c
|| !do_lxcapi_is_defined(c
))
3776 if (container_mem_lock(c
))
3778 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3779 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3783 /* Make sure the container doesn't yet exist. */
3788 lxcpath
= do_lxcapi_get_config_path(c
);
3790 ret
= strnprintf(newpath
, sizeof(newpath
), "%s/%s/%s", lxcpath
, newname
, LXC_CONFIG_FNAME
);
3792 SYSERROR("clone: failed making config pathname");
3796 if (file_exists(newpath
)) {
3797 ERROR("error: clone: %s exists", newpath
);
3801 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3802 if (ret
< 0 && errno
!= EEXIST
) {
3803 ERROR("Error creating container dir for %s", newpath
);
3807 /* Copy the configuration. Tweak it as needed. */
3808 if (c
->lxc_conf
->rootfs
.path
) {
3809 origroot
= c
->lxc_conf
->rootfs
.path
;
3810 c
->lxc_conf
->rootfs
.path
= NULL
;
3813 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3814 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3816 SYSERROR("Failed to open \"%s\"", newpath
);
3820 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3821 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3822 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3823 if (!c
->lxc_conf
->unexpanded_config
) {
3828 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3829 write_config(fd
, c
->lxc_conf
);
3832 c
->lxc_conf
->rootfs
.path
= origroot
;
3834 free(c
->lxc_conf
->unexpanded_config
);
3835 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3836 saved_unexp_conf
= NULL
;
3837 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3839 ret
= strnprintf(newpath
, sizeof(newpath
), "%s/%s/%s", lxcpath
, newname
, LXC_ROOTFS_DNAME
);
3841 SYSERROR("clone: failed making rootfs pathname");
3845 ret
= mkdir(newpath
, 0755);
3847 /* For an overlay container the rootfs is considered immutable
3848 * and will not have been removed when restoring from a
3851 if (errno
!= ENOENT
&&
3852 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3853 SYSERROR("Failed to create directory \"%s\"", newpath
);
3858 if (am_guest_unpriv()) {
3859 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3860 ERROR("Error chowning %s to container root", newpath
);
3865 c2
= lxc_container_new(newname
, lxcpath
);
3867 ERROR("clone: failed to create new container (%s %s)", newname
,
3872 /* copy/snapshot rootfs's */
3873 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3877 /* update utsname */
3878 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3879 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3880 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3882 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3883 ERROR("Error setting new hostname");
3889 ret
= copyhooks(c
, c2
);
3891 ERROR("error copying hooks");
3895 if (copy_fstab(c
, c2
) < 0) {
3896 ERROR("error copying fstab");
3900 /* update macaddrs */
3901 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3902 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3903 ERROR("Error updating mac addresses");
3908 /* Update absolute paths for overlay mount directories. */
3909 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3912 /* We've now successfully created c2's storage, so clear it out if we
3917 if (!c2
->save_config(c2
, NULL
))
3920 if ((pid
= fork()) < 0) {
3926 ret
= wait_for_pid(pid
);
3930 container_mem_unlock(c
);
3937 data
.hookargs
= hookargs
;
3939 if (am_guest_unpriv())
3940 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3941 &data
, "clone_update_rootfs_wrapper");
3943 ret
= clone_update_rootfs(&data
);
3945 _exit(EXIT_FAILURE
);
3947 container_mem_unlock(c
);
3948 _exit(EXIT_SUCCESS
);
3951 container_mem_unlock(c
);
3953 if (!storage_copied
)
3954 c2
->lxc_conf
->rootfs
.path
= NULL
;
3957 lxc_container_put(c2
);
3963 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3964 const char *lxcpath
, int flags
,
3965 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3968 struct lxc_container
* ret
;
3970 current_config
= c
? c
->lxc_conf
: NULL
;
3971 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3972 current_config
= NULL
;
3977 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3979 struct lxc_storage
*bdev
;
3980 struct lxc_container
*newc
;
3982 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3985 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3986 ERROR("Renaming a container with snapshots is not supported");
3990 if (lxc_storage_prepare(c
->lxc_conf
)) {
3991 ERROR("Failed to find original backing store type");
3994 bdev
= c
->lxc_conf
->rootfs
.storage
;
3996 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3997 lxc_storage_put(c
->lxc_conf
);
3999 lxc_container_put(newc
);
4003 if (newc
&& lxcapi_is_defined(newc
))
4004 lxc_container_put(newc
);
4006 if (!container_destroy(c
, NULL
)) {
4007 ERROR("Could not destroy existing container %s", c
->name
);
4014 WRAP_API_1(bool, lxcapi_rename
, const char *)
4016 static int lxcapi_attach(struct lxc_container
*c
,
4017 lxc_attach_exec_t exec_function
, void *exec_payload
,
4018 lxc_attach_options_t
*options
, pid_t
*attached_process
)
4025 current_config
= c
->lxc_conf
;
4027 ret
= lxc_attach(c
, exec_function
, exec_payload
, options
,
4029 current_config
= NULL
;
4033 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
,
4034 lxc_attach_options_t
*options
,
4035 const char *program
,
4036 const char *const argv
[])
4038 lxc_attach_command_t command
;
4045 command
.program
= (char *)program
;
4046 command
.argv
= (char **)argv
;
4048 ret
= lxc_attach(c
, lxc_attach_run_command
, &command
, options
, &pid
);
4052 return lxc_wait_for_pid_status(pid
);
4055 static int lxcapi_attach_run_wait(struct lxc_container
*c
,
4056 lxc_attach_options_t
*options
,
4057 const char *program
, const char *const argv
[])
4061 current_config
= c
? c
->lxc_conf
: NULL
;
4062 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4063 current_config
= NULL
;
4068 static int get_next_index(const char *lxcpath
, char *cname
)
4070 __do_free
char *fname
= NULL
;
4074 fname
= must_realloc(NULL
, strlen(lxcpath
) + 20);
4077 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4079 ret
= stat(fname
, &sb
);
4087 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4092 * If the old style snapshot path exists, use it
4093 * /var/lib/lxc -> /var/lib/lxcsnaps
4095 ret
= strnprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4099 if (dir_exists(snappath
)) {
4100 ret
= strnprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4108 * Use the new style path
4109 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4111 ret
= strnprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4118 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4120 __do_free
char *dfnam
= NULL
;
4125 struct lxc_container
*c2
;
4126 char snappath
[PATH_MAX
], newname
[20];
4130 if (!c
|| !lxcapi_is_defined(c
))
4133 if (!storage_can_backup(c
->lxc_conf
)) {
4134 ERROR("%s's backing store cannot be backed up", c
->name
);
4135 ERROR("Your container must use another backing store type");
4139 if (!get_snappath_dir(c
, snappath
))
4142 i
= get_next_index(snappath
, c
->name
);
4144 if (mkdir_p(snappath
, 0755) < 0) {
4145 ERROR("Failed to create snapshot directory %s", snappath
);
4149 ret
= strnprintf(newname
, 20, "snap%d", i
);
4154 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4155 * created in the original container
4157 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4158 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4159 if (storage_is_dir(c
->lxc_conf
)) {
4160 ERROR("Snapshot of directory-backed container requested");
4161 ERROR("Making a copy-clone. If you do want snapshots, then");
4162 ERROR("please create overlay clone first, snapshot that");
4163 ERROR("and keep the original container pristine");
4164 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4167 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4169 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4173 lxc_container_put(c2
);
4175 /* Now write down the creation time. */
4178 if (!localtime_r(&timer
, &tm_info
)) {
4179 ERROR("Failed to get localtime");
4183 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4185 len
= strlen(snappath
) + 1 + strlen(newname
) + 1 + strlen(LXC_TIMESTAMP_FNAME
) + 1;
4186 dfnam
= must_realloc(NULL
, len
);
4187 ret
= strnprintf(dfnam
, len
, "%s/%s/%s", snappath
, newname
, LXC_TIMESTAMP_FNAME
);
4190 f
= fopen(dfnam
, "we");
4192 ERROR("Failed to open %s", dfnam
);
4196 if (fprintf(f
, "%s", buffer
) < 0) {
4197 SYSERROR("Writing timestamp");
4204 SYSERROR("Writing timestamp");
4209 __do_free
char *path
= NULL
;
4210 /* $p / $name / comment \0 */
4211 len
= strlen(snappath
) + 1 + strlen(newname
) + 1 + strlen(LXC_COMMENT_FNAME
) + 1;
4213 path
= must_realloc(NULL
, len
);
4214 ret
= strnprintf(path
, len
, "%s/%s/%s", snappath
, newname
, LXC_COMMENT_FNAME
);
4217 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4223 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4225 static void lxcsnap_free(struct lxc_snapshot
*s
)
4228 free(s
->comment_pathname
);
4233 static char *get_snapcomment_path(char *snappath
, char *name
)
4235 __do_free
char *s
= NULL
;
4236 /* $snappath/$name/comment */
4237 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4243 ret
= strnprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4250 static char *get_timestamp(char* snappath
, char *name
)
4252 __do_free
char *s
= NULL
;
4253 __do_fclose
FILE *fin
= NULL
;
4254 char path
[PATH_MAX
];
4257 ret
= strnprintf(path
, sizeof(path
), "%s/%s/ts", snappath
, name
);
4261 fin
= fopen(path
, "re");
4265 (void) fseek(fin
, 0, SEEK_END
);
4267 (void) fseek(fin
, 0, SEEK_SET
);
4274 nbytes
= fread(s
, 1, len
, fin
);
4275 if (nbytes
< 0 || nbytes
!= (ssize_t
)len
)
4276 return log_error_errno(NULL
, errno
, "reading timestamp");
4283 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4285 __do_closedir
DIR *dir
= NULL
;
4286 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4288 struct dirent
*direntp
;
4289 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4291 if (!c
|| !lxcapi_is_defined(c
))
4294 if (!get_snappath_dir(c
, snappath
)) {
4295 ERROR("path name too long");
4299 dir
= opendir(snappath
);
4301 INFO("Failed to open %s - assuming no snapshots", snappath
);
4305 while ((direntp
= readdir(dir
))) {
4306 if (strequal(direntp
->d_name
, "."))
4309 if (strequal(direntp
->d_name
, ".."))
4312 ret
= strnprintf(path2
, sizeof(path2
), "%s/%s/%s", snappath
, direntp
->d_name
, LXC_CONFIG_FNAME
);
4314 ERROR("pathname too long");
4318 if (!file_exists(path2
))
4321 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4323 SYSERROR("Out of memory");
4328 snaps
[count
].free
= lxcsnap_free
;
4329 snaps
[count
].name
= strdup(direntp
->d_name
);
4330 if (!snaps
[count
].name
)
4333 snaps
[count
].lxcpath
= strdup(snappath
);
4334 if (!snaps
[count
].lxcpath
) {
4335 free(snaps
[count
].name
);
4339 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4340 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4349 for (int i
= 0; i
< count
; i
++)
4350 lxcsnap_free(&snaps
[i
]);
4358 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4360 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4362 char clonelxcpath
[PATH_MAX
];
4364 struct lxc_container
*snap
, *rest
;
4365 struct lxc_storage
*bdev
;
4368 if (!c
|| !c
->name
|| !c
->config_path
)
4371 if (has_fs_snapshots(c
)) {
4372 ERROR("container rootfs has dependent snapshots");
4376 if (lxc_storage_prepare(c
->lxc_conf
)) {
4377 ERROR("Failed to find original backing store type");
4380 bdev
= c
->lxc_conf
->rootfs
.storage
;
4382 /* For an overlay container the rootfs is considered immutable
4383 * and cannot be removed when restoring from a snapshot. We pass this
4384 * internal flag along to communicate this to various parts of the
4387 if (strequal(bdev
->type
, "overlay") || strequal(bdev
->type
, "overlayfs"))
4388 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4393 if (!get_snappath_dir(c
, clonelxcpath
)) {
4394 lxc_storage_put(c
->lxc_conf
);
4397 /* how should we lock this? */
4399 snap
= lxc_container_new(snapname
, clonelxcpath
);
4400 if (!snap
|| !lxcapi_is_defined(snap
)) {
4401 ERROR("Could not open snapshot %s", snapname
);
4404 lxc_container_put(snap
);
4406 lxc_storage_put(c
->lxc_conf
);
4410 if (strequal(c
->name
, newname
)) {
4411 if (!container_destroy(c
, bdev
)) {
4412 ERROR("Could not destroy existing container %s", newname
);
4413 lxc_container_put(snap
);
4414 lxc_storage_put(c
->lxc_conf
);
4419 if (!strequal(bdev
->type
, "dir") && !strequal(bdev
->type
, "loop"))
4420 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4422 if (strequal(bdev
->type
, "overlay") || strequal(bdev
->type
, "overlayfs"))
4423 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4425 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4427 lxc_storage_put(c
->lxc_conf
);
4428 if (rest
&& lxcapi_is_defined(rest
))
4432 lxc_container_put(rest
);
4434 lxc_container_put(snap
);
4438 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4440 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4442 struct lxc_container
*snap
= NULL
;
4445 snap
= lxc_container_new(snapname
, clonelxcpath
);
4447 ERROR("Could not find snapshot %s", snapname
);
4451 if (!do_lxcapi_destroy(snap
)) {
4452 ERROR("Could not destroy snapshot %s", snapname
);
4460 lxc_container_put(snap
);
4465 static bool remove_all_snapshots(const char *path
)
4467 __do_closedir
DIR *dir
= NULL
;
4468 struct dirent
*direntp
;
4471 dir
= opendir(path
);
4473 SYSERROR("opendir on snapshot path %s", path
);
4477 while ((direntp
= readdir(dir
))) {
4478 if (strequal(direntp
->d_name
, "."))
4481 if (strequal(direntp
->d_name
, ".."))
4484 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4491 SYSERROR("Error removing directory %s", path
);
4496 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4498 char clonelxcpath
[PATH_MAX
];
4500 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4503 if (!get_snappath_dir(c
, clonelxcpath
))
4506 return do_snapshot_destroy(snapname
, clonelxcpath
);
4509 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4511 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4513 char clonelxcpath
[PATH_MAX
];
4515 if (!c
|| !c
->name
|| !c
->config_path
)
4518 if (!get_snappath_dir(c
, clonelxcpath
))
4521 return remove_all_snapshots(clonelxcpath
);
4524 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4526 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4531 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4534 WRAP_API(bool, lxcapi_may_control
)
4536 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4542 char chrootpath
[PATH_MAX
];
4543 char *directory_path
= NULL
;
4547 SYSERROR("Failed to fork()");
4552 ret
= wait_for_pid(pid
);
4554 ERROR("Failed to create device node");
4561 /* prepare the path */
4562 ret
= strnprintf(chrootpath
, sizeof(chrootpath
), "/proc/%d/root", init_pid
);
4566 ret
= chroot(chrootpath
);
4568 _exit(EXIT_FAILURE
);
4572 _exit(EXIT_FAILURE
);
4574 /* remove path if it exists */
4575 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4579 SYSERROR("Failed to remove \"%s\"", path
);
4580 _exit(EXIT_FAILURE
);
4585 _exit(EXIT_SUCCESS
);
4587 /* create any missing directories */
4590 _exit(EXIT_FAILURE
);
4592 directory_path
= dirname(tmp
);
4593 ret
= mkdir_p(directory_path
, 0755);
4594 if (ret
< 0 && errno
!= EEXIST
) {
4595 SYSERROR("Failed to create path \"%s\"", directory_path
);
4597 _exit(EXIT_FAILURE
);
4600 /* create the device node */
4601 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4604 SYSERROR("Failed to create device node at \"%s\"", path
);
4605 _exit(EXIT_FAILURE
);
4608 _exit(EXIT_SUCCESS
);
4611 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4615 char value
[LXC_MAX_BUFFER
];
4619 /* make sure container is running */
4620 if (!do_lxcapi_is_running(c
)) {
4621 ERROR("container is not running");
4625 /* use src_path if dest_path is NULL otherwise use dest_path */
4626 p
= dest_path
? dest_path
: src_path
;
4628 /* make sure we can access p */
4629 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4632 /* continue if path is character device or block device */
4633 if (S_ISCHR(st
.st_mode
))
4634 ret
= strnprintf(value
, sizeof(value
), "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4635 else if (S_ISBLK(st
.st_mode
))
4636 ret
= strnprintf(value
, sizeof(value
), "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4642 init_pid
= do_lxcapi_init_pid(c
);
4644 ERROR("Failed to get init pid");
4648 if (!do_add_remove_node(init_pid
, p
, add
, &st
))
4651 /* add or remove device to/from cgroup access list */
4653 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4654 ERROR("set_cgroup_item failed while adding the device node");
4658 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4659 ERROR("set_cgroup_item failed while removing the device node");
4667 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4669 // cannot mknod if we're not privileged wrt init_user_ns
4670 if (am_host_unpriv()) {
4671 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4675 return add_remove_device_node(c
, src_path
, dest_path
, true);
4678 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4680 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4682 if (am_guest_unpriv()) {
4683 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4687 return add_remove_device_node(c
, src_path
, dest_path
, false);
4690 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4692 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4694 const char *dst_ifname
)
4699 if (am_guest_unpriv()) {
4700 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4705 ERROR("No source interface name given");
4709 ret
= lxc_netdev_isup(ifname
);
4711 /* netdev of ifname is up. */
4712 ret
= lxc_netdev_down(ifname
);
4717 init_pid
= do_lxcapi_init_pid(c
);
4719 ERROR("Failed to get init pid");
4723 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4727 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4734 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4736 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4738 const char *dst_ifname
)
4741 pid_t pid
, pid_outside
;
4742 __do_free
char *physname
= NULL
;
4745 * TODO - if this is a physical device, then we need am_host_unpriv.
4746 * But for other types guest privilege suffices.
4748 if (am_guest_unpriv()) {
4749 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4754 ERROR("No source interface name given");
4758 pid_outside
= lxc_raw_getpid();
4761 ERROR("Failed to fork");
4765 if (pid
== 0) { /* child */
4768 init_pid
= do_lxcapi_init_pid(c
);
4770 ERROR("Failed to get init pid");
4771 _exit(EXIT_FAILURE
);
4773 if (!switch_to_ns(init_pid
, "net")) {
4774 ERROR("Failed to enter network namespace");
4775 _exit(EXIT_FAILURE
);
4778 /* create new mount namespace for use with remounting /sys and is_wlan() below. */
4779 ret
= unshare(CLONE_NEWNS
);
4781 ERROR("Failed to unshare mount namespace");
4782 _exit(EXIT_FAILURE
);
4785 /* set / recursively as private so that mount propagation doesn't affect us. */
4786 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4787 ERROR("Failed to recursively set / as private in mount namespace");
4788 _exit(EXIT_FAILURE
);
4791 ret
= lxc_netdev_isup(ifname
);
4793 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4794 _exit(EXIT_FAILURE
);
4797 /* netdev of ifname is up. */
4799 ret
= lxc_netdev_down(ifname
);
4801 ERROR("Failed to set network device \"%s\" down", ifname
);
4802 _exit(EXIT_FAILURE
);
4806 /* remount /sys so is_wlan() can check if this device is a wlan device. */
4807 lxc_attach_remount_sys_proc();
4808 physname
= is_wlan(ifname
);
4810 ret
= lxc_netdev_move_wlan(physname
, ifname
, pid_outside
, dst_ifname
);
4812 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4814 /* -EINVAL means there is no netdev named as ifname. */
4817 ERROR("Network device \"%s\" not found", ifname
);
4819 ERROR("Failed to remove network device \"%s\"", ifname
);
4821 _exit(EXIT_FAILURE
);
4824 _exit(EXIT_SUCCESS
);
4827 ret
= wait_for_pid(pid
);
4831 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4835 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4837 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4838 struct migrate_opts
*opts
, unsigned int size
)
4841 struct migrate_opts
*valid_opts
= opts
;
4842 uint64_t features_to_check
= 0;
4844 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4845 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4846 * to do anything special.
4848 if (size
> sizeof(*opts
)) {
4849 unsigned char *addr
;
4852 addr
= (void *)opts
+ sizeof(*opts
);
4853 end
= (void *)opts
+ size
;
4855 for (; addr
< end
; addr
++)
4860 /* If the caller has a smaller struct, let's zero out the end for them
4861 * so we don't accidentally use bits of it that they didn't know about
4864 if (size
< sizeof(*opts
)) {
4865 valid_opts
= malloc(sizeof(*opts
));
4869 memset(valid_opts
, 0, sizeof(*opts
));
4870 memcpy(valid_opts
, opts
, size
);
4874 case MIGRATE_PRE_DUMP
:
4875 if (!do_lxcapi_is_running(c
)) {
4876 ERROR("container is not running");
4880 ret
= !__criu_pre_dump(c
, valid_opts
);
4883 if (!do_lxcapi_is_running(c
)) {
4884 ERROR("container is not running");
4888 ret
= !__criu_dump(c
, valid_opts
);
4890 case MIGRATE_RESTORE
:
4891 if (do_lxcapi_is_running(c
)) {
4892 ERROR("container is already running");
4896 ret
= !__criu_restore(c
, valid_opts
);
4898 case MIGRATE_FEATURE_CHECK
:
4899 features_to_check
= valid_opts
->features_to_check
;
4900 ret
= !__criu_check_feature(&features_to_check
);
4902 /* Something went wrong. Let's let the caller
4903 * know which feature checks failed. */
4904 valid_opts
->features_to_check
= features_to_check
;
4908 ERROR("invalid migrate command %u", cmd
);
4913 if (size
< sizeof(*opts
))
4919 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4921 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4923 struct migrate_opts opts
;
4925 memset(&opts
, 0, sizeof(opts
));
4927 opts
.directory
= directory
;
4929 opts
.verbose
= verbose
;
4931 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4934 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4936 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4938 struct migrate_opts opts
;
4940 memset(&opts
, 0, sizeof(opts
));
4942 opts
.directory
= directory
;
4943 opts
.verbose
= verbose
;
4945 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4948 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4950 /* @st_mode is the st_mode field of the stat(source) return struct */
4951 static int create_mount_target(const char *dest
, mode_t st_mode
)
4953 char *dirdup
, *destdirname
;
4956 dirdup
= strdup(dest
);
4958 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4961 destdirname
= dirname(dirdup
);
4963 ret
= mkdir_p(destdirname
, 0755);
4965 SYSERROR("Failed to create \"%s\"", destdirname
);
4973 if (S_ISDIR(st_mode
))
4974 ret
= mkdir(dest
, 0000);
4976 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4979 TRACE("Created mount target \"%s\"", dest
);
4980 else if (ret
< 0 && errno
!= EEXIST
) {
4981 SYSERROR("Failed to create mount target \"%s\"", dest
);
4988 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4989 const char *target
, const char *filesystemtype
,
4990 unsigned long mountflags
, const void *data
,
4991 struct lxc_mount
*mnt
)
4994 char template[PATH_MAX
], path
[PATH_MAX
];
4995 pid_t pid
, init_pid
;
4998 int ret
= -1, fd
= -EBADF
;
5000 if (!c
|| !c
->lxc_conf
) {
5001 ERROR("Container or configuration is NULL");
5005 if (!c
->lxc_conf
->shmount
.path_host
) {
5006 ERROR("Host path to shared mountpoint must be specified in the config\n");
5010 ret
= strnprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5012 SYSERROR("Error writing shmounts tempdir name");
5016 /* Create a temporary file / dir under the shared mountpoint */
5017 if (!source
|| strequal(source
, "")) {
5018 /* If source is not specified, maybe we want to mount a filesystem? */
5019 sb
.st_mode
= S_IFDIR
;
5021 ret
= stat(source
, &sb
);
5023 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5028 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5030 sret
= mkdtemp(template);
5032 SYSERROR("Could not create shmounts temporary dir");
5036 fd
= lxc_make_tmpfile(template, false);
5038 SYSERROR("Could not create shmounts temporary file");
5046 SYSERROR("Could not fork");
5052 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5054 SYSERROR("Failed to mount onto \"%s\"", template);
5055 _exit(EXIT_FAILURE
);
5057 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5059 init_pid
= do_lxcapi_init_pid(c
);
5061 ERROR("Failed to obtain container's init pid");
5062 _exit(EXIT_FAILURE
);
5065 /* Enter the container namespaces */
5066 if (!list_empty(&c
->lxc_conf
->id_map
)) {
5067 if (!switch_to_ns(init_pid
, "user")) {
5068 ERROR("Failed to enter user namespace");
5069 _exit(EXIT_FAILURE
);
5072 if (!lxc_switch_uid_gid(0, 0))
5073 _exit(EXIT_FAILURE
);
5076 if (!switch_to_ns(init_pid
, "mnt")) {
5077 ERROR("Failed to enter mount namespace");
5078 _exit(EXIT_FAILURE
);
5081 ret
= create_mount_target(target
, sb
.st_mode
);
5083 _exit(EXIT_FAILURE
);
5085 suff
= strrchr(template, '/');
5087 goto cleanup_target_in_child
;
5089 ret
= strnprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5091 SYSERROR("Error writing container mountpoint name");
5092 goto cleanup_target_in_child
;
5095 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5097 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5098 goto cleanup_target_in_child
;
5100 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5102 _exit(EXIT_SUCCESS
);
5104 cleanup_target_in_child
:
5105 (void)remove(target
);
5106 _exit(EXIT_FAILURE
);
5109 ret
= wait_for_pid(pid
);
5111 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5115 if (umount2(template, MNT_DETACH
))
5116 SYSWARN("Failed to remove temporary mount \"%s\"", template);
5119 (void)rmdir(template);
5121 (void)unlink(template);
5130 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5131 unsigned long, const void *, struct lxc_mount
*)
5133 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5134 unsigned long flags
, struct lxc_mount
*mnt
)
5136 pid_t pid
, init_pid
;
5139 if (!c
|| !c
->lxc_conf
) {
5140 ERROR("Container or configuration is NULL");
5147 SYSERROR("Could not fork");
5152 init_pid
= do_lxcapi_init_pid(c
);
5154 ERROR("Failed to obtain container's init pid");
5155 _exit(EXIT_FAILURE
);
5158 /* Enter the container namespaces */
5159 if (!list_empty(&c
->lxc_conf
->id_map
)) {
5160 if (!switch_to_ns(init_pid
, "user")) {
5161 ERROR("Failed to enter user namespace");
5162 _exit(EXIT_FAILURE
);
5166 if (!switch_to_ns(init_pid
, "mnt")) {
5167 ERROR("Failed to enter mount namespace");
5168 _exit(EXIT_FAILURE
);
5171 /* Do the unmount */
5172 ret
= umount2(target
, flags
);
5174 SYSERROR("Failed to umount \"%s\"", target
);
5175 _exit(EXIT_FAILURE
);
5178 _exit(EXIT_SUCCESS
);
5181 ret
= wait_for_pid(pid
);
5183 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5190 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5192 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5201 current_config
= c
->lxc_conf
;
5204 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5208 ERROR("Memory allocation error.");
5214 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5218 current_config
= NULL
;
5222 static int do_lxcapi_seccomp_notify_fd(struct lxc_container
*c
)
5224 if (!c
|| !c
->lxc_conf
)
5225 return ret_set_errno(-1, -EINVAL
);
5227 return lxc_seccomp_get_notify_fd(&c
->lxc_conf
->seccomp
);
5230 WRAP_API(int, lxcapi_seccomp_notify_fd
)
5232 static int do_lxcapi_seccomp_notify_fd_active(struct lxc_container
*c
)
5234 if (!c
|| !c
->lxc_conf
)
5235 return ret_set_errno(-1, -EINVAL
);
5237 return lxc_cmd_get_seccomp_notify_fd(c
->name
, c
->config_path
);
5240 WRAP_API(int, lxcapi_seccomp_notify_fd_active
)
5242 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5244 struct lxc_container
*c
;
5251 c
= malloc(sizeof(*c
));
5253 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5256 memset(c
, 0, sizeof(*c
));
5259 c
->config_path
= strdup(configpath
);
5261 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5262 if (!c
->config_path
) {
5263 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5267 remove_trailing_slashes(c
->config_path
);
5270 c
->name
= malloc(len
+ 1);
5272 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5275 (void)strlcpy(c
->name
, name
, len
+ 1);
5278 c
->slock
= lxc_newlock(c
->config_path
, name
);
5280 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5284 c
->privlock
= lxc_newlock(NULL
, NULL
);
5286 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5290 if (!set_config_filename(c
)) {
5291 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5295 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5296 fprintf(stderr
, "Failed to load config for %s\n", name
);
5300 rc
= ongoing_create(c
);
5302 case LXC_CREATE_INCOMPLETE
:
5303 SYSERROR("Failed to complete container creation for %s", c
->name
);
5304 container_destroy(c
, NULL
);
5305 lxcapi_clear_config(c
);
5307 case LXC_CREATE_ONGOING
:
5308 /* container creation going on */
5310 case LXC_CREATE_FAILED
:
5311 /* container creation failed */
5312 if (errno
!= EACCES
&& errno
!= EPERM
) {
5313 /* insufficient privileges */
5314 SYSERROR("Failed checking for incomplete container %s creation", c
->name
);
5320 c
->daemonize
= true;
5323 /* Assign the member functions. */
5324 c
->is_defined
= lxcapi_is_defined
;
5325 c
->state
= lxcapi_state
;
5326 c
->is_running
= lxcapi_is_running
;
5327 c
->freeze
= lxcapi_freeze
;
5328 c
->unfreeze
= lxcapi_unfreeze
;
5329 c
->console
= lxcapi_console
;
5330 c
->console_getfd
= lxcapi_console_getfd
;
5331 c
->devpts_fd
= lxcapi_devpts_fd
;
5332 c
->init_pid
= lxcapi_init_pid
;
5333 c
->init_pidfd
= lxcapi_init_pidfd
;
5334 c
->load_config
= lxcapi_load_config
;
5335 c
->want_daemonize
= lxcapi_want_daemonize
;
5336 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5337 c
->start
= lxcapi_start
;
5338 c
->startl
= lxcapi_startl
;
5339 c
->stop
= lxcapi_stop
;
5340 c
->config_file_name
= lxcapi_config_file_name
;
5341 c
->wait
= lxcapi_wait
;
5342 c
->set_config_item
= lxcapi_set_config_item
;
5343 c
->destroy
= lxcapi_destroy
;
5344 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5345 c
->rename
= lxcapi_rename
;
5346 c
->save_config
= lxcapi_save_config
;
5347 c
->get_keys
= lxcapi_get_keys
;
5348 c
->create
= lxcapi_create
;
5349 c
->createl
= lxcapi_createl
;
5350 c
->shutdown
= lxcapi_shutdown
;
5351 c
->reboot
= lxcapi_reboot
;
5352 c
->reboot2
= lxcapi_reboot2
;
5353 c
->clear_config
= lxcapi_clear_config
;
5354 c
->clear_config_item
= lxcapi_clear_config_item
;
5355 c
->get_config_item
= lxcapi_get_config_item
;
5356 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5357 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5358 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5359 c
->get_config_path
= lxcapi_get_config_path
;
5360 c
->set_config_path
= lxcapi_set_config_path
;
5361 c
->clone
= lxcapi_clone
;
5362 c
->get_interfaces
= lxcapi_get_interfaces
;
5363 c
->get_ips
= lxcapi_get_ips
;
5364 c
->attach
= lxcapi_attach
;
5365 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5366 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5367 c
->snapshot
= lxcapi_snapshot
;
5368 c
->snapshot_list
= lxcapi_snapshot_list
;
5369 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5370 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5371 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5372 c
->may_control
= lxcapi_may_control
;
5373 c
->add_device_node
= lxcapi_add_device_node
;
5374 c
->remove_device_node
= lxcapi_remove_device_node
;
5375 c
->attach_interface
= lxcapi_attach_interface
;
5376 c
->detach_interface
= lxcapi_detach_interface
;
5377 c
->checkpoint
= lxcapi_checkpoint
;
5378 c
->restore
= lxcapi_restore
;
5379 c
->migrate
= lxcapi_migrate
;
5380 c
->console_log
= lxcapi_console_log
;
5381 c
->mount
= lxcapi_mount
;
5382 c
->umount
= lxcapi_umount
;
5383 c
->seccomp_notify_fd
= lxcapi_seccomp_notify_fd
;
5384 c
->seccomp_notify_fd_active
= lxcapi_seccomp_notify_fd_active
;
5389 lxc_container_free(c
);
5393 int lxc_get_wait_states(const char **states
)
5398 for (i
=0; i
<MAX_STATE
; i
++)
5399 states
[i
] = lxc_state2str(i
);
5405 * These next two could probably be done smarter with reusing a common function
5406 * with different iterators and tests...
5408 int list_defined_containers(const char *lxcpath
, char ***names
,
5409 struct lxc_container
***cret
)
5411 __do_closedir
DIR *dir
= NULL
;
5412 size_t array_len
= 0, name_array_len
= 0, ct_array_len
= 0;
5413 struct dirent
*direntp
;
5414 struct lxc_container
*c
;
5417 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5419 dir
= opendir(lxcpath
);
5421 SYSERROR("opendir on lxcpath");
5431 while ((direntp
= readdir(dir
))) {
5432 /* Ignore '.', '..' and any hidden directory. */
5433 if (strnequal(direntp
->d_name
, ".", 1))
5436 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5440 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5442 INFO("Container %s:%s has a config but could not be loaded",
5443 lxcpath
, direntp
->d_name
);
5447 if (!do_lxcapi_is_defined(c
)) {
5448 INFO("Container %s:%s has a config but is not defined",
5449 lxcpath
, direntp
->d_name
);
5451 lxc_container_put(c
);
5457 if (!add_to_array(names
, direntp
->d_name
, array_len
))
5463 if (!add_to_clist(cret
, c
, array_len
, true)) {
5464 lxc_container_put(c
);
5476 if (names
&& *names
) {
5477 for (size_t i
= 0; i
< name_array_len
; i
++)
5482 if (cret
&& *cret
) {
5483 for (size_t i
= 0; i
< ct_array_len
; i
++)
5484 lxc_container_put((*cret
)[i
]);
5491 int list_active_containers(const char *lxcpath
, char ***nret
,
5492 struct lxc_container
***cret
)
5494 __do_free
char *line
= NULL
;
5495 __do_fclose
FILE *f
= NULL
;
5496 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5498 char **ct_name
= NULL
;
5500 struct lxc_container
*c
= NULL
;
5504 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5505 lxcpath_len
= strlen(lxcpath
);
5513 f
= fopen("/proc/net/unix", "re");
5517 while (getline(&line
, &len
, f
) != -1) {
5518 char *p
= strrchr(line
, ' '), *p2
;
5529 if (strnequal(p
, lxcpath
, lxcpath_len
)) {
5531 } else if (strnequal(p
, "lxc/", 4)) {
5541 /* Now p is the start of lxc_name. */
5542 p2
= strchr(p
, '/');
5543 if (!p2
|| !strnequal(p2
, "/command", 8))
5548 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5552 if (!strnequal(lxcpath
, recvpath
, lxcpath_len
)) {
5558 p
= lxc_cmd_get_name(p
);
5563 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5569 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5572 goto free_cret_list
;
5583 c
= lxc_container_new(p
, lxcpath
);
5585 INFO("Container %s:%s is running but could not be loaded", lxcpath
, p
);
5589 goto free_cret_list
;
5596 * If this is an anonymous container, then is_defined *can*
5597 * return false. So we don't do that check. Count on the
5598 * fact that the command socket exists.
5601 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5602 lxc_container_put(c
);
5603 goto free_cret_list
;
5609 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5611 lxc_container_put(c
);
5612 goto free_cret_list
;
5624 if (cret
&& *cret
) {
5625 for (i
= 0; i
< cret_cnt
; i
++)
5626 lxc_container_put((*cret
)[i
]);
5632 for (i
= 0; i
< ct_name_cnt
; i
++)
5641 int list_all_containers(const char *lxcpath
, char ***nret
,
5642 struct lxc_container
***cret
)
5644 int active_cnt
, ct_cnt
, ct_list_cnt
, ret
;
5645 char **active_name
= NULL
, **ct_name
= NULL
;
5646 struct lxc_container
**ct_list
= NULL
;
5648 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5652 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5653 if (active_cnt
< 0) {
5659 for (int i
= 0; i
< active_cnt
; i
++) {
5660 if (array_contains(&ct_name
, active_name
[i
], ct_cnt
))
5663 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
))
5664 goto free_active_name
;
5671 for (int i
= 0; i
< ct_cnt
; i
++) {
5672 __put_lxc_container
struct lxc_container
*c
= NULL
;
5674 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5676 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5680 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false))
5690 for (int i
= 0; i
< active_cnt
; i
++)
5691 free(active_name
[i
]);
5697 for (int i
= 0; i
< ct_cnt
; i
++)
5705 for (int i
= 0; i
< ct_list_cnt
; i
++)
5706 lxc_container_put(ct_list
[i
]);
5710 for (int i
= 0; i
< active_cnt
; i
++)
5711 free(active_name
[i
]);
5715 for (int i
= 0; i
< ct_cnt
; i
++)
5722 bool lxc_config_item_is_supported(const char *key
)
5724 return !!lxc_get_config_exact(key
);
5727 bool lxc_has_api_extension(const char *extension
)
5729 /* The NULL API extension is always present. :) */
5733 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5734 if (strequal(api_extensions
[i
], extension
))