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