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