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