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