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