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