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