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