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