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