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