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