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