]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
log: convert to strnprintf()
[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);
1b5d4bd8 105 ret = snprintf(fname, len, "%s/%s/%s", lxcpath, cname, LXC_CONFIG_FNAME);
ef1ab8f1 106 if (ret < 0 || (size_t)ret >= len)
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);
1b5d4bd8 138 ret = snprintf(path, len, "%s/%s/%s", c->config_path, c->name, LXC_PARTIAL_FNAME);
444249ea 139 if (ret < 0 || (size_t)ret >= len)
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);
1b5d4bd8 184 ret = snprintf(path, len, "%s/%s/%s", c->config_path, c->name, LXC_PARTIAL_FNAME);
f5cd0252 185 if (ret < 0 || (size_t)ret >= len)
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);
1b5d4bd8 222 ret = snprintf(path, len, "%s/%s/%s", c->config_path, c->name, LXC_PARTIAL_FNAME);
a3740e80 223 if (ret < 0 || (size_t)ret >= len)
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
SH
665 */
666 if (strcmp(fname, c->configfile) == 0)
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))) {
d630991d 747 if (strcmp(direntp->d_name, ".") == 0)
2d834aa8
SH
748 continue;
749
d630991d 750 if (strcmp(direntp->d_name, "..") == 0)
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
CB
981 */
982 ret = snprintf(title, sizeof(title), "[lxc monitor] %s %s", c->config_path, c->name);
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
b07ea13d 1046 w = snprintf(pidstr, sizeof(pidstr), "%d", lxc_raw_getpid());
979a0d93 1047 if (w < 0 || (size_t)w >= sizeof(pidstr)) {
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
78d44e5a 1222 if (!lxc_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{
dfa7eaeb
CB
1234 int ret;
1235 size_t len;
72d0e1cb 1236 char *s;
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
2a59a681 1243 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
dfa7eaeb 1244 if (ret < 0 || (size_t)ret >= len) {
72d0e1cb
SG
1245 free(s);
1246 return false;
1247 }
dfa7eaeb 1248
d5752559 1249 ret = do_create_container_dir(s, c->lxc_conf);
72d0e1cb 1250 free(s);
dfa7eaeb 1251
72d0e1cb
SG
1252 return ret == 0;
1253}
1254
10bc1861
CB
1255/* do_storage_create: thin wrapper around storage_create(). Like
1256 * storage_create(), it returns a mounted bdev on success, NULL on error.
72d0e1cb 1257 */
10bc1861
CB
1258static struct lxc_storage *do_storage_create(struct lxc_container *c,
1259 const char *type,
1260 struct bdev_specs *specs)
1897e3bc 1261{
7a99b5a0 1262 __do_free char *dest = NULL;
e9e29a33 1263 int ret;
1897e3bc 1264 size_t len;
10bc1861 1265 struct lxc_storage *bdev;
1897e3bc 1266
cd219ae6 1267 /* rootfs.path or lxcpath/lxcname/rootfs */
e9e29a33
CB
1268 if (c->lxc_conf->rootfs.path &&
1269 (access(c->lxc_conf->rootfs.path, F_OK) == 0)) {
cf465fe4
SH
1270 const char *rpath = c->lxc_conf->rootfs.path;
1271 len = strlen(rpath) + 1;
f5849fd7 1272 dest = must_realloc(NULL, len);
cf465fe4 1273 ret = snprintf(dest, len, "%s", rpath);
cd219ae6 1274 } else {
858377e4 1275 const char *lxcpath = do_lxcapi_get_config_path(c);
1b5d4bd8 1276 len = strlen(c->name) + 1 + strlen(lxcpath) + 1 + strlen(LXC_ROOTFS_DNAME) + 1;
f5849fd7 1277 dest = must_realloc(NULL, len);
1b5d4bd8 1278 ret = snprintf(dest, len, "%s/%s/%s", lxcpath, c->name, LXC_ROOTFS_DNAME);
cd219ae6 1279 }
e9e29a33 1280 if (ret < 0 || (size_t)ret >= len)
1897e3bc
SH
1281 return NULL;
1282
facdf925 1283 bdev = storage_create(dest, type, c->name, specs, c->lxc_conf);
d44e88c2 1284 if (!bdev) {
e9e29a33 1285 ERROR("Failed to create \"%s\" storage", type);
1897e3bc 1286 return NULL;
d44e88c2
SH
1287 }
1288
7a96a068 1289 if (!c->set_config_item(c, "lxc.rootfs.path", bdev->src)) {
e9e29a33 1290 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev->src);
8ea91347 1291 storage_put(bdev);
f7ac4459
CB
1292 return NULL;
1293 }
cf3ef16d 1294
e9e29a33
CB
1295 /* If we are not root, chown the rootfs dir to root in the target user
1296 * namespace.
f7ac4459 1297 */
facdf925 1298 if (am_guest_unpriv() || !lxc_list_empty(&c->lxc_conf->id_map)) {
e9e29a33
CB
1299 ret = chown_mapped_root(bdev->dest, c->lxc_conf);
1300 if (ret < 0) {
1301 ERROR("Error chowning \"%s\" to container root", bdev->dest);
97e9cfa0 1302 suggest_default_idmap();
10bc1861 1303 storage_put(bdev);
cf3ef16d
SH
1304 return NULL;
1305 }
1306 }
1307
1897e3bc
SH
1308 return bdev;
1309}
1310
85e02f56
PR
1311/* Strip path and return name of file for argv[0] passed to execvp */
1312static char *lxctemplatefilename(char *tpath)
72d0e1cb 1313{
47e55887
CB
1314 char *p;
1315
85e02f56
PR
1316 p = tpath + strlen(tpath) - 1;
1317 while ( (p-1) >= tpath && *(p-1) != '/')
96b3cb40 1318 p--;
47e55887 1319
96b3cb40
SH
1320 return p;
1321}
72d0e1cb 1322
47e55887
CB
1323static bool create_run_template(struct lxc_container *c, char *tpath,
1324 bool need_null_stdfds, char *const argv[])
96b3cb40 1325{
47e55887 1326 int ret;
96b3cb40 1327 pid_t pid;
72d0e1cb 1328
72d0e1cb 1329 if (!tpath)
96b3cb40 1330 return true;
72d0e1cb
SG
1331
1332 pid = fork();
1333 if (pid < 0) {
7e34710e 1334 SYSERROR("Failed to fork task for container creation template");
96b3cb40 1335 return false;
72d0e1cb
SG
1336 }
1337
1a0e70ac 1338 if (pid == 0) { /* child */
47e55887
CB
1339 int i, len;
1340 char *namearg, *patharg, *rootfsarg;
96b3cb40 1341 char **newargv;
47e55887
CB
1342 int nargs = 0;
1343 struct lxc_storage *bdev = NULL;
cf3ef16d 1344 struct lxc_conf *conf = c->lxc_conf;
47e55887 1345 uid_t euid;
72d0e1cb 1346
47e55887
CB
1347 if (need_null_stdfds) {
1348 ret = null_stdfds();
1349 if (ret < 0)
1350 _exit(EXIT_FAILURE);
dc23c1c8 1351 }
1897e3bc 1352
8a388ed4 1353 bdev = storage_init(c->lxc_conf);
1897e3bc 1354 if (!bdev) {
47e55887 1355 ERROR("Failed to initialize storage");
7e34710e 1356 _exit(EXIT_FAILURE);
1897e3bc
SH
1357 }
1358
47e55887
CB
1359 euid = geteuid();
1360 if (euid == 0) {
1361 ret = unshare(CLONE_NEWNS);
1362 if (ret < 0) {
1363 ERROR("Failed to unshare CLONE_NEWNS");
7e34710e 1364 _exit(EXIT_FAILURE);
cf3ef16d 1365 }
47e55887 1366
9e61fb1f
CB
1367 if (detect_shared_rootfs() && mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL))
1368 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
4de2791f 1369 }
47e55887
CB
1370
1371 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "btrfs") != 0) {
1372 if (euid != 0) {
1373 ERROR("Unprivileged users can only create "
1374 "btrfs and directory-backed containers");
eb70aaf0 1375 _exit(EXIT_FAILURE);
4de2791f 1376 }
241978fa 1377
47e55887
CB
1378 if (strcmp(bdev->type, "overlay") == 0 ||
1379 strcmp(bdev->type, "overlayfs") == 0) {
241978fa
CB
1380 /* If we create an overlay container we need to
1381 * rsync the contents into
1382 * <container-path>/<container-name>/rootfs.
1383 * However, the overlay mount function will
f073d460 1384 * mount
241978fa
CB
1385 * <container-path>/<container-name>/delta0
1386 * over
1387 * <container-path>/<container-name>/rootfs
1388 * which means we would rsync the rootfs into
1389 * the delta directory. That doesn't make sense
1390 * since the delta directory only exists to
1391 * record the differences to
1392 * <container-path>/<container-name>/rootfs. So
1393 * let's simply bind-mount here and then rsync
1394 * directly into
1395 * <container-path>/<container-name>/rootfs.
1396 */
1397 char *src;
1398
1399 src = ovl_get_rootfs(bdev->src, &(size_t){0});
1400 if (!src) {
1401 ERROR("Failed to get rootfs");
eb70aaf0 1402 _exit(EXIT_FAILURE);
241978fa
CB
1403 }
1404
1405 ret = mount(src, bdev->dest, "bind", MS_BIND | MS_REC, NULL);
1406 if (ret < 0) {
1407 ERROR("Failed to mount rootfs");
8f55c742 1408 _exit(EXIT_FAILURE);
241978fa
CB
1409 }
1410 } else {
47e55887
CB
1411 ret = bdev->ops->mount(bdev);
1412 if (ret < 0) {
241978fa 1413 ERROR("Failed to mount rootfs");
eb70aaf0 1414 _exit(EXIT_FAILURE);
241978fa 1415 }
cf3ef16d 1416 }
1a0e70ac 1417 } else { /* TODO come up with a better way here! */
41dc7155 1418 const char *src;
f10fad2f 1419 free(bdev->dest);
e9705550
CB
1420 src = lxc_storage_get_path(bdev->src, bdev->type);
1421 bdev->dest = strdup(src);
1897e3bc
SH
1422 }
1423
47e55887
CB
1424 /* Create our new array, pre-pend the template name and base
1425 * args.
72d0e1cb
SG
1426 */
1427 if (argv)
a73846d8 1428 for (nargs = 0; argv[nargs]; nargs++)
47e55887 1429 ;
a73846d8 1430
47e55887
CB
1431 /* template, path, rootfs and name args */
1432 nargs += 4;
cf3ef16d 1433
72d0e1cb
SG
1434 newargv = malloc(nargs * sizeof(*newargv));
1435 if (!newargv)
7e34710e 1436 _exit(EXIT_FAILURE);
85e02f56 1437 newargv[0] = lxctemplatefilename(tpath);
72d0e1cb 1438
47e55887 1439 /* --path */
2a59a681 1440 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
72d0e1cb
SG
1441 patharg = malloc(len);
1442 if (!patharg)
7e34710e 1443 _exit(EXIT_FAILURE);
a73846d8 1444
2a59a681 1445 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
72d0e1cb 1446 if (ret < 0 || ret >= len)
7e34710e 1447 _exit(EXIT_FAILURE);
72d0e1cb 1448 newargv[1] = patharg;
47e55887
CB
1449
1450 /* --name */
72d0e1cb
SG
1451 len = strlen("--name=") + strlen(c->name) + 1;
1452 namearg = malloc(len);
1453 if (!namearg)
7e34710e 1454 _exit(EXIT_FAILURE);
a73846d8 1455
72d0e1cb
SG
1456 ret = snprintf(namearg, len, "--name=%s", c->name);
1457 if (ret < 0 || ret >= len)
7e34710e 1458 _exit(EXIT_FAILURE);
72d0e1cb
SG
1459 newargv[2] = namearg;
1460
47e55887 1461 /* --rootfs */
1897e3bc
SH
1462 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
1463 rootfsarg = malloc(len);
1464 if (!rootfsarg)
7e34710e 1465 _exit(EXIT_FAILURE);
a73846d8 1466
1897e3bc
SH
1467 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
1468 if (ret < 0 || ret >= len)
7e34710e 1469 _exit(EXIT_FAILURE);
1897e3bc
SH
1470 newargv[3] = rootfsarg;
1471
72d0e1cb
SG
1472 /* add passed-in args */
1473 if (argv)
1897e3bc 1474 for (i = 4; i < nargs; i++)
47e55887 1475 newargv[i] = argv[i - 4];
72d0e1cb
SG
1476
1477 /* add trailing NULL */
1478 nargs++;
1479 newargv = realloc(newargv, nargs * sizeof(*newargv));
1480 if (!newargv)
7e34710e 1481 _exit(EXIT_FAILURE);
72d0e1cb
SG
1482 newargv[nargs - 1] = NULL;
1483
47e55887
CB
1484 /* If we're running the template in a mapped userns, then we
1485 * prepend the template command with: lxc-usernsexec <-m map1>
1486 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1487 * the mapped uid for our geteuid()
cf3ef16d 1488 */
0e6e3a41 1489 if (!lxc_list_empty(&conf->id_map)) {
47e55887
CB
1490 int extraargs, hostuid_mapped, hostgid_mapped;
1491 char **n2;
1492 char txtuid[20], txtgid[20];
cf3ef16d
SH
1493 struct lxc_list *it;
1494 struct id_map *map;
47e55887 1495 int n2args = 1;
cf3ef16d 1496
47e55887
CB
1497 n2 = malloc(n2args * sizeof(*n2));
1498 if (!n2)
7e34710e 1499 _exit(EXIT_FAILURE);
47e55887 1500
cf3ef16d
SH
1501 newargv[0] = tpath;
1502 tpath = "lxc-usernsexec";
1503 n2[0] = "lxc-usernsexec";
a73846d8 1504
cf3ef16d
SH
1505 lxc_list_for_each(it, &conf->id_map) {
1506 map = it->elem;
1507 n2args += 2;
57d116ab 1508 n2 = realloc(n2, n2args * sizeof(char *));
cf3ef16d 1509 if (!n2)
7e34710e 1510 _exit(EXIT_FAILURE);
47e55887
CB
1511
1512 n2[n2args - 2] = "-m";
1513 n2[n2args - 1] = malloc(200);
1514 if (!n2[n2args - 1])
7e34710e 1515 _exit(EXIT_FAILURE);
47e55887
CB
1516
1517 ret = snprintf(n2[n2args - 1], 200, "%c:%lu:%lu:%lu",
1518 map->idtype == ID_TYPE_UID ? 'u' : 'g',
1519 map->nsid, map->hostid, map->range);
cf3ef16d 1520 if (ret < 0 || ret >= 200)
7e34710e 1521 _exit(EXIT_FAILURE);
cf3ef16d 1522 }
47e55887
CB
1523
1524 hostuid_mapped = mapped_hostid(geteuid(), conf, ID_TYPE_UID);
1525 extraargs = hostuid_mapped >= 0 ? 1 : 3;
a73846d8 1526
57d116ab 1527 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
cf3ef16d 1528 if (!n2)
7e34710e 1529 _exit(EXIT_FAILURE);
47e55887
CB
1530
1531 if (hostuid_mapped < 0) {
1532 hostuid_mapped = find_unmapped_nsid(conf, ID_TYPE_UID);
cf3ef16d 1533 n2[n2args++] = "-m";
47e55887
CB
1534 if (hostuid_mapped < 0) {
1535 ERROR("Failed to find free uid to map");
7e34710e 1536 _exit(EXIT_FAILURE);
cf3ef16d 1537 }
47e55887 1538
cf3ef16d 1539 n2[n2args++] = malloc(200);
47e55887 1540 if (!n2[n2args - 1]) {
cf3ef16d 1541 SYSERROR("out of memory");
7e34710e 1542 _exit(EXIT_FAILURE);
cf3ef16d 1543 }
a73846d8 1544
47e55887
CB
1545 ret = snprintf(n2[n2args - 1], 200, "u:%d:%d:1",
1546 hostuid_mapped, geteuid());
1547 if (ret < 0 || ret >= 200)
7e34710e 1548 _exit(EXIT_FAILURE);
cf3ef16d 1549 }
47e55887
CB
1550
1551 hostgid_mapped = mapped_hostid(getegid(), conf, ID_TYPE_GID);
2133f58c 1552 extraargs = hostgid_mapped >= 0 ? 1 : 3;
a73846d8 1553
2133f58c
SH
1554 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1555 if (!n2)
7e34710e 1556 _exit(EXIT_FAILURE);
47e55887 1557
2133f58c 1558 if (hostgid_mapped < 0) {
339efad9 1559 hostgid_mapped = find_unmapped_nsid(conf, ID_TYPE_GID);
2133f58c
SH
1560 n2[n2args++] = "-m";
1561 if (hostgid_mapped < 0) {
47e55887 1562 ERROR("Failed to find free gid to map");
7e34710e 1563 _exit(EXIT_FAILURE);
2133f58c 1564 }
47e55887 1565
2133f58c 1566 n2[n2args++] = malloc(200);
47e55887 1567 if (!n2[n2args - 1]) {
2133f58c 1568 SYSERROR("out of memory");
7e34710e 1569 _exit(EXIT_FAILURE);
2133f58c 1570 }
47e55887
CB
1571
1572 ret = snprintf(n2[n2args - 1], 200, "g:%d:%d:1",
1573 hostgid_mapped, getegid());
1574 if (ret < 0 || ret >= 200)
7e34710e 1575 _exit(EXIT_FAILURE);
2133f58c 1576 }
a73846d8 1577
cf3ef16d 1578 n2[n2args++] = "--";
a73846d8 1579
cf3ef16d
SH
1580 for (i = 0; i < nargs; i++)
1581 n2[i + n2args] = newargv[i];
57d116ab 1582 n2args += nargs;
47e55887
CB
1583
1584 /* Finally add "--mapped-uid $uid" to tell template what
1585 * to chown cached images to.
1a0e70ac 1586 */
2133f58c 1587 n2args += 4;
57d116ab 1588 n2 = realloc(n2, n2args * sizeof(char *));
47e55887 1589 if (!n2)
7e34710e 1590 _exit(EXIT_FAILURE);
47e55887 1591
1a0e70ac 1592 /* note n2[n2args-1] is NULL */
47e55887 1593 n2[n2args - 5] = "--mapped-uid";
4250ef64
CB
1594
1595 ret = snprintf(txtuid, 20, "%d", hostuid_mapped);
1596 if (ret < 0 || ret >= 20) {
1597 free(newargv);
1598 free(n2);
1599 _exit(EXIT_FAILURE);
1600 }
1601
47e55887
CB
1602 n2[n2args - 4] = txtuid;
1603 n2[n2args - 3] = "--mapped-gid";
4250ef64 1604
1f080b1d
CB
1605 ret = snprintf(txtgid, 20, "%d", hostgid_mapped);
1606 if (ret < 0 || ret >= 20) {
1607 free(newargv);
1608 free(n2);
1609 _exit(EXIT_FAILURE);
1610 }
4250ef64 1611
47e55887
CB
1612 n2[n2args - 2] = txtgid;
1613 n2[n2args - 1] = NULL;
cf3ef16d
SH
1614 free(newargv);
1615 newargv = n2;
1616 }
47e55887 1617
cf3ef16d 1618 execvp(tpath, newargv);
e9705550 1619 SYSERROR("Failed to execute template %s", tpath);
7e34710e 1620 _exit(EXIT_FAILURE);
72d0e1cb
SG
1621 }
1622
47e55887
CB
1623 ret = wait_for_pid(pid);
1624 if (ret != 0) {
1625 ERROR("Failed to create container from template");
96b3cb40
SH
1626 return false;
1627 }
1628
1629 return true;
1630}
1631
74a3920a 1632static bool prepend_lxc_header(char *path, const char *t, char *const argv[])
3ce74686 1633{
1fd9bd50 1634 long flen;
630ac7c6 1635 size_t len;
b4569e93 1636 char *contents;
3ce74686 1637 FILE *f;
025ed0f3 1638 int ret = -1;
fa2bb6ba 1639#if HAVE_OPENSSL
7c3d3976
JF
1640 int i;
1641 unsigned int md_len = 0;
fa2bb6ba 1642 unsigned char md_value[EVP_MAX_MD_SIZE];
b4569e93 1643 char *tpath;
52026772 1644#endif
3ce74686 1645
4110345b 1646 f = fopen(path, "re");
025ed0f3 1647 if (f == NULL)
3ce74686 1648 return false;
025ed0f3 1649
630ac7c6
CB
1650 ret = fseek(f, 0, SEEK_END);
1651 if (ret < 0)
025ed0f3 1652 goto out_error;
630ac7c6
CB
1653
1654 ret = -1;
1655 flen = ftell(f);
1656 if (flen < 0)
025ed0f3 1657 goto out_error;
630ac7c6
CB
1658
1659 ret = fseek(f, 0, SEEK_SET);
1660 if (ret < 0)
025ed0f3 1661 goto out_error;
630ac7c6
CB
1662
1663 ret = fseek(f, 0, SEEK_SET);
1664 if (ret < 0)
1665 goto out_error;
1666
1667 ret = -1;
1668 contents = malloc(flen + 1);
1669 if (!contents)
025ed0f3 1670 goto out_error;
630ac7c6
CB
1671
1672 len = fread(contents, 1, flen, f);
1673 if (len != flen)
025ed0f3
SH
1674 goto out_free_contents;
1675
3ce74686 1676 contents[flen] = '\0';
a73846d8 1677
025ed0f3 1678 ret = fclose(f);
025ed0f3
SH
1679 f = NULL;
1680 if (ret < 0)
1681 goto out_free_contents;
3ce74686 1682
fa2bb6ba 1683#if HAVE_OPENSSL
01efd4d3 1684 tpath = get_template_path(t);
85db5535 1685 if (!tpath) {
630ac7c6 1686 ERROR("Invalid template \"%s\" specified", t);
025ed0f3 1687 goto out_free_contents;
3ce74686
SH
1688 }
1689
fa2bb6ba 1690 ret = sha1sum_file(tpath, md_value, &md_len);
85db5535 1691 if (ret < 0) {
630ac7c6 1692 ERROR("Failed to get sha1sum of %s", tpath);
cef701ed 1693 free(tpath);
85db5535 1694 goto out_free_contents;
3ce74686 1695 }
cef701ed 1696 free(tpath);
3ce74686
SH
1697#endif
1698
4110345b 1699 f = fopen(path, "we");
025ed0f3 1700 if (f == NULL) {
630ac7c6 1701 SYSERROR("Reopening config for writing");
3ce74686
SH
1702 free(contents);
1703 return false;
1704 }
630ac7c6 1705
3ce74686
SH
1706 fprintf(f, "# Template used to create this container: %s\n", t);
1707 if (argv) {
1708 fprintf(f, "# Parameters passed to the template:");
1709 while (*argv) {
1710 fprintf(f, " %s", *argv);
1711 argv++;
1712 }
1713 fprintf(f, "\n");
1714 }
a73846d8 1715
fa2bb6ba 1716#if HAVE_OPENSSL
56698177 1717 fprintf(f, "# Template script checksum (SHA-1): ");
fa2bb6ba 1718 for (i=0; i<md_len; i++)
56698177
SH
1719 fprintf(f, "%02x", md_value[i]);
1720 fprintf(f, "\n");
3ce74686 1721#endif
0520c252 1722 fprintf(f, "# For additional config options, please look at lxc.container.conf(5)\n");
49a2ed80
SH
1723 fprintf(f, "\n# Uncomment the following line to support nesting containers:\n");
1724 fprintf(f, "#lxc.include = " LXCTEMPLATECONFIG "/nesting.conf\n");
1725 fprintf(f, "# (Be aware this has security implications)\n\n");
3ce74686
SH
1726 if (fwrite(contents, 1, flen, f) != flen) {
1727 SYSERROR("Writing original contents");
1728 free(contents);
1729 fclose(f);
1730 return false;
1731 }
630ac7c6 1732
025ed0f3 1733 ret = 0;
630ac7c6 1734
025ed0f3 1735out_free_contents:
3ce74686 1736 free(contents);
630ac7c6 1737
025ed0f3
SH
1738out_error:
1739 if (f) {
1740 int newret;
025ed0f3 1741 newret = fclose(f);
025ed0f3
SH
1742 if (ret == 0)
1743 ret = newret;
1744 }
630ac7c6 1745
025ed0f3
SH
1746 if (ret < 0) {
1747 SYSERROR("Error prepending header");
3ce74686
SH
1748 return false;
1749 }
630ac7c6 1750
3ce74686
SH
1751 return true;
1752}
1753
4df7f012
SH
1754static void lxcapi_clear_config(struct lxc_container *c)
1755{
e62fd16f
CB
1756 if (!c || !c->lxc_conf)
1757 return;
1758
1759 lxc_conf_free(c->lxc_conf);
1760 c->lxc_conf = NULL;
4df7f012
SH
1761}
1762
858377e4
SH
1763#define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1764
96b3cb40
SH
1765/*
1766 * lxcapi_create:
1767 * create a container with the given parameters.
1768 * @c: container to be created. It has the lxcpath, name, and a starting
1769 * configuration already set
1770 * @t: the template to execute to instantiate the root filesystem and
1771 * adjust the configuration.
1772 * @bdevtype: backing store type to use. If NULL, dir will be used.
1773 * @specs: additional parameters for the backing store, i.e. LVM vg to
1774 * use.
1775 *
1776 * @argv: the arguments to pass to the template, terminated by NULL. If no
1777 * arguments, you can just pass NULL.
1778 */
858377e4 1779static bool do_lxcapi_create(struct lxc_container *c, const char *t,
85aec4ac
CB
1780 const char *bdevtype, struct bdev_specs *specs,
1781 int flags, char *const argv[])
96b3cb40 1782{
e9e29a33 1783 int partial_fd;
51f0f73b 1784 mode_t mask;
96b3cb40 1785 pid_t pid;
92fa4347 1786 bool ret = false, rootfs_managed = true;
85db5535 1787 char *tpath = NULL;
96b3cb40
SH
1788
1789 if (!c)
1790 return false;
1791
85db5535
DE
1792 if (t) {
1793 tpath = get_template_path(t);
1794 if (!tpath) {
e9e29a33 1795 ERROR("Unknown template \"%s\"", t);
85db5535
DE
1796 goto out;
1797 }
96b3cb40
SH
1798 }
1799
e9e29a33
CB
1800 /* If a template is passed in, and the rootfs already is defined in the
1801 * container config and exists, then the caller is trying to create an
1802 * existing container. Return an error, but do NOT delete the container.
cf465fe4 1803 */
858377e4 1804 if (do_lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
a73846d8 1805 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
e9e29a33
CB
1806 ERROR("Container \"%s\" already exists in \"%s\"", c->name,
1807 c->config_path);
6c6892b5 1808 goto free_tpath;
cf465fe4
SH
1809 }
1810
6c6892b5 1811 if (!c->lxc_conf) {
858377e4 1812 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
e9e29a33
CB
1813 ERROR("Error loading default configuration file %s",
1814 lxc_global_config_value("lxc.default_config"));
6c6892b5
DE
1815 goto free_tpath;
1816 }
96b3cb40
SH
1817 }
1818
6c6892b5
DE
1819 if (!create_container_dir(c))
1820 goto free_tpath;
1821
92fa4347
CB
1822 if (c->lxc_conf->rootfs.path)
1823 rootfs_managed = false;
1824
e9e29a33
CB
1825 /* If both template and rootfs.path are set, template is setup as
1826 * rootfs.path. The container is already created if we have a config and
1827 * rootfs.path is accessible
0590e82c 1828 */
00370edd 1829 if (!c->lxc_conf->rootfs.path && !tpath) {
e9e29a33 1830 /* No template passed in and rootfs does not exist. */
00370edd 1831 if (!c->save_config(c, NULL)) {
e9e29a33 1832 ERROR("Failed to save initial config for \"%s\"", c->name);
00370edd
DW
1833 goto out;
1834 }
1835 ret = true;
0590e82c 1836 goto out;
00370edd 1837 }
e9e29a33
CB
1838
1839 /* Rootfs passed into configuration, but does not exist. */
0590e82c 1840 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
0590e82c 1841 goto out;
e9e29a33 1842
858377e4 1843 if (do_lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
e9e29a33
CB
1844 /* Rootfs already existed, user just wanted to save the loaded
1845 * configuration.
1846 */
0f4cdd77 1847 if (!c->save_config(c, NULL))
e9e29a33 1848 ERROR("Failed to save initial config for \"%s\"", c->name);
a73846d8 1849
0590e82c
SH
1850 ret = true;
1851 goto out;
a69aad27 1852 }
96b3cb40
SH
1853
1854 /* Mark that this container is being created */
e9e29a33
CB
1855 partial_fd = create_partial(c);
1856 if (partial_fd < 0)
96b3cb40
SH
1857 goto out;
1858
e9e29a33 1859 /* No need to get disk lock bc we have the partial lock. */
96b3cb40 1860
51f0f73b
KR
1861 mask = umask(0022);
1862
e9e29a33 1863 /* Create the storage.
96b3cb40
SH
1864 * Note we can't do this in the same task as we use to execute the
1865 * template because of the way zfs works.
1866 * After you 'zfs create', zfs mounts the fs only in the initial
1867 * namespace.
1868 */
1869 pid = fork();
1870 if (pid < 0) {
e9e29a33 1871 SYSERROR("Failed to fork task for container creation template");
8eb5694b
SH
1872 goto out_unlock;
1873 }
1874
1a0e70ac 1875 if (pid == 0) { /* child */
10bc1861 1876 struct lxc_storage *bdev = NULL;
96b3cb40 1877
10bc1861
CB
1878 bdev = do_storage_create(c, bdevtype, specs);
1879 if (!bdev) {
e9e29a33
CB
1880 ERROR("Failed to create %s storage for %s",
1881 bdevtype ? bdevtype : "(none)", c->name);
85aec4ac 1882 _exit(EXIT_FAILURE);
96b3cb40
SH
1883 }
1884
e9e29a33 1885 /* Save config file again to store the new rootfs location. */
858377e4 1886 if (!do_lxcapi_save_config(c, NULL)) {
e9e29a33
CB
1887 ERROR("Failed to save initial config for %s", c->name);
1888 /* Parent task won't see the storage driver in the
1889 * config so we delete it.
1890 */
96b3cb40
SH
1891 bdev->ops->umount(bdev);
1892 bdev->ops->destroy(bdev);
85aec4ac 1893 _exit(EXIT_FAILURE);
96b3cb40 1894 }
a73846d8 1895
85aec4ac 1896 _exit(EXIT_SUCCESS);
96b3cb40 1897 }
a73846d8 1898
96b3cb40 1899 if (wait_for_pid(pid) != 0)
a09295f8 1900 goto out_unlock;
96b3cb40 1901
e9e29a33 1902 /* Reload config to get the rootfs. */
a3b47c09 1903 lxc_conf_free(c->lxc_conf);
96b3cb40 1904 c->lxc_conf = NULL;
a73846d8 1905
96b3cb40 1906 if (!load_config_locked(c, c->configfile))
a09295f8 1907 goto out_unlock;
96b3cb40 1908
dc23c1c8 1909 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
96b3cb40
SH
1910 goto out_unlock;
1911
1a0e70ac
CB
1912 /* Now clear out the lxc_conf we have, reload from the created
1913 * container.
1914 */
858377e4 1915 do_lxcapi_clear_config(c);
3ce74686 1916
9d65a487
KY
1917 if (t) {
1918 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
e9e29a33 1919 ERROR("Failed to prepend header to config file");
9d65a487
KY
1920 goto out_unlock;
1921 }
3ce74686 1922 }
a73846d8 1923
a69aad27 1924 ret = load_config_locked(c, c->configfile);
72d0e1cb
SG
1925
1926out_unlock:
51f0f73b 1927 umask(mask);
b20e0599 1928 remove_partial(c, partial_fd);
a73846d8 1929
72d0e1cb 1930out:
92fa4347
CB
1931 if (!ret) {
1932 bool reset_managed = c->lxc_conf->rootfs.managed;
1933
1934 /*
1935 * Ensure that we don't destroy storage we didn't create
1936 * ourselves.
1937 */
1938 if (!rootfs_managed)
1939 c->lxc_conf->rootfs.managed = false;
17a367d8 1940 container_destroy(c, NULL);
92fa4347
CB
1941 c->lxc_conf->rootfs.managed = reset_managed;
1942 }
a73846d8 1943
6c6892b5 1944free_tpath:
f10fad2f 1945 free(tpath);
a69aad27 1946 return ret;
72d0e1cb
SG
1947}
1948
858377e4 1949static bool lxcapi_create(struct lxc_container *c, const char *t,
e9e29a33
CB
1950 const char *bdevtype, struct bdev_specs *specs,
1951 int flags, char *const argv[])
858377e4
SH
1952{
1953 bool ret;
a73846d8 1954
858377e4 1955 current_config = c ? c->lxc_conf : NULL;
a73846d8 1956
858377e4
SH
1957 ret = do_lxcapi_create(c, t, bdevtype, specs, flags, argv);
1958 current_config = NULL;
1959 return ret;
1960}
1961
1962static bool do_lxcapi_reboot(struct lxc_container *c)
3e625e2d 1963{
f62cf1d4 1964 __do_close int pidfd = -EBADF;
9837ee46 1965 pid_t pid = -1;
9dd54153 1966 int ret;
dd267776 1967 int rebootsignal = SIGINT;
3e625e2d
SH
1968
1969 if (!c)
1970 return false;
9dd54153 1971
858377e4 1972 if (!do_lxcapi_is_running(c))
3e625e2d 1973 return false;
9dd54153 1974
9837ee46
CB
1975 pidfd = do_lxcapi_init_pidfd(c);
1976 if (pidfd < 0) {
1977 pid = do_lxcapi_init_pid(c);
1978 if (pid <= 0)
1979 return false;
1980 }
9dd54153 1981
dd267776
BP
1982 if (c->lxc_conf && c->lxc_conf->rebootsignal)
1983 rebootsignal = c->lxc_conf->rebootsignal;
9dd54153 1984
9837ee46
CB
1985 if (pidfd >= 0)
1986 ret = lxc_raw_pidfd_send_signal(pidfd, rebootsignal, NULL, 0);
1987 else
1988 ret = kill(pid, rebootsignal);
1989 if (ret < 0)
1990 return log_warn(false, "Failed to send signal %d to pid %d",
1991 rebootsignal, pid);
3e625e2d 1992
9dd54153 1993 return true;
3e625e2d
SH
1994}
1995
858377e4
SH
1996WRAP_API(bool, lxcapi_reboot)
1997
d39b10eb
CB
1998static bool do_lxcapi_reboot2(struct lxc_container *c, int timeout)
1999{
f62cf1d4 2000 __do_close int pidfd = -EBADF, state_client_fd = -EBADF;
9837ee46
CB
2001 int rebootsignal = SIGINT;
2002 pid_t pid = -1;
d39b10eb 2003 lxc_state_t states[MAX_STATE] = {0};
9837ee46 2004 int killret, ret;
d39b10eb
CB
2005
2006 if (!c)
2007 return false;
2008
2009 if (!do_lxcapi_is_running(c))
2010 return true;
2011
9837ee46
CB
2012 pidfd = do_lxcapi_init_pidfd(c);
2013 if (pidfd < 0) {
2014 pid = do_lxcapi_init_pid(c);
2015 if (pid <= 0)
2016 return true;
2017 }
d39b10eb
CB
2018
2019 if (c->lxc_conf && c->lxc_conf->rebootsignal)
2020 rebootsignal = c->lxc_conf->rebootsignal;
2021
2022 /* Add a new state client before sending the shutdown signal so that we
2023 * don't miss a state.
2024 */
2025 if (timeout != 0) {
2026 states[RUNNING] = 2;
2027 ret = lxc_cmd_add_state_client(c->name, c->config_path, states,
2028 &state_client_fd);
2029 if (ret < 0)
2030 return false;
2031
2032 if (state_client_fd < 0)
2033 return false;
2034
2035 if (ret == RUNNING)
2036 return true;
2037
2038 if (ret < MAX_STATE)
2039 return false;
2040 }
2041
2042 /* Send reboot signal to container. */
9837ee46
CB
2043 if (pidfd >= 0)
2044 killret = lxc_raw_pidfd_send_signal(pidfd, rebootsignal, NULL, 0);
2045 else
2046 killret = kill(pid, rebootsignal);
2047 if (killret < 0)
2048 return log_warn(false, "Failed to send signal %d to pid %d", rebootsignal, pid);
d39b10eb
CB
2049 TRACE("Sent signal %d to pid %d", rebootsignal, pid);
2050
a579fa51 2051 if (timeout == 0)
d39b10eb
CB
2052 return true;
2053
2054 ret = lxc_cmd_sock_rcv_state(state_client_fd, timeout);
d39b10eb
CB
2055 if (ret < 0)
2056 return false;
2057
2058 TRACE("Received state \"%s\"", lxc_state2str(ret));
2059 if (ret != RUNNING)
2060 return false;
2061
2062 return true;
2063}
2064
2065WRAP_API_1(bool, lxcapi_reboot2, int)
2066
858377e4 2067static bool do_lxcapi_shutdown(struct lxc_container *c, int timeout)
72d0e1cb 2068{
f62cf1d4 2069 __do_close int pidfd = -EBADF, state_client_fd = -EBADF;
ea2a070b 2070 int haltsignal = SIGPWR;
9837ee46 2071 pid_t pid = -1;
ea2a070b 2072 lxc_state_t states[MAX_STATE] = {0};
f8bdb6dc 2073 int killret, ret;
72d0e1cb
SG
2074
2075 if (!c)
2076 return false;
2077
858377e4 2078 if (!do_lxcapi_is_running(c))
72d0e1cb 2079 return true;
f8bdb6dc 2080
9837ee46 2081 pidfd = do_lxcapi_init_pidfd(c);
08eccae8
CB
2082 pid = do_lxcapi_init_pid(c);
2083 if (pid <= 0)
2084 return true;
330ae3d3
CB
2085
2086 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
b0227444 2087 if (c->lxc_conf && c->lxc_conf->haltsignal)
f0f1d8c0 2088 haltsignal = c->lxc_conf->haltsignal;
573ad77f 2089 else if (task_blocks_signal(pid, (SIGRTMIN + 3)))
eabf1ea9 2090 haltsignal = (SIGRTMIN + 3);
330ae3d3 2091
08eccae8
CB
2092
2093 /*
2094 * Add a new state client before sending the shutdown signal so
2095 * that we don't miss a state.
92e35018 2096 */
f8bdb6dc
CB
2097 if (timeout != 0) {
2098 states[STOPPED] = 1;
2099 ret = lxc_cmd_add_state_client(c->name, c->config_path, states,
2100 &state_client_fd);
2101 if (ret < 0)
2102 return false;
92e35018 2103
f8bdb6dc
CB
2104 if (state_client_fd < 0)
2105 return false;
2106
2107 if (ret == STOPPED)
2108 return true;
591614a7 2109
f8bdb6dc 2110 if (ret < MAX_STATE)
92e35018 2111 return false;
60cd5091 2112 }
92e35018 2113
60cd5091
RV
2114 if (pidfd >= 0) {
2115 struct pollfd pidfd_poll = {
2116 .events = POLLIN,
2117 .fd = pidfd,
2118 };
08eccae8 2119
60cd5091
RV
2120 killret = lxc_raw_pidfd_send_signal(pidfd, haltsignal,
2121 NULL, 0);
2122 if (killret < 0)
2123 return log_warn(false, "Failed to send signal %d to pidfd %d",
2124 haltsignal, pidfd);
08eccae8 2125
60cd5091 2126 TRACE("Sent signal %d to pidfd %d", haltsignal, pidfd);
9837ee46 2127
60cd5091
RV
2128 /*
2129 * No need for going through all of the state server
2130 * complications anymore. We can just poll on pidfds. :)
2131 */
08eccae8 2132
60cd5091
RV
2133 if (timeout != 0) {
2134 ret = poll(&pidfd_poll, 1, timeout * 1000);
2135 if (ret < 0 || !(pidfd_poll.revents & POLLIN))
2136 return false;
08eccae8 2137
60cd5091 2138 TRACE("Pidfd polling detected container exit");
08eccae8 2139 }
60cd5091
RV
2140 } else {
2141 killret = kill(pid, haltsignal);
2142 if (killret < 0)
2143 return log_warn(false, "Failed to send signal %d to pid %d",
2144 haltsignal, pid);
2145
2146 TRACE("Sent signal %d to pid %d", haltsignal, pid);
9837ee46 2147 }
f8bdb6dc 2148
923929f6 2149 if (timeout == 0)
f8bdb6dc
CB
2150 return true;
2151
2152 ret = lxc_cmd_sock_rcv_state(state_client_fd, timeout);
f8bdb6dc
CB
2153 if (ret < 0)
2154 return false;
2155
2156 TRACE("Received state \"%s\"", lxc_state2str(ret));
2157 if (ret != STOPPED)
2158 return false;
2159
2160 return true;
72d0e1cb
SG
2161}
2162
858377e4
SH
2163WRAP_API_1(bool, lxcapi_shutdown, int)
2164
1897e3bc 2165static bool lxcapi_createl(struct lxc_container *c, const char *t,
dc23c1c8 2166 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
72d0e1cb
SG
2167{
2168 bool bret = false;
a0e93eeb 2169 char **args = NULL;
72d0e1cb 2170 va_list ap;
72d0e1cb
SG
2171
2172 if (!c)
2173 return false;
2174
858377e4
SH
2175 current_config = c->lxc_conf;
2176
72d0e1cb
SG
2177 /*
2178 * since we're going to wait for create to finish, I don't think we
2179 * need to get a copy of the arguments.
2180 */
dc23c1c8 2181 va_start(ap, flags);
a0e93eeb 2182 args = lxc_va_arg_list_to_argv(ap, 0, 0);
72d0e1cb 2183 va_end(ap);
a0e93eeb 2184 if (!args) {
e9e29a33 2185 ERROR("Failed to allocate memory");
a0e93eeb
CS
2186 goto out;
2187 }
72d0e1cb 2188
858377e4 2189 bret = do_lxcapi_create(c, t, bdevtype, specs, flags, args);
72d0e1cb
SG
2190
2191out:
a0e93eeb 2192 free(args);
858377e4 2193 current_config = NULL;
72d0e1cb
SG
2194 return bret;
2195}
2196
6b0d5538
SH
2197static void do_clear_unexp_config_line(struct lxc_conf *conf, const char *key)
2198{
4222a9f4
CB
2199 if (!strcmp(key, "lxc.cgroup"))
2200 return clear_unexp_config_line(conf, key, true);
2201
2202 if (!strcmp(key, "lxc.network"))
2203 return clear_unexp_config_line(conf, key, true);
2204
2205 if (!strcmp(key, "lxc.net"))
2206 return clear_unexp_config_line(conf, key, true);
2207
2208 /* Clear a network with a specific index. */
2209 if (!strncmp(key, "lxc.net.", 8)) {
2210 int ret;
2211 const char *idx;
2212
2213 idx = key + 8;
2214 ret = lxc_safe_uint(idx, &(unsigned int){0});
2215 if (!ret)
2216 return clear_unexp_config_line(conf, key, true);
2217 }
2218
2219 if (!strcmp(key, "lxc.hook"))
2220 return clear_unexp_config_line(conf, key, true);
2221
2222 return clear_unexp_config_line(conf, key, false);
6b0d5538
SH
2223}
2224
6afd673f
CB
2225static bool do_lxcapi_clear_config_item(struct lxc_container *c,
2226 const char *key)
72d0e1cb 2227{
6afd673f
CB
2228 int ret = 1;
2229 struct lxc_config_t *config;
72d0e1cb
SG
2230
2231 if (!c || !c->lxc_conf)
2232 return false;
6afd673f 2233
5cee8c50 2234 if (container_mem_lock(c))
72d0e1cb 2235 return false;
6afd673f 2236
300df83e 2237 config = lxc_get_config(key);
6afd673f
CB
2238 /* Verify that the config key exists and that it has a callback
2239 * implemented.
2240 */
2241 if (config && config->clr)
26471403 2242 ret = config->clr(key, c->lxc_conf, NULL);
a73846d8 2243
6b0d5538
SH
2244 if (!ret)
2245 do_clear_unexp_config_line(c->lxc_conf, key);
6afd673f 2246
5cee8c50 2247 container_mem_unlock(c);
72d0e1cb
SG
2248 return ret == 0;
2249}
2250
858377e4
SH
2251WRAP_API_1(bool, lxcapi_clear_config_item, const char *)
2252
e0f59189 2253static inline bool enter_net_ns(struct lxc_container *c)
51d0854c 2254{
858377e4 2255 pid_t pid = do_lxcapi_init_pid(c);
ae22a220 2256
caab004f
TA
2257 if (pid < 0)
2258 return false;
2259
a73846d8 2260 if ((geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) &&
2261 (access("/proc/self/ns/user", F_OK) == 0))
51d0854c
DY
2262 if (!switch_to_ns(pid, "user"))
2263 return false;
a73846d8 2264
51d0854c 2265 return switch_to_ns(pid, "net");
799f29ab
ÇO
2266}
2267
1a0e70ac 2268/* Used by qsort and bsearch functions for comparing names. */
9c88ff1f
ÇO
2269static inline int string_cmp(char **first, char **second)
2270{
2271 return strcmp(*first, *second);
2272}
2273
1a0e70ac
CB
2274/* Used by qsort and bsearch functions for comparing container names. */
2275static inline int container_cmp(struct lxc_container **first,
2276 struct lxc_container **second)
9c88ff1f
ÇO
2277{
2278 return strcmp((*first)->name, (*second)->name);
2279}
2280
2281static bool add_to_array(char ***names, char *cname, int pos)
2282{
2283 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
2284 if (!newnames) {
2285 ERROR("Out of memory");
2286 return false;
2287 }
2288
2289 *names = newnames;
2290 newnames[pos] = strdup(cname);
2291 if (!newnames[pos])
2292 return false;
2293
3b034c39 2294 /* Sort the array as we will use binary search on it. */
1a0e70ac
CB
2295 qsort(newnames, pos + 1, sizeof(char *),
2296 (int (*)(const void *, const void *))string_cmp);
9c88ff1f
ÇO
2297
2298 return true;
2299}
2300
1a0e70ac
CB
2301static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c,
2302 int pos, bool sort)
9c88ff1f 2303{
1a0e70ac 2304 struct lxc_container **newlist = realloc(*list, (pos + 1) * sizeof(struct lxc_container *));
9c88ff1f
ÇO
2305 if (!newlist) {
2306 ERROR("Out of memory");
2307 return false;
2308 }
2309
2310 *list = newlist;
2311 newlist[pos] = c;
2312
3b034c39 2313 /* Sort the array as we will use binary search on it. */
2871830a 2314 if (sort)
1a0e70ac
CB
2315 qsort(newlist, pos + 1, sizeof(struct lxc_container *),
2316 (int (*)(const void *, const void *))container_cmp);
9c88ff1f
ÇO
2317
2318 return true;
2319}
2320
2321static char** get_from_array(char ***names, char *cname, int size)
2322{
2323 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
2324}
2325
a73846d8 2326static bool array_contains(char ***names, char *cname, int size)
2327{
9c88ff1f
ÇO
2328 if(get_from_array(names, cname, size) != NULL)
2329 return true;
a73846d8 2330
9c88ff1f
ÇO
2331 return false;
2332}
2333
2334static bool remove_from_array(char ***names, char *cname, int size)
2335{
2336 char **result = get_from_array(names, cname, size);
2337 if (result != NULL) {
2338 free(result);
2339 return true;
2340 }
a73846d8 2341
9c88ff1f
ÇO
2342 return false;
2343}
2344
9f4866a6 2345static char **do_lxcapi_get_interfaces(struct lxc_container *c)
799f29ab 2346{
ae22a220
ÇO
2347 pid_t pid;
2348 int i, count = 0, pipefd[2];
9c88ff1f 2349 char **interfaces = NULL;
ae22a220 2350 char interface[IFNAMSIZ];
799f29ab 2351
c4ef8f4c
CB
2352 if (pipe2(pipefd, O_CLOEXEC))
2353 return log_error_errno(NULL, errno, "Failed to create pipe");
c868b261 2354
ae22a220
ÇO
2355 pid = fork();
2356 if (pid < 0) {
ae22a220
ÇO
2357 close(pipefd[0]);
2358 close(pipefd[1]);
c4ef8f4c 2359 return log_error_errno(NULL, errno, "Failed to fork task to get interfaces information");
ae22a220 2360 }
799f29ab 2361
c4ef8f4c
CB
2362 if (pid == 0) {
2363 call_cleaner(netns_freeifaddrs) struct netns_ifaddrs *ifaddrs = NULL;
2364 struct netns_ifaddrs *ifa = NULL;
2365 int ret = 1;
2366 int nbytes;
ae22a220
ÇO
2367
2368 /* close the read-end of the pipe */
2369 close(pipefd[0]);
2370
e0f59189 2371 if (!enter_net_ns(c)) {
9f4866a6 2372 SYSERROR("Failed to enter network namespace");
ae22a220
ÇO
2373 goto out;
2374 }
2375
2376 /* Grab the list of interfaces */
c4ef8f4c 2377 if (netns_getifaddrs(&ifaddrs, -1, &(bool){false})) {
9f4866a6 2378 SYSERROR("Failed to get interfaces list");
ae22a220
ÇO
2379 goto out;
2380 }
2381
2382 /* Iterate through the interfaces */
c4ef8f4c
CB
2383 for (ifa = ifaddrs; ifa != NULL;
2384 ifa = ifa->ifa_next) {
2385 nbytes = lxc_write_nointr(pipefd[1], ifa->ifa_name, IFNAMSIZ);
9f4866a6 2386 if (nbytes < 0)
ae22a220 2387 goto out;
9f4866a6 2388
ae22a220
ÇO
2389 count++;
2390 }
a73846d8 2391
ae22a220
ÇO
2392 ret = 0;
2393
2394 out:
ae22a220
ÇO
2395 /* close the write-end of the pipe, thus sending EOF to the reader */
2396 close(pipefd[1]);
02c611b0 2397 _exit(ret);
799f29ab
ÇO
2398 }
2399
ae22a220
ÇO
2400 /* close the write-end of the pipe */
2401 close(pipefd[1]);
2402
3e1e9db8 2403 while (lxc_read_nointr(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
3151d4e2
CB
2404 interface[IFNAMSIZ - 1] = '\0';
2405
ae22a220 2406 if (array_contains(&interfaces, interface, count))
9f4866a6 2407 continue;
799f29ab 2408
9f4866a6 2409 if (!add_to_array(&interfaces, interface, count))
3151d4e2
CB
2410 ERROR("Failed to add \"%s\" to array", interface);
2411
9c88ff1f
ÇO
2412 count++;
2413 }
799f29ab 2414
c4ef8f4c 2415 if (wait_for_pid(pid)) {
9f4866a6 2416 for (i = 0; i < count; i++)
ae22a220 2417 free(interfaces[i]);
a73846d8 2418
ae22a220
ÇO
2419 free(interfaces);
2420 interfaces = NULL;
2421 }
9c88ff1f 2422
ae22a220
ÇO
2423 /* close the read-end of the pipe */
2424 close(pipefd[0]);
799f29ab 2425
9c88ff1f 2426 /* Append NULL to the array */
9f4866a6 2427 if (interfaces)
9c88ff1f 2428 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
799f29ab 2429
9c88ff1f 2430 return interfaces;
799f29ab
ÇO
2431}
2432
858377e4
SH
2433WRAP_API(char **, lxcapi_get_interfaces)
2434
02a0e184
CB
2435static char **do_lxcapi_get_ips(struct lxc_container *c, const char *interface,
2436 const char *family, int scope)
799f29ab 2437{
02a0e184 2438 int i, ret;
ae22a220 2439 pid_t pid;
02a0e184 2440 int pipefd[2];
ae22a220 2441 char address[INET6_ADDRSTRLEN];
02a0e184
CB
2442 int count = 0;
2443 char **addresses = NULL;
799f29ab 2444
0ac84f04 2445 ret = pipe2(pipefd, O_CLOEXEC);
c4ef8f4c
CB
2446 if (ret < 0)
2447 return log_error_errno(NULL, errno, "Failed to create pipe");
c868b261 2448
ae22a220
ÇO
2449 pid = fork();
2450 if (pid < 0) {
02a0e184 2451 SYSERROR("Failed to create new process");
ae22a220
ÇO
2452 close(pipefd[0]);
2453 close(pipefd[1]);
2454 return NULL;
9c83a661
SG
2455 }
2456
02a0e184 2457 if (pid == 0) {
c4ef8f4c
CB
2458 call_cleaner(netns_freeifaddrs) struct netns_ifaddrs *ifaddrs = NULL;
2459 struct netns_ifaddrs *ifa = NULL;
02a0e184 2460 ssize_t nbytes;
ae22a220 2461 char addressOutputBuffer[INET6_ADDRSTRLEN];
a7547c5c 2462 char *address_ptr = NULL;
c4ef8f4c 2463 void *address_ptr_tmp = NULL;
fe218ca3 2464
ae22a220
ÇO
2465 /* close the read-end of the pipe */
2466 close(pipefd[0]);
2467
e0f59189 2468 if (!enter_net_ns(c)) {
02a0e184 2469 SYSERROR("Failed to attach to network namespace");
ae22a220 2470 goto out;
9c83a661 2471 }
ae22a220
ÇO
2472
2473 /* Grab the list of interfaces */
c4ef8f4c 2474 if (netns_getifaddrs(&ifaddrs, -1, &(bool){false})) {
02a0e184 2475 SYSERROR("Failed to get interfaces list");
ae22a220
ÇO
2476 goto out;
2477 }
2478
2479 /* Iterate through the interfaces */
c4ef8f4c
CB
2480 for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) {
2481 if (ifa->ifa_addr == NULL)
9c83a661
SG
2482 continue;
2483
6ce39620
CB
2484#pragma GCC diagnostic push
2485#pragma GCC diagnostic ignored "-Wcast-align"
2486
c4ef8f4c 2487 if (ifa->ifa_addr->sa_family == AF_INET) {
ae22a220
ÇO
2488 if (family && strcmp(family, "inet"))
2489 continue;
02a0e184 2490
c4ef8f4c 2491 address_ptr_tmp = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
02a0e184 2492 } else {
ae22a220
ÇO
2493 if (family && strcmp(family, "inet6"))
2494 continue;
2495
c4ef8f4c 2496 if (((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id != scope)
ae22a220
ÇO
2497 continue;
2498
c4ef8f4c 2499 address_ptr_tmp = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
ae22a220
ÇO
2500 }
2501
6ce39620
CB
2502#pragma GCC diagnostic pop
2503
c4ef8f4c 2504 if (interface && strcmp(interface, ifa->ifa_name))
ae22a220 2505 continue;
c4ef8f4c 2506 else if (!interface && strcmp("lo", ifa->ifa_name) == 0)
9c83a661
SG
2507 continue;
2508
c4ef8f4c
CB
2509 address_ptr = (char *)inet_ntop(ifa->ifa_addr->sa_family, address_ptr_tmp,
2510 addressOutputBuffer,
2511 sizeof(addressOutputBuffer));
a7547c5c 2512 if (!address_ptr)
02a0e184 2513 continue;
ae22a220 2514
a7547c5c 2515 nbytes = lxc_write_nointr(pipefd[1], address_ptr, INET6_ADDRSTRLEN);
02a0e184 2516 if (nbytes != INET6_ADDRSTRLEN) {
c4ef8f4c 2517 SYSERROR("Failed to send ipv6 address \"%s\"", address_ptr);
ae22a220
ÇO
2518 goto out;
2519 }
a73846d8 2520
ae22a220 2521 count++;
9c83a661 2522 }
a73846d8 2523
ae22a220 2524 ret = 0;
9c83a661 2525
ae22a220 2526 out:
ae22a220
ÇO
2527 /* close the write-end of the pipe, thus sending EOF to the reader */
2528 close(pipefd[1]);
fe1ce58c 2529 _exit(ret);
6849cb5b 2530 }
9c83a661 2531
ae22a220
ÇO
2532 /* close the write-end of the pipe */
2533 close(pipefd[1]);
2534
02a0e184
CB
2535 while (lxc_read_nointr(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
2536 address[INET6_ADDRSTRLEN - 1] = '\0';
2537
2538 if (!add_to_array(&addresses, address, count))
ae22a220 2539 ERROR("PARENT: add_to_array failed");
02a0e184 2540
9c88ff1f 2541 count++;
9c83a661
SG
2542 }
2543
c4ef8f4c 2544 if (wait_for_pid(pid)) {
02a0e184 2545 for (i = 0; i < count; i++)
ae22a220 2546 free(addresses[i]);
02a0e184 2547
ae22a220
ÇO
2548 free(addresses);
2549 addresses = NULL;
2550 }
9c83a661 2551
ae22a220
ÇO
2552 /* close the read-end of the pipe */
2553 close(pipefd[0]);
9c83a661
SG
2554
2555 /* Append NULL to the array */
02a0e184 2556 if (addresses)
9c88ff1f 2557 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
9c83a661
SG
2558
2559 return addresses;
2560}
2561
858377e4
SH
2562WRAP_API_3(char **, lxcapi_get_ips, const char *, const char *, int)
2563
2564static int do_lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb 2565{
fce687aa
CB
2566 int ret = -1;
2567 struct lxc_config_t *config;
72d0e1cb
SG
2568
2569 if (!c || !c->lxc_conf)
2570 return -1;
fce687aa 2571
5cee8c50 2572 if (container_mem_lock(c))
72d0e1cb 2573 return -1;
fce687aa 2574
300df83e 2575 config = lxc_get_config(key);
fce687aa
CB
2576 /* Verify that the config key exists and that it has a callback
2577 * implemented.
2578 */
2579 if (config && config->get)
cccd2219 2580 ret = config->get(key, retv, inlen, c->lxc_conf, NULL);
fce687aa 2581
5cee8c50 2582 container_mem_unlock(c);
72d0e1cb
SG
2583 return ret;
2584}
2585
858377e4
SH
2586WRAP_API_3(int, lxcapi_get_config_item, const char *, char *, int)
2587
2588static char* do_lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
8ac18377
ÇO
2589{
2590 char *ret;
2591
2592 if (!c || !c->lxc_conf)
2593 return NULL;
a73846d8 2594
8ac18377
ÇO
2595 if (container_mem_lock(c))
2596 return NULL;
a73846d8 2597
858377e4 2598 ret = lxc_cmd_get_config_item(c->name, key, do_lxcapi_get_config_path(c));
8ac18377
ÇO
2599 container_mem_unlock(c);
2600 return ret;
2601}
2602
858377e4
SH
2603WRAP_API_1(char *, lxcapi_get_running_config_item, const char *)
2604
2605static int do_lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb 2606{
300df83e
CB
2607 int ret = -1;
2608
2609 /* List all config items. */
72d0e1cb 2610 if (!key)
cfc67626 2611 return lxc_list_config_items(retv, inlen);
300df83e 2612
72d0e1cb
SG
2613 if (!c || !c->lxc_conf)
2614 return -1;
300df83e 2615
5cee8c50 2616 if (container_mem_lock(c))
72d0e1cb 2617 return -1;
300df83e
CB
2618
2619 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2620 * This is an intelligent result to show which keys are valid given the
2621 * type of nic it is.
2622 */
6fba98b5 2623 if (strncmp(key, "lxc.net.", 8) == 0)
01f55c40 2624 ret = lxc_list_net(c->lxc_conf, key, retv, inlen);
fe9b7349
CB
2625 else
2626 ret = lxc_list_subkeys(c->lxc_conf, key, retv, inlen);
300df83e 2627
5cee8c50 2628 container_mem_unlock(c);
72d0e1cb
SG
2629 return ret;
2630}
2631
858377e4
SH
2632WRAP_API_3(int, lxcapi_get_keys, const char *, char *, int)
2633
2634static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 2635{
0e1a60b0 2636 int fd, lret;
39dc698c 2637 bool ret = false, need_disklock = false;
39dc698c 2638
72d0e1cb
SG
2639 if (!alt_file)
2640 alt_file = c->configfile;
a73846d8 2641
72d0e1cb 2642 if (!alt_file)
1a0e70ac 2643 return false;
39dc698c 2644
1a0e70ac 2645 /* If we haven't yet loaded a config, load the stock config. */
39dc698c 2646 if (!c->lxc_conf) {
858377e4 2647 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
0e1a60b0
CB
2648 ERROR("Error loading default configuration file %s "
2649 "while saving %s",
2650 lxc_global_config_value("lxc.default_config"),
2651 c->name);
72d0e1cb
SG
2652 return false;
2653 }
39dc698c 2654 }
72d0e1cb 2655
5a3d2e1e
SG
2656 if (!create_container_dir(c))
2657 return false;
2658
1a0e70ac
CB
2659 /* If we're writing to the container's config file, take the disk lock.
2660 * Otherwise just take the memlock to protect the struct lxc_container
2661 * while we're traversing it.
39dc698c
SH
2662 */
2663 if (strcmp(c->configfile, alt_file) == 0)
2664 need_disklock = true;
2665
2666 if (need_disklock)
2667 lret = container_disk_lock(c);
2668 else
2669 lret = container_mem_lock(c);
39dc698c 2670 if (lret)
72d0e1cb 2671 return false;
39dc698c 2672
10034af5 2673 fd = open(alt_file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
e581b9b5 2674 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
0e1a60b0
CB
2675 if (fd < 0)
2676 goto on_error;
2677
2678 lret = write_config(fd, c->lxc_conf);
2679 close(fd);
2680 if (lret < 0)
2681 goto on_error;
2682
39dc698c
SH
2683 ret = true;
2684
0e1a60b0 2685on_error:
39dc698c
SH
2686 if (need_disklock)
2687 container_disk_unlock(c);
2688 else
2689 container_mem_unlock(c);
0e1a60b0 2690
39dc698c 2691 return ret;
72d0e1cb
SG
2692}
2693
858377e4
SH
2694WRAP_API_1(bool, lxcapi_save_config, const char *)
2695
0ea055b3
CB
2696
2697static bool mod_rdep(struct lxc_container *c0, struct lxc_container *c, bool inc)
dfb31b25 2698{
0ea055b3
CB
2699 FILE *f1;
2700 struct stat fbuf;
42342bed
CB
2701 void *buf = NULL;
2702 char *del = NULL;
8a22c168
CB
2703 char path[PATH_MAX];
2704 char newpath[PATH_MAX];
0ea055b3 2705 int fd, ret, n = 0, v = 0;
dfb31b25 2706 bool bret = false;
42342bed 2707 size_t len = 0, bytes = 0;
dfb31b25 2708
0ea055b3 2709 if (container_disk_lock(c0))
dfb31b25 2710 return false;
0ea055b3 2711
8a22c168
CB
2712 ret = snprintf(path, PATH_MAX, "%s/%s/lxc_snapshots", c0->config_path, c0->name);
2713 if (ret < 0 || ret > PATH_MAX)
dfb31b25 2714 goto out;
a73846d8 2715
8a22c168
CB
2716 ret = snprintf(newpath, PATH_MAX, "%s\n%s\n", c->config_path, c->name);
2717 if (ret < 0 || ret > PATH_MAX)
dfb31b25 2718 goto out;
0ea055b3
CB
2719
2720 /* If we find an lxc-snapshot file using the old format only listing the
2721 * number of snapshots we will keep using it. */
4110345b 2722 f1 = fopen(path, "re");
0ea055b3
CB
2723 if (f1) {
2724 n = fscanf(f1, "%d", &v);
2725 fclose(f1);
2726 if (n == 1 && v == 0) {
dc509bf2
CB
2727 ret = remove(path);
2728 if (ret < 0)
6d1400b5 2729 SYSERROR("Failed to remove \"%s\"", path);
2730
0ea055b3
CB
2731 n = 0;
2732 }
dfb31b25 2733 }
6d1400b5 2734
0ea055b3
CB
2735 if (n == 1) {
2736 v += inc ? 1 : -1;
4110345b 2737 f1 = fopen(path, "we");
0ea055b3
CB
2738 if (!f1)
2739 goto out;
6d1400b5 2740
0ea055b3
CB
2741 if (fprintf(f1, "%d\n", v) < 0) {
2742 ERROR("Error writing new snapshots value");
2743 fclose(f1);
2744 goto out;
2745 }
6d1400b5 2746
0ea055b3
CB
2747 ret = fclose(f1);
2748 if (ret != 0) {
2749 SYSERROR("Error writing to or closing snapshots file");
2750 goto out;
2751 }
2752 } else {
2753 /* Here we know that we have or can use an lxc-snapshot file
2754 * using the new format. */
2755 if (inc) {
4110345b 2756 f1 = fopen(path, "ae");
0ea055b3
CB
2757 if (!f1)
2758 goto out;
2759
2760 if (fprintf(f1, "%s", newpath) < 0) {
2761 ERROR("Error writing new snapshots entry");
2762 ret = fclose(f1);
2763 if (ret != 0)
2764 SYSERROR("Error writing to or closing snapshots file");
2765 goto out;
2766 }
2767
2768 ret = fclose(f1);
2769 if (ret != 0) {
2770 SYSERROR("Error writing to or closing snapshots file");
2771 goto out;
2772 }
2773 } else if (!inc) {
d028235d
SG
2774 if ((fd = open(path, O_RDWR | O_CLOEXEC)) < 0)
2775 goto out;
2776
2777 if (fstat(fd, &fbuf) < 0) {
2778 close(fd);
2779 goto out;
2780 }
2781
2782 if (fbuf.st_size != 0) {
25086a5f 2783 buf = lxc_strmmap(NULL, fbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
d028235d
SG
2784 if (buf == MAP_FAILED) {
2785 SYSERROR("Failed to create mapping %s", path);
2786 close(fd);
2787 goto out;
2788 }
2789
2790 len = strlen(newpath);
2791 while ((del = strstr((char *)buf, newpath))) {
2792 memmove(del, del + len, strlen(del) - len + 1);
2793 bytes += len;
2794 }
2795
25086a5f 2796 lxc_strmunmap(buf, fbuf.st_size);
d028235d
SG
2797 if (ftruncate(fd, fbuf.st_size - bytes) < 0) {
2798 SYSERROR("Failed to truncate file %s", path);
2799 close(fd);
2800 goto out;
2801 }
2802 }
a73846d8 2803
d028235d
SG
2804 close(fd);
2805 }
0ea055b3
CB
2806
2807 /* If the lxc-snapshot file is empty, remove it. */
2808 if (stat(path, &fbuf) < 0)
2809 goto out;
6d1400b5 2810
d028235d 2811 if (!fbuf.st_size) {
71261a5c
CB
2812 ret = remove(path);
2813 if (ret < 0)
2814 SYSERROR("Failed to remove \"%s\"", path);
0ea055b3 2815 }
dfb31b25
SH
2816 }
2817
2818 bret = true;
2819
2820out:
0ea055b3 2821 container_disk_unlock(c0);
dfb31b25
SH
2822 return bret;
2823}
2824
d825fff3 2825void mod_all_rdeps(struct lxc_container *c, bool inc)
dfb31b25 2826{
768e7ba2
CB
2827 __do_free char *lxcpath = NULL, *lxcname = NULL;
2828 __do_fclose FILE *f = NULL;
dfb31b25 2829 size_t pathlen = 0, namelen = 0;
768e7ba2
CB
2830 struct lxc_container *p;
2831 char path[PATH_MAX];
dfb31b25
SH
2832 int ret;
2833
8a22c168 2834 ret = snprintf(path, PATH_MAX, "%s/%s/lxc_rdepends",
dfb31b25 2835 c->config_path, c->name);
8a22c168 2836 if (ret < 0 || ret >= PATH_MAX) {
dfb31b25
SH
2837 ERROR("Path name too long");
2838 return;
2839 }
a73846d8 2840
4110345b 2841 f = fopen(path, "re");
768e7ba2 2842 if (!f)
dfb31b25 2843 return;
a73846d8 2844
dfb31b25
SH
2845 while (getline(&lxcpath, &pathlen, f) != -1) {
2846 if (getline(&lxcname, &namelen, f) == -1) {
959aee9c 2847 ERROR("badly formatted file %s", path);
768e7ba2 2848 return;
dfb31b25 2849 }
7ad37670
CB
2850
2851 remove_trailing_newlines(lxcpath);
2852 remove_trailing_newlines(lxcname);
2853
dfb31b25
SH
2854 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
2855 ERROR("Unable to find dependent container %s:%s",
2856 lxcpath, lxcname);
2857 continue;
2858 }
a73846d8 2859
0ea055b3
CB
2860 if (!mod_rdep(p, c, inc))
2861 ERROR("Failed to update snapshots file for %s:%s",
dfb31b25 2862 lxcpath, lxcname);
a73846d8 2863
dfb31b25
SH
2864 lxc_container_put(p);
2865 }
dfb31b25
SH
2866}
2867
18aa217b 2868static bool has_fs_snapshots(struct lxc_container *c)
dfb31b25 2869{
768e7ba2 2870 __do_fclose FILE *f = NULL;
8a22c168 2871 char path[PATH_MAX];
dfb31b25 2872 int ret, v;
0ea055b3 2873 struct stat fbuf;
dfb31b25 2874
8a22c168 2875 ret = snprintf(path, PATH_MAX, "%s/%s/lxc_snapshots", c->config_path,
dfb31b25 2876 c->name);
8a22c168 2877 if (ret < 0 || ret > PATH_MAX)
768e7ba2 2878 return false;
a73846d8 2879
0ea055b3
CB
2880 /* If the file doesn't exist there are no snapshots. */
2881 if (stat(path, &fbuf) < 0)
768e7ba2 2882 return false;
a73846d8 2883
0ea055b3
CB
2884 v = fbuf.st_size;
2885 if (v != 0) {
4110345b 2886 f = fopen(path, "re");
0ea055b3 2887 if (!f)
768e7ba2 2888 return false;
a73846d8 2889
0ea055b3 2890 ret = fscanf(f, "%d", &v);
0ea055b3
CB
2891 if (ret != 1)
2892 INFO("Container uses new lxc-snapshots format %s", path);
2893 }
a73846d8 2894
768e7ba2 2895 return v != 0;
dfb31b25
SH
2896}
2897
18aa217b
SH
2898static bool has_snapshots(struct lxc_container *c)
2899{
4110345b 2900 __do_closedir DIR *dir = NULL;
8a22c168 2901 char path[PATH_MAX];
74f96976 2902 struct dirent *direntp;
4110345b 2903 int count = 0;
18aa217b
SH
2904
2905 if (!get_snappath_dir(c, path))
2906 return false;
a73846d8 2907
18aa217b
SH
2908 dir = opendir(path);
2909 if (!dir)
2910 return false;
a73846d8 2911
74f96976 2912 while ((direntp = readdir(dir))) {
18aa217b
SH
2913 if (!strcmp(direntp->d_name, "."))
2914 continue;
2915
2916 if (!strcmp(direntp->d_name, ".."))
2917 continue;
2918 count++;
2919 break;
2920 }
a73846d8 2921
18aa217b
SH
2922 return count > 0;
2923}
2924
297c2d58 2925static bool do_destroy_container(struct lxc_conf *conf) {
ee484f7f
CB
2926 int ret;
2927
e0010464 2928 if (am_guest_unpriv()) {
ee484f7f
CB
2929 ret = userns_exec_full(conf, storage_destroy_wrapper, conf,
2930 "storage_destroy_wrapper");
2931 if (ret < 0)
d028235d 2932 return false;
ee484f7f 2933
d028235d
SG
2934 return true;
2935 }
ee484f7f 2936
10bc1861 2937 return storage_destroy(conf);
297c2d58
CB
2938}
2939
4355ab5f
SH
2940static int lxc_rmdir_onedev_wrapper(void *data)
2941{
2942 char *arg = (char *) data;
18aa217b 2943 return lxc_rmdir_onedev(arg, "snaps");
4355ab5f
SH
2944}
2945
17a367d8 2946static int lxc_unlink_exec_wrapper(void *data)
72d0e1cb 2947{
17a367d8
CB
2948 char *arg = data;
2949 return unlink(arg);
2950}
2951
2952static bool container_destroy(struct lxc_container *c,
2953 struct lxc_storage *storage)
2954{
2955 const char *p1;
2956 size_t len;
2957 struct lxc_conf *conf;
2958 char *path = NULL;
c868b261 2959 bool bret = false;
297c2d58 2960 int ret = 0;
72d0e1cb 2961
858377e4 2962 if (!c || !do_lxcapi_is_defined(c))
5a3d2e1e
SG
2963 return false;
2964
a70a69e8 2965 conf = c->lxc_conf;
3bc449ed 2966 if (container_disk_lock(c))
72d0e1cb 2967 return false;
72d0e1cb 2968
39dc698c 2969 if (!is_stopped(c)) {
1a0e70ac 2970 /* We should queue some sort of error - in c->error_string? */
60bf62d4
SH
2971 ERROR("container %s is not stopped", c->name);
2972 goto out;
72d0e1cb
SG
2973 }
2974
a70a69e8 2975 if (conf && !lxc_list_empty(&conf->hooks[LXCHOOK_DESTROY])) {
37cf711b 2976 /* Start of environment variable setup for hooks */
cb8ff4d0 2977 if (setenv("LXC_NAME", c->name, 1))
17a367d8
CB
2978 SYSERROR("Failed to set environment variable for container name");
2979
2980 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
2981 SYSERROR("Failed to set environment variable for config path");
2982
2983 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
2984 SYSERROR("Failed to set environment variable for rootfs mount");
2985
2986 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
2987 SYSERROR("Failed to set environment variable for rootfs mount");
2988
2989 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
2990 SYSERROR("Failed to set environment variable for console path");
2991
2992 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
2993 SYSERROR("Failed to set environment variable for console log");
37cf711b
SY
2994 /* End of environment variable setup for hooks */
2995
14a7b0f9 2996 if (run_lxc_hooks(c->name, "destroy", conf, NULL)) {
17a367d8 2997 ERROR("Failed to execute clone hook for \"%s\"", c->name);
37cf711b
SY
2998 goto out;
2999 }
3000 }
3001
3002 if (current_config && conf == current_config) {
858377e4 3003 current_config = NULL;
a73846d8 3004
37cf711b
SY
3005 if (conf->logfd != -1) {
3006 close(conf->logfd);
3007 conf->logfd = -1;
858377e4
SH
3008 }
3009 }
3010
6e54330c
CB
3011 /* LXC is not managing the storage of the container. */
3012 if (conf && !conf->rootfs.managed)
3013 goto on_success;
3014
d028235d
SG
3015 if (conf && conf->rootfs.path && conf->rootfs.mount) {
3016 if (!do_destroy_container(conf)) {
3017 ERROR("Error destroying rootfs for %s", c->name);
3018 goto out;
3019 }
3020 INFO("Destroyed rootfs for %s", c->name);
3021 }
60bf62d4 3022
dfb31b25
SH
3023 mod_all_rdeps(c, false);
3024
17a367d8
CB
3025 p1 = do_lxcapi_get_config_path(c);
3026 /* strlen(p1)
3027 * +
3028 * /
3029 * +
3030 * strlen(c->name)
3031 * +
3032 * /
3033 * +
3034 * strlen("config") = 6
3035 * +
3036 * \0
3037 */
1b5d4bd8 3038 len = strlen(p1) + 1 + strlen(c->name) + 1 + strlen(LXC_CONFIG_FNAME) + 1;
17a367d8
CB
3039 path = malloc(len);
3040 if (!path) {
3041 ERROR("Failed to allocate memory");
3042 goto out;
3043 }
3044
3045 /* For an overlay container the rootfs is considered immutable and
3046 * cannot be removed when restoring from a snapshot.
3047 */
3048 if (storage && (!strcmp(storage->type, "overlay") ||
3049 !strcmp(storage->type, "overlayfs")) &&
3050 (storage->flags & LXC_STORAGE_INTERNAL_OVERLAY_RESTORE)) {
1b5d4bd8 3051 ret = snprintf(path, len, "%s/%s/%s", p1, c->name, LXC_CONFIG_FNAME);
17a367d8
CB
3052 if (ret < 0 || (size_t)ret >= len)
3053 goto out;
3054
e0010464 3055 if (am_guest_unpriv())
17a367d8
CB
3056 ret = userns_exec_1(conf, lxc_unlink_exec_wrapper, path,
3057 "lxc_unlink_exec_wrapper");
3058 else
3059 ret = unlink(path);
3060 if (ret < 0) {
3061 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3062 path, c->name);
3063 goto out;
3064 }
3065 INFO("Destroyed config file \"%s\" for \"%s\"", path, c->name);
3066
3067 bret = true;
3068 goto out;
3069 }
3070
3071 ret = snprintf(path, len, "%s/%s", p1, c->name);
3072 if (ret < 0 || (size_t)ret >= len)
3073 goto out;
a73846d8 3074
e0010464 3075 if (am_guest_unpriv())
ee484f7f
CB
3076 ret = userns_exec_full(conf, lxc_rmdir_onedev_wrapper, path,
3077 "lxc_rmdir_onedev_wrapper");
4355ab5f 3078 else
18aa217b 3079 ret = lxc_rmdir_onedev(path, "snaps");
4355ab5f 3080 if (ret < 0) {
17a367d8
CB
3081 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path,
3082 c->name);
60bf62d4
SH
3083 goto out;
3084 }
17a367d8 3085 INFO("Destroyed directory \"%s\" for \"%s\"", path, c->name);
297c2d58 3086
6e54330c 3087on_success:
fef48dc9 3088 bret = true;
60bf62d4
SH
3089
3090out:
17a367d8
CB
3091 if (path)
3092 free(path);
a73846d8 3093
3bc449ed 3094 container_disk_unlock(c);
fef48dc9 3095 return bret;
72d0e1cb
SG
3096}
3097
858377e4 3098static bool do_lxcapi_destroy(struct lxc_container *c)
18aa217b
SH
3099{
3100 if (!c || !lxcapi_is_defined(c))
3101 return false;
2b2655a8 3102
6e54330c
CB
3103 if (c->lxc_conf && c->lxc_conf->rootfs.managed) {
3104 if (has_snapshots(c)) {
3105 ERROR("Container %s has snapshots; not removing", c->name);
3106 return false;
3107 }
18aa217b 3108
6e54330c
CB
3109 if (has_fs_snapshots(c)) {
3110 ERROR("container %s has snapshots on its rootfs", c->name);
3111 return false;
3112 }
18aa217b
SH
3113 }
3114
17a367d8 3115 return container_destroy(c, NULL);
18aa217b
SH
3116}
3117
858377e4 3118WRAP_API(bool, lxcapi_destroy)
18aa217b 3119
858377e4 3120static bool do_lxcapi_destroy_with_snapshots(struct lxc_container *c)
18aa217b
SH
3121{
3122 if (!c || !lxcapi_is_defined(c))
3123 return false;
a73846d8 3124
18aa217b
SH
3125 if (!lxcapi_snapshot_destroy_all(c)) {
3126 ERROR("Error deleting all snapshots");
3127 return false;
3128 }
a73846d8 3129
18aa217b
SH
3130 return lxcapi_destroy(c);
3131}
3132
858377e4
SH
3133WRAP_API(bool, lxcapi_destroy_with_snapshots)
3134
0d9cd9c3
CB
3135int lxc_set_config_item_locked(struct lxc_conf *conf, const char *key,
3136 const char *v)
96532523 3137{
0d9cd9c3 3138 int ret;
96532523 3139 struct lxc_config_t *config;
0d9cd9c3
CB
3140 bool bret = true;
3141
3142 config = lxc_get_config(key);
3143 if (!config)
3144 return -EINVAL;
3145
3146 ret = config->set(key, v, conf, NULL);
3147 if (ret < 0)
3148 return -EINVAL;
3149
3150 if (lxc_config_value_empty(v))
3151 do_clear_unexp_config_line(conf, key);
3152 else
3153 bret = do_append_unexp_config_line(conf, key, v);
3154 if (!bret)
3155 return -ENOMEM;
3156
3157 return 0;
3158}
3159
3160static bool do_set_config_item_locked(struct lxc_container *c, const char *key,
3161 const char *v)
3162{
3163 int ret;
96532523
SH
3164
3165 if (!c->lxc_conf)
3166 c->lxc_conf = lxc_conf_init();
4222a9f4 3167
6b0d5538 3168 if (!c->lxc_conf)
96532523 3169 return false;
4222a9f4 3170
0d9cd9c3
CB
3171 ret = lxc_set_config_item_locked(c->lxc_conf, key, v);
3172 if (ret < 0)
f979ac15 3173 return false;
4222a9f4 3174
0d9cd9c3 3175 return true;
96532523
SH
3176}
3177
858377e4 3178static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb 3179{
72d0e1cb 3180 bool b = false;
72d0e1cb
SG
3181
3182 if (!c)
3183 return false;
3184
5cee8c50 3185 if (container_mem_lock(c))
72d0e1cb
SG
3186 return false;
3187
0d9cd9c3 3188 b = do_set_config_item_locked(c, key, v);
72d0e1cb 3189
5cee8c50 3190 container_mem_unlock(c);
72d0e1cb
SG
3191 return b;
3192}
3193
858377e4
SH
3194WRAP_API_2(bool, lxcapi_set_config_item, const char *, const char *)
3195
72d0e1cb
SG
3196static char *lxcapi_config_file_name(struct lxc_container *c)
3197{
3198 if (!c || !c->configfile)
3199 return NULL;
a73846d8 3200
72d0e1cb
SG
3201 return strdup(c->configfile);
3202}
3203
2a59a681
SH
3204static const char *lxcapi_get_config_path(struct lxc_container *c)
3205{
3206 if (!c || !c->config_path)
3207 return NULL;
a73846d8 3208
2a59a681
SH
3209 return (const char *)(c->config_path);
3210}
3211
afeecbba
SH
3212/*
3213 * not for export
3214 * Just recalculate the c->configfile based on the
3215 * c->config_path, which must be set.
3216 * The lxc_container must be locked or not yet public.
3217 */
3218static bool set_config_filename(struct lxc_container *c)
3219{
3220 char *newpath;
3221 int len, ret;
3222
3223 if (!c->config_path)
3224 return false;
3225
3226 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1b5d4bd8 3227 len = strlen(c->config_path) + 1 + strlen(c->name) + 1 + strlen(LXC_CONFIG_FNAME) + 1;
afeecbba
SH
3228 newpath = malloc(len);
3229 if (!newpath)
3230 return false;
3231
1b5d4bd8 3232 ret = snprintf(newpath, len, "%s/%s/%s", c->config_path, c->name, LXC_CONFIG_FNAME);
afeecbba
SH
3233 if (ret < 0 || ret >= len) {
3234 fprintf(stderr, "Error printing out config file name\n");
3235 free(newpath);
3236 return false;
3237 }
3238
f10fad2f 3239 free(c->configfile);
afeecbba
SH
3240 c->configfile = newpath;
3241
3242 return true;
3243}
3244
858377e4 3245static bool do_lxcapi_set_config_path(struct lxc_container *c, const char *path)
2a59a681
SH
3246{
3247 char *p;
3248 bool b = false;
afeecbba 3249 char *oldpath = NULL;
2a59a681
SH
3250
3251 if (!c)
3252 return b;
3253
5cee8c50 3254 if (container_mem_lock(c))
2a59a681
SH
3255 return b;
3256
3257 p = strdup(path);
afeecbba
SH
3258 if (!p) {
3259 ERROR("Out of memory setting new lxc path");
2a59a681 3260 goto err;
afeecbba
SH
3261 }
3262
2a59a681
SH
3263 b = true;
3264 if (c->config_path)
afeecbba 3265 oldpath = c->config_path;
2a59a681 3266 c->config_path = p;
afeecbba
SH
3267
3268 /* Since we've changed the config path, we have to change the
3269 * config file name too */
3270 if (!set_config_filename(c)) {
3271 ERROR("Out of memory setting new config filename");
3272 b = false;
3273 free(c->config_path);
3274 c->config_path = oldpath;
3275 oldpath = NULL;
3276 }
a73846d8 3277
2a59a681 3278err:
f10fad2f 3279 free(oldpath);
5cee8c50 3280 container_mem_unlock(c);
2a59a681
SH
3281 return b;
3282}
3283
858377e4 3284WRAP_API_1(bool, lxcapi_set_config_path, const char *)
2a59a681 3285
858377e4 3286static bool do_lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
794dd120 3287{
5a076633 3288 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
69edb51d 3289 int ret;
794dd120
SH
3290
3291 if (!c)
3292 return false;
3293
3bc449ed 3294 if (is_stopped(c))
794dd120
SH
3295 return false;
3296
bfe2971a 3297 ret = cgroup_set(c->name, c->config_path, subsys, value);
739af847 3298 if (ret == -ENOCGROUP2) {
69edb51d
CB
3299 cgroup_ops = cgroup_init(c->lxc_conf);
3300 if (!cgroup_ops)
3301 return false;
2202afc9 3302
b7aeda96 3303 ret = cgroup_ops->set(cgroup_ops, subsys, value, c->name, c->config_path);
69edb51d
CB
3304 }
3305
3306 return ret == 0;
794dd120
SH
3307}
3308
858377e4
SH
3309WRAP_API_2(bool, lxcapi_set_cgroup_item, const char *, const char *)
3310
3311static int do_lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
794dd120 3312{
5a076633 3313 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
efb4b3e8 3314 int ret;
794dd120 3315
6502006a 3316 if (!c)
794dd120
SH
3317 return -1;
3318
3bc449ed 3319 if (is_stopped(c))
794dd120
SH
3320 return -1;
3321
bfe2971a 3322 ret = cgroup_get(c->name, c->config_path, subsys, retv, inlen);
739af847 3323 if (ret == -ENOCGROUP2) {
a29cc280
CB
3324 cgroup_ops = cgroup_init(c->lxc_conf);
3325 if (!cgroup_ops)
3326 return -1;
3327
3328 return cgroup_ops->get(cgroup_ops, subsys, retv, inlen, c->name, c->config_path);
3329 }
2202afc9 3330
a29cc280 3331 return ret;
794dd120
SH
3332}
3333
858377e4
SH
3334WRAP_API_3(int, lxcapi_get_cgroup_item, const char *, char *, int)
3335
593e8478 3336const char *lxc_get_global_config_item(const char *key)
83c98d82 3337{
593e8478 3338 return lxc_global_config_value(key);
a8428dfa
SH
3339}
3340
b6b918a1
SG
3341const char *lxc_get_version(void)
3342{
95ee490b 3343 return LXC_VERSION;
b6b918a1
SG
3344}
3345
f0ca2726 3346static int copy_file(const char *old, const char *new)
9be53773
SH
3347{
3348 int in, out;
3349 ssize_t len, ret;
3350 char buf[8096];
3351 struct stat sbuf;
3352
3353 if (file_exists(new)) {
3354 ERROR("copy destination %s exists", new);
3355 return -1;
3356 }
a73846d8 3357
9be53773
SH
3358 ret = stat(old, &sbuf);
3359 if (ret < 0) {
dfb31b25 3360 INFO("Error stat'ing %s", old);
9be53773
SH
3361 return -1;
3362 }
3363
3364 in = open(old, O_RDONLY);
3365 if (in < 0) {
dfb31b25 3366 SYSERROR("Error opening original file %s", old);
9be53773
SH
3367 return -1;
3368 }
a73846d8 3369
9be53773
SH
3370 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
3371 if (out < 0) {
dfb31b25 3372 SYSERROR("Error opening new file %s", new);
9be53773
SH
3373 close(in);
3374 return -1;
3375 }
3376
51a8a74c 3377 for (;;) {
3e1e9db8 3378 len = lxc_read_nointr(in, buf, 8096);
9be53773 3379 if (len < 0) {
dfb31b25 3380 SYSERROR("Error reading old file %s", old);
9be53773
SH
3381 goto err;
3382 }
a73846d8 3383
9be53773
SH
3384 if (len == 0)
3385 break;
a73846d8 3386
2a2a676d 3387 ret = lxc_write_nointr(out, buf, len);
1a0e70ac 3388 if (ret < len) { /* should we retry? */
dfb31b25 3389 SYSERROR("Error: write to new file %s was interrupted", new);
9be53773
SH
3390 goto err;
3391 }
3392 }
a73846d8 3393
9be53773
SH
3394 close(in);
3395 close(out);
3396
1a0e70ac 3397 /* We set mode, but not owner/group. */
9be53773
SH
3398 ret = chmod(new, sbuf.st_mode);
3399 if (ret) {
dfb31b25 3400 SYSERROR("Error setting mode on %s", new);
9be53773
SH
3401 return -1;
3402 }
3403
3404 return 0;
3405
3406err:
3407 close(in);
3408 close(out);
3409 return -1;
3410}
3411
9be53773
SH
3412static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
3413{
7a99b5a0 3414 __do_free char *cpath = NULL;
619256b5 3415 int i, len, ret;
9be53773 3416 struct lxc_list *it;
619256b5
ÇO
3417
3418 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
f5849fd7 3419 cpath = must_realloc(NULL, len);
619256b5
ÇO
3420 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
3421 if (ret < 0 || ret >= len)
3422 return -1;
9be53773
SH
3423
3424 for (i=0; i<NUM_LXC_HOOKS; i++) {
3425 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
3426 char *hookname = it->elem;
c32981c3 3427 char *fname = strrchr(hookname, '/');
8a22c168 3428 char tmppath[PATH_MAX];
1a0e70ac 3429 if (!fname) /* relative path - we don't support, but maybe we should */
9be53773 3430 return 0;
a73846d8 3431
619256b5 3432 if (strncmp(hookname, cpath, len - 1) != 0) {
1a0e70ac 3433 /* this hook is public - ignore */
619256b5
ÇO
3434 continue;
3435 }
a73846d8 3436
1a0e70ac 3437 /* copy the script, and change the entry in confile */
8a22c168 3438 ret = snprintf(tmppath, PATH_MAX, "%s/%s/%s",
9be53773 3439 c->config_path, c->name, fname+1);
8a22c168 3440 if (ret < 0 || ret >= PATH_MAX)
9be53773 3441 return -1;
a73846d8 3442
9be53773
SH
3443 ret = copy_file(it->elem, tmppath);
3444 if (ret < 0)
3445 return -1;
a73846d8 3446
9be53773 3447 free(it->elem);
a73846d8 3448
9be53773
SH
3449 it->elem = strdup(tmppath);
3450 if (!it->elem) {
3451 ERROR("out of memory copying hook path");
3452 return -1;
3453 }
9be53773
SH
3454 }
3455 }
3456
67702c21
SH
3457 if (!clone_update_unexp_hooks(c->lxc_conf, oldc->config_path,
3458 c->config_path, oldc->name, c->name)) {
6b0d5538
SH
3459 ERROR("Error saving new hooks in clone");
3460 return -1;
3461 }
a73846d8 3462
858377e4 3463 do_lxcapi_save_config(c, NULL);
9be53773
SH
3464 return 0;
3465}
3466
9be53773
SH
3467
3468static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
3469{
8a22c168 3470 char newpath[PATH_MAX];
9be53773
SH
3471 char *oldpath = oldc->lxc_conf->fstab;
3472 int ret;
3473
3474 if (!oldpath)
3475 return 0;
3476
47148e96
CB
3477 clear_unexp_config_line(c->lxc_conf, "lxc.mount.fstab", false);
3478
c32981c3 3479 char *p = strrchr(oldpath, '/');
9be53773
SH
3480 if (!p)
3481 return -1;
a73846d8 3482
8a22c168 3483 ret = snprintf(newpath, PATH_MAX, "%s/%s%s",
9be53773 3484 c->config_path, c->name, p);
8a22c168 3485 if (ret < 0 || ret >= PATH_MAX) {
9be53773
SH
3486 ERROR("error printing new path for %s", oldpath);
3487 return -1;
3488 }
a73846d8 3489
9be53773
SH
3490 if (file_exists(newpath)) {
3491 ERROR("error: fstab file %s exists", newpath);
3492 return -1;
3493 }
3494
3495 if (copy_file(oldpath, newpath) < 0) {
3496 ERROR("error: copying %s to %s", oldpath, newpath);
3497 return -1;
3498 }
a73846d8 3499
9be53773 3500 free(c->lxc_conf->fstab);
a73846d8 3501
9be53773
SH
3502 c->lxc_conf->fstab = strdup(newpath);
3503 if (!c->lxc_conf->fstab) {
3504 ERROR("error: allocating pathname");
3505 return -1;
3506 }
a73846d8 3507
47148e96 3508 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.mount.fstab", newpath)) {
6b0d5538
SH
3509 ERROR("error saving new lxctab");
3510 return -1;
3511 }
9be53773
SH
3512
3513 return 0;
3514}
3515
dfb31b25
SH
3516static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
3517{
8a22c168 3518 char path0[PATH_MAX], path1[PATH_MAX];
dfb31b25
SH
3519 int ret;
3520
8a22c168 3521 ret = snprintf(path0, PATH_MAX, "%s/%s/lxc_rdepends", c0->config_path,
dfb31b25 3522 c0->name);
8a22c168 3523 if (ret < 0 || ret >= PATH_MAX) {
dfb31b25
SH
3524 WARN("Error copying reverse dependencies");
3525 return;
3526 }
a73846d8 3527
8a22c168 3528 ret = snprintf(path1, PATH_MAX, "%s/%s/lxc_rdepends", c->config_path,
dfb31b25 3529 c->name);
8a22c168 3530 if (ret < 0 || ret >= PATH_MAX) {
dfb31b25
SH
3531 WARN("Error copying reverse dependencies");
3532 return;
3533 }
a73846d8 3534
dfb31b25
SH
3535 if (copy_file(path0, path1) < 0) {
3536 INFO("Error copying reverse dependencies");
3537 return;
3538 }
3539}
3540
3541static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
3542{
768e7ba2 3543 __do_fclose FILE *f = NULL;
dfb31b25 3544 int ret;
8a22c168 3545 char path[PATH_MAX];
dfb31b25 3546
768e7ba2
CB
3547 ret = snprintf(path, sizeof(path), "%s/%s/lxc_rdepends", c->config_path, c->name);
3548 if (ret < 0 || ret >= sizeof(path))
dfb31b25 3549 return false;
a73846d8 3550
4110345b 3551 f = fopen(path, "ae");
dfb31b25
SH
3552 if (!f)
3553 return false;
a73846d8 3554
1a0e70ac 3555 /* If anything goes wrong, just return an error. */
768e7ba2 3556 return fprintf(f, "%s\n%s\n", c0->config_path, c0->name) > 0;
dfb31b25
SH
3557}
3558
15a90a10
SH
3559/*
3560 * If the fs natively supports snapshot clones with no penalty,
3561 * then default to those even if not requested.
3562 * Currently we only do this for btrfs.
3563 */
59eac805 3564static bool should_default_to_snapshot(struct lxc_container *c0,
15a90a10
SH
3565 struct lxc_container *c1)
3566{
7a99b5a0 3567 __do_free char *p0 = NULL, *p1 = NULL;
2afdc31f 3568 int ret;
15a90a10
SH
3569 size_t l0 = strlen(c0->config_path) + strlen(c0->name) + 2;
3570 size_t l1 = strlen(c1->config_path) + strlen(c1->name) + 2;
6e0fa6a0 3571 char *rootfs = c0->lxc_conf->rootfs.path;
15a90a10 3572
f5849fd7
CB
3573 p0 = must_realloc(NULL, l0 + 1);
3574 p1 = must_realloc(NULL, l1 + 1);
2afdc31f
CB
3575 ret = snprintf(p0, l0, "%s/%s", c0->config_path, c0->name);
3576 if (ret < 0 || ret >= l0)
3577 return false;
3578
3579 ret = snprintf(p1, l1, "%s/%s", c1->config_path, c1->name);
3580 if (ret < 0 || ret >= l1)
3581 return false;
9a09badc
CB
3582
3583 if (!is_btrfs_fs(p0) || !is_btrfs_fs(p1))
3584 return false;
3585
6e0fa6a0
CB
3586 if (is_btrfs_subvol(rootfs) <= 0)
3587 return false;
3588
15a90a10
SH
3589 return btrfs_same_fs(p0, p1) == 0;
3590}
3591
9be53773 3592static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
763429b6
CB
3593 const char *newtype, int flags, const char *bdevdata,
3594 uint64_t newsize)
9be53773 3595{
10bc1861 3596 struct lxc_storage *bdev;
07db51a2 3597 bool need_rdep;
9be53773 3598
15a90a10
SH
3599 if (should_default_to_snapshot(c0, c))
3600 flags |= LXC_CLONE_SNAPSHOT;
3601
10bc1861
CB
3602 bdev = storage_copy(c0, c->name, c->config_path, newtype, flags,
3603 bdevdata, newsize, &need_rdep);
9be53773 3604 if (!bdev) {
763429b6 3605 ERROR("Error copying storage.");
9be53773
SH
3606 return -1;
3607 }
763429b6
CB
3608
3609 /* Set new rootfs. */
9be53773
SH
3610 free(c->lxc_conf->rootfs.path);
3611 c->lxc_conf->rootfs.path = strdup(bdev->src);
10bc1861 3612 storage_put(bdev);
763429b6 3613
dfb31b25 3614 if (!c->lxc_conf->rootfs.path) {
763429b6
CB
3615 ERROR("Out of memory while setting storage path.");
3616 return -1;
3617 }
763429b6 3618
7a96a068
CB
3619 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3620 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.path", false);
3621 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs.path",
763429b6
CB
3622 c->lxc_conf->rootfs.path)) {
3623 ERROR("Error saving new rootfs to cloned config.");
d0218321
SH
3624 return -1;
3625 }
763429b6 3626
eee59f94
SH
3627 if (flags & LXC_CLONE_SNAPSHOT)
3628 copy_rdepends(c, c0);
a73846d8 3629
dfb31b25
SH
3630 if (need_rdep) {
3631 if (!add_rdepends(c, c0))
3632 WARN("Error adding reverse dependency from %s to %s",
763429b6 3633 c->name, c0->name);
dfb31b25
SH
3634 }
3635
3636 mod_all_rdeps(c, true);
3637
9be53773
SH
3638 return 0;
3639}
3640
1354955b
SH
3641struct clone_update_data {
3642 struct lxc_container *c0;
3643 struct lxc_container *c1;
3644 int flags;
3645 char **hookargs;
3646};
3647
3648static int clone_update_rootfs(struct clone_update_data *data)
9be53773 3649{
1354955b
SH
3650 struct lxc_container *c0 = data->c0;
3651 struct lxc_container *c = data->c1;
3652 int flags = data->flags;
3653 char **hookargs = data->hookargs;
9be53773 3654 int ret = -1;
8a22c168 3655 char path[PATH_MAX];
10bc1861 3656 struct lxc_storage *bdev;
9be53773 3657 FILE *fout;
148e91f5 3658 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
3659
3660 /* update hostname in rootfs */
3661 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3662
8917c382 3663 (void)lxc_drop_groups();
b58214ac 3664
1354955b
SH
3665 if (setgid(0) < 0) {
3666 ERROR("Failed to setgid to 0");
3667 return -1;
3668 }
a73846d8 3669
1354955b
SH
3670 if (setuid(0) < 0) {
3671 ERROR("Failed to setuid to 0");
9be53773 3672 return -1;
1354955b 3673 }
a73846d8 3674
1354955b
SH
3675 if (unshare(CLONE_NEWNS) < 0)
3676 return -1;
a73846d8 3677
8a388ed4 3678 bdev = storage_init(c->lxc_conf);
9be53773 3679 if (!bdev)
1354955b 3680 return -1;
a73846d8 3681
cf3ef16d
SH
3682 if (strcmp(bdev->type, "dir") != 0) {
3683 if (unshare(CLONE_NEWNS) < 0) {
3684 ERROR("error unsharing mounts");
10bc1861 3685 storage_put(bdev);
1354955b 3686 return -1;
cf3ef16d 3687 }
a73846d8 3688
9e61fb1f
CB
3689 if (detect_shared_rootfs() && mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL))
3690 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
a73846d8 3691
e7de366c 3692 if (bdev->ops->mount(bdev) < 0) {
10bc1861 3693 storage_put(bdev);
1354955b 3694 return -1;
e7de366c 3695 }
1a0e70ac 3696 } else { /* TODO come up with a better way */
f10fad2f 3697 free(bdev->dest);
3d7e738a 3698 bdev->dest = strdup(lxc_storage_get_path(bdev->src, bdev->type));
cf3ef16d 3699 }
148e91f5
SH
3700
3701 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
3702 /* Start of environment variable setup for hooks */
a73846d8 3703 if (c0->name && setenv("LXC_SRC_NAME", c0->name, 1))
1143ed39 3704 SYSERROR("failed to set environment variable for source container name");
a73846d8 3705
3706 if (setenv("LXC_NAME", c->name, 1))
148e91f5 3707 SYSERROR("failed to set environment variable for container name");
a73846d8 3708
3709 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
148e91f5 3710 SYSERROR("failed to set environment variable for config path");
a73846d8 3711
3712 if (bdev->dest && setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1))
148e91f5 3713 SYSERROR("failed to set environment variable for rootfs mount");
a73846d8 3714
3715 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
148e91f5 3716 SYSERROR("failed to set environment variable for rootfs mount");
148e91f5 3717
14a7b0f9 3718 if (run_lxc_hooks(c->name, "clone", conf, hookargs)) {
148e91f5 3719 ERROR("Error executing clone hook for %s", c->name);
10bc1861 3720 storage_put(bdev);
1354955b 3721 return -1;
148e91f5
SH
3722 }
3723 }
3724
3725 if (!(flags & LXC_CLONE_KEEPNAME)) {
8a22c168 3726 ret = snprintf(path, PATH_MAX, "%s/etc/hostname", bdev->dest);
10bc1861 3727 storage_put(bdev);
e7de366c 3728
8a22c168 3729 if (ret < 0 || ret >= PATH_MAX)
1354955b 3730 return -1;
a73846d8 3731
8058be39 3732 if (!file_exists(path))
1354955b 3733 return 0;
a73846d8 3734
4110345b 3735 if (!(fout = fopen(path, "we"))) {
959aee9c 3736 SYSERROR("unable to open %s: ignoring", path);
1354955b 3737 return 0;
148e91f5 3738 }
a73846d8 3739
a684f0b7
ÇO
3740 if (fprintf(fout, "%s", c->name) < 0) {
3741 fclose(fout);
1354955b 3742 return -1;
6849cb5b 3743 }
a73846d8 3744
148e91f5 3745 if (fclose(fout) < 0)
1354955b 3746 return -1;
10bc1861
CB
3747 } else {
3748 storage_put(bdev);
9be53773 3749 }
e7de366c 3750
1354955b
SH
3751 return 0;
3752}
3753
3754static int clone_update_rootfs_wrapper(void *data)
3755{
3756 struct clone_update_data *arg = (struct clone_update_data *) data;
3757 return clone_update_rootfs(arg);
9be53773
SH
3758}
3759
3760/*
3761 * We want to support:
3762sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3763 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3764
ba115175
CB
3765-s [ implies overlay]
3766-s -B overlay
9be53773
SH
3767
3768only rootfs gets converted (copied/snapshotted) on clone.
3769*/
3770
d5752559 3771static int create_file_dirname(char *path, struct lxc_conf *conf)
9be53773 3772{
c32981c3 3773 char *p = strrchr(path, '/');
d5752559 3774 int ret = -1;
9be53773
SH
3775
3776 if (!p)
3777 return -1;
a73846d8 3778
9be53773 3779 *p = '\0';
d028235d 3780 ret = do_create_container_dir(path, conf);
9be53773 3781 *p = '/';
a73846d8 3782
9be53773
SH
3783 return ret;
3784}
3785
858377e4 3786static struct lxc_container *do_lxcapi_clone(struct lxc_container *c, const char *newname,
9be53773 3787 const char *lxcpath, int flags,
d659597e 3788 const char *bdevtype, const char *bdevdata, uint64_t newsize,
148e91f5 3789 char **hookargs)
9be53773 3790{
8a22c168 3791 char newpath[PATH_MAX];
0e1a60b0 3792 int fd, ret;
1354955b 3793 struct clone_update_data data;
3b392519 3794 size_t saved_unexp_len;
1354955b 3795 pid_t pid;
17a367d8
CB
3796 int storage_copied = 0;
3797 char *origroot = NULL, *saved_unexp_conf = NULL;
3798 struct lxc_container *c2 = NULL;
9be53773 3799
858377e4 3800 if (!c || !do_lxcapi_is_defined(c))
9be53773
SH
3801 return NULL;
3802
5cee8c50 3803 if (container_mem_lock(c))
9be53773 3804 return NULL;
754076f5
BH
3805 if (!is_stopped(c) && !(flags & LXC_CLONE_ALLOW_RUNNING)) {
3806 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c->name);
9be53773
SH
3807 goto out;
3808 }
3809
1a0e70ac 3810 /* Make sure the container doesn't yet exist. */
05d53f4c
SH
3811 if (!newname)
3812 newname = c->name;
a73846d8 3813
05d53f4c 3814 if (!lxcpath)
858377e4 3815 lxcpath = do_lxcapi_get_config_path(c);
a73846d8 3816
1b5d4bd8 3817 ret = snprintf(newpath, PATH_MAX, "%s/%s/%s", lxcpath, newname, LXC_CONFIG_FNAME);
8a22c168 3818 if (ret < 0 || ret >= PATH_MAX) {
9be53773
SH
3819 SYSERROR("clone: failed making config pathname");
3820 goto out;
3821 }
17a367d8 3822
9be53773
SH
3823 if (file_exists(newpath)) {
3824 ERROR("error: clone: %s exists", newpath);
3825 goto out;
3826 }
3827
d5752559 3828 ret = create_file_dirname(newpath, c->lxc_conf);
96532523 3829 if (ret < 0 && errno != EEXIST) {
9be53773
SH
3830 ERROR("Error creating container dir for %s", newpath);
3831 goto out;
3832 }
3833
1a0e70ac 3834 /* Copy the configuration. Tweak it as needed. */
8d2efe40
SH
3835 if (c->lxc_conf->rootfs.path) {
3836 origroot = c->lxc_conf->rootfs.path;
3837 c->lxc_conf->rootfs.path = NULL;
3838 }
0e1a60b0
CB
3839
3840 fd = open(newpath, O_WRONLY | O_CREAT | O_CLOEXEC,
e581b9b5 3841 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
0e1a60b0
CB
3842 if (fd < 0) {
3843 SYSERROR("Failed to open \"%s\"", newpath);
9be53773
SH
3844 goto out;
3845 }
5eea90e8
SH
3846
3847 saved_unexp_conf = c->lxc_conf->unexpanded_config;
3b392519 3848 saved_unexp_len = c->lxc_conf->unexpanded_len;
5eea90e8
SH
3849 c->lxc_conf->unexpanded_config = strdup(saved_unexp_conf);
3850 if (!c->lxc_conf->unexpanded_config) {
0e1a60b0 3851 close(fd);
5eea90e8
SH
3852 goto out;
3853 }
7a96a068 3854
7a96a068 3855 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.path", false);
0e1a60b0
CB
3856 write_config(fd, c->lxc_conf);
3857 close(fd);
a73846d8 3858
8d2efe40 3859 c->lxc_conf->rootfs.path = origroot;
a73846d8 3860
5eea90e8
SH
3861 free(c->lxc_conf->unexpanded_config);
3862 c->lxc_conf->unexpanded_config = saved_unexp_conf;
3863 saved_unexp_conf = NULL;
3b392519 3864 c->lxc_conf->unexpanded_len = saved_unexp_len;
9be53773 3865
1b5d4bd8 3866 ret = snprintf(newpath, PATH_MAX, "%s/%s/%s", lxcpath, newname, LXC_ROOTFS_DNAME);
8a22c168 3867 if (ret < 0 || ret >= PATH_MAX) {
90b366fc
CB
3868 SYSERROR("clone: failed making rootfs pathname");
3869 goto out;
3870 }
17a367d8
CB
3871
3872 ret = mkdir(newpath, 0755);
3873 if (ret < 0) {
3874 /* For an overlay container the rootfs is considered immutable
3875 * and will not have been removed when restoring from a
3876 * snapshot.
3877 */
3878 if (errno != ENOENT &&
3879 !(flags & LXC_STORAGE_INTERNAL_OVERLAY_RESTORE)) {
3880 SYSERROR("Failed to create directory \"%s\"", newpath);
3881 goto out;
3882 }
9be53773
SH
3883 }
3884
e0010464 3885 if (am_guest_unpriv()) {
1354955b 3886 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
959aee9c 3887 ERROR("Error chowning %s to container root", newpath);
1354955b
SH
3888 goto out;
3889 }
3890 }
3891
05d53f4c 3892 c2 = lxc_container_new(newname, lxcpath);
375c2258 3893 if (!c2) {
05d53f4c
SH
3894 ERROR("clone: failed to create new container (%s %s)", newname,
3895 lxcpath);
9be53773
SH
3896 goto out;
3897 }
8d2efe40 3898
1a0e70ac 3899 /* copy/snapshot rootfs's */
8d2efe40
SH
3900 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
3901 if (ret < 0)
3902 goto out;
9be53773 3903
1a0e70ac 3904 /* update utsname */
3d7ad474
CB
3905 if (!(flags & LXC_CLONE_KEEPNAME)) {
3906 clear_unexp_config_line(c2->lxc_conf, "lxc.utsname", false);
b67771bc 3907 clear_unexp_config_line(c2->lxc_conf, "lxc.uts.name", false);
3d7ad474 3908
0d9cd9c3 3909 if (!do_set_config_item_locked(c2, "lxc.uts.name", newname)) {
3d7ad474
CB
3910 ERROR("Error setting new hostname");
3911 goto out;
3912 }
96532523
SH
3913 }
3914
1a0e70ac 3915 /* copy hooks */
619256b5
ÇO
3916 ret = copyhooks(c, c2);
3917 if (ret < 0) {
3918 ERROR("error copying hooks");
3919 goto out;
9be53773
SH
3920 }
3921
3922 if (copy_fstab(c, c2) < 0) {
3923 ERROR("error copying fstab");
9be53773
SH
3924 goto out;
3925 }
3926
1a0e70ac 3927 /* update macaddrs */
6b0d5538 3928 if (!(flags & LXC_CLONE_KEEPMACADDR)) {
67702c21
SH
3929 if (!network_new_hwaddrs(c2->lxc_conf)) {
3930 ERROR("Error updating mac addresses");
6b0d5538
SH
3931 goto out;
3932 }
3933 }
9be53773 3934
1a0e70ac 3935 /* Update absolute paths for overlay mount directories. */
83e79752 3936 if (ovl_update_abs_paths(c2->lxc_conf, c->config_path, c->name, lxcpath, newname) < 0)
030ce9a9
CB
3937 goto out;
3938
1a0e70ac
CB
3939 /* We've now successfully created c2's storage, so clear it out if we
3940 * fail after this.
3941 */
176d9acb
SH
3942 storage_copied = 1;
3943
375c2258 3944 if (!c2->save_config(c2, NULL))
9be53773 3945 goto out;
9be53773 3946
1354955b
SH
3947 if ((pid = fork()) < 0) {
3948 SYSERROR("fork");
9be53773 3949 goto out;
1354955b 3950 }
a73846d8 3951
1354955b
SH
3952 if (pid > 0) {
3953 ret = wait_for_pid(pid);
3954 if (ret)
3955 goto out;
a73846d8 3956
1354955b
SH
3957 container_mem_unlock(c);
3958 return c2;
3959 }
a73846d8 3960
1354955b
SH
3961 data.c0 = c;
3962 data.c1 = c2;
3963 data.flags = flags;
3964 data.hookargs = hookargs;
a73846d8 3965
e0010464 3966 if (am_guest_unpriv())
ee484f7f
CB
3967 ret = userns_exec_full(c->lxc_conf, clone_update_rootfs_wrapper,
3968 &data, "clone_update_rootfs_wrapper");
1354955b
SH
3969 else
3970 ret = clone_update_rootfs(&data);
3971 if (ret < 0)
d8480a31 3972 _exit(EXIT_FAILURE);
9be53773 3973
5cee8c50 3974 container_mem_unlock(c);
d8480a31 3975 _exit(EXIT_SUCCESS);
9be53773
SH
3976
3977out:
5cee8c50 3978 container_mem_unlock(c);
375c2258 3979 if (c2) {
176d9acb
SH
3980 if (!storage_copied)
3981 c2->lxc_conf->rootfs.path = NULL;
a73846d8 3982
375c2258 3983 c2->destroy(c2);
9be53773 3984 lxc_container_put(c2);
375c2258 3985 }
9be53773
SH
3986
3987 return NULL;
3988}
3989
858377e4
SH
3990static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
3991 const char *lxcpath, int flags,
3992 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3993 char **hookargs)
3994{
3995 struct lxc_container * ret;
a73846d8 3996
858377e4
SH
3997 current_config = c ? c->lxc_conf : NULL;
3998 ret = do_lxcapi_clone(c, newname, lxcpath, flags, bdevtype, bdevdata, newsize, hookargs);
3999 current_config = NULL;
a73846d8 4000
858377e4
SH
4001 return ret;
4002}
4003
4004static bool do_lxcapi_rename(struct lxc_container *c, const char *newname)
06e5650e 4005{
10bc1861 4006 struct lxc_storage *bdev;
06e5650e 4007 struct lxc_container *newc;
06e5650e 4008
d693cf93 4009 if (!c || !c->name || !c->config_path || !c->lxc_conf)
06e5650e
ÇO
4010 return false;
4011
18aa217b
SH
4012 if (has_fs_snapshots(c) || has_snapshots(c)) {
4013 ERROR("Renaming a container with snapshots is not supported");
4014 return false;
4015 }
a73846d8 4016
8a388ed4 4017 bdev = storage_init(c->lxc_conf);
06e5650e
ÇO
4018 if (!bdev) {
4019 ERROR("Failed to find original backing store type");
4020 return false;
4021 }
4022
619256b5 4023 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
10bc1861 4024 storage_put(bdev);
06e5650e
ÇO
4025 if (!newc) {
4026 lxc_container_put(newc);
4027 return false;
4028 }
4029
4030 if (newc && lxcapi_is_defined(newc))
4031 lxc_container_put(newc);
4032
17a367d8 4033 if (!container_destroy(c, NULL)) {
06e5650e
ÇO
4034 ERROR("Could not destroy existing container %s", c->name);
4035 return false;
4036 }
a73846d8 4037
06e5650e
ÇO
4038 return true;
4039}
4040
858377e4
SH
4041WRAP_API_1(bool, lxcapi_rename, const char *)
4042
d6430143
CB
4043static int lxcapi_attach(struct lxc_container *c,
4044 lxc_attach_exec_t exec_function, void *exec_payload,
4045 lxc_attach_options_t *options, pid_t *attached_process)
a0e93eeb 4046{
858377e4
SH
4047 int ret;
4048
a0e93eeb
CS
4049 if (!c)
4050 return -1;
4051
858377e4
SH
4052 current_config = c->lxc_conf;
4053
d6430143
CB
4054 ret = lxc_attach(c, exec_function, exec_payload, options,
4055 attached_process);
858377e4
SH
4056 current_config = NULL;
4057 return ret;
a0e93eeb
CS
4058}
4059
d6430143
CB
4060static int do_lxcapi_attach_run_wait(struct lxc_container *c,
4061 lxc_attach_options_t *options,
4062 const char *program,
4063 const char *const argv[])
a0e93eeb
CS
4064{
4065 lxc_attach_command_t command;
4066 pid_t pid;
d6430143 4067 int ret;
a0e93eeb
CS
4068
4069 if (!c)
4070 return -1;
4071
d6430143
CB
4072 command.program = (char *)program;
4073 command.argv = (char **)argv;
a73846d8 4074
d6430143
CB
4075 ret = lxc_attach(c, lxc_attach_run_command, &command, options, &pid);
4076 if (ret < 0)
4077 return ret;
a73846d8 4078
a0e93eeb
CS
4079 return lxc_wait_for_pid_status(pid);
4080}
4081
d6430143
CB
4082static int lxcapi_attach_run_wait(struct lxc_container *c,
4083 lxc_attach_options_t *options,
4084 const char *program, const char *const argv[])
858377e4
SH
4085{
4086 int ret;
a73846d8 4087
858377e4
SH
4088 current_config = c ? c->lxc_conf : NULL;
4089 ret = do_lxcapi_attach_run_wait(c, options, program, argv);
4090 current_config = NULL;
a73846d8 4091
858377e4
SH
4092 return ret;
4093}
4094
74a3920a 4095static int get_next_index(const char *lxcpath, char *cname)
f5dd1d53 4096{
7a99b5a0 4097 __do_free char *fname = NULL;
f5dd1d53
SH
4098 struct stat sb;
4099 int i = 0, ret;
4100
f5849fd7 4101 fname = must_realloc(NULL, strlen(lxcpath) + 20);
a73846d8 4102
51a8a74c 4103 for (;;) {
f5dd1d53 4104 sprintf(fname, "%s/snap%d", lxcpath, i);
a73846d8 4105
f5dd1d53
SH
4106 ret = stat(fname, &sb);
4107 if (ret != 0)
4108 return i;
a73846d8 4109
f5dd1d53
SH
4110 i++;
4111 }
4112}
4113
18aa217b
SH
4114static bool get_snappath_dir(struct lxc_container *c, char *snappath)
4115{
4116 int ret;
a73846d8 4117
18aa217b
SH
4118 /*
4119 * If the old style snapshot path exists, use it
4120 * /var/lib/lxc -> /var/lib/lxcsnaps
4121 */
8a22c168
CB
4122 ret = snprintf(snappath, PATH_MAX, "%ssnaps", c->config_path);
4123 if (ret < 0 || ret >= PATH_MAX)
18aa217b 4124 return false;
a73846d8 4125
18aa217b 4126 if (dir_exists(snappath)) {
8a22c168
CB
4127 ret = snprintf(snappath, PATH_MAX, "%ssnaps/%s", c->config_path, c->name);
4128 if (ret < 0 || ret >= PATH_MAX)
18aa217b 4129 return false;
a73846d8 4130
18aa217b
SH
4131 return true;
4132 }
4133
4134 /*
4135 * Use the new style path
4136 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4137 */
8a22c168
CB
4138 ret = snprintf(snappath, PATH_MAX, "%s/%s/snaps", c->config_path, c->name);
4139 if (ret < 0 || ret >= PATH_MAX)
18aa217b 4140 return false;
a73846d8 4141
18aa217b
SH
4142 return true;
4143}
4144
858377e4 4145static int do_lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
f5dd1d53 4146{
f5849fd7 4147 __do_free char *dfnam = NULL;
1b5d4bd8 4148 int len;
f5dd1d53 4149 int i, flags, ret;
df05fa0f 4150 time_t timer;
4151 struct tm tm_info;
f5dd1d53 4152 struct lxc_container *c2;
8a22c168 4153 char snappath[PATH_MAX], newname[20];
df05fa0f 4154 char buffer[25];
4155 FILE *f;
f5dd1d53 4156
840f05df
SH
4157 if (!c || !lxcapi_is_defined(c))
4158 return -1;
4159
10bc1861 4160 if (!storage_can_backup(c->lxc_conf)) {
df05fa0f 4161 ERROR("%s's backing store cannot be backed up", c->name);
4162 ERROR("Your container must use another backing store type");
cdd01be2
SH
4163 return -1;
4164 }
4165
18aa217b 4166 if (!get_snappath_dir(c, snappath))
f5dd1d53 4167 return -1;
18aa217b 4168
f5dd1d53
SH
4169 i = get_next_index(snappath, c->name);
4170
4171 if (mkdir_p(snappath, 0755) < 0) {
4172 ERROR("Failed to create snapshot directory %s", snappath);
4173 return -1;
4174 }
4175
4176 ret = snprintf(newname, 20, "snap%d", i);
4177 if (ret < 0 || ret >= 20)
4178 return -1;
4179
0a83cbbb
SH
4180 /*
4181 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4182 * created in the original container
4183 */
4184 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
4185 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
068aa488 4186 if (storage_is_dir(c->lxc_conf)) {
df05fa0f 4187 ERROR("Snapshot of directory-backed container requested");
8c39f7a4 4188 ERROR("Making a copy-clone. If you do want snapshots, then");
12e6ab5d 4189 ERROR("please create overlay clone first, snapshot that");
df05fa0f 4190 ERROR("and keep the original container pristine");
8c39f7a4
SH
4191 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
4192 }
a73846d8 4193
858377e4 4194 c2 = do_lxcapi_clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
f5dd1d53 4195 if (!c2) {
df05fa0f 4196 ERROR("Failed to clone of %s:%s", c->config_path, c->name);
f5dd1d53
SH
4197 return -1;
4198 }
4199
4200 lxc_container_put(c2);
4201
1a0e70ac 4202 /* Now write down the creation time. */
f5dd1d53 4203 time(&timer);
f5dd1d53 4204
df05fa0f 4205 if (!localtime_r(&timer, &tm_info)) {
4206 ERROR("Failed to get localtime");
4207 return -1;
4208 }
4209
4210 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", &tm_info);
f5dd1d53 4211
1b5d4bd8
RK
4212 len = strlen(snappath) + 1 + strlen(newname) + 1 + strlen(LXC_TIMESTAMP_FNAME) + 1;
4213 dfnam = must_realloc(NULL, len);
4214 snprintf(dfnam, len, "%s/%s/%s", snappath, newname, LXC_TIMESTAMP_FNAME);
4110345b 4215 f = fopen(dfnam, "we");
f5dd1d53 4216 if (!f) {
959aee9c 4217 ERROR("Failed to open %s", dfnam);
f5dd1d53
SH
4218 return -1;
4219 }
a73846d8 4220
f5dd1d53
SH
4221 if (fprintf(f, "%s", buffer) < 0) {
4222 SYSERROR("Writing timestamp");
4223 fclose(f);
4224 return -1;
4225 }
a73846d8 4226
025ed0f3 4227 ret = fclose(f);
025ed0f3 4228 if (ret != 0) {
f5dd1d53
SH
4229 SYSERROR("Writing timestamp");
4230 return -1;
4231 }
4232
4233 if (commentfile) {
7a99b5a0 4234 __do_free char *path = NULL;
1a0e70ac 4235 /* $p / $name / comment \0 */
1b5d4bd8 4236 len = strlen(snappath) + 1 + strlen(newname) + 1 + strlen(LXC_COMMENT_FNAME) + 1;
a73846d8 4237
f5849fd7 4238 path = must_realloc(NULL, len);
1b5d4bd8 4239 snprintf(path, len, "%s/%s/%s", snappath, newname, LXC_COMMENT_FNAME);
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
4256static char *get_snapcomment_path(char* snappath, char *name)
4257{
1a0e70ac 4258 /* $snappath/$name/comment */
f5dd1d53
SH
4259 int ret, len = strlen(snappath) + strlen(name) + 10;
4260 char *s = malloc(len);
4261
4262 if (s) {
4263 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
4264 if (ret < 0 || ret >= len) {
4265 free(s);
4266 s = NULL;
4267 }
4268 }
a73846d8 4269
f5dd1d53
SH
4270 return s;
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
8a22c168
CB
4280 ret = snprintf(path, PATH_MAX, "%s/%s/ts", snappath, name);
4281 if (ret < 0 || ret >= PATH_MAX)
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))) {
f5dd1d53
SH
4326 if (!strcmp(direntp->d_name, "."))
4327 continue;
4328
4329 if (!strcmp(direntp->d_name, ".."))
4330 continue;
4331
1b5d4bd8 4332 ret = snprintf(path2, PATH_MAX, "%s/%s/%s", snappath, direntp->d_name, LXC_CONFIG_FNAME);
8a22c168 4333 if (ret < 0 || ret >= PATH_MAX) {
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
8a388ed4 4396 bdev = storage_init(c->lxc_conf);
f5dd1d53
SH
4397 if (!bdev) {
4398 ERROR("Failed to find original backing store type");
4399 return false;
4400 }
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 */
4407 if (!strcmp(bdev->type, "overlay") || !strcmp(bdev->type, "overlayfs"))
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)) {
10bc1861 4414 storage_put(bdev);
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
10bc1861 4426 storage_put(bdev);
f5dd1d53
SH
4427 return false;
4428 }
4429
17a367d8
CB
4430 if (!strcmp(c->name, newname)) {
4431 if (!container_destroy(c, bdev)) {
7e36f87e
ÇO
4432 ERROR("Could not destroy existing container %s", newname);
4433 lxc_container_put(snap);
10bc1861 4434 storage_put(bdev);
7e36f87e
ÇO
4435 return false;
4436 }
4437 }
4438
de269ee8
SH
4439 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
4440 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
17a367d8
CB
4441
4442 if (!strcmp(bdev->type, "overlay") || !strcmp(bdev->type, "overlayfs"))
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);
10bc1861 4447 storage_put(bdev);
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))) {
18aa217b
SH
4498 if (!strcmp(direntp->d_name, "."))
4499 continue;
a73846d8 4500
18aa217b
SH
4501 if (!strcmp(direntp->d_name, ".."))
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 */
8a22c168
CB
4582 ret = snprintf(chrootpath, PATH_MAX, "/proc/%d/root", init_pid);
4583 if (ret < 0 || ret >= PATH_MAX)
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))
238b3e5e 4654 ret = snprintf(value, LXC_MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
c6a9b0d7 4655 else if (S_ISBLK(st.st_mode))
238b3e5e 4656 ret = snprintf(value, LXC_MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
a9a0ed90 4657 else
d5aa23e6 4658 return false;
a9a0ed90
ÇO
4659
4660 /* check snprintf return code */
238b3e5e 4661 if (ret < 0 || ret >= LXC_MAX_BUFFER)
d5aa23e6 4662 return false;
a9a0ed90 4663
caab004f
TA
4664 init_pid = do_lxcapi_init_pid(c);
4665 if (init_pid < 0) {
4666 ERROR("Failed to get init pid");
4667 return false;
4668 }
4669
4670 if (!do_add_remove_node(init_pid, p, add, &st))
d5aa23e6 4671 return false;
a9a0ed90 4672
d5aa23e6 4673 /* add or remove device to/from cgroup access list */
a9a0ed90 4674 if (add) {
858377e4 4675 if (!do_lxcapi_set_cgroup_item(c, "devices.allow", value)) {
a9a0ed90 4676 ERROR("set_cgroup_item failed while adding the device node");
d5aa23e6 4677 return false;
a9a0ed90
ÇO
4678 }
4679 } else {
858377e4 4680 if (!do_lxcapi_set_cgroup_item(c, "devices.deny", value)) {
a9a0ed90 4681 ERROR("set_cgroup_item failed while removing the device node");
d5aa23e6 4682 return false;
a9a0ed90
ÇO
4683 }
4684 }
d5aa23e6 4685
a9a0ed90 4686 return true;
a9a0ed90
ÇO
4687}
4688
858377e4 4689static bool do_lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 4690{
e0010464 4691 // cannot mknod if we're not privileged wrt init_user_ns
5384e99d 4692 if (am_host_unpriv()) {
238b3e5e 4693 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
c868b261
ÇO
4694 return false;
4695 }
a73846d8 4696
a9a0ed90
ÇO
4697 return add_remove_device_node(c, src_path, dest_path, true);
4698}
4699
858377e4
SH
4700WRAP_API_2(bool, lxcapi_add_device_node, const char *, const char *)
4701
4702static bool do_lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 4703{
e0010464 4704 if (am_guest_unpriv()) {
238b3e5e 4705 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
c868b261
ÇO
4706 return false;
4707 }
a73846d8 4708
a9a0ed90
ÇO
4709 return add_remove_device_node(c, src_path, dest_path, false);
4710}
4711
858377e4
SH
4712WRAP_API_2(bool, lxcapi_remove_device_node, const char *, const char *)
4713
c7d76c09
CB
4714static bool do_lxcapi_attach_interface(struct lxc_container *c,
4715 const char *ifname,
4716 const char *dst_ifname)
e58fae8f 4717{
c7d76c09 4718 pid_t init_pid;
e58fae8f 4719 int ret = 0;
c7d76c09 4720
e0010464 4721 if (am_guest_unpriv()) {
238b3e5e 4722 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
e58fae8f
DY
4723 return false;
4724 }
4725
4726 if (!ifname) {
4727 ERROR("No source interface name given");
4728 return false;
4729 }
4730
4731 ret = lxc_netdev_isup(ifname);
e5848d39
SH
4732 if (ret > 0) {
4733 /* netdev of ifname is up. */
e58fae8f
DY
4734 ret = lxc_netdev_down(ifname);
4735 if (ret)
4736 goto err;
4737 }
4738
c7d76c09 4739 init_pid = do_lxcapi_init_pid(c);
caab004f
TA
4740 if (init_pid < 0) {
4741 ERROR("Failed to get init pid");
4742 goto err;
4743 }
4744
c7d76c09 4745 ret = lxc_netdev_move_by_name(ifname, init_pid, dst_ifname);
e58fae8f
DY
4746 if (ret)
4747 goto err;
4748
c7d76c09 4749 INFO("Moved network device \"%s\" to network namespace of %d", ifname, init_pid);
e58fae8f 4750 return true;
e5848d39 4751
e58fae8f 4752err:
e58fae8f
DY
4753 return false;
4754}
4755
858377e4
SH
4756WRAP_API_2(bool, lxcapi_attach_interface, const char *, const char *)
4757
c7d76c09
CB
4758static bool do_lxcapi_detach_interface(struct lxc_container *c,
4759 const char *ifname,
4760 const char *dst_ifname)
e58fae8f 4761{
c7d76c09 4762 int ret;
e58fae8f 4763 pid_t pid, pid_outside;
e4103cf6 4764 __do_free char *physname = NULL;
e58fae8f 4765
e0010464
SH
4766 /*
4767 * TODO - if this is a physical device, then we need am_host_unpriv.
4768 * But for other types guest privilege suffices.
4769 */
4770 if (am_guest_unpriv()) {
238b3e5e 4771 ERROR(LXC_UNPRIV_EOPNOTSUPP, __FUNCTION__);
e58fae8f
DY
4772 return false;
4773 }
4774
4775 if (!ifname) {
4776 ERROR("No source interface name given");
4777 return false;
4778 }
4779
0059379f 4780 pid_outside = lxc_raw_getpid();
e58fae8f
DY
4781 pid = fork();
4782 if (pid < 0) {
c7d76c09 4783 ERROR("Failed to fork");
e58fae8f
DY
4784 return false;
4785 }
4786
1a0e70ac 4787 if (pid == 0) { /* child */
acbfeda8
CB
4788 pid_t init_pid;
4789
4790 init_pid = do_lxcapi_init_pid(c);
caab004f
TA
4791 if (init_pid < 0) {
4792 ERROR("Failed to get init pid");
4793 _exit(EXIT_FAILURE);
4794 }
acbfeda8
CB
4795 if (!switch_to_ns(init_pid, "net")) {
4796 ERROR("Failed to enter network namespace");
8d7b6c25 4797 _exit(EXIT_FAILURE);
e58fae8f
DY
4798 }
4799
e4103cf6
TP
4800 /* create new mount namespace for use with remounting /sys and is_wlan() below. */
4801 ret = unshare(CLONE_NEWNS);
4802 if (ret < 0) {
4803 ERROR("Failed to unshare mount namespace");
4804 _exit(EXIT_FAILURE);
4805 }
4806
4807 /* set / recursively as private so that mount propagation doesn't affect us. */
4808 if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0) < 0) {
4809 ERROR("Failed to recursively set / as private in mount namespace");
4810 _exit(EXIT_FAILURE);
4811 }
4812
e58fae8f 4813 ret = lxc_netdev_isup(ifname);
c7d76c09
CB
4814 if (ret < 0) {
4815 ERROR("Failed to determine whether network device \"%s\" is up", ifname);
8d7b6c25 4816 _exit(EXIT_FAILURE);
c7d76c09 4817 }
e58fae8f
DY
4818
4819 /* netdev of ifname is up. */
4820 if (ret) {
4821 ret = lxc_netdev_down(ifname);
c7d76c09
CB
4822 if (ret) {
4823 ERROR("Failed to set network device \"%s\" down", ifname);
8d7b6c25 4824 _exit(EXIT_FAILURE);
c7d76c09 4825 }
e58fae8f
DY
4826 }
4827
e4103cf6
TP
4828 /* remount /sys so is_wlan() can check if this device is a wlan device. */
4829 lxc_attach_remount_sys_proc();
4830 physname = is_wlan(ifname);
4831 if (physname)
4832 ret = lxc_netdev_move_wlan(physname, ifname, pid_outside, dst_ifname);
4833 else
4834 ret = lxc_netdev_move_by_name(ifname, pid_outside, dst_ifname);
4835
c7d76c09
CB
4836 /* -EINVAL means there is no netdev named as ifname. */
4837 if (ret < 0) {
4838 if (ret == -EINVAL)
4839 ERROR("Network device \"%s\" not found", ifname);
4840 else
4841 ERROR("Failed to remove network device \"%s\"", ifname);
a73846d8 4842
8d7b6c25 4843 _exit(EXIT_FAILURE);
e58fae8f 4844 }
c7d76c09 4845
8d7b6c25 4846 _exit(EXIT_SUCCESS);
e58fae8f
DY
4847 }
4848
c7d76c09
CB
4849 ret = wait_for_pid(pid);
4850 if (ret != 0)
e58fae8f
DY
4851 return false;
4852
c7d76c09 4853 INFO("Moved network device \"%s\" to network namespace of %d", ifname, pid_outside);
e58fae8f
DY
4854 return true;
4855}
4856
858377e4
SH
4857WRAP_API_2(bool, lxcapi_detach_interface, const char *, const char *)
4858
aef3d51e
TA
4859static int do_lxcapi_migrate(struct lxc_container *c, unsigned int cmd,
4860 struct migrate_opts *opts, unsigned int size)
bbd4e13e 4861{
6b9be523 4862 int ret = -1;
2cb80427 4863 struct migrate_opts *valid_opts = opts;
b5b12b9e 4864 uint64_t features_to_check = 0;
85c50991 4865
aef3d51e
TA
4866 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4867 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4868 * to do anything special.
4869 */
4870 if (size > sizeof(*opts)) {
4871 unsigned char *addr;
4872 unsigned char *end;
4873
4874 addr = (void *)opts + sizeof(*opts);
4875 end = (void *)opts + size;
a73846d8 4876
4877 for (; addr < end; addr++)
4878 if (*addr)
aef3d51e 4879 return -E2BIG;
85c50991
TA
4880 }
4881
2cb80427
TA
4882 /* If the caller has a smaller struct, let's zero out the end for them
4883 * so we don't accidentally use bits of it that they didn't know about
4884 * to initialize.
4885 */
4886 if (size < sizeof(*opts)) {
4887 valid_opts = malloc(sizeof(*opts));
4888 if (!valid_opts)
4889 return -ENOMEM;
4890
4891 memset(valid_opts, 0, sizeof(*opts));
4892 memcpy(valid_opts, opts, size);
4893 }
4894
aef3d51e
TA
4895 switch (cmd) {
4896 case MIGRATE_PRE_DUMP:
7ad13c91
TA
4897 if (!do_lxcapi_is_running(c)) {
4898 ERROR("container is not running");
6b9be523 4899 goto on_error;
7ad13c91 4900 }
a73846d8 4901
2cb80427 4902 ret = !__criu_pre_dump(c, valid_opts);
aef3d51e
TA
4903 break;
4904 case MIGRATE_DUMP:
7ad13c91
TA
4905 if (!do_lxcapi_is_running(c)) {
4906 ERROR("container is not running");
6b9be523 4907 goto on_error;
7ad13c91 4908 }
a73846d8 4909
2cb80427 4910 ret = !__criu_dump(c, valid_opts);
aef3d51e
TA
4911 break;
4912 case MIGRATE_RESTORE:
7ad13c91
TA
4913 if (do_lxcapi_is_running(c)) {
4914 ERROR("container is already running");
6b9be523 4915 goto on_error;
7ad13c91 4916 }
a73846d8 4917
2cb80427 4918 ret = !__criu_restore(c, valid_opts);
aef3d51e 4919 break;
b5b12b9e
AR
4920 case MIGRATE_FEATURE_CHECK:
4921 features_to_check = valid_opts->features_to_check;
4922 ret = !__criu_check_feature(&features_to_check);
4923 if (ret) {
4924 /* Something went wrong. Let's let the caller
4925 * know which feature checks failed. */
4926 valid_opts->features_to_check = features_to_check;
4927 }
4928 break;
aef3d51e
TA
4929 default:
4930 ERROR("invalid migrate command %u", cmd);
4931 ret = -EINVAL;
4932 }
735f2c6e 4933
6b9be523 4934on_error:
f686506d
TA
4935 if (size < sizeof(*opts))
4936 free(valid_opts);
4937
aef3d51e
TA
4938 return ret;
4939}
735f2c6e 4940
aef3d51e 4941WRAP_API_3(int, lxcapi_migrate, unsigned int, struct migrate_opts *, unsigned int)
735f2c6e 4942
aef3d51e
TA
4943static bool do_lxcapi_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose)
4944{
ebb088e1
AR
4945 struct migrate_opts opts;
4946
4947 memset(&opts, 0, sizeof(opts));
4948
4949 opts.directory = directory;
4950 opts.stop = stop;
4951 opts.verbose = verbose;
735f2c6e 4952
aef3d51e 4953 return !do_lxcapi_migrate(c, MIGRATE_DUMP, &opts, sizeof(opts));
735f2c6e
TA
4954}
4955
858377e4
SH
4956WRAP_API_3(bool, lxcapi_checkpoint, char *, bool, bool)
4957
4958static bool do_lxcapi_restore(struct lxc_container *c, char *directory, bool verbose)
c9d8f2ee 4959{
ebb088e1
AR
4960 struct migrate_opts opts;
4961
4962 memset(&opts, 0, sizeof(opts));
4963
4964 opts.directory = directory;
4965 opts.verbose = verbose;
c9d8f2ee 4966
aef3d51e 4967 return !do_lxcapi_migrate(c, MIGRATE_RESTORE, &opts, sizeof(opts));
735f2c6e
TA
4968}
4969
858377e4
SH
4970WRAP_API_2(bool, lxcapi_restore, char *, bool)
4971
1f5a90f9
CB
4972/* @st_mode is the st_mode field of the stat(source) return struct */
4973static int create_mount_target(const char *dest, mode_t st_mode)
4974{
4975 char *dirdup, *destdirname;
4976 int ret;
4977
4978 dirdup = strdup(dest);
4979 if (!dirdup) {
4980 SYSERROR("Failed to duplicate target name \"%s\"", dest);
4981 return -1;
4982 }
4983 destdirname = dirname(dirdup);
4984
4985 ret = mkdir_p(destdirname, 0755);
4986 if (ret < 0) {
4987 SYSERROR("Failed to create \"%s\"", destdirname);
4988 free(dirdup);
4989 return ret;
4990 }
4991 free(dirdup);
4992
4993 (void)remove(dest);
4994
4995 if (S_ISDIR(st_mode))
4996 ret = mkdir(dest, 0000);
4997 else
4998 ret = mknod(dest, S_IFREG | 0000, 0);
71521317
SG
4999
5000 if (ret == 0)
5001 TRACE("Created mount target \"%s\"", dest);
d8bc14a7 5002 else if (ret < 0 && errno != EEXIST) {
1f5a90f9
CB
5003 SYSERROR("Failed to create mount target \"%s\"", dest);
5004 return -1;
5005 }
5006
5007 return 0;
5008}
5009
3340f441
CB
5010static int do_lxcapi_mount(struct lxc_container *c, const char *source,
5011 const char *target, const char *filesystemtype,
5012 unsigned long mountflags, const void *data,
5013 struct lxc_mount *mnt)
5014{
29df56cd 5015 char *suff, *sret;
8a22c168 5016 char template[PATH_MAX], path[PATH_MAX];
29df56cd 5017 pid_t pid, init_pid;
c6885c3f 5018 struct stat sb;
ecce75a6 5019 bool is_dir;
29df56cd
LT
5020 int ret = -1, fd = -EBADF;
5021
5022 if (!c || !c->lxc_conf) {
5023 ERROR("Container or configuration is NULL");
5024 return -EINVAL;
5025 }
5026
7a41e857 5027 if (!c->lxc_conf->shmount.path_host) {
29df56cd
LT
5028 ERROR("Host path to shared mountpoint must be specified in the config\n");
5029 return -EINVAL;
5030 }
29df56cd 5031
60534030
LT
5032 ret = snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c->lxc_conf->shmount.path_host);
5033 if (ret < 0 || (size_t)ret >= sizeof(template)) {
29df56cd
LT
5034 SYSERROR("Error writing shmounts tempdir name");
5035 goto out;
5036 }
5037
c6885c3f
LT
5038 /* Create a temporary file / dir under the shared mountpoint */
5039 if (!source || strcmp(source, "") == 0) {
5040 /* If source is not specified, maybe we want to mount a filesystem? */
5041 sb.st_mode = S_IFDIR;
5042 } else {
5043 ret = stat(source, &sb);
5044 if (ret < 0) {
5045 SYSERROR("Error getting stat info about the source \"%s\"", source);
5046 goto out;
5047 }
5048 }
5049
ecce75a6
CB
5050 is_dir = (S_ISDIR(sb.st_mode) != 0);
5051 if (is_dir) {
c6885c3f
LT
5052 sret = mkdtemp(template);
5053 if (!sret) {
5054 SYSERROR("Could not create shmounts temporary dir");
5055 goto out;
5056 }
c6885c3f
LT
5057 } else {
5058 fd = lxc_make_tmpfile(template, false);
5059 if (fd < 0) {
5060 SYSERROR("Could not create shmounts temporary file");
5061 goto out;
5062 }
29df56cd
LT
5063 }
5064
5065 /* Do the fork */
5066 pid = fork();
5067 if (pid < 0) {
5068 SYSERROR("Could not fork");
5069 goto out;
5070 }
5071
5072 if (pid == 0) {
5073 /* Do the mount */
5074 ret = mount(source, template, filesystemtype, mountflags, data);
5075 if (ret < 0) {
c6885c3f 5076 SYSERROR("Failed to mount onto \"%s\"", template);
29df56cd
LT
5077 _exit(EXIT_FAILURE);
5078 }
3340f441 5079 TRACE("Mounted \"%s\" onto \"%s\"", source, template);
29df56cd
LT
5080
5081 init_pid = do_lxcapi_init_pid(c);
5082 if (init_pid < 0) {
5083 ERROR("Failed to obtain container's init pid");
5084 _exit(EXIT_FAILURE);
5085 }
5086
5087 /* Enter the container namespaces */
5088 if (!lxc_list_empty(&c->lxc_conf->id_map)) {
4e5a9657 5089 if (!switch_to_ns(init_pid, "user")) {
29df56cd
LT
5090 ERROR("Failed to enter user namespace");
5091 _exit(EXIT_FAILURE);
5092 }
4e5a9657
CB
5093
5094 if (!lxc_switch_uid_gid(0, 0))
5095 _exit(EXIT_FAILURE);
29df56cd 5096 }
3340f441 5097
29df56cd
LT
5098 if (!switch_to_ns(init_pid, "mnt")) {
5099 ERROR("Failed to enter mount namespace");
5100 _exit(EXIT_FAILURE);
5101 }
5102
71521317
SG
5103 ret = create_mount_target(target, sb.st_mode);
5104 if (ret < 0)
5105 _exit(EXIT_FAILURE);
c6885c3f 5106
29df56cd
LT
5107 suff = strrchr(template, '/');
5108 if (!suff)
1f77c35e 5109 goto cleanup_target_in_child;
29df56cd 5110
60534030
LT
5111 ret = snprintf(path, sizeof(path), "%s%s", c->lxc_conf->shmount.path_cont, suff);
5112 if (ret < 0 || (size_t)ret >= sizeof(path)) {
29df56cd 5113 SYSERROR("Error writing container mountpoint name");
1f77c35e 5114 goto cleanup_target_in_child;
29df56cd
LT
5115 }
5116
3340f441 5117 ret = mount(path, target, NULL, MS_MOVE | MS_REC, NULL);
29df56cd
LT
5118 if (ret < 0) {
5119 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path, target);
1f77c35e 5120 goto cleanup_target_in_child;
29df56cd 5121 }
3340f441 5122 TRACE("Moved mount from \"%s\" to \"%s\"", path, target);
29df56cd
LT
5123
5124 _exit(EXIT_SUCCESS);
1f77c35e
CB
5125
5126 cleanup_target_in_child:
5127 (void)remove(target);
5128 _exit(EXIT_FAILURE);
29df56cd
LT
5129 }
5130
5131 ret = wait_for_pid(pid);
1f77c35e
CB
5132 if (ret < 0)
5133 SYSERROR("Wait for the child with pid %ld failed", (long)pid);
5134 else
5135 ret = 0;
29df56cd 5136
1f77c35e
CB
5137 if (umount2(template, MNT_DETACH))
5138 SYSWARN("Failed to remove temporary mount \"%s\"", template);
29df56cd 5139
ecce75a6
CB
5140 if (is_dir)
5141 (void)rmdir(template);
5142 else
5143 (void)unlink(template);
29df56cd
LT
5144
5145out:
5146 if (fd >= 0)
5147 close(fd);
3340f441 5148
29df56cd
LT
5149 return ret;
5150}
5151
5152WRAP_API_6(int, lxcapi_mount, const char *, const char *, const char *,
d83da817
LT
5153 unsigned long, const void *, struct lxc_mount *)
5154
5155static int do_lxcapi_umount(struct lxc_container *c, const char *target,
7a41e857 5156 unsigned long flags, struct lxc_mount *mnt)
d83da817
LT
5157{
5158 pid_t pid, init_pid;
5159 int ret = -1;
5160
5161 if (!c || !c->lxc_conf) {
5162 ERROR("Container or configuration is NULL");
5163 return -EINVAL;
5164 }
5165
5166 /* Do the fork */
5167 pid = fork();
5168 if (pid < 0) {
5169 SYSERROR("Could not fork");
5170 return -1;
5171 }
5172
5173 if (pid == 0) {
5174 init_pid = do_lxcapi_init_pid(c);
5175 if (init_pid < 0) {
5176 ERROR("Failed to obtain container's init pid");
5177 _exit(EXIT_FAILURE);
5178 }
5179
5180 /* Enter the container namespaces */
5181 if (!lxc_list_empty(&c->lxc_conf->id_map)) {
5182 if (!switch_to_ns(init_pid, "user")) {
5183 ERROR("Failed to enter user namespace");
5184 _exit(EXIT_FAILURE);
5185 }
5186 }
5187
5188 if (!switch_to_ns(init_pid, "mnt")) {
5189 ERROR("Failed to enter mount namespace");
5190 _exit(EXIT_FAILURE);
5191 }
5192
5193 /* Do the unmount */
7a41e857 5194 ret = umount2(target, flags);
d83da817
LT
5195 if (ret < 0) {
5196 SYSERROR("Failed to umount \"%s\"", target);
5197 _exit(EXIT_FAILURE);
5198 }
5199
5200 _exit(EXIT_SUCCESS);
5201 }
5202
5203 ret = wait_for_pid(pid);
5204 if (ret < 0) {
5205 SYSERROR("Wait for the child with pid %ld failed", (long)pid);
5206 return -ret;
5207 }
5208
5209 return 0;
5210}
5211
5212WRAP_API_3(int, lxcapi_umount, const char *, unsigned long, struct lxc_mount*)
29df56cd 5213
a0e93eeb
CS
5214static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
5215{
5216 va_list ap;
5217 const char **argv;
5218 int ret;
5219
5220 if (!c)
5221 return -1;
5222
858377e4
SH
5223 current_config = c->lxc_conf;
5224
a0e93eeb
CS
5225 va_start(ap, arg);
5226 argv = lxc_va_arg_list_to_argv_const(ap, 1);
5227 va_end(ap);
5228
5229 if (!argv) {
5230 ERROR("Memory allocation error.");
858377e4
SH
5231 ret = -1;
5232 goto out;
a0e93eeb
CS
5233 }
5234 argv[0] = arg;
5235
858377e4 5236 ret = do_lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
a0e93eeb 5237 free((void*)argv);
a73846d8 5238
858377e4
SH
5239out:
5240 current_config = NULL;
a0e93eeb
CS
5241 return ret;
5242}
5243
679289bf 5244static int do_lxcapi_seccomp_notify_fd(struct lxc_container *c)
cdb2a47f 5245{
cdb2a47f 5246 if (!c || !c->lxc_conf)
b18f6aac 5247 return ret_set_errno(-1, -EINVAL);
cdb2a47f 5248
679289bf 5249 return lxc_seccomp_get_notify_fd(&c->lxc_conf->seccomp);
cdb2a47f
CB
5250}
5251
679289bf 5252WRAP_API(int, lxcapi_seccomp_notify_fd)
cdb2a47f 5253
21405769
CB
5254static int do_lxcapi_seccomp_notify_fd_active(struct lxc_container *c)
5255{
5256 if (!c || !c->lxc_conf)
5257 return ret_set_errno(-1, -EINVAL);
5258
5259 return lxc_cmd_get_seccomp_notify_fd(c->name, c->config_path);
5260}
5261
5262WRAP_API(int, lxcapi_seccomp_notify_fd_active)
5263
afeecbba 5264struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
5265{
5266 struct lxc_container *c;
cbb9c7c7 5267 size_t len;
9fbe07f6 5268 int rc;
72d0e1cb 5269
18aa217b
SH
5270 if (!name)
5271 return NULL;
5272
72d0e1cb
SG
5273 c = malloc(sizeof(*c));
5274 if (!c) {
e9e29a33 5275 fprintf(stderr, "Failed to allocate memory for %s\n", name);
72d0e1cb
SG
5276 return NULL;
5277 }
5278 memset(c, 0, sizeof(*c));
5279
afeecbba
SH
5280 if (configpath)
5281 c->config_path = strdup(configpath);
5282 else
593e8478 5283 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
2a59a681 5284 if (!c->config_path) {
e9e29a33 5285 fprintf(stderr, "Failed to allocate memory for %s\n", name);
2a59a681
SH
5286 goto err;
5287 }
5288
f5dd1d53 5289 remove_trailing_slashes(c->config_path);
cbb9c7c7
DJ
5290
5291 len = strlen(name);
5292 c->name = malloc(len + 1);
72d0e1cb 5293 if (!c->name) {
e9e29a33 5294 fprintf(stderr, "Failed to allocate memory for %s\n", name);
72d0e1cb
SG
5295 goto err;
5296 }
cbb9c7c7 5297 (void)strlcpy(c->name, name, len + 1);
72d0e1cb
SG
5298
5299 c->numthreads = 1;
e9e29a33
CB
5300 c->slock = lxc_newlock(c->config_path, name);
5301 if (!c->slock) {
5302 fprintf(stderr, "Failed to create lock for %s\n", name);
72d0e1cb
SG
5303 goto err;
5304 }
5305
e9e29a33
CB
5306 c->privlock = lxc_newlock(NULL, NULL);
5307 if (!c->privlock) {
5308 fprintf(stderr, "Failed to create private lock for %s\n", name);
72d0e1cb
SG
5309 goto err;
5310 }
5311
afeecbba 5312 if (!set_config_filename(c)) {
e9e29a33 5313 fprintf(stderr, "Failed to create config file name for %s\n", name);
72d0e1cb
SG
5314 goto err;
5315 }
72d0e1cb 5316
e9e29a33
CB
5317 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL)) {
5318 fprintf(stderr, "Failed to load config for %s\n", name);
bac806d1 5319 goto err;
e9e29a33 5320 }
72d0e1cb 5321
9fbe07f6
RK
5322 rc = ongoing_create(c);
5323 switch (rc) {
5324 case LXC_CREATE_INCOMPLETE:
5325 SYSERROR("Failed to complete container creation for %s", c->name);
17a367d8 5326 container_destroy(c, NULL);
4df7f012 5327 lxcapi_clear_config(c);
9fbe07f6
RK
5328 break;
5329 case LXC_CREATE_ONGOING:
5330 /* container creation going on */
5331 break;
5332 case LXC_CREATE_FAILED:
5333 /* container creation failed */
5334 if (errno != EACCES && errno != EPERM) {
5335 /* insufficient privileges */
5336 SYSERROR("Failed checking for incomplete container %s creation", c->name);
5337 goto err;
5338 }
5339 break;
3e625e2d 5340 }
a73846d8 5341
a2739df5 5342 c->daemonize = true;
72cf75fa 5343 c->pidfile = NULL;
3e625e2d 5344
1a0e70ac 5345 /* Assign the member functions. */
72d0e1cb
SG
5346 c->is_defined = lxcapi_is_defined;
5347 c->state = lxcapi_state;
5348 c->is_running = lxcapi_is_running;
5349 c->freeze = lxcapi_freeze;
5350 c->unfreeze = lxcapi_unfreeze;
0115f8fd 5351 c->console = lxcapi_console;
b5159817 5352 c->console_getfd = lxcapi_console_getfd;
f797f05e 5353 c->devpts_fd = lxcapi_devpts_fd;
72d0e1cb 5354 c->init_pid = lxcapi_init_pid;
fa3621ea 5355 c->init_pidfd = lxcapi_init_pidfd;
72d0e1cb
SG
5356 c->load_config = lxcapi_load_config;
5357 c->want_daemonize = lxcapi_want_daemonize;
130a1888 5358 c->want_close_all_fds = lxcapi_want_close_all_fds;
72d0e1cb
SG
5359 c->start = lxcapi_start;
5360 c->startl = lxcapi_startl;
5361 c->stop = lxcapi_stop;
5362 c->config_file_name = lxcapi_config_file_name;
5363 c->wait = lxcapi_wait;
5364 c->set_config_item = lxcapi_set_config_item;
5365 c->destroy = lxcapi_destroy;
18aa217b 5366 c->destroy_with_snapshots = lxcapi_destroy_with_snapshots;
06e5650e 5367 c->rename = lxcapi_rename;
72d0e1cb
SG
5368 c->save_config = lxcapi_save_config;
5369 c->get_keys = lxcapi_get_keys;
5370 c->create = lxcapi_create;
5371 c->createl = lxcapi_createl;
5372 c->shutdown = lxcapi_shutdown;
3e625e2d 5373 c->reboot = lxcapi_reboot;
d39b10eb 5374 c->reboot2 = lxcapi_reboot2;
4df7f012 5375 c->clear_config = lxcapi_clear_config;
72d0e1cb
SG
5376 c->clear_config_item = lxcapi_clear_config_item;
5377 c->get_config_item = lxcapi_get_config_item;
8ac18377 5378 c->get_running_config_item = lxcapi_get_running_config_item;
794dd120
SH
5379 c->get_cgroup_item = lxcapi_get_cgroup_item;
5380 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
5381 c->get_config_path = lxcapi_get_config_path;
5382 c->set_config_path = lxcapi_set_config_path;
9be53773 5383 c->clone = lxcapi_clone;
799f29ab 5384 c->get_interfaces = lxcapi_get_interfaces;
9c83a661 5385 c->get_ips = lxcapi_get_ips;
a0e93eeb
CS
5386 c->attach = lxcapi_attach;
5387 c->attach_run_wait = lxcapi_attach_run_wait;
5388 c->attach_run_waitl = lxcapi_attach_run_waitl;
f5dd1d53
SH
5389 c->snapshot = lxcapi_snapshot;
5390 c->snapshot_list = lxcapi_snapshot_list;
5391 c->snapshot_restore = lxcapi_snapshot_restore;
771d96b3 5392 c->snapshot_destroy = lxcapi_snapshot_destroy;
18aa217b 5393 c->snapshot_destroy_all = lxcapi_snapshot_destroy_all;
b494d2dd 5394 c->may_control = lxcapi_may_control;
a9a0ed90
ÇO
5395 c->add_device_node = lxcapi_add_device_node;
5396 c->remove_device_node = lxcapi_remove_device_node;
e58fae8f
DY
5397 c->attach_interface = lxcapi_attach_interface;
5398 c->detach_interface = lxcapi_detach_interface;
735f2c6e
TA
5399 c->checkpoint = lxcapi_checkpoint;
5400 c->restore = lxcapi_restore;
aef3d51e 5401 c->migrate = lxcapi_migrate;
191d43cc 5402 c->console_log = lxcapi_console_log;
29df56cd 5403 c->mount = lxcapi_mount;
d83da817 5404 c->umount = lxcapi_umount;
679289bf 5405 c->seccomp_notify_fd = lxcapi_seccomp_notify_fd;
21405769 5406 c->seccomp_notify_fd_active = lxcapi_seccomp_notify_fd_active;
72d0e1cb 5407
72d0e1cb
SG
5408 return c;
5409
5410err:
5411 lxc_container_free(c);
5412 return NULL;
5413}
5414
4a7c7daa 5415int lxc_get_wait_states(const char **states)
72d0e1cb
SG
5416{
5417 int i;
5418
5419 if (states)
5420 for (i=0; i<MAX_STATE; i++)
5421 states[i] = lxc_state2str(i);
a73846d8 5422
72d0e1cb
SG
5423 return MAX_STATE;
5424}
a41f104b 5425
a41f104b
SH
5426/*
5427 * These next two could probably be done smarter with reusing a common function
5428 * with different iterators and tests...
5429 */
5430int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
5431{
4110345b 5432 __do_closedir DIR *dir = NULL;
a41f104b 5433 int i, cfound = 0, nfound = 0;
74f96976 5434 struct dirent *direntp;
a41f104b
SH
5435 struct lxc_container *c;
5436
5437 if (!lxcpath)
593e8478 5438 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b 5439
a41f104b 5440 dir = opendir(lxcpath);
a41f104b
SH
5441 if (!dir) {
5442 SYSERROR("opendir on lxcpath");
5443 return -1;
5444 }
5445
5446 if (cret)
5447 *cret = NULL;
a73846d8 5448
a41f104b
SH
5449 if (names)
5450 *names = NULL;
5451
74f96976 5452 while ((direntp = readdir(dir))) {
1a0e70ac 5453 /* Ignore '.', '..' and any hidden directory. */
e4ebeab1 5454 if (!strncmp(direntp->d_name, ".", 1))
a41f104b
SH
5455 continue;
5456
5457 if (!config_file_exists(lxcpath, direntp->d_name))
5458 continue;
5459
a73846d8 5460 if (names)
9c88ff1f 5461 if (!add_to_array(names, direntp->d_name, cfound))
a41f104b 5462 goto free_bad;
a73846d8 5463
a41f104b
SH
5464 cfound++;
5465
5466 if (!cret) {
5467 nfound++;
5468 continue;
5469 }
5470
5471 c = lxc_container_new(direntp->d_name, lxcpath);
5472 if (!c) {
5473 INFO("Container %s:%s has a config but could not be loaded",
5474 lxcpath, direntp->d_name);
a73846d8 5475
a41f104b 5476 if (names)
9c88ff1f
ÇO
5477 if(!remove_from_array(names, direntp->d_name, cfound--))
5478 goto free_bad;
a73846d8 5479
a41f104b
SH
5480 continue;
5481 }
a73846d8 5482
858377e4 5483 if (!do_lxcapi_is_defined(c)) {
a41f104b
SH
5484 INFO("Container %s:%s has a config but is not defined",
5485 lxcpath, direntp->d_name);
a73846d8 5486
a41f104b 5487 if (names)
9c88ff1f
ÇO
5488 if(!remove_from_array(names, direntp->d_name, cfound--))
5489 goto free_bad;
a73846d8 5490
a41f104b
SH
5491 lxc_container_put(c);
5492 continue;
5493 }
5494
2871830a 5495 if (!add_to_clist(cret, c, nfound, true)) {
a41f104b
SH
5496 lxc_container_put(c);
5497 goto free_bad;
5498 }
a73846d8 5499
a41f104b
SH
5500 nfound++;
5501 }
5502
a41f104b
SH
5503 return nfound;
5504
5505free_bad:
5506 if (names && *names) {
4110345b 5507 for (i = 0; i < cfound; i++)
a41f104b
SH
5508 free((*names)[i]);
5509 free(*names);
5510 }
a73846d8 5511
a41f104b 5512 if (cret && *cret) {
4110345b 5513 for (i = 0; i < nfound; i++)
a41f104b
SH
5514 lxc_container_put((*cret)[i]);
5515 free(*cret);
5516 }
a73846d8 5517
a41f104b
SH
5518 return -1;
5519}
5520
148a9d27
DE
5521int list_active_containers(const char *lxcpath, char ***nret,
5522 struct lxc_container ***cret)
a41f104b 5523{
768e7ba2
CB
5524 __do_free char *line = NULL;
5525 __do_fclose FILE *f = NULL;
148a9d27 5526 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
a41f104b 5527 int lxcpath_len;
148a9d27 5528 char **ct_name = NULL;
a41f104b 5529 size_t len = 0;
97bc2422 5530 struct lxc_container *c = NULL;
88556fd7 5531 bool is_hashed;
a41f104b
SH
5532
5533 if (!lxcpath)
593e8478 5534 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b
SH
5535 lxcpath_len = strlen(lxcpath);
5536
5537 if (cret)
5538 *cret = NULL;
a73846d8 5539
148a9d27
DE
5540 if (nret)
5541 *nret = NULL;
a41f104b 5542
768e7ba2 5543 f = fopen("/proc/net/unix", "re");
a41f104b
SH
5544 if (!f)
5545 return -1;
5546
5547 while (getline(&line, &len, f) != -1) {
0f8f9c8a 5548 char *p = strrchr(line, ' '), *p2;
a41f104b
SH
5549 if (!p)
5550 continue;
5551 p++;
a73846d8 5552
a41f104b
SH
5553 if (*p != 0x40)
5554 continue;
5555 p++;
88556fd7
ÇO
5556
5557 is_hashed = false;
a73846d8 5558
88556fd7
ÇO
5559 if (strncmp(p, lxcpath, lxcpath_len) == 0) {
5560 p += lxcpath_len;
5561 } else if (strncmp(p, "lxc/", 4) == 0) {
5562 p += 4;
5563 is_hashed = true;
5564 } else {
a41f104b 5565 continue;
88556fd7
ÇO
5566 }
5567
a41f104b
SH
5568 while (*p == '/')
5569 p++;
5570
1a0e70ac 5571 /* Now p is the start of lxc_name. */
46cd2845 5572 p2 = strchr(p, '/');
a41f104b
SH
5573 if (!p2 || strncmp(p2, "/command", 8) != 0)
5574 continue;
5575 *p2 = '\0';
5576
88556fd7 5577 if (is_hashed) {
899a9f55
CB
5578 char *recvpath = lxc_cmd_get_lxcpath(p);
5579 if (!recvpath)
5580 continue;
a73846d8 5581
e07eafa8
L
5582 if (strncmp(lxcpath, recvpath, lxcpath_len) != 0) {
5583 free(recvpath);
88556fd7 5584 continue;
e07eafa8
L
5585 }
5586 free(recvpath);
a73846d8 5587
88556fd7 5588 p = lxc_cmd_get_name(p);
ee2d7093
L
5589 if (!p)
5590 continue;
88556fd7
ÇO
5591 }
5592
e07eafa8
L
5593 if (array_contains(&ct_name, p, ct_name_cnt)) {
5594 if (is_hashed)
5595 free(p);
9c88ff1f 5596 continue;
e07eafa8 5597 }
9c88ff1f 5598
e07eafa8
L
5599 if (!add_to_array(&ct_name, p, ct_name_cnt)) {
5600 if (is_hashed)
5601 free(p);
148a9d27 5602 goto free_cret_list;
e07eafa8 5603 }
9c88ff1f 5604
148a9d27 5605 ct_name_cnt++;
a41f104b 5606
e07eafa8
L
5607 if (!cret) {
5608 if (is_hashed)
5609 free(p);
a41f104b 5610 continue;
e07eafa8 5611 }
a41f104b
SH
5612
5613 c = lxc_container_new(p, lxcpath);
5614 if (!c) {
5615 INFO("Container %s:%s is running but could not be loaded",
5616 lxcpath, p);
a73846d8 5617
148a9d27 5618 remove_from_array(&ct_name, p, ct_name_cnt--);
e07eafa8
L
5619 if (is_hashed)
5620 free(p);
a73846d8 5621
a41f104b
SH
5622 continue;
5623 }
5624
e07eafa8
L
5625 if (is_hashed)
5626 free(p);
5627
a41f104b
SH
5628 /*
5629 * If this is an anonymous container, then is_defined *can*
5630 * return false. So we don't do that check. Count on the
5631 * fact that the command socket exists.
5632 */
5633
148a9d27 5634 if (!add_to_clist(cret, c, cret_cnt, true)) {
a41f104b 5635 lxc_container_put(c);
148a9d27 5636 goto free_cret_list;
a41f104b 5637 }
a73846d8 5638
148a9d27 5639 cret_cnt++;
a41f104b
SH
5640 }
5641
97bc2422
CB
5642 if (nret && cret && cret_cnt != ct_name_cnt) {
5643 if (c)
5644 lxc_container_put(c);
5645 goto free_cret_list;
5646 }
5647
148a9d27
DE
5648 ret = ct_name_cnt;
5649 if (nret)
5650 *nret = ct_name;
5651 else
5652 goto free_ct_name;
a73846d8 5653
148a9d27 5654 goto out;
a41f104b 5655
148a9d27 5656free_cret_list:
a41f104b 5657 if (cret && *cret) {
148a9d27 5658 for (i = 0; i < cret_cnt; i++)
a41f104b
SH
5659 lxc_container_put((*cret)[i]);
5660 free(*cret);
5661 }
148a9d27
DE
5662
5663free_ct_name:
5664 if (ct_name) {
5665 for (i = 0; i < ct_name_cnt; i++)
5666 free(ct_name[i]);
5667 free(ct_name);
5668 }
5669
5670out:
148a9d27 5671 return ret;
a41f104b 5672}
2871830a
DE
5673
5674int list_all_containers(const char *lxcpath, char ***nret,
5675 struct lxc_container ***cret)
5676{
5677 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
5678 char **active_name;
5679 char **ct_name;
5680 struct lxc_container **ct_list = NULL;
5681
5682 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
5683 if (ct_cnt < 0)
5684 return ct_cnt;
5685
5686 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
5687 if (active_cnt < 0) {
5688 ret = active_cnt;
5689 goto free_ct_name;
5690 }
5691
5692 for (i = 0; i < active_cnt; i++) {
5693 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
5694 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
5695 ret = -1;
5696 goto free_active_name;
5697 }
a73846d8 5698
2871830a
DE
5699 ct_cnt++;
5700 }
a73846d8 5701
2871830a
DE
5702 free(active_name[i]);
5703 active_name[i] = NULL;
5704 }
a73846d8 5705
2871830a
DE
5706 free(active_name);
5707 active_name = NULL;
5708 active_cnt = 0;
5709
5710 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
5711 struct lxc_container *c;
5712
5713 c = lxc_container_new(ct_name[i], lxcpath);
5714 if (!c) {
5715 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
5716 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
5717 continue;
5718 }
5719
5720 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
5721 lxc_container_put(c);
5722 ret = -1;
5723 goto free_ct_list;
5724 }
a73846d8 5725
2871830a
DE
5726 ct_list_cnt++;
5727 }
5728
5729 if (cret)
5730 *cret = ct_list;
5731
a73846d8 5732 if (nret) {
2871830a 5733 *nret = ct_name;
a73846d8 5734 } else {
2871830a
DE
5735 ret = ct_cnt;
5736 goto free_ct_name;
5737 }
a73846d8 5738
2871830a
DE
5739 return ct_cnt;
5740
5741free_ct_list:
5742 for (i = 0; i < ct_list_cnt; i++) {
5743 lxc_container_put(ct_list[i]);
5744 }
f10fad2f 5745 free(ct_list);
2871830a
DE
5746
5747free_active_name:
5748 for (i = 0; i < active_cnt; i++) {
f10fad2f 5749 free(active_name[i]);
2871830a 5750 }
f10fad2f 5751 free(active_name);
2871830a
DE
5752
5753free_ct_name:
5754 for (i = 0; i < ct_cnt; i++) {
5755 free(ct_name[i]);
5756 }
5757 free(ct_name);
5758 return ret;
5759}
12461428
CB
5760
5761bool lxc_config_item_is_supported(const char *key)
5762{
6eb516a7 5763 return !!lxc_get_config_exact(key);
12461428 5764}
aafa5f96
CB
5765
5766bool lxc_has_api_extension(const char *extension)
5767{
5768 /* The NULL API extension is always present. :) */
5769 if (!extension)
5770 return true;
5771
5772 for (size_t i = 0; i < nr_api_extensions; i++)
5773 if (strcmp(api_extensions[i], extension) == 0)
5774 return true;
5775
5776 return false;
5777}