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