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