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