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