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