]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
ubuntu templates: don't check for $rootfs/run/shm
[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
148a9d27 22#include <assert.h>
a0e93eeb 23#include <stdarg.h>
71454076 24#include <pthread.h>
9be53773
SH
25#include <unistd.h>
26#include <sys/types.h>
27#include <sys/wait.h>
4de2791f 28#include <sys/mount.h>
9be53773 29#include <errno.h>
93dc5327 30#include <fcntl.h>
9be53773 31#include <sched.h>
f5dd1d53 32#include <dirent.h>
f2363e38
ÇO
33#include <sched.h>
34#include <arpa/inet.h>
35#include <libgen.h>
d659597e 36#include <stdint.h>
c476bdce 37#include <grp.h>
5f7eba0b 38#include <sys/syscall.h>
f2363e38
ÇO
39
40#include <lxc/lxccontainer.h>
41#include <lxc/version.h>
42
9be53773 43#include "config.h"
72d0e1cb
SG
44#include "lxc.h"
45#include "state.h"
72d0e1cb 46#include "conf.h"
72d0e1cb 47#include "confile.h"
b5159817 48#include "console.h"
72d0e1cb
SG
49#include "cgroup.h"
50#include "commands.h"
51#include "log.h"
9be53773 52#include "bdev.h"
6a44839f 53#include "utils.h"
a0e93eeb 54#include "attach.h"
f2363e38
ÇO
55#include "monitor.h"
56#include "namespace.h"
95ee490b 57#include "lxclock.h"
4ba0d9af
SG
58
59#if HAVE_IFADDRS_H
9c83a661 60#include <ifaddrs.h>
4ba0d9af
SG
61#else
62#include <../include/ifaddrs.h>
63#endif
72d0e1cb 64
a9a0ed90
ÇO
65#define MAX_BUFFER 4096
66
c868b261
ÇO
67#define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
68
5f7eba0b
SG
69/* Define faccessat() if missing from the C library */
70#ifndef HAVE_FACCESSAT
71static int faccessat(int __fd, const char *__file, int __type, int __flag)
72{
73#ifdef __NR_faccessat
74return syscall(__NR_faccessat, __fd, __file, __type, __flag);
75#else
76errno = ENOSYS;
77return -1;
78#endif
79}
80#endif
81
82
72d0e1cb
SG
83lxc_log_define(lxc_container, lxc);
84
a41f104b
SH
85static bool config_file_exists(const char *lxcpath, const char *cname)
86{
87 /* $lxcpath + '/' + $cname + '/config' + \0 */
88 int ret, len = strlen(lxcpath) + strlen(cname) + 9;
89 char *fname = alloca(len);
90
91 ret = snprintf(fname, len, "%s/%s/config", lxcpath, cname);
92 if (ret < 0 || ret >= len)
93 return false;
94
95 return file_exists(fname);
96}
97
3e625e2d
SH
98/*
99 * A few functions to help detect when a container creation failed.
100 * If a container creation was killed partway through, then trying
101 * to actually start that container could harm the host. We detect
102 * this by creating a 'partial' file under the container directory,
103 * and keeping an advisory lock. When container creation completes,
104 * we remove that file. When we load or try to start a container, if
105 * we find that file, without a flock, we remove the container.
106 */
74a3920a 107static int ongoing_create(struct lxc_container *c)
3e625e2d
SH
108{
109 int len = strlen(c->config_path) + strlen(c->name) + 10;
110 char *path = alloca(len);
111 int fd, ret;
93dc5327
SH
112 struct flock lk;
113
3e625e2d
SH
114 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
115 if (ret < 0 || ret >= len) {
116 ERROR("Error writing partial pathname");
117 return -1;
118 }
119
120 if (!file_exists(path))
121 return 0;
025ed0f3 122 fd = open(path, O_RDWR);
025ed0f3 123 if (fd < 0) {
3e625e2d
SH
124 // give benefit of the doubt
125 SYSERROR("Error opening partial file");
3e625e2d
SH
126 return 0;
127 }
93dc5327
SH
128 lk.l_type = F_WRLCK;
129 lk.l_whence = SEEK_SET;
130 lk.l_start = 0;
131 lk.l_len = 0;
132 lk.l_pid = -1;
133 if (fcntl(fd, F_GETLK, &lk) == 0 && lk.l_pid != -1) {
3e625e2d
SH
134 // create is still ongoing
135 close(fd);
3e625e2d
SH
136 return 1;
137 }
138 // create completed but partial is still there.
139 close(fd);
3e625e2d
SH
140 return 2;
141}
142
74a3920a 143static int create_partial(struct lxc_container *c)
3e625e2d
SH
144{
145 // $lxcpath + '/' + $name + '/partial' + \0
146 int len = strlen(c->config_path) + strlen(c->name) + 10;
147 char *path = alloca(len);
148 int fd, ret;
93dc5327
SH
149 struct flock lk;
150
3e625e2d
SH
151 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
152 if (ret < 0 || ret >= len) {
153 ERROR("Error writing partial pathname");
154 return -1;
155 }
93dc5327 156 if ((fd=open(path, O_RDWR | O_CREAT | O_EXCL, 0755)) < 0) {
3e625e2d 157 SYSERROR("Erorr creating partial file");
3e625e2d
SH
158 return -1;
159 }
93dc5327
SH
160 lk.l_type = F_WRLCK;
161 lk.l_whence = SEEK_SET;
162 lk.l_start = 0;
163 lk.l_len = 0;
164 if (fcntl(fd, F_SETLKW, &lk) < 0) {
3e625e2d
SH
165 SYSERROR("Error locking partial file %s", path);
166 close(fd);
3e625e2d
SH
167 return -1;
168 }
3e625e2d
SH
169
170 return fd;
171}
172
74a3920a 173static void remove_partial(struct lxc_container *c, int fd)
3e625e2d
SH
174{
175 // $lxcpath + '/' + $name + '/partial' + \0
176 int len = strlen(c->config_path) + strlen(c->name) + 10;
177 char *path = alloca(len);
178 int ret;
179
180 close(fd);
181 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
182 if (ret < 0 || ret >= len) {
183 ERROR("Error writing partial pathname");
184 return;
185 }
3e625e2d
SH
186 if (unlink(path) < 0)
187 SYSERROR("Error unlink partial file %s", path);
3e625e2d
SH
188}
189
72d0e1cb 190/* LOCKING
3bc449ed
SH
191 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
192 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
193 * container configuration file.
194 * The container_disk_lock also takes the container_mem_lock.
195 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
72d0e1cb
SG
196 * NOTHING mutexes two independent programs with their own struct
197 * lxc_container for the same c->name, between API calls. For instance,
198 * c->config_read(); c->start(); Between those calls, data on disk
199 * could change (which shouldn't bother the caller unless for instance
200 * the rootfs get moved). c->config_read(); update; c->config_write();
201 * Two such updaters could race. The callers should therefore check their
202 * results. Trying to prevent that would necessarily expose us to deadlocks
203 * due to hung callers. So I prefer to keep the locks only within our own
204 * functions, not across functions.
205 *
3bc449ed 206 * If you're going to clone while holding a lxccontainer, increment
72d0e1cb
SG
207 * c->numthreads (under privlock) before forking. When deleting,
208 * decrement numthreads under privlock, then if it hits 0 you can delete.
209 * Do not ever use a lxccontainer whose numthreads you did not bump.
210 */
211
212static void lxc_container_free(struct lxc_container *c)
213{
214 if (!c)
215 return;
216
217 if (c->configfile) {
218 free(c->configfile);
219 c->configfile = NULL;
220 }
221 if (c->error_string) {
222 free(c->error_string);
223 c->error_string = NULL;
224 }
d95db067 225 if (c->slock) {
df271a59 226 lxc_putlock(c->slock);
d95db067
DE
227 c->slock = NULL;
228 }
72d0e1cb 229 if (c->privlock) {
df271a59 230 lxc_putlock(c->privlock);
72d0e1cb
SG
231 c->privlock = NULL;
232 }
233 if (c->name) {
234 free(c->name);
235 c->name = NULL;
236 }
d95db067
DE
237 if (c->lxc_conf) {
238 lxc_conf_free(c->lxc_conf);
239 c->lxc_conf = NULL;
240 }
2a59a681
SH
241 if (c->config_path) {
242 free(c->config_path);
243 c->config_path = NULL;
244 }
72cf75fa 245
72d0e1cb
SG
246 free(c);
247}
248
43d1aa34
SH
249/*
250 * Consider the following case:
251freer | racing get()er
252==================================================================
253lxc_container_put() | lxc_container_get()
254\ lxclock(c->privlock) | c->numthreads < 1? (no)
255\ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
256\ lxcunlock() | \
257\ lxc_container_free() | \ lxclock() returns
258 | \ c->numthreads < 1 -> return 0
259\ \ (free stuff) |
260\ \ sem_destroy(privlock) |
261
262 * When the get()er checks numthreads the first time, one of the following
263 * is true:
264 * 1. freer has set numthreads = 0. get() returns 0
265 * 2. freer is between lxclock and setting numthreads to 0. get()er will
266 * sem_wait on privlock, get lxclock after freer() drops it, then see
267 * numthreads is 0 and exit without touching lxclock again..
268 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
269 * will see --numthreads = 1 and not call lxc_container_free().
270*/
271
72d0e1cb
SG
272int lxc_container_get(struct lxc_container *c)
273{
274 if (!c)
275 return 0;
276
43d1aa34
SH
277 // if someone else has already started freeing the container, don't
278 // try to take the lock, which may be invalid
279 if (c->numthreads < 1)
280 return 0;
281
5cee8c50 282 if (container_mem_lock(c))
72d0e1cb
SG
283 return 0;
284 if (c->numthreads < 1) {
285 // bail without trying to unlock, bc the privlock is now probably
286 // in freed memory
287 return 0;
288 }
289 c->numthreads++;
5cee8c50 290 container_mem_unlock(c);
72d0e1cb
SG
291 return 1;
292}
293
294int lxc_container_put(struct lxc_container *c)
295{
296 if (!c)
297 return -1;
5cee8c50 298 if (container_mem_lock(c))
72d0e1cb
SG
299 return -1;
300 if (--c->numthreads < 1) {
5cee8c50 301 container_mem_unlock(c);
72d0e1cb
SG
302 lxc_container_free(c);
303 return 1;
304 }
5cee8c50 305 container_mem_unlock(c);
72d0e1cb
SG
306 return 0;
307}
308
72d0e1cb
SG
309static bool lxcapi_is_defined(struct lxc_container *c)
310{
311 struct stat statbuf;
312 bool ret = false;
313 int statret;
314
315 if (!c)
316 return false;
317
5cee8c50 318 if (container_mem_lock(c))
72d0e1cb
SG
319 return false;
320 if (!c->configfile)
321 goto out;
322 statret = stat(c->configfile, &statbuf);
323 if (statret != 0)
324 goto out;
325 ret = true;
326
327out:
5cee8c50 328 container_mem_unlock(c);
72d0e1cb
SG
329 return ret;
330}
331
332static const char *lxcapi_state(struct lxc_container *c)
333{
72d0e1cb
SG
334 lxc_state_t s;
335
336 if (!c)
337 return NULL;
13f5be62 338 s = lxc_getstate(c->name, c->config_path);
39dc698c 339 return lxc_state2str(s);
72d0e1cb
SG
340}
341
39dc698c 342static bool is_stopped(struct lxc_container *c)
794dd120
SH
343{
344 lxc_state_t s;
13f5be62 345 s = lxc_getstate(c->name, c->config_path);
794dd120
SH
346 return (s == STOPPED);
347}
348
72d0e1cb
SG
349static bool lxcapi_is_running(struct lxc_container *c)
350{
351 const char *s;
352
353 if (!c)
354 return false;
355 s = lxcapi_state(c);
356 if (!s || strcmp(s, "STOPPED") == 0)
357 return false;
358 return true;
359}
360
361static bool lxcapi_freeze(struct lxc_container *c)
362{
363 int ret;
364 if (!c)
365 return false;
366
9123e471 367 ret = lxc_freeze(c->name, c->config_path);
72d0e1cb
SG
368 if (ret)
369 return false;
370 return true;
371}
372
373static bool lxcapi_unfreeze(struct lxc_container *c)
374{
375 int ret;
376 if (!c)
377 return false;
378
9123e471 379 ret = lxc_unfreeze(c->name, c->config_path);
72d0e1cb
SG
380 if (ret)
381 return false;
382 return true;
383}
384
b5159817 385static int lxcapi_console_getfd(struct lxc_container *c, int *ttynum, int *masterfd)
0115f8fd
DE
386{
387 int ttyfd;
388 if (!c)
389 return -1;
390
b5159817 391 ttyfd = lxc_console_getfd(c, ttynum, masterfd);
0115f8fd
DE
392 return ttyfd;
393}
394
b5159817
DE
395static int lxcapi_console(struct lxc_container *c, int ttynum, int stdinfd,
396 int stdoutfd, int stderrfd, int escape)
397{
398 return lxc_console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape);
399}
400
72d0e1cb
SG
401static pid_t lxcapi_init_pid(struct lxc_container *c)
402{
72d0e1cb
SG
403 if (!c)
404 return -1;
405
5cee8c50 406 return lxc_cmd_get_init_pid(c->name, c->config_path);
72d0e1cb
SG
407}
408
12a50cc6 409static bool load_config_locked(struct lxc_container *c, const char *fname)
8eb5694b
SH
410{
411 if (!c->lxc_conf)
412 c->lxc_conf = lxc_conf_init();
6b0d5538
SH
413 if (!c->lxc_conf)
414 return false;
415 if (!lxc_config_read(fname, c->lxc_conf, false))
8eb5694b
SH
416 return true;
417 return false;
418}
419
12a50cc6 420static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 421{
39dc698c
SH
422 bool ret = false, need_disklock = false;
423 int lret;
12a50cc6 424 const char *fname;
72d0e1cb
SG
425 if (!c)
426 return false;
427
428 fname = c->configfile;
429 if (alt_file)
430 fname = alt_file;
431 if (!fname)
432 return false;
39dc698c
SH
433 /*
434 * If we're reading something other than the container's config,
435 * we only need to lock the in-memory container. If loading the
436 * container's config file, take the disk lock.
437 */
438 if (strcmp(fname, c->configfile) == 0)
439 need_disklock = true;
440
441 if (need_disklock)
442 lret = container_disk_lock(c);
443 else
444 lret = container_mem_lock(c);
445 if (lret)
72d0e1cb 446 return false;
39dc698c 447
8eb5694b 448 ret = load_config_locked(c, fname);
39dc698c
SH
449
450 if (need_disklock)
451 container_disk_unlock(c);
452 else
453 container_mem_unlock(c);
72d0e1cb
SG
454 return ret;
455}
456
540f932a 457static bool lxcapi_want_daemonize(struct lxc_container *c, bool state)
72d0e1cb 458{
497a2995 459 if (!c || !c->lxc_conf)
540f932a 460 return false;
f02abefe 461 if (container_mem_lock(c)) {
3bc449ed 462 ERROR("Error getting mem lock");
540f932a 463 return false;
3bc449ed 464 }
540f932a 465 c->daemonize = state;
83758ed0 466 /* daemonize implies close_all_fds so set it */
540f932a
SG
467 if (state == 1)
468 c->lxc_conf->close_all_fds = 1;
3bc449ed 469 container_mem_unlock(c);
540f932a 470 return true;
72d0e1cb
SG
471}
472
540f932a 473static bool lxcapi_want_close_all_fds(struct lxc_container *c, bool state)
130a1888
ÇO
474{
475 if (!c || !c->lxc_conf)
49badbbe 476 return false;
130a1888
ÇO
477 if (container_mem_lock(c)) {
478 ERROR("Error getting mem lock");
49badbbe 479 return false;
130a1888 480 }
540f932a 481 c->lxc_conf->close_all_fds = state;
130a1888 482 container_mem_unlock(c);
49badbbe 483 return true;
130a1888
ÇO
484}
485
12a50cc6 486static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
7a44c8b4
SG
487{
488 int ret;
489
490 if (!c)
491 return false;
492
67e571de 493 ret = lxc_wait(c->name, state, timeout, c->config_path);
7a44c8b4
SG
494 return ret == 0;
495}
496
497
03f064ff 498static bool wait_on_daemonized_start(struct lxc_container *c, int pid)
7a44c8b4
SG
499{
500 /* we'll probably want to make this timeout configurable? */
697fa639 501 int timeout = 5, ret, status;
7a44c8b4 502
697fa639
SH
503 /*
504 * our child is going to fork again, then exit. reap the
505 * child
506 */
03f064ff 507 ret = waitpid(pid, &status, 0);
697fa639
SH
508 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
509 DEBUG("failed waiting for first dual-fork child");
7a44c8b4
SG
510 return lxcapi_wait(c, "RUNNING", timeout);
511}
512
2d834aa8
SH
513static bool am_single_threaded(void)
514{
515 struct dirent dirent, *direntp;
516 DIR *dir;
517 int count=0;
518
2d834aa8 519 dir = opendir("/proc/self/task");
2d834aa8
SH
520 if (!dir) {
521 INFO("failed to open /proc/self/task");
522 return false;
523 }
524
525 while (!readdir_r(dir, &dirent, &direntp)) {
526 if (!direntp)
527 break;
528
529 if (!strcmp(direntp->d_name, "."))
530 continue;
531
532 if (!strcmp(direntp->d_name, ".."))
533 continue;
534 if (++count > 1)
535 break;
536 }
2d834aa8 537 closedir(dir);
2d834aa8
SH
538 return count == 1;
539}
540
72d0e1cb
SG
541/*
542 * I can't decide if it'd be more convenient for callers if we accept '...',
543 * or a null-terminated array (i.e. execl vs execv)
544 */
12a50cc6 545static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
72d0e1cb
SG
546{
547 int ret;
548 struct lxc_conf *conf;
540f932a 549 bool daemonize = false;
6eaac303 550 FILE *pid_fp = NULL;
72d0e1cb
SG
551 char *default_args[] = {
552 "/sbin/init",
13aad0ae 553 NULL,
72d0e1cb
SG
554 };
555
556 /* container exists */
557 if (!c)
558 return false;
559 /* container has been setup */
560 if (!c->lxc_conf)
561 return false;
562
3e625e2d
SH
563 if ((ret = ongoing_create(c)) < 0) {
564 ERROR("Error checking for incomplete creation");
565 return false;
566 }
567 if (ret == 2) {
568 ERROR("Error: %s creation was not completed", c->name);
569 c->destroy(c);
570 return false;
571 } else if (ret == 1) {
572 ERROR("Error: creation of %s is ongoing", c->name);
573 return false;
574 }
575
72d0e1cb
SG
576 /* is this app meant to be run through lxcinit, as in lxc-execute? */
577 if (useinit && !argv)
578 return false;
579
5cee8c50 580 if (container_mem_lock(c))
72d0e1cb
SG
581 return false;
582 conf = c->lxc_conf;
583 daemonize = c->daemonize;
5cee8c50 584 container_mem_unlock(c);
72d0e1cb
SG
585
586 if (useinit) {
13f5be62 587 ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
72d0e1cb
SG
588 return ret == 0 ? true : false;
589 }
590
591 if (!argv)
592 argv = default_args;
593
594 /*
595 * say, I'm not sure - what locks do we want here? Any?
596 * Is liblxc's locking enough here to protect the on disk
597 * container? We don't want to exclude things like lxc_info
598 * while container is running...
599 */
600 if (daemonize) {
e51d4895 601 lxc_monitord_spawn(c->config_path);
71454076 602
72d0e1cb 603 pid_t pid = fork();
844f7a38 604 if (pid < 0)
72d0e1cb 605 return false;
6eaac303
QH
606
607 if (pid != 0) {
608 /* Set to NULL because we don't want father unlink
609 * the PID file, child will do the free and unlink.
610 */
611 c->pidfile = NULL;
03f064ff 612 return wait_on_daemonized_start(c, pid);
6eaac303 613 }
025ed0f3 614
697fa639
SH
615 /* second fork to be reparented by init */
616 pid = fork();
617 if (pid < 0) {
618 SYSERROR("Error doing dual-fork");
619 return false;
620 }
621 if (pid != 0)
622 exit(0);
72d0e1cb 623 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
c278cef2
SH
624 if (chdir("/")) {
625 SYSERROR("Error chdir()ing to /.");
626 return false;
627 }
72d0e1cb
SG
628 close(0);
629 close(1);
630 close(2);
eddaaafd 631 open("/dev/zero", O_RDONLY);
72d0e1cb
SG
632 open("/dev/null", O_RDWR);
633 open("/dev/null", O_RDWR);
634 setsid();
2d834aa8
SH
635 } else {
636 if (!am_single_threaded()) {
637 ERROR("Cannot start non-daemonized container when threaded");
638 return false;
639 }
72d0e1cb
SG
640 }
641
6eaac303
QH
642 /* We need to write PID file after daeminize, so we always
643 * write the right PID.
644 */
645 if (c->pidfile) {
646 pid_fp = fopen(c->pidfile, "w");
647 if (pid_fp == NULL) {
648 SYSERROR("Failed to create pidfile '%s' for '%s'",
649 c->pidfile, c->name);
650 return false;
651 }
652
653 if (fprintf(pid_fp, "%d\n", getpid()) < 0) {
654 SYSERROR("Failed to write '%s'", c->pidfile);
655 fclose(pid_fp);
656 pid_fp = NULL;
657 return false;
658 }
659
660 fclose(pid_fp);
661 pid_fp = NULL;
662 }
663
72d0e1cb
SG
664reboot:
665 conf->reboot = 0;
13f5be62 666 ret = lxc_start(c->name, argv, conf, c->config_path);
d4ef230c 667 c->error_num = ret;
72d0e1cb
SG
668
669 if (conf->reboot) {
670 INFO("container requested reboot");
671 conf->reboot = 0;
72d0e1cb
SG
672 goto reboot;
673 }
674
487d8008
QH
675 if (c->pidfile) {
676 unlink(c->pidfile);
677 free(c->pidfile);
678 c->pidfile = NULL;
679 }
680
844f7a38 681 if (daemonize)
05e5d7dc 682 exit (ret == 0 ? true : false);
844f7a38 683 else
05e5d7dc 684 return (ret == 0 ? true : false);
72d0e1cb
SG
685}
686
687/*
688 * note there MUST be an ending NULL
689 */
690static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
691{
692 va_list ap;
a0e93eeb 693 char **inargs = NULL;
72d0e1cb
SG
694 bool bret = false;
695
696 /* container exists */
697 if (!c)
698 return false;
699
72d0e1cb 700 va_start(ap, useinit);
a0e93eeb 701 inargs = lxc_va_arg_list_to_argv(ap, 0, 1);
72d0e1cb
SG
702 va_end(ap);
703
a0e93eeb
CS
704 if (!inargs) {
705 ERROR("Memory allocation error.");
706 goto out;
72d0e1cb
SG
707 }
708
a0e93eeb
CS
709 /* pass NULL if no arguments were supplied */
710 bret = lxcapi_start(c, useinit, *inargs ? inargs : NULL);
72d0e1cb
SG
711
712out:
713 if (inargs) {
4e03ae57
DE
714 char **arg;
715 for (arg = inargs; *arg; arg++)
716 free(*arg);
72d0e1cb
SG
717 free(inargs);
718 }
719
720 return bret;
721}
722
723static bool lxcapi_stop(struct lxc_container *c)
724{
725 int ret;
726
727 if (!c)
728 return false;
729
ef6e34ee 730 ret = lxc_cmd_stop(c->name, c->config_path);
72d0e1cb
SG
731
732 return ret == 0;
72d0e1cb
SG
733}
734
72d0e1cb
SG
735/*
736 * create the standard expected container dir
737 */
738static bool create_container_dir(struct lxc_container *c)
739{
740 char *s;
741 int len, ret;
742
2a59a681 743 len = strlen(c->config_path) + strlen(c->name) + 2;
72d0e1cb
SG
744 s = malloc(len);
745 if (!s)
746 return false;
2a59a681 747 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
72d0e1cb
SG
748 if (ret < 0 || ret >= len) {
749 free(s);
750 return false;
751 }
752 ret = mkdir(s, 0755);
753 if (ret) {
754 if (errno == EEXIST)
755 ret = 0;
756 else
959aee9c 757 SYSERROR("failed to create container path for %s", c->name);
72d0e1cb
SG
758 }
759 free(s);
760 return ret == 0;
761}
762
1897e3bc
SH
763static const char *lxcapi_get_config_path(struct lxc_container *c);
764static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v);
765
72d0e1cb 766/*
1897e3bc
SH
767 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
768 * it returns a mounted bdev on success, NULL on error.
72d0e1cb 769 */
1897e3bc
SH
770static struct bdev *do_bdev_create(struct lxc_container *c, const char *type,
771 struct bdev_specs *specs)
772{
773 char *dest;
1897e3bc
SH
774 size_t len;
775 struct bdev *bdev;
776 int ret;
777
cd219ae6
SY
778 /* rootfs.path or lxcpath/lxcname/rootfs */
779 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0) {
cf465fe4
SH
780 const char *rpath = c->lxc_conf->rootfs.path;
781 len = strlen(rpath) + 1;
cd219ae6 782 dest = alloca(len);
cf465fe4 783 ret = snprintf(dest, len, "%s", rpath);
cd219ae6 784 } else {
cf465fe4 785 const char *lxcpath = lxcapi_get_config_path(c);
cd219ae6
SY
786 len = strlen(c->name) + strlen(lxcpath) + 9;
787 dest = alloca(len);
788 ret = snprintf(dest, len, "%s/%s/rootfs", lxcpath, c->name);
789 }
1897e3bc
SH
790 if (ret < 0 || ret >= len)
791 return NULL;
792
793 bdev = bdev_create(dest, type, c->name, specs);
d44e88c2 794 if (!bdev) {
959aee9c 795 ERROR("Failed to create backing store type %s", type);
1897e3bc 796 return NULL;
d44e88c2
SH
797 }
798
1897e3bc 799 lxcapi_set_config_item(c, "lxc.rootfs", bdev->src);
cf3ef16d
SH
800
801 /* if we are not root, chown the rootfs dir to root in the
802 * target uidmap */
803
0e6e3a41 804 if (geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) {
c4d10a05 805 if (chown_mapped_root(bdev->dest, c->lxc_conf) < 0) {
959aee9c 806 ERROR("Error chowning %s to container root", bdev->dest);
97e9cfa0 807 suggest_default_idmap();
cf3ef16d
SH
808 bdev_put(bdev);
809 return NULL;
810 }
811 }
812
1897e3bc
SH
813 return bdev;
814}
815
cbee8106
SH
816/*
817 * Given the '-t' template option to lxc-create, figure out what to
818 * do. If the template is a full executable path, use that. If it
85db5535
DE
819 * is something like 'sshd', then return $templatepath/lxc-sshd.
820 * On success return the template, on error return NULL.
cbee8106 821 */
85db5535 822static char *get_template_path(const char *t)
cbee8106
SH
823{
824 int ret, len;
825 char *tpath;
826
cbee8106
SH
827 if (t[0] == '/' && access(t, X_OK) == 0) {
828 tpath = strdup(t);
cbee8106
SH
829 return tpath;
830 }
831
832 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
833 tpath = malloc(len);
834 if (!tpath)
85db5535 835 return NULL;
cbee8106
SH
836 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
837 if (ret < 0 || ret >= len) {
838 free(tpath);
85db5535 839 return NULL;
cbee8106
SH
840 }
841 if (access(tpath, X_OK) < 0) {
959aee9c 842 SYSERROR("bad template: %s", t);
cbee8106 843 free(tpath);
85db5535 844 return NULL;
cbee8106
SH
845 }
846
847 return tpath;
848}
849
96b3cb40 850static char *lxcbasename(char *path)
72d0e1cb 851{
96b3cb40
SH
852 char *p = path + strlen(path) - 1;
853 while (*p != '/' && p > path)
854 p--;
855 return p;
856}
72d0e1cb 857
dc23c1c8 858static bool create_run_template(struct lxc_container *c, char *tpath, bool quiet,
96b3cb40
SH
859 char *const argv[])
860{
861 pid_t pid;
72d0e1cb 862
72d0e1cb 863 if (!tpath)
96b3cb40 864 return true;
72d0e1cb
SG
865
866 pid = fork();
867 if (pid < 0) {
959aee9c 868 SYSERROR("failed to fork task for container creation template");
96b3cb40 869 return false;
72d0e1cb
SG
870 }
871
872 if (pid == 0) { // child
1897e3bc
SH
873 char *patharg, *namearg, *rootfsarg, *src;
874 struct bdev *bdev = NULL;
72d0e1cb 875 int i;
96b3cb40
SH
876 int ret, len, nargs = 0;
877 char **newargv;
cf3ef16d 878 struct lxc_conf *conf = c->lxc_conf;
72d0e1cb 879
dc23c1c8
SH
880 if (quiet) {
881 close(0);
882 close(1);
883 close(2);
884 open("/dev/zero", O_RDONLY);
885 open("/dev/null", O_RDWR);
886 open("/dev/null", O_RDWR);
887 }
1897e3bc
SH
888
889 src = c->lxc_conf->rootfs.path;
890 /*
1f92162d 891 * for an overlay create, what the user wants is the template to fill
1897e3bc
SH
892 * in what will become the readonly lower layer. So don't mount for
893 * the template
894 */
1f92162d
SG
895 if (strncmp(src, "overlayfs:", 10) == 0)
896 src = overlay_getlower(src+10);
897 if (strncmp(src, "aufs:", 5) == 0)
898 src = overlay_getlower(src+5);
899
76a26f55 900 bdev = bdev_init(c->lxc_conf, src, c->lxc_conf->rootfs.mount, NULL);
1897e3bc
SH
901 if (!bdev) {
902 ERROR("Error opening rootfs");
903 exit(1);
904 }
905
4de2791f 906 if (geteuid() == 0) {
cf3ef16d
SH
907 if (unshare(CLONE_NEWNS) < 0) {
908 ERROR("error unsharing mounts");
909 exit(1);
910 }
4de2791f 911 if (detect_shared_rootfs()) {
c597baa8 912 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
4de2791f
SH
913 SYSERROR("Failed to make / rslave to run template");
914 ERROR("Continuing...");
915 }
916 }
917 }
2659c7cb 918 if (strcmp(bdev->type, "dir") && strcmp(bdev->type, "btrfs")) {
4de2791f 919 if (geteuid() != 0) {
2659c7cb 920 ERROR("non-root users can only create btrfs and directory-backed containers");
4de2791f
SH
921 exit(1);
922 }
cf3ef16d
SH
923 if (bdev->ops->mount(bdev) < 0) {
924 ERROR("Error mounting rootfs");
925 exit(1);
926 }
927 } else { // TODO come up with a better way here!
928 if (bdev->dest)
929 free(bdev->dest);
930 bdev->dest = strdup(bdev->src);
1897e3bc
SH
931 }
932
72d0e1cb
SG
933 /*
934 * create our new array, pre-pend the template name and
935 * base args
936 */
937 if (argv)
1897e3bc 938 for (nargs = 0; argv[nargs]; nargs++) ;
6849cb5b 939 nargs += 4; // template, path, rootfs and name args
cf3ef16d 940
72d0e1cb
SG
941 newargv = malloc(nargs * sizeof(*newargv));
942 if (!newargv)
943 exit(1);
96b3cb40 944 newargv[0] = lxcbasename(tpath);
72d0e1cb 945
2a59a681 946 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
72d0e1cb
SG
947 patharg = malloc(len);
948 if (!patharg)
949 exit(1);
2a59a681 950 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
72d0e1cb
SG
951 if (ret < 0 || ret >= len)
952 exit(1);
953 newargv[1] = patharg;
954 len = strlen("--name=") + strlen(c->name) + 1;
955 namearg = malloc(len);
956 if (!namearg)
957 exit(1);
958 ret = snprintf(namearg, len, "--name=%s", c->name);
959 if (ret < 0 || ret >= len)
960 exit(1);
961 newargv[2] = namearg;
962
1897e3bc
SH
963 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
964 rootfsarg = malloc(len);
965 if (!rootfsarg)
966 exit(1);
967 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
968 if (ret < 0 || ret >= len)
969 exit(1);
970 newargv[3] = rootfsarg;
971
72d0e1cb
SG
972 /* add passed-in args */
973 if (argv)
1897e3bc
SH
974 for (i = 4; i < nargs; i++)
975 newargv[i] = argv[i-4];
72d0e1cb
SG
976
977 /* add trailing NULL */
978 nargs++;
979 newargv = realloc(newargv, nargs * sizeof(*newargv));
980 if (!newargv)
981 exit(1);
982 newargv[nargs - 1] = NULL;
983
cf3ef16d
SH
984 /*
985 * If we're running the template in a mapped userns, then
986 * we prepend the template command with:
987 * lxc-usernsexec <-m map1> ... <-m mapn> --
57d116ab
SH
988 * and we append "--mapped-uid x", where x is the mapped uid
989 * for our geteuid()
cf3ef16d 990 */
0e6e3a41 991 if (!lxc_list_empty(&conf->id_map)) {
cf3ef16d 992 int n2args = 1;
57d116ab 993 char txtuid[20];
2133f58c 994 char txtgid[20];
cf3ef16d
SH
995 char **n2 = malloc(n2args * sizeof(*n2));
996 struct lxc_list *it;
997 struct id_map *map;
998
57d116ab
SH
999 if (!n2) {
1000 SYSERROR("out of memory");
1001 exit(1);
1002 }
cf3ef16d
SH
1003 newargv[0] = tpath;
1004 tpath = "lxc-usernsexec";
1005 n2[0] = "lxc-usernsexec";
1006 lxc_list_for_each(it, &conf->id_map) {
1007 map = it->elem;
1008 n2args += 2;
57d116ab 1009 n2 = realloc(n2, n2args * sizeof(char *));
cf3ef16d
SH
1010 if (!n2)
1011 exit(1);
1012 n2[n2args-2] = "-m";
1013 n2[n2args-1] = malloc(200);
1014 if (!n2[n2args-1])
1015 exit(1);
1016 ret = snprintf(n2[n2args-1], 200, "%c:%lu:%lu:%lu",
1017 map->idtype == ID_TYPE_UID ? 'u' : 'g',
1018 map->nsid, map->hostid, map->range);
1019 if (ret < 0 || ret >= 200)
1020 exit(1);
1021 }
2133f58c 1022 int hostid_mapped = mapped_hostid(geteuid(), conf, ID_TYPE_UID);
6849cb5b 1023 int extraargs = hostid_mapped >= 0 ? 1 : 3;
57d116ab 1024 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
cf3ef16d
SH
1025 if (!n2)
1026 exit(1);
57d116ab 1027 if (hostid_mapped < 0) {
2133f58c 1028 hostid_mapped = find_unmapped_nsuid(conf, ID_TYPE_UID);
cf3ef16d 1029 n2[n2args++] = "-m";
57d116ab 1030 if (hostid_mapped < 0) {
cf3ef16d
SH
1031 ERROR("Could not find free uid to map");
1032 exit(1);
1033 }
1034 n2[n2args++] = malloc(200);
1035 if (!n2[n2args-1]) {
1036 SYSERROR("out of memory");
1037 exit(1);
1038 }
1039 ret = snprintf(n2[n2args-1], 200, "u:%d:%d:1",
57d116ab 1040 hostid_mapped, geteuid());
cf3ef16d
SH
1041 if (ret < 0 || ret >= 200) {
1042 ERROR("string too long");
1043 exit(1);
1044 }
1045 }
2133f58c
SH
1046 int hostgid_mapped = mapped_hostid(getegid(), conf, ID_TYPE_GID);
1047 extraargs = hostgid_mapped >= 0 ? 1 : 3;
1048 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1049 if (!n2)
1050 exit(1);
1051 if (hostgid_mapped < 0) {
1052 hostgid_mapped = find_unmapped_nsuid(conf, ID_TYPE_GID);
1053 n2[n2args++] = "-m";
1054 if (hostgid_mapped < 0) {
1055 ERROR("Could not find free uid to map");
1056 exit(1);
1057 }
1058 n2[n2args++] = malloc(200);
1059 if (!n2[n2args-1]) {
1060 SYSERROR("out of memory");
1061 exit(1);
1062 }
1063 ret = snprintf(n2[n2args-1], 200, "g:%d:%d:1",
1064 hostgid_mapped, getegid());
1065 if (ret < 0 || ret >= 200) {
1066 ERROR("string too long");
1067 exit(1);
1068 }
1069 }
cf3ef16d
SH
1070 n2[n2args++] = "--";
1071 for (i = 0; i < nargs; i++)
1072 n2[i + n2args] = newargv[i];
57d116ab
SH
1073 n2args += nargs;
1074 // Finally add "--mapped-uid $uid" to tell template what to chown
1075 // cached images to
2133f58c 1076 n2args += 4;
57d116ab
SH
1077 n2 = realloc(n2, n2args * sizeof(char *));
1078 if (!n2) {
1079 SYSERROR("out of memory");
1080 exit(1);
1081 }
1082 // note n2[n2args-1] is NULL
2133f58c 1083 n2[n2args-5] = "--mapped-uid";
57d116ab 1084 snprintf(txtuid, 20, "%d", hostid_mapped);
2133f58c
SH
1085 n2[n2args-4] = txtuid;
1086 n2[n2args-3] = "--mapped-gid";
1087 snprintf(txtgid, 20, "%d", hostgid_mapped);
1088 n2[n2args-2] = txtgid;
57d116ab 1089 n2[n2args-1] = NULL;
cf3ef16d
SH
1090 free(newargv);
1091 newargv = n2;
1092 }
72d0e1cb 1093 /* execute */
cf3ef16d 1094 execvp(tpath, newargv);
72d0e1cb
SG
1095 SYSERROR("failed to execute template %s", tpath);
1096 exit(1);
1097 }
1098
9be53773 1099 if (wait_for_pid(pid) != 0) {
959aee9c 1100 ERROR("container creation template for %s failed", c->name);
96b3cb40
SH
1101 return false;
1102 }
1103
1104 return true;
1105}
1106
74a3920a 1107static bool prepend_lxc_header(char *path, const char *t, char *const argv[])
3ce74686 1108{
1fd9bd50 1109 long flen;
b4569e93 1110 char *contents;
3ce74686 1111 FILE *f;
025ed0f3 1112 int ret = -1;
52026772 1113#if HAVE_LIBGNUTLS
025ed0f3 1114 int i;
3ce74686 1115 unsigned char md_value[SHA_DIGEST_LENGTH];
b4569e93 1116 char *tpath;
52026772 1117#endif
3ce74686 1118
025ed0f3 1119 f = fopen(path, "r");
025ed0f3 1120 if (f == NULL)
3ce74686 1121 return false;
025ed0f3
SH
1122
1123 if (fseek(f, 0, SEEK_END) < 0)
1124 goto out_error;
1125 if ((flen = ftell(f)) < 0)
1126 goto out_error;
1127 if (fseek(f, 0, SEEK_SET) < 0)
1128 goto out_error;
1129 if ((contents = malloc(flen + 1)) == NULL)
1130 goto out_error;
1131 if (fread(contents, 1, flen, f) != flen)
1132 goto out_free_contents;
1133
3ce74686 1134 contents[flen] = '\0';
025ed0f3 1135 ret = fclose(f);
025ed0f3
SH
1136 f = NULL;
1137 if (ret < 0)
1138 goto out_free_contents;
3ce74686 1139
b4569e93 1140#if HAVE_LIBGNUTLS
01efd4d3 1141 tpath = get_template_path(t);
85db5535 1142 if (!tpath) {
959aee9c 1143 ERROR("bad template: %s", t);
025ed0f3 1144 goto out_free_contents;
3ce74686
SH
1145 }
1146
85db5535
DE
1147 ret = sha1sum_file(tpath, md_value);
1148 if (ret < 0) {
1149 ERROR("Error getting sha1sum of %s", tpath);
3ce74686 1150 free(tpath);
85db5535 1151 goto out_free_contents;
3ce74686 1152 }
85db5535 1153 free(tpath);
3ce74686
SH
1154#endif
1155
025ed0f3 1156 f = fopen(path, "w");
025ed0f3 1157 if (f == NULL) {
3ce74686
SH
1158 SYSERROR("reopening config for writing");
1159 free(contents);
1160 return false;
1161 }
1162 fprintf(f, "# Template used to create this container: %s\n", t);
1163 if (argv) {
1164 fprintf(f, "# Parameters passed to the template:");
1165 while (*argv) {
1166 fprintf(f, " %s", *argv);
1167 argv++;
1168 }
1169 fprintf(f, "\n");
1170 }
1171#if HAVE_LIBGNUTLS
56698177
SH
1172 fprintf(f, "# Template script checksum (SHA-1): ");
1173 for (i=0; i<SHA_DIGEST_LENGTH; i++)
1174 fprintf(f, "%02x", md_value[i]);
1175 fprintf(f, "\n");
3ce74686 1176#endif
0520c252 1177 fprintf(f, "# For additional config options, please look at lxc.container.conf(5)\n");
3ce74686
SH
1178 if (fwrite(contents, 1, flen, f) != flen) {
1179 SYSERROR("Writing original contents");
1180 free(contents);
1181 fclose(f);
1182 return false;
1183 }
025ed0f3
SH
1184 ret = 0;
1185out_free_contents:
3ce74686 1186 free(contents);
025ed0f3
SH
1187out_error:
1188 if (f) {
1189 int newret;
025ed0f3 1190 newret = fclose(f);
025ed0f3
SH
1191 if (ret == 0)
1192 ret = newret;
1193 }
1194 if (ret < 0) {
1195 SYSERROR("Error prepending header");
3ce74686
SH
1196 return false;
1197 }
1198 return true;
1199}
1200
4df7f012
SH
1201static void lxcapi_clear_config(struct lxc_container *c)
1202{
f979ac15
SH
1203 if (c) {
1204 if (c->lxc_conf) {
1205 lxc_conf_free(c->lxc_conf);
1206 c->lxc_conf = NULL;
1207 }
4df7f012
SH
1208 }
1209}
1210
96b3cb40 1211static bool lxcapi_destroy(struct lxc_container *c);
18aa217b
SH
1212static bool container_destroy(struct lxc_container *c);
1213static bool get_snappath_dir(struct lxc_container *c, char *snappath);
96b3cb40
SH
1214/*
1215 * lxcapi_create:
1216 * create a container with the given parameters.
1217 * @c: container to be created. It has the lxcpath, name, and a starting
1218 * configuration already set
1219 * @t: the template to execute to instantiate the root filesystem and
1220 * adjust the configuration.
1221 * @bdevtype: backing store type to use. If NULL, dir will be used.
1222 * @specs: additional parameters for the backing store, i.e. LVM vg to
1223 * use.
1224 *
1225 * @argv: the arguments to pass to the template, terminated by NULL. If no
1226 * arguments, you can just pass NULL.
1227 */
1228static bool lxcapi_create(struct lxc_container *c, const char *t,
dc23c1c8 1229 const char *bdevtype, struct bdev_specs *specs, int flags,
96b3cb40
SH
1230 char *const argv[])
1231{
a69aad27 1232 bool ret = false;
96b3cb40 1233 pid_t pid;
85db5535 1234 char *tpath = NULL;
cbee8106 1235 int partial_fd;
96b3cb40
SH
1236
1237 if (!c)
1238 return false;
1239
85db5535
DE
1240 if (t) {
1241 tpath = get_template_path(t);
1242 if (!tpath) {
959aee9c 1243 ERROR("bad template: %s", t);
85db5535
DE
1244 goto out;
1245 }
96b3cb40
SH
1246 }
1247
cf465fe4
SH
1248 /*
1249 * If a template is passed in, and the rootfs already is defined in
1250 * the container config and exists, then * caller is trying to create
1251 * an existing container. Return an error, but do NOT delete the
1252 * container.
1253 */
1254 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
1255 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
1256 ERROR("Container %s:%s already exists", c->config_path, c->name);
6c6892b5 1257 goto free_tpath;
cf465fe4
SH
1258 }
1259
6c6892b5 1260 if (!c->lxc_conf) {
dad87e3b 1261 if (!c->load_config(c, lxc_global_config_value("lxc.default_config"))) {
959aee9c 1262 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
6c6892b5
DE
1263 goto free_tpath;
1264 }
96b3cb40
SH
1265 }
1266
6c6892b5
DE
1267 if (!create_container_dir(c))
1268 goto free_tpath;
1269
0590e82c
SH
1270 /*
1271 * either template or rootfs.path should be set.
1272 * if both template and rootfs.path are set, template is setup as rootfs.path.
1273 * container is already created if we have a config and rootfs.path is accessible
1274 */
1275 if (!c->lxc_conf->rootfs.path && !tpath)
1276 /* no template passed in and rootfs does not exist: error */
1277 goto out;
1278 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
1279 /* rootfs passed into configuration, but does not exist: error */
1280 goto out;
1281 if (lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
1282 /* Rootfs already existed, user just wanted to save the
1283 * loaded configuration */
1284 ret = true;
1285 goto out;
a69aad27 1286 }
96b3cb40
SH
1287
1288 /* Mark that this container is being created */
1289 if ((partial_fd = create_partial(c)) < 0)
1290 goto out;
1291
1292 /* no need to get disk lock bc we have the partial locked */
1293
1294 /*
1295 * Create the backing store
1296 * Note we can't do this in the same task as we use to execute the
1297 * template because of the way zfs works.
1298 * After you 'zfs create', zfs mounts the fs only in the initial
1299 * namespace.
1300 */
1301 pid = fork();
1302 if (pid < 0) {
959aee9c 1303 SYSERROR("failed to fork task for container creation template");
8eb5694b
SH
1304 goto out_unlock;
1305 }
1306
96b3cb40
SH
1307 if (pid == 0) { // child
1308 struct bdev *bdev = NULL;
1309
1310 if (!(bdev = do_bdev_create(c, bdevtype, specs))) {
1311 ERROR("Error creating backing store type %s for %s",
1312 bdevtype ? bdevtype : "(none)", c->name);
1313 exit(1);
1314 }
1315
1316 /* save config file again to store the new rootfs location */
1317 if (!c->save_config(c, NULL)) {
959aee9c 1318 ERROR("failed to save starting configuration for %s", c->name);
96b3cb40
SH
1319 // parent task won't see bdev in config so we delete it
1320 bdev->ops->umount(bdev);
1321 bdev->ops->destroy(bdev);
1322 exit(1);
1323 }
1324 exit(0);
1325 }
1326 if (wait_for_pid(pid) != 0)
a09295f8 1327 goto out_unlock;
96b3cb40
SH
1328
1329 /* reload config to get the rootfs */
a3b47c09 1330 lxc_conf_free(c->lxc_conf);
96b3cb40
SH
1331 c->lxc_conf = NULL;
1332 if (!load_config_locked(c, c->configfile))
a09295f8 1333 goto out_unlock;
96b3cb40 1334
dc23c1c8 1335 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
96b3cb40
SH
1336 goto out_unlock;
1337
8eb5694b
SH
1338 // now clear out the lxc_conf we have, reload from the created
1339 // container
4df7f012 1340 lxcapi_clear_config(c);
3ce74686 1341
9d65a487
KY
1342 if (t) {
1343 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
1344 ERROR("Error prepending header to configuration file");
1345 goto out_unlock;
1346 }
3ce74686 1347 }
a69aad27 1348 ret = load_config_locked(c, c->configfile);
72d0e1cb
SG
1349
1350out_unlock:
3e625e2d
SH
1351 if (partial_fd >= 0)
1352 remove_partial(c, partial_fd);
72d0e1cb 1353out:
a69aad27 1354 if (!ret && c)
18aa217b 1355 container_destroy(c);
6c6892b5
DE
1356free_tpath:
1357 if (tpath)
1358 free(tpath);
a69aad27 1359 return ret;
72d0e1cb
SG
1360}
1361
3e625e2d
SH
1362static bool lxcapi_reboot(struct lxc_container *c)
1363{
1364 pid_t pid;
1365
1366 if (!c)
1367 return false;
1368 if (!c->is_running(c))
1369 return false;
1370 pid = c->init_pid(c);
1371 if (pid <= 0)
1372 return false;
1373 if (kill(pid, SIGINT) < 0)
1374 return false;
1375 return true;
1376
1377}
1378
72d0e1cb
SG
1379static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
1380{
1381 bool retv;
1382 pid_t pid;
f0f1d8c0 1383 int haltsignal = SIGPWR;
72d0e1cb
SG
1384
1385 if (!c)
1386 return false;
1387
72d0e1cb
SG
1388 if (!c->is_running(c))
1389 return true;
1390 pid = c->init_pid(c);
1391 if (pid <= 0)
1392 return true;
b0227444 1393 if (c->lxc_conf && c->lxc_conf->haltsignal)
f0f1d8c0
DE
1394 haltsignal = c->lxc_conf->haltsignal;
1395 kill(pid, haltsignal);
72d0e1cb 1396 retv = c->wait(c, "STOPPED", timeout);
72d0e1cb
SG
1397 return retv;
1398}
1399
1897e3bc 1400static bool lxcapi_createl(struct lxc_container *c, const char *t,
dc23c1c8 1401 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
72d0e1cb
SG
1402{
1403 bool bret = false;
a0e93eeb 1404 char **args = NULL;
72d0e1cb 1405 va_list ap;
72d0e1cb
SG
1406
1407 if (!c)
1408 return false;
1409
1410 /*
1411 * since we're going to wait for create to finish, I don't think we
1412 * need to get a copy of the arguments.
1413 */
dc23c1c8 1414 va_start(ap, flags);
a0e93eeb 1415 args = lxc_va_arg_list_to_argv(ap, 0, 0);
72d0e1cb 1416 va_end(ap);
a0e93eeb
CS
1417 if (!args) {
1418 ERROR("Memory allocation error.");
1419 goto out;
1420 }
72d0e1cb 1421
dc23c1c8 1422 bret = c->create(c, t, bdevtype, specs, flags, args);
72d0e1cb
SG
1423
1424out:
a0e93eeb 1425 free(args);
72d0e1cb
SG
1426 return bret;
1427}
1428
6b0d5538
SH
1429static void do_clear_unexp_config_line(struct lxc_conf *conf, const char *key)
1430{
1431 if (strcmp(key, "lxc.cgroup") == 0)
1432 clear_unexp_config_line(conf, key, true);
1433 else if (strcmp(key, "lxc.network") == 0)
1434 clear_unexp_config_line(conf, key, true);
1435 else if (strcmp(key, "lxc.hook") == 0)
1436 clear_unexp_config_line(conf, key, true);
1437 else
1438 clear_unexp_config_line(conf, key, false);
1439 if (!do_append_unexp_config_line(conf, key, ""))
1440 WARN("Error clearing configuration for %s", key);
1441}
1442
12a50cc6 1443static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
72d0e1cb
SG
1444{
1445 int ret;
1446
1447 if (!c || !c->lxc_conf)
1448 return false;
5cee8c50 1449 if (container_mem_lock(c))
72d0e1cb 1450 return false;
72d0e1cb 1451 ret = lxc_clear_config_item(c->lxc_conf, key);
6b0d5538
SH
1452 if (!ret)
1453 do_clear_unexp_config_line(c->lxc_conf, key);
5cee8c50 1454 container_mem_unlock(c);
72d0e1cb
SG
1455 return ret == 0;
1456}
1457
ae22a220
ÇO
1458static inline bool enter_to_ns(struct lxc_container *c) {
1459 int netns, userns, ret = 0, init_pid = 0;;
9c83a661 1460 char new_netns_path[MAXPATHLEN];
ae22a220 1461 char new_userns_path[MAXPATHLEN];
9c83a661
SG
1462
1463 if (!c->is_running(c))
1464 goto out;
1465
ae22a220
ÇO
1466 init_pid = c->init_pid(c);
1467
1468 /* Switch to new userns */
0e6e3a41 1469 if ((geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) && access("/proc/self/ns/user", F_OK) == 0) {
ae22a220
ÇO
1470 ret = snprintf(new_userns_path, MAXPATHLEN, "/proc/%d/ns/user", init_pid);
1471 if (ret < 0 || ret >= MAXPATHLEN)
1472 goto out;
1473
1474 userns = open(new_userns_path, O_RDONLY);
1475 if (userns < 0) {
1476 SYSERROR("failed to open %s", new_userns_path);
1477 goto out;
1478 }
1479
1480 if (setns(userns, CLONE_NEWUSER)) {
1481 SYSERROR("failed to setns for CLONE_NEWUSER");
452c9141 1482 close(userns);
ae22a220
ÇO
1483 goto out;
1484 }
452c9141 1485 close(userns);
9c83a661
SG
1486 }
1487
1488 /* Switch to new netns */
ae22a220 1489 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", init_pid);
9c83a661
SG
1490 if (ret < 0 || ret >= MAXPATHLEN)
1491 goto out;
1492
ae22a220
ÇO
1493 netns = open(new_netns_path, O_RDONLY);
1494 if (netns < 0) {
9c83a661
SG
1495 SYSERROR("failed to open %s", new_netns_path);
1496 goto out;
1497 }
1498
ae22a220
ÇO
1499 if (setns(netns, CLONE_NEWNET)) {
1500 SYSERROR("failed to setns for CLONE_NEWNET");
32f4b9c7 1501 close(netns);
9c83a661
SG
1502 goto out;
1503 }
32f4b9c7 1504 close(netns);
799f29ab
ÇO
1505 return true;
1506out:
799f29ab
ÇO
1507 return false;
1508}
1509
9c88ff1f
ÇO
1510// used by qsort and bsearch functions for comparing names
1511static inline int string_cmp(char **first, char **second)
1512{
1513 return strcmp(*first, *second);
1514}
1515
1516// used by qsort and bsearch functions for comparing container names
1517static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1518{
1519 return strcmp((*first)->name, (*second)->name);
1520}
1521
1522static bool add_to_array(char ***names, char *cname, int pos)
1523{
1524 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1525 if (!newnames) {
1526 ERROR("Out of memory");
1527 return false;
1528 }
1529
1530 *names = newnames;
1531 newnames[pos] = strdup(cname);
1532 if (!newnames[pos])
1533 return false;
1534
1535 // sort the arrray as we will use binary search on it
1536 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1537
1538 return true;
1539}
1540
2871830a 1541static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
9c88ff1f
ÇO
1542{
1543 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1544 if (!newlist) {
1545 ERROR("Out of memory");
1546 return false;
1547 }
1548
1549 *list = newlist;
1550 newlist[pos] = c;
1551
1552 // sort the arrray as we will use binary search on it
2871830a
DE
1553 if (sort)
1554 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
9c88ff1f
ÇO
1555
1556 return true;
1557}
1558
1559static char** get_from_array(char ***names, char *cname, int size)
1560{
1561 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1562}
1563
1564
1565static bool array_contains(char ***names, char *cname, int size) {
1566 if(get_from_array(names, cname, size) != NULL)
1567 return true;
1568 return false;
1569}
1570
1571static bool remove_from_array(char ***names, char *cname, int size)
1572{
1573 char **result = get_from_array(names, cname, size);
1574 if (result != NULL) {
1575 free(result);
1576 return true;
1577 }
1578 return false;
1579}
1580
799f29ab
ÇO
1581static char** lxcapi_get_interfaces(struct lxc_container *c)
1582{
ae22a220
ÇO
1583 pid_t pid;
1584 int i, count = 0, pipefd[2];
9c88ff1f 1585 char **interfaces = NULL;
ae22a220 1586 char interface[IFNAMSIZ];
799f29ab 1587
ae22a220
ÇO
1588 if(pipe(pipefd) < 0) {
1589 SYSERROR("pipe failed");
1590 return NULL;
c868b261
ÇO
1591 }
1592
ae22a220
ÇO
1593 pid = fork();
1594 if (pid < 0) {
959aee9c 1595 SYSERROR("failed to fork task to get interfaces information");
ae22a220
ÇO
1596 close(pipefd[0]);
1597 close(pipefd[1]);
1598 return NULL;
1599 }
799f29ab 1600
ae22a220
ÇO
1601 if (pid == 0) { // child
1602 int ret = 1, nbytes;
1603 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1604
1605 /* close the read-end of the pipe */
1606 close(pipefd[0]);
1607
1608 if (!enter_to_ns(c)) {
1609 SYSERROR("failed to enter namespace");
1610 goto out;
1611 }
1612
1613 /* Grab the list of interfaces */
1614 if (getifaddrs(&interfaceArray)) {
1615 SYSERROR("failed to get interfaces list");
1616 goto out;
1617 }
1618
1619 /* Iterate through the interfaces */
1620 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1621 nbytes = write(pipefd[1], tempIfAddr->ifa_name, IFNAMSIZ);
1622 if (nbytes < 0) {
1623 ERROR("write failed");
1624 goto out;
1625 }
1626 count++;
1627 }
1628 ret = 0;
1629
1630 out:
1631 if (interfaceArray)
1632 freeifaddrs(interfaceArray);
1633
1634 /* close the write-end of the pipe, thus sending EOF to the reader */
1635 close(pipefd[1]);
1636 exit(ret);
799f29ab
ÇO
1637 }
1638
ae22a220
ÇO
1639 /* close the write-end of the pipe */
1640 close(pipefd[1]);
1641
358afd84 1642 while (read(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
ae22a220
ÇO
1643 if (array_contains(&interfaces, interface, count))
1644 continue;
799f29ab 1645
ae22a220
ÇO
1646 if(!add_to_array(&interfaces, interface, count))
1647 ERROR("PARENT: add_to_array failed");
9c88ff1f
ÇO
1648 count++;
1649 }
799f29ab 1650
ae22a220
ÇO
1651 if (wait_for_pid(pid) != 0) {
1652 for(i=0;i<count;i++)
1653 free(interfaces[i]);
1654 free(interfaces);
1655 interfaces = NULL;
1656 }
9c88ff1f 1657
ae22a220
ÇO
1658 /* close the read-end of the pipe */
1659 close(pipefd[0]);
799f29ab 1660
9c88ff1f
ÇO
1661 /* Append NULL to the array */
1662 if(interfaces)
1663 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
799f29ab 1664
9c88ff1f 1665 return interfaces;
799f29ab
ÇO
1666}
1667
f0ca2726 1668static char** lxcapi_get_ips(struct lxc_container *c, const char* interface, const char* family, int scope)
799f29ab 1669{
ae22a220
ÇO
1670 pid_t pid;
1671 int i, count = 0, pipefd[2];
9c88ff1f 1672 char **addresses = NULL;
ae22a220 1673 char address[INET6_ADDRSTRLEN];
799f29ab 1674
ae22a220
ÇO
1675 if(pipe(pipefd) < 0) {
1676 SYSERROR("pipe failed");
1677 return NULL;
c868b261
ÇO
1678 }
1679
ae22a220
ÇO
1680 pid = fork();
1681 if (pid < 0) {
959aee9c 1682 SYSERROR("failed to fork task to get container ips");
ae22a220
ÇO
1683 close(pipefd[0]);
1684 close(pipefd[1]);
1685 return NULL;
9c83a661
SG
1686 }
1687
ae22a220
ÇO
1688 if (pid == 0) { // child
1689 int ret = 1, nbytes;
1690 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1691 char addressOutputBuffer[INET6_ADDRSTRLEN];
1692 void *tempAddrPtr = NULL;
1693 char *address = NULL;
fe218ca3 1694
ae22a220
ÇO
1695 /* close the read-end of the pipe */
1696 close(pipefd[0]);
1697
1698 if (!enter_to_ns(c)) {
1699 SYSERROR("failed to enter namespace");
1700 goto out;
9c83a661 1701 }
ae22a220
ÇO
1702
1703 /* Grab the list of interfaces */
1704 if (getifaddrs(&interfaceArray)) {
1705 SYSERROR("failed to get interfaces list");
1706 goto out;
1707 }
1708
1709 /* Iterate through the interfaces */
1710 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1711 if (tempIfAddr->ifa_addr == NULL)
9c83a661
SG
1712 continue;
1713
ae22a220
ÇO
1714 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1715 if (family && strcmp(family, "inet"))
1716 continue;
1717 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1718 }
1719 else {
1720 if (family && strcmp(family, "inet6"))
1721 continue;
1722
1723 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1724 continue;
1725
1726 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1727 }
1728
1729 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1730 continue;
1731 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
9c83a661
SG
1732 continue;
1733
ae22a220
ÇO
1734 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1735 tempAddrPtr,
1736 addressOutputBuffer,
1737 sizeof(addressOutputBuffer));
1738 if (!address)
1739 continue;
1740
1741 nbytes = write(pipefd[1], address, INET6_ADDRSTRLEN);
1742 if (nbytes < 0) {
1743 ERROR("write failed");
1744 goto out;
1745 }
1746 count++;
9c83a661 1747 }
ae22a220 1748 ret = 0;
9c83a661 1749
ae22a220
ÇO
1750 out:
1751 if(interfaceArray)
1752 freeifaddrs(interfaceArray);
9c83a661 1753
ae22a220
ÇO
1754 /* close the write-end of the pipe, thus sending EOF to the reader */
1755 close(pipefd[1]);
1756 exit(ret);
6849cb5b 1757 }
9c83a661 1758
ae22a220
ÇO
1759 /* close the write-end of the pipe */
1760 close(pipefd[1]);
1761
358afd84 1762 while (read(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
9c88ff1f 1763 if(!add_to_array(&addresses, address, count))
ae22a220 1764 ERROR("PARENT: add_to_array failed");
9c88ff1f 1765 count++;
9c83a661
SG
1766 }
1767
ae22a220
ÇO
1768 if (wait_for_pid(pid) != 0) {
1769 for(i=0;i<count;i++)
1770 free(addresses[i]);
1771 free(addresses);
1772 addresses = NULL;
1773 }
9c83a661 1774
ae22a220
ÇO
1775 /* close the read-end of the pipe */
1776 close(pipefd[0]);
9c83a661
SG
1777
1778 /* Append NULL to the array */
9c88ff1f
ÇO
1779 if(addresses)
1780 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
9c83a661
SG
1781
1782 return addresses;
1783}
1784
12a50cc6 1785static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1786{
1787 int ret;
1788
1789 if (!c || !c->lxc_conf)
1790 return -1;
5cee8c50 1791 if (container_mem_lock(c))
72d0e1cb 1792 return -1;
72d0e1cb 1793 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
5cee8c50 1794 container_mem_unlock(c);
72d0e1cb
SG
1795 return ret;
1796}
1797
8ac18377
ÇO
1798static char* lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
1799{
1800 char *ret;
1801
1802 if (!c || !c->lxc_conf)
1803 return NULL;
1804 if (container_mem_lock(c))
1805 return NULL;
1806 ret = lxc_cmd_get_config_item(c->name, key, c->get_config_path(c));
1807 container_mem_unlock(c);
1808 return ret;
1809}
1810
12a50cc6 1811static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1812{
1813 if (!key)
1814 return lxc_listconfigs(retv, inlen);
1815 /*
1816 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1817 * This is an intelligent result to show which keys are valid given
1818 * the type of nic it is
1819 */
1820 if (!c || !c->lxc_conf)
1821 return -1;
5cee8c50 1822 if (container_mem_lock(c))
72d0e1cb
SG
1823 return -1;
1824 int ret = -1;
1825 if (strncmp(key, "lxc.network.", 12) == 0)
6849cb5b 1826 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
5cee8c50 1827 container_mem_unlock(c);
72d0e1cb
SG
1828 return ret;
1829}
1830
12a50cc6 1831static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 1832{
39dc698c
SH
1833 FILE *fout;
1834 bool ret = false, need_disklock = false;
1835 int lret;
1836
72d0e1cb
SG
1837 if (!alt_file)
1838 alt_file = c->configfile;
1839 if (!alt_file)
6849cb5b 1840 return false; // should we write to stdout if no file is specified?
39dc698c
SH
1841
1842 // If we haven't yet loaded a config, load the stock config
1843 if (!c->lxc_conf) {
dad87e3b 1844 if (!c->load_config(c, lxc_global_config_value("lxc.default_config"))) {
959aee9c 1845 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c->name);
72d0e1cb
SG
1846 return false;
1847 }
39dc698c 1848 }
72d0e1cb 1849
5a3d2e1e
SG
1850 if (!create_container_dir(c))
1851 return false;
1852
39dc698c
SH
1853 /*
1854 * If we're writing to the container's config file, take the
1855 * disk lock. Otherwise just take the memlock to protect the
1856 * struct lxc_container while we're traversing it.
1857 */
1858 if (strcmp(c->configfile, alt_file) == 0)
1859 need_disklock = true;
1860
1861 if (need_disklock)
1862 lret = container_disk_lock(c);
1863 else
1864 lret = container_mem_lock(c);
1865
1866 if (lret)
72d0e1cb 1867 return false;
39dc698c
SH
1868
1869 fout = fopen(alt_file, "w");
1870 if (!fout)
1871 goto out;
6b0d5538 1872 write_config(fout, c->lxc_conf);
72d0e1cb 1873 fclose(fout);
39dc698c
SH
1874 ret = true;
1875
1876out:
1877 if (need_disklock)
1878 container_disk_unlock(c);
1879 else
1880 container_mem_unlock(c);
1881 return ret;
72d0e1cb
SG
1882}
1883
dfb31b25
SH
1884static bool mod_rdep(struct lxc_container *c, bool inc)
1885{
1886 char path[MAXPATHLEN];
1887 int ret, v = 0;
1888 FILE *f;
1889 bool bret = false;
1890
1891 if (container_disk_lock(c))
1892 return false;
1893 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1894 c->name);
1895 if (ret < 0 || ret > MAXPATHLEN)
1896 goto out;
1897 f = fopen(path, "r");
1898 if (f) {
1899 ret = fscanf(f, "%d", &v);
1900 fclose(f);
1901 if (ret != 1) {
1902 ERROR("Corrupted file %s", path);
1903 goto out;
1904 }
1905 }
1906 v += inc ? 1 : -1;
1907 f = fopen(path, "w");
1908 if (!f)
1909 goto out;
1910 if (fprintf(f, "%d\n", v) < 0) {
1911 ERROR("Error writing new snapshots value");
1912 fclose(f);
1913 goto out;
1914 }
025ed0f3 1915 ret = fclose(f);
025ed0f3 1916 if (ret != 0) {
dfb31b25
SH
1917 SYSERROR("Error writing to or closing snapshots file");
1918 goto out;
1919 }
1920
1921 bret = true;
1922
1923out:
1924 container_disk_unlock(c);
1925 return bret;
1926}
1927
1928static void strip_newline(char *p)
1929{
1930 size_t len = strlen(p);
1931 if (len < 1)
1932 return;
1933 if (p[len-1] == '\n')
1934 p[len-1] = '\0';
1935}
1936
1937static void mod_all_rdeps(struct lxc_container *c, bool inc)
1938{
1939 struct lxc_container *p;
1940 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
1941 size_t pathlen = 0, namelen = 0;
1942 FILE *f;
1943 int ret;
1944
1945 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
1946 c->config_path, c->name);
1947 if (ret < 0 || ret >= MAXPATHLEN) {
1948 ERROR("Path name too long");
1949 return;
1950 }
025ed0f3 1951 f = fopen(path, "r");
025ed0f3 1952 if (f == NULL)
dfb31b25
SH
1953 return;
1954 while (getline(&lxcpath, &pathlen, f) != -1) {
1955 if (getline(&lxcname, &namelen, f) == -1) {
959aee9c 1956 ERROR("badly formatted file %s", path);
dfb31b25
SH
1957 goto out;
1958 }
1959 strip_newline(lxcpath);
1960 strip_newline(lxcname);
1961 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
1962 ERROR("Unable to find dependent container %s:%s",
1963 lxcpath, lxcname);
1964 continue;
1965 }
1966 if (!mod_rdep(p, inc))
1967 ERROR("Failed to increase numsnapshots for %s:%s",
1968 lxcpath, lxcname);
1969 lxc_container_put(p);
1970 }
1971out:
1972 if (lxcpath) free(lxcpath);
1973 if (lxcname) free(lxcname);
1974 fclose(f);
1975}
1976
18aa217b 1977static bool has_fs_snapshots(struct lxc_container *c)
dfb31b25
SH
1978{
1979 char path[MAXPATHLEN];
1980 int ret, v;
1981 FILE *f;
1982 bool bret = false;
1983
1984 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1985 c->name);
1986 if (ret < 0 || ret > MAXPATHLEN)
1987 goto out;
1988 f = fopen(path, "r");
1989 if (!f)
1990 goto out;
1991 ret = fscanf(f, "%d", &v);
1992 fclose(f);
1993 if (ret != 1)
1994 goto out;
1995 bret = v != 0;
1996
1997out:
1998 return bret;
1999}
2000
18aa217b
SH
2001static bool has_snapshots(struct lxc_container *c)
2002{
2003 char path[MAXPATHLEN];
2004 struct dirent dirent, *direntp;
2005 int count=0;
2006 DIR *dir;
2007
2008 if (!get_snappath_dir(c, path))
2009 return false;
2010 dir = opendir(path);
2011 if (!dir)
2012 return false;
2013 while (!readdir_r(dir, &dirent, &direntp)) {
2014 if (!direntp)
2015 break;
2016
2017 if (!strcmp(direntp->d_name, "."))
2018 continue;
2019
2020 if (!strcmp(direntp->d_name, ".."))
2021 continue;
2022 count++;
2023 break;
2024 }
2025 closedir(dir);
2026 return count > 0;
2027}
2028
4355ab5f
SH
2029static int lxc_rmdir_onedev_wrapper(void *data)
2030{
2031 char *arg = (char *) data;
18aa217b 2032 return lxc_rmdir_onedev(arg, "snaps");
4355ab5f
SH
2033}
2034
44a706bd
SH
2035static int do_bdev_destroy(struct lxc_conf *conf)
2036{
2037 struct bdev *r;
2038 int ret = 0;
2039
76a26f55 2040 r = bdev_init(conf, conf->rootfs.path, conf->rootfs.mount, NULL);
44a706bd
SH
2041 if (!r)
2042 return -1;
2043
2044 if (r->ops->destroy(r) < 0)
2045 ret = -1;
2046 bdev_put(r);
2047 return ret;
2048}
2049
2050static int bdev_destroy_wrapper(void *data)
2051{
2052 struct lxc_conf *conf = data;
2053
2054 if (setgid(0) < 0) {
2055 ERROR("Failed to setgid to 0");
2056 return -1;
2057 }
2058 if (setgroups(0, NULL) < 0)
2059 WARN("Failed to clear groups");
2060 if (setuid(0) < 0) {
2061 ERROR("Failed to setuid to 0");
2062 return -1;
2063 }
2064 return do_bdev_destroy(conf);
2065}
2066
18aa217b 2067static bool container_destroy(struct lxc_container *c)
72d0e1cb 2068{
c868b261 2069 bool bret = false;
fef48dc9 2070 int ret;
72d0e1cb 2071
1897e3bc 2072 if (!c || !lxcapi_is_defined(c))
5a3d2e1e
SG
2073 return false;
2074
3bc449ed 2075 if (container_disk_lock(c))
72d0e1cb 2076 return false;
72d0e1cb 2077
39dc698c 2078 if (!is_stopped(c)) {
60bf62d4
SH
2079 // we should queue some sort of error - in c->error_string?
2080 ERROR("container %s is not stopped", c->name);
2081 goto out;
72d0e1cb
SG
2082 }
2083
44a706bd
SH
2084 if (c->lxc_conf && c->lxc_conf->rootfs.path && c->lxc_conf->rootfs.mount) {
2085 if (am_unpriv())
2086 ret = userns_exec_1(c->lxc_conf, bdev_destroy_wrapper, c->lxc_conf);
2087 else
2088 ret = do_bdev_destroy(c->lxc_conf);
2089 if (ret < 0) {
2090 ERROR("Error destroying rootfs for %s", c->name);
2091 goto out;
60bf62d4
SH
2092 }
2093 }
2094
dfb31b25
SH
2095 mod_all_rdeps(c, false);
2096
60bf62d4
SH
2097 const char *p1 = lxcapi_get_config_path(c);
2098 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
2099 sprintf(path, "%s/%s", p1, c->name);
c868b261 2100 if (am_unpriv())
4355ab5f
SH
2101 ret = userns_exec_1(c->lxc_conf, lxc_rmdir_onedev_wrapper, path);
2102 else
18aa217b 2103 ret = lxc_rmdir_onedev(path, "snaps");
4355ab5f 2104 if (ret < 0) {
60bf62d4
SH
2105 ERROR("Error destroying container directory for %s", c->name);
2106 goto out;
2107 }
fef48dc9 2108 bret = true;
60bf62d4
SH
2109
2110out:
3bc449ed 2111 container_disk_unlock(c);
fef48dc9 2112 return bret;
72d0e1cb
SG
2113}
2114
18aa217b
SH
2115static bool lxcapi_destroy(struct lxc_container *c)
2116{
2117 if (!c || !lxcapi_is_defined(c))
2118 return false;
2119 if (has_snapshots(c)) {
2120 ERROR("Container %s has snapshots; not removing", c->name);
2121 return false;
2122 }
2123
2124 if (has_fs_snapshots(c)) {
2125 ERROR("container %s has snapshots on its rootfs", c->name);
2126 return false;
2127 }
2128
2129 return container_destroy(c);
2130}
2131
2132static bool lxcapi_snapshot_destroy_all(struct lxc_container *c);
2133
2134static bool lxcapi_destroy_with_snapshots(struct lxc_container *c)
2135{
2136 if (!c || !lxcapi_is_defined(c))
2137 return false;
2138 if (!lxcapi_snapshot_destroy_all(c)) {
2139 ERROR("Error deleting all snapshots");
2140 return false;
2141 }
2142 return lxcapi_destroy(c);
2143}
2144
96532523
SH
2145static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
2146{
2147 struct lxc_config_t *config;
2148
2149 if (!c->lxc_conf)
2150 c->lxc_conf = lxc_conf_init();
6b0d5538 2151 if (!c->lxc_conf)
96532523
SH
2152 return false;
2153 config = lxc_getconfig(key);
2154 if (!config)
2155 return false;
6b0d5538 2156 if (config->cb(key, v, c->lxc_conf) != 0)
f979ac15 2157 return false;
6b0d5538 2158 return do_append_unexp_config_line(c->lxc_conf, key, v);
96532523
SH
2159}
2160
12a50cc6 2161static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb 2162{
72d0e1cb 2163 bool b = false;
72d0e1cb
SG
2164
2165 if (!c)
2166 return false;
2167
5cee8c50 2168 if (container_mem_lock(c))
72d0e1cb
SG
2169 return false;
2170
96532523 2171 b = set_config_item_locked(c, key, v);
72d0e1cb 2172
5cee8c50 2173 container_mem_unlock(c);
72d0e1cb
SG
2174 return b;
2175}
2176
2177static char *lxcapi_config_file_name(struct lxc_container *c)
2178{
2179 if (!c || !c->configfile)
2180 return NULL;
2181 return strdup(c->configfile);
2182}
2183
2a59a681
SH
2184static const char *lxcapi_get_config_path(struct lxc_container *c)
2185{
2186 if (!c || !c->config_path)
2187 return NULL;
2188 return (const char *)(c->config_path);
2189}
2190
afeecbba
SH
2191/*
2192 * not for export
2193 * Just recalculate the c->configfile based on the
2194 * c->config_path, which must be set.
2195 * The lxc_container must be locked or not yet public.
2196 */
2197static bool set_config_filename(struct lxc_container *c)
2198{
2199 char *newpath;
2200 int len, ret;
2201
2202 if (!c->config_path)
2203 return false;
2204
2205 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2206 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
2207 newpath = malloc(len);
2208 if (!newpath)
2209 return false;
2210
2211 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
2212 if (ret < 0 || ret >= len) {
2213 fprintf(stderr, "Error printing out config file name\n");
2214 free(newpath);
2215 return false;
2216 }
2217
2218 if (c->configfile)
2219 free(c->configfile);
2220 c->configfile = newpath;
2221
2222 return true;
2223}
2224
2a59a681
SH
2225static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
2226{
2227 char *p;
2228 bool b = false;
afeecbba 2229 char *oldpath = NULL;
2a59a681
SH
2230
2231 if (!c)
2232 return b;
2233
5cee8c50 2234 if (container_mem_lock(c))
2a59a681
SH
2235 return b;
2236
2237 p = strdup(path);
afeecbba
SH
2238 if (!p) {
2239 ERROR("Out of memory setting new lxc path");
2a59a681 2240 goto err;
afeecbba
SH
2241 }
2242
2a59a681
SH
2243 b = true;
2244 if (c->config_path)
afeecbba 2245 oldpath = c->config_path;
2a59a681 2246 c->config_path = p;
afeecbba
SH
2247
2248 /* Since we've changed the config path, we have to change the
2249 * config file name too */
2250 if (!set_config_filename(c)) {
2251 ERROR("Out of memory setting new config filename");
2252 b = false;
2253 free(c->config_path);
2254 c->config_path = oldpath;
2255 oldpath = NULL;
2256 }
2a59a681 2257err:
afeecbba
SH
2258 if (oldpath)
2259 free(oldpath);
5cee8c50 2260 container_mem_unlock(c);
2a59a681
SH
2261 return b;
2262}
2263
2264
794dd120
SH
2265static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
2266{
2267 int ret;
794dd120
SH
2268
2269 if (!c)
2270 return false;
2271
3bc449ed 2272 if (is_stopped(c))
794dd120
SH
2273 return false;
2274
3bc449ed
SH
2275 if (container_disk_lock(c))
2276 return false;
794dd120 2277
33ad9f1a 2278 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
3bc449ed
SH
2279
2280 container_disk_unlock(c);
2281 return ret == 0;
794dd120
SH
2282}
2283
2284static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
2285{
3bc449ed 2286 int ret;
794dd120 2287
6502006a 2288 if (!c)
794dd120
SH
2289 return -1;
2290
3bc449ed 2291 if (is_stopped(c))
794dd120
SH
2292 return -1;
2293
3bc449ed
SH
2294 if (container_disk_lock(c))
2295 return -1;
794dd120 2296
33ad9f1a 2297 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
794dd120 2298
3bc449ed 2299 container_disk_unlock(c);
794dd120
SH
2300 return ret;
2301}
2302
593e8478 2303const char *lxc_get_global_config_item(const char *key)
83c98d82 2304{
593e8478 2305 return lxc_global_config_value(key);
a8428dfa
SH
2306}
2307
b6b918a1
SG
2308const char *lxc_get_version(void)
2309{
95ee490b 2310 return LXC_VERSION;
b6b918a1
SG
2311}
2312
f0ca2726 2313static int copy_file(const char *old, const char *new)
9be53773
SH
2314{
2315 int in, out;
2316 ssize_t len, ret;
2317 char buf[8096];
2318 struct stat sbuf;
2319
2320 if (file_exists(new)) {
2321 ERROR("copy destination %s exists", new);
2322 return -1;
2323 }
2324 ret = stat(old, &sbuf);
2325 if (ret < 0) {
dfb31b25 2326 INFO("Error stat'ing %s", old);
9be53773
SH
2327 return -1;
2328 }
2329
2330 in = open(old, O_RDONLY);
2331 if (in < 0) {
dfb31b25 2332 SYSERROR("Error opening original file %s", old);
9be53773
SH
2333 return -1;
2334 }
2335 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
2336 if (out < 0) {
dfb31b25 2337 SYSERROR("Error opening new file %s", new);
9be53773
SH
2338 close(in);
2339 return -1;
2340 }
2341
2342 while (1) {
2343 len = read(in, buf, 8096);
2344 if (len < 0) {
dfb31b25 2345 SYSERROR("Error reading old file %s", old);
9be53773
SH
2346 goto err;
2347 }
2348 if (len == 0)
2349 break;
2350 ret = write(out, buf, len);
6849cb5b 2351 if (ret < len) { // should we retry?
dfb31b25 2352 SYSERROR("Error: write to new file %s was interrupted", new);
9be53773
SH
2353 goto err;
2354 }
2355 }
2356 close(in);
2357 close(out);
2358
2359 // we set mode, but not owner/group
2360 ret = chmod(new, sbuf.st_mode);
2361 if (ret) {
dfb31b25 2362 SYSERROR("Error setting mode on %s", new);
9be53773
SH
2363 return -1;
2364 }
2365
2366 return 0;
2367
2368err:
2369 close(in);
2370 close(out);
2371 return -1;
2372}
2373
9be53773
SH
2374static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2375{
619256b5 2376 int i, len, ret;
9be53773 2377 struct lxc_list *it;
619256b5
ÇO
2378 char *cpath;
2379
2380 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
2381 cpath = alloca(len);
2382 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
2383 if (ret < 0 || ret >= len)
2384 return -1;
9be53773
SH
2385
2386 for (i=0; i<NUM_LXC_HOOKS; i++) {
2387 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2388 char *hookname = it->elem;
c32981c3 2389 char *fname = strrchr(hookname, '/');
9be53773
SH
2390 char tmppath[MAXPATHLEN];
2391 if (!fname) // relative path - we don't support, but maybe we should
2392 return 0;
619256b5
ÇO
2393 if (strncmp(hookname, cpath, len - 1) != 0) {
2394 // this hook is public - ignore
2395 continue;
2396 }
9be53773
SH
2397 // copy the script, and change the entry in confile
2398 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2399 c->config_path, c->name, fname+1);
2400 if (ret < 0 || ret >= MAXPATHLEN)
2401 return -1;
2402 ret = copy_file(it->elem, tmppath);
2403 if (ret < 0)
2404 return -1;
2405 free(it->elem);
2406 it->elem = strdup(tmppath);
2407 if (!it->elem) {
2408 ERROR("out of memory copying hook path");
2409 return -1;
2410 }
9be53773
SH
2411 }
2412 }
2413
6b0d5538
SH
2414 if (!clone_update_unexp_hooks(c->lxc_conf)) {
2415 ERROR("Error saving new hooks in clone");
2416 return -1;
2417 }
9be53773
SH
2418 c->save_config(c, NULL);
2419 return 0;
2420}
2421
2422static void new_hwaddr(char *hwaddr)
2423{
025ed0f3 2424 FILE *f;
025ed0f3 2425 f = fopen("/dev/urandom", "r");
9be53773
SH
2426 if (f) {
2427 unsigned int seed;
2428 int ret = fread(&seed, sizeof(seed), 1, f);
2429 if (ret != 1)
2430 seed = time(NULL);
2431 fclose(f);
2432 srand(seed);
2433 } else
2434 srand(time(NULL));
2435 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
2436 rand() % 255, rand() % 255, rand() % 255);
2437}
2438
2439static void network_new_hwaddrs(struct lxc_container *c)
2440{
2441 struct lxc_list *it;
2442
2443 lxc_list_for_each(it, &c->lxc_conf->network) {
2444 struct lxc_netdev *n = it->elem;
2445 if (n->hwaddr)
2446 new_hwaddr(n->hwaddr);
2447 }
2448}
2449
2450static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2451{
2452 char newpath[MAXPATHLEN];
2453 char *oldpath = oldc->lxc_conf->fstab;
2454 int ret;
2455
2456 if (!oldpath)
2457 return 0;
2458
6b0d5538
SH
2459 clear_unexp_config_line(c->lxc_conf, "lxc.mount", false);
2460
c32981c3 2461 char *p = strrchr(oldpath, '/');
9be53773
SH
2462 if (!p)
2463 return -1;
2464 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2465 c->config_path, c->name, p);
2466 if (ret < 0 || ret >= MAXPATHLEN) {
2467 ERROR("error printing new path for %s", oldpath);
2468 return -1;
2469 }
2470 if (file_exists(newpath)) {
2471 ERROR("error: fstab file %s exists", newpath);
2472 return -1;
2473 }
2474
2475 if (copy_file(oldpath, newpath) < 0) {
2476 ERROR("error: copying %s to %s", oldpath, newpath);
2477 return -1;
2478 }
2479 free(c->lxc_conf->fstab);
2480 c->lxc_conf->fstab = strdup(newpath);
2481 if (!c->lxc_conf->fstab) {
2482 ERROR("error: allocating pathname");
2483 return -1;
2484 }
6b0d5538
SH
2485 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.mount", newpath)) {
2486 ERROR("error saving new lxctab");
2487 return -1;
2488 }
9be53773
SH
2489
2490 return 0;
2491}
2492
dfb31b25
SH
2493static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2494{
2495 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2496 int ret;
2497
2498 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2499 c0->name);
2500 if (ret < 0 || ret >= MAXPATHLEN) {
2501 WARN("Error copying reverse dependencies");
2502 return;
2503 }
2504 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2505 c->name);
2506 if (ret < 0 || ret >= MAXPATHLEN) {
2507 WARN("Error copying reverse dependencies");
2508 return;
2509 }
2510 if (copy_file(path0, path1) < 0) {
2511 INFO("Error copying reverse dependencies");
2512 return;
2513 }
2514}
2515
2516static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2517{
2518 int ret;
2519 char path[MAXPATHLEN];
2520 FILE *f;
2521 bool bret;
2522
2523 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2524 c->name);
2525 if (ret < 0 || ret >= MAXPATHLEN)
2526 return false;
2527 f = fopen(path, "a");
2528 if (!f)
2529 return false;
2530 bret = true;
2531 // if anything goes wrong, just return an error
2532 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2533 bret = false;
2534 if (fclose(f) != 0)
2535 bret = false;
2536 return bret;
2537}
2538
9be53773 2539static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
d659597e 2540 const char *newtype, int flags, const char *bdevdata, uint64_t newsize)
9be53773
SH
2541{
2542 struct bdev *bdev;
dfb31b25 2543 int need_rdep;
9be53773 2544
1354955b 2545 bdev = bdev_copy(c0, c->name, c->config_path, newtype, flags,
dfb31b25 2546 bdevdata, newsize, &need_rdep);
9be53773 2547 if (!bdev) {
dfb31b25 2548 ERROR("Error copying storage");
9be53773
SH
2549 return -1;
2550 }
2551 free(c->lxc_conf->rootfs.path);
2552 c->lxc_conf->rootfs.path = strdup(bdev->src);
2553 bdev_put(bdev);
dfb31b25
SH
2554 if (!c->lxc_conf->rootfs.path) {
2555 ERROR("Out of memory while setting storage path");
9be53773 2556 return -1;
dfb31b25 2557 }
6b0d5538
SH
2558 // We will simply append a new lxc.rootfs entry to the unexpanded config
2559 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs", false);
2560 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs", c->lxc_conf->rootfs.path)) {
2561 ERROR("Error saving new rootfs to cloend config");
d0218321
SH
2562 return -1;
2563 }
eee59f94
SH
2564 if (flags & LXC_CLONE_SNAPSHOT)
2565 copy_rdepends(c, c0);
dfb31b25
SH
2566 if (need_rdep) {
2567 if (!add_rdepends(c, c0))
2568 WARN("Error adding reverse dependency from %s to %s",
2569 c->name, c0->name);
2570 }
2571
2572 mod_all_rdeps(c, true);
2573
9be53773
SH
2574 return 0;
2575}
2576
1354955b
SH
2577struct clone_update_data {
2578 struct lxc_container *c0;
2579 struct lxc_container *c1;
2580 int flags;
2581 char **hookargs;
2582};
2583
2584static int clone_update_rootfs(struct clone_update_data *data)
9be53773 2585{
1354955b
SH
2586 struct lxc_container *c0 = data->c0;
2587 struct lxc_container *c = data->c1;
2588 int flags = data->flags;
2589 char **hookargs = data->hookargs;
9be53773
SH
2590 int ret = -1;
2591 char path[MAXPATHLEN];
2592 struct bdev *bdev;
2593 FILE *fout;
148e91f5 2594 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
2595
2596 /* update hostname in rootfs */
2597 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2598
1354955b
SH
2599 if (setgid(0) < 0) {
2600 ERROR("Failed to setgid to 0");
2601 return -1;
2602 }
2603 if (setuid(0) < 0) {
2604 ERROR("Failed to setuid to 0");
9be53773 2605 return -1;
1354955b 2606 }
c476bdce
SH
2607 if (setgroups(0, NULL) < 0)
2608 WARN("Failed to clear groups");
9be53773 2609
1354955b
SH
2610 if (unshare(CLONE_NEWNS) < 0)
2611 return -1;
76a26f55 2612 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
9be53773 2613 if (!bdev)
1354955b 2614 return -1;
cf3ef16d
SH
2615 if (strcmp(bdev->type, "dir") != 0) {
2616 if (unshare(CLONE_NEWNS) < 0) {
2617 ERROR("error unsharing mounts");
e7de366c 2618 bdev_put(bdev);
1354955b 2619 return -1;
cf3ef16d 2620 }
2c6f3fc9
SH
2621 if (detect_shared_rootfs()) {
2622 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
2623 SYSERROR("Failed to make / rslave");
2624 ERROR("Continuing...");
2625 }
2626 }
e7de366c
SG
2627 if (bdev->ops->mount(bdev) < 0) {
2628 bdev_put(bdev);
1354955b 2629 return -1;
e7de366c 2630 }
cf3ef16d
SH
2631 } else { // TODO come up with a better way
2632 if (bdev->dest)
2633 free(bdev->dest);
2634 bdev->dest = strdup(bdev->src);
2635 }
148e91f5
SH
2636
2637 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2638 /* Start of environment variable setup for hooks */
1143ed39
DE
2639 if (setenv("LXC_SRC_NAME", c0->name, 1)) {
2640 SYSERROR("failed to set environment variable for source container name");
2641 }
148e91f5
SH
2642 if (setenv("LXC_NAME", c->name, 1)) {
2643 SYSERROR("failed to set environment variable for container name");
2644 }
2645 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
2646 SYSERROR("failed to set environment variable for config path");
2647 }
24ef39f4 2648 if (setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1)) {
148e91f5
SH
2649 SYSERROR("failed to set environment variable for rootfs mount");
2650 }
2651 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
2652 SYSERROR("failed to set environment variable for rootfs mount");
2653 }
2654
283678ed 2655 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
148e91f5 2656 ERROR("Error executing clone hook for %s", c->name);
e7de366c 2657 bdev_put(bdev);
1354955b 2658 return -1;
148e91f5
SH
2659 }
2660 }
2661
2662 if (!(flags & LXC_CLONE_KEEPNAME)) {
2663 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
e7de366c
SG
2664 bdev_put(bdev);
2665
148e91f5 2666 if (ret < 0 || ret >= MAXPATHLEN)
1354955b 2667 return -1;
8058be39 2668 if (!file_exists(path))
1354955b 2669 return 0;
148e91f5 2670 if (!(fout = fopen(path, "w"))) {
959aee9c 2671 SYSERROR("unable to open %s: ignoring", path);
1354955b 2672 return 0;
148e91f5 2673 }
a684f0b7
ÇO
2674 if (fprintf(fout, "%s", c->name) < 0) {
2675 fclose(fout);
1354955b 2676 return -1;
6849cb5b 2677 }
148e91f5 2678 if (fclose(fout) < 0)
1354955b 2679 return -1;
9be53773 2680 }
e7de366c
SG
2681 else
2682 bdev_put(bdev);
2683
1354955b
SH
2684 return 0;
2685}
2686
2687static int clone_update_rootfs_wrapper(void *data)
2688{
2689 struct clone_update_data *arg = (struct clone_update_data *) data;
2690 return clone_update_rootfs(arg);
9be53773
SH
2691}
2692
2693/*
2694 * We want to support:
2695sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2696 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2697
2698-s [ implies overlayfs]
2699-s -B overlayfs
2700-s -B aufs
2701
2702only rootfs gets converted (copied/snapshotted) on clone.
2703*/
2704
2705static int create_file_dirname(char *path)
2706{
c32981c3 2707 char *p = strrchr(path, '/');
9be53773
SH
2708 int ret;
2709
2710 if (!p)
2711 return -1;
2712 *p = '\0';
2713 ret = mkdir(path, 0755);
2714 if (ret && errno != EEXIST)
959aee9c 2715 SYSERROR("creating container path %s", path);
9be53773
SH
2716 *p = '/';
2717 return ret;
2718}
2719
74a3920a 2720static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
9be53773 2721 const char *lxcpath, int flags,
d659597e 2722 const char *bdevtype, const char *bdevdata, uint64_t newsize,
148e91f5 2723 char **hookargs)
9be53773
SH
2724{
2725 struct lxc_container *c2 = NULL;
2726 char newpath[MAXPATHLEN];
176d9acb 2727 int ret, storage_copied = 0;
9be53773 2728 const char *n, *l;
8d2efe40 2729 char *origroot = NULL;
1354955b 2730 struct clone_update_data data;
9be53773 2731 FILE *fout;
1354955b 2732 pid_t pid;
9be53773
SH
2733
2734 if (!c || !c->is_defined(c))
2735 return NULL;
2736
5cee8c50 2737 if (container_mem_lock(c))
9be53773
SH
2738 return NULL;
2739
39dc698c 2740 if (!is_stopped(c)) {
9be53773
SH
2741 ERROR("error: Original container (%s) is running", c->name);
2742 goto out;
2743 }
2744
2745 // Make sure the container doesn't yet exist.
2746 n = newname ? newname : c->name;
2747 l = lxcpath ? lxcpath : c->get_config_path(c);
2748 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
6849cb5b 2749 if (ret < 0 || ret >= MAXPATHLEN) {
9be53773
SH
2750 SYSERROR("clone: failed making config pathname");
2751 goto out;
2752 }
2753 if (file_exists(newpath)) {
2754 ERROR("error: clone: %s exists", newpath);
2755 goto out;
2756 }
2757
96532523
SH
2758 ret = create_file_dirname(newpath);
2759 if (ret < 0 && errno != EEXIST) {
9be53773
SH
2760 ERROR("Error creating container dir for %s", newpath);
2761 goto out;
2762 }
2763
2764 // copy the configuration, tweak it as needed,
8d2efe40
SH
2765 if (c->lxc_conf->rootfs.path) {
2766 origroot = c->lxc_conf->rootfs.path;
2767 c->lxc_conf->rootfs.path = NULL;
2768 }
9be53773
SH
2769 fout = fopen(newpath, "w");
2770 if (!fout) {
2771 SYSERROR("open %s", newpath);
2772 goto out;
2773 }
6b0d5538 2774 write_config(fout, c->lxc_conf);
9be53773 2775 fclose(fout);
8d2efe40 2776 c->lxc_conf->rootfs.path = origroot;
9be53773 2777
9be53773
SH
2778 sprintf(newpath, "%s/%s/rootfs", l, n);
2779 if (mkdir(newpath, 0755) < 0) {
2780 SYSERROR("error creating %s", newpath);
2781 goto out;
2782 }
2783
1354955b
SH
2784 if (am_unpriv()) {
2785 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
959aee9c 2786 ERROR("Error chowning %s to container root", newpath);
1354955b
SH
2787 goto out;
2788 }
2789 }
2790
9be53773 2791 c2 = lxc_container_new(n, l);
375c2258 2792 if (!c2) {
9be53773
SH
2793 ERROR("clone: failed to create new container (%s %s)", n, l);
2794 goto out;
2795 }
8d2efe40
SH
2796
2797 // copy/snapshot rootfs's
2798 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
2799 if (ret < 0)
2800 goto out;
9be53773 2801
6b0d5538
SH
2802 clear_unexp_config_line(c2->lxc_conf, "lxc.utsname", false);
2803
96532523
SH
2804 // update utsname
2805 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
2806 ERROR("Error setting new hostname");
2807 goto out;
2808 }
2809
619256b5
ÇO
2810 // copy hooks
2811 ret = copyhooks(c, c2);
2812 if (ret < 0) {
2813 ERROR("error copying hooks");
2814 goto out;
9be53773
SH
2815 }
2816
2817 if (copy_fstab(c, c2) < 0) {
2818 ERROR("error copying fstab");
9be53773
SH
2819 goto out;
2820 }
2821
2822 // update macaddrs
6b0d5538 2823 if (!(flags & LXC_CLONE_KEEPMACADDR)) {
9be53773 2824 network_new_hwaddrs(c2);
6b0d5538
SH
2825 if (!clone_update_unexp_network(c2->lxc_conf)) {
2826 ERROR("Error updating network for clone");
2827 goto out;
2828 }
2829 }
9be53773 2830
176d9acb
SH
2831 // We've now successfully created c2's storage, so clear it out if we
2832 // fail after this
2833 storage_copied = 1;
2834
375c2258 2835 if (!c2->save_config(c2, NULL))
9be53773 2836 goto out;
9be53773 2837
1354955b
SH
2838 if ((pid = fork()) < 0) {
2839 SYSERROR("fork");
9be53773 2840 goto out;
1354955b
SH
2841 }
2842 if (pid > 0) {
2843 ret = wait_for_pid(pid);
2844 if (ret)
2845 goto out;
2846 container_mem_unlock(c);
2847 return c2;
2848 }
2849 data.c0 = c;
2850 data.c1 = c2;
2851 data.flags = flags;
2852 data.hookargs = hookargs;
2853 if (am_unpriv())
2854 ret = userns_exec_1(c->lxc_conf, clone_update_rootfs_wrapper,
2855 &data);
2856 else
2857 ret = clone_update_rootfs(&data);
2858 if (ret < 0)
2859 exit(1);
9be53773 2860
5cee8c50 2861 container_mem_unlock(c);
1354955b 2862 exit(0);
9be53773
SH
2863
2864out:
5cee8c50 2865 container_mem_unlock(c);
375c2258 2866 if (c2) {
176d9acb
SH
2867 if (!storage_copied)
2868 c2->lxc_conf->rootfs.path = NULL;
375c2258 2869 c2->destroy(c2);
9be53773 2870 lxc_container_put(c2);
375c2258 2871 }
9be53773
SH
2872
2873 return NULL;
2874}
2875
06e5650e
ÇO
2876static bool lxcapi_rename(struct lxc_container *c, const char *newname)
2877{
2878 struct bdev *bdev;
2879 struct lxc_container *newc;
06e5650e 2880
d693cf93 2881 if (!c || !c->name || !c->config_path || !c->lxc_conf)
06e5650e
ÇO
2882 return false;
2883
18aa217b
SH
2884 if (has_fs_snapshots(c) || has_snapshots(c)) {
2885 ERROR("Renaming a container with snapshots is not supported");
2886 return false;
2887 }
76a26f55 2888 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
06e5650e
ÇO
2889 if (!bdev) {
2890 ERROR("Failed to find original backing store type");
2891 return false;
2892 }
2893
619256b5 2894 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
06e5650e
ÇO
2895 bdev_put(bdev);
2896 if (!newc) {
2897 lxc_container_put(newc);
2898 return false;
2899 }
2900
2901 if (newc && lxcapi_is_defined(newc))
2902 lxc_container_put(newc);
2903
18aa217b 2904 if (!container_destroy(c)) {
06e5650e
ÇO
2905 ERROR("Could not destroy existing container %s", c->name);
2906 return false;
2907 }
2908 return true;
2909}
2910
a0e93eeb
CS
2911static 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)
2912{
2913 if (!c)
2914 return -1;
2915
2916 return lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
2917}
2918
2919static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
2920{
2921 lxc_attach_command_t command;
2922 pid_t pid;
2923 int r;
2924
2925 if (!c)
2926 return -1;
2927
2928 command.program = (char*)program;
2929 command.argv = (char**)argv;
2930 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
2931 if (r < 0) {
2932 ERROR("ups");
2933 return r;
2934 }
2935 return lxc_wait_for_pid_status(pid);
2936}
2937
74a3920a 2938static int get_next_index(const char *lxcpath, char *cname)
f5dd1d53
SH
2939{
2940 char *fname;
2941 struct stat sb;
2942 int i = 0, ret;
2943
2944 fname = alloca(strlen(lxcpath) + 20);
2945 while (1) {
2946 sprintf(fname, "%s/snap%d", lxcpath, i);
2947 ret = stat(fname, &sb);
2948 if (ret != 0)
2949 return i;
2950 i++;
2951 }
2952}
2953
18aa217b
SH
2954static bool get_snappath_dir(struct lxc_container *c, char *snappath)
2955{
2956 int ret;
2957 /*
2958 * If the old style snapshot path exists, use it
2959 * /var/lib/lxc -> /var/lib/lxcsnaps
2960 */
2961 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps", c->config_path);
2962 if (ret < 0 || ret >= MAXPATHLEN)
2963 return false;
2964 if (dir_exists(snappath)) {
2965 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2966 if (ret < 0 || ret >= MAXPATHLEN)
2967 return false;
2968 return true;
2969 }
2970
2971 /*
2972 * Use the new style path
2973 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
2974 */
2975 ret = snprintf(snappath, MAXPATHLEN, "%s/%s/snaps", c->config_path, c->name);
2976 if (ret < 0 || ret >= MAXPATHLEN)
2977 return false;
2978 return true;
2979}
2980
f0ca2726 2981static int lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
f5dd1d53
SH
2982{
2983 int i, flags, ret;
2984 struct lxc_container *c2;
2985 char snappath[MAXPATHLEN], newname[20];
2986
840f05df
SH
2987 if (!c || !lxcapi_is_defined(c))
2988 return -1;
2989
18aa217b 2990 if (!get_snappath_dir(c, snappath))
f5dd1d53 2991 return -1;
18aa217b 2992
f5dd1d53
SH
2993 i = get_next_index(snappath, c->name);
2994
2995 if (mkdir_p(snappath, 0755) < 0) {
2996 ERROR("Failed to create snapshot directory %s", snappath);
2997 return -1;
2998 }
2999
3000 ret = snprintf(newname, 20, "snap%d", i);
3001 if (ret < 0 || ret >= 20)
3002 return -1;
3003
0a83cbbb
SH
3004 /*
3005 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3006 * created in the original container
3007 */
3008 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
3009 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
76a26f55 3010 if (bdev_is_dir(c->lxc_conf, c->lxc_conf->rootfs.path)) {
8c39f7a4
SH
3011 ERROR("Snapshot of directory-backed container requested.");
3012 ERROR("Making a copy-clone. If you do want snapshots, then");
1f92162d 3013 ERROR("please create an aufs or overlayfs clone first, snapshot that");
8c39f7a4
SH
3014 ERROR("and keep the original container pristine.");
3015 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3016 }
f5dd1d53
SH
3017 c2 = c->clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
3018 if (!c2) {
959aee9c 3019 ERROR("clone of %s:%s failed", c->config_path, c->name);
f5dd1d53
SH
3020 return -1;
3021 }
3022
3023 lxc_container_put(c2);
3024
3025 // Now write down the creation time
3026 time_t timer;
3027 char buffer[25];
3028 struct tm* tm_info;
025ed0f3 3029 FILE *f;
f5dd1d53
SH
3030
3031 time(&timer);
3032 tm_info = localtime(&timer);
3033
3034 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
3035
3036 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
3037 sprintf(dfnam, "%s/%s/ts", snappath, newname);
025ed0f3 3038 f = fopen(dfnam, "w");
f5dd1d53 3039 if (!f) {
959aee9c 3040 ERROR("Failed to open %s", dfnam);
f5dd1d53
SH
3041 return -1;
3042 }
3043 if (fprintf(f, "%s", buffer) < 0) {
3044 SYSERROR("Writing timestamp");
3045 fclose(f);
3046 return -1;
3047 }
025ed0f3 3048 ret = fclose(f);
025ed0f3 3049 if (ret != 0) {
f5dd1d53
SH
3050 SYSERROR("Writing timestamp");
3051 return -1;
3052 }
3053
3054 if (commentfile) {
3055 // $p / $name / comment \0
3056 int len = strlen(snappath) + strlen(newname) + 10;
3057 char *path = alloca(len);
3058 sprintf(path, "%s/%s/comment", snappath, newname);
3059 return copy_file(commentfile, path) < 0 ? -1 : i;
3060 }
3061
3062 return i;
3063}
3064
3065static void lxcsnap_free(struct lxc_snapshot *s)
3066{
3067 if (s->name)
3068 free(s->name);
3069 if (s->comment_pathname)
3070 free(s->comment_pathname);
3071 if (s->timestamp)
3072 free(s->timestamp);
3073 if (s->lxcpath)
3074 free(s->lxcpath);
3075}
3076
3077static char *get_snapcomment_path(char* snappath, char *name)
3078{
3079 // $snappath/$name/comment
3080 int ret, len = strlen(snappath) + strlen(name) + 10;
3081 char *s = malloc(len);
3082
3083 if (s) {
3084 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
3085 if (ret < 0 || ret >= len) {
3086 free(s);
3087 s = NULL;
3088 }
3089 }
3090 return s;
3091}
3092
3093static char *get_timestamp(char* snappath, char *name)
3094{
3095 char path[MAXPATHLEN], *s = NULL;
3096 int ret, len;
3097 FILE *fin;
3098
3099 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
3100 if (ret < 0 || ret >= MAXPATHLEN)
3101 return NULL;
025ed0f3 3102 fin = fopen(path, "r");
025ed0f3 3103 if (!fin)
f5dd1d53
SH
3104 return NULL;
3105 (void) fseek(fin, 0, SEEK_END);
3106 len = ftell(fin);
3107 (void) fseek(fin, 0, SEEK_SET);
3108 if (len > 0) {
3109 s = malloc(len+1);
3110 if (s) {
3111 s[len] = '\0';
3112 if (fread(s, 1, len, fin) != len) {
3113 SYSERROR("reading timestamp");
3114 free(s);
3115 s = NULL;
3116 }
3117 }
3118 }
3119 fclose(fin);
3120 return s;
3121}
3122
3123static int lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
3124{
3125 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
18aa217b 3126 int count = 0, ret;
f5dd1d53
SH
3127 struct dirent dirent, *direntp;
3128 struct lxc_snapshot *snaps =NULL, *nsnaps;
3129 DIR *dir;
3130
3131 if (!c || !lxcapi_is_defined(c))
3132 return -1;
c868b261 3133
18aa217b 3134 if (!get_snappath_dir(c, snappath)) {
f5dd1d53
SH
3135 ERROR("path name too long");
3136 return -1;
3137 }
025ed0f3 3138 dir = opendir(snappath);
025ed0f3 3139 if (!dir) {
f5dd1d53
SH
3140 INFO("failed to open %s - assuming no snapshots", snappath);
3141 return 0;
3142 }
3143
3144 while (!readdir_r(dir, &dirent, &direntp)) {
3145 if (!direntp)
3146 break;
3147
3148 if (!strcmp(direntp->d_name, "."))
3149 continue;
3150
3151 if (!strcmp(direntp->d_name, ".."))
3152 continue;
3153
3154 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
3155 if (ret < 0 || ret >= MAXPATHLEN) {
3156 ERROR("pathname too long");
3157 goto out_free;
3158 }
3159 if (!file_exists(path2))
3160 continue;
3161 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
3162 if (!nsnaps) {
3163 SYSERROR("Out of memory");
3164 goto out_free;
3165 }
3166 snaps = nsnaps;
3167 snaps[count].free = lxcsnap_free;
3168 snaps[count].name = strdup(direntp->d_name);
3169 if (!snaps[count].name)
3170 goto out_free;
3171 snaps[count].lxcpath = strdup(snappath);
3172 if (!snaps[count].lxcpath) {
3173 free(snaps[count].name);
3174 goto out_free;
3175 }
3176 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
3177 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
3178 count++;
3179 }
3180
3181 if (closedir(dir))
3182 WARN("failed to close directory");
3183
3184 *ret_snaps = snaps;
3185 return count;
3186
3187out_free:
3188 if (snaps) {
3189 int i;
3190 for (i=0; i<count; i++)
3191 lxcsnap_free(&snaps[i]);
3192 free(snaps);
3193 }
9baa57bd
SH
3194 if (closedir(dir))
3195 WARN("failed to close directory");
f5dd1d53
SH
3196 return -1;
3197}
3198
f0ca2726 3199static bool lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
f5dd1d53
SH
3200{
3201 char clonelxcpath[MAXPATHLEN];
18aa217b 3202 int flags = 0;
f5dd1d53
SH
3203 struct lxc_container *snap, *rest;
3204 struct bdev *bdev;
3205 bool b = false;
3206
3207 if (!c || !c->name || !c->config_path)
3208 return false;
3209
18aa217b
SH
3210 if (has_fs_snapshots(c)) {
3211 ERROR("container rootfs has dependent snapshots");
3212 return false;
3213 }
3214
76a26f55 3215 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
f5dd1d53
SH
3216 if (!bdev) {
3217 ERROR("Failed to find original backing store type");
3218 return false;
3219 }
3220
3221 if (!newname)
3222 newname = c->name;
7e36f87e 3223
18aa217b 3224 if (!get_snappath_dir(c, clonelxcpath)) {
f5dd1d53
SH
3225 bdev_put(bdev);
3226 return false;
3227 }
3228 // how should we lock this?
3229
3230 snap = lxc_container_new(snapname, clonelxcpath);
3231 if (!snap || !lxcapi_is_defined(snap)) {
3232 ERROR("Could not open snapshot %s", snapname);
3233 if (snap) lxc_container_put(snap);
3234 bdev_put(bdev);
3235 return false;
3236 }
3237
7e36f87e 3238 if (strcmp(c->name, newname) == 0) {
18aa217b 3239 if (!container_destroy(c)) {
7e36f87e
ÇO
3240 ERROR("Could not destroy existing container %s", newname);
3241 lxc_container_put(snap);
3242 bdev_put(bdev);
3243 return false;
3244 }
3245 }
3246
de269ee8
SH
3247 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
3248 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3249 rest = lxcapi_clone(snap, newname, c->config_path, flags,
3250 bdev->type, NULL, 0, NULL);
f5dd1d53
SH
3251 bdev_put(bdev);
3252 if (rest && lxcapi_is_defined(rest))
3253 b = true;
3254 if (rest)
3255 lxc_container_put(rest);
3256 lxc_container_put(snap);
3257 return b;
3258}
3259
18aa217b 3260static bool do_snapshot_destroy(const char *snapname, const char *clonelxcpath)
771d96b3 3261{
771d96b3 3262 struct lxc_container *snap = NULL;
18aa217b 3263 bool bret = false;
771d96b3
ÇO
3264
3265 snap = lxc_container_new(snapname, clonelxcpath);
18aa217b 3266 if (!snap) {
771d96b3
ÇO
3267 ERROR("Could not find snapshot %s", snapname);
3268 goto err;
3269 }
3270
3271 if (!lxcapi_destroy(snap)) {
3272 ERROR("Could not destroy snapshot %s", snapname);
3273 goto err;
3274 }
18aa217b 3275 bret = true;
771d96b3 3276
771d96b3
ÇO
3277err:
3278 if (snap)
3279 lxc_container_put(snap);
18aa217b
SH
3280 return bret;
3281}
3282
3283static bool remove_all_snapshots(const char *path)
3284{
3285 DIR *dir;
3286 struct dirent dirent, *direntp;
3287 bool bret = true;
3288
3289 dir = opendir(path);
3290 if (!dir) {
3291 SYSERROR("opendir on snapshot path %s", path);
3292 return false;
3293 }
3294 while (!readdir_r(dir, &dirent, &direntp)) {
3295 if (!direntp)
3296 break;
3297 if (!strcmp(direntp->d_name, "."))
3298 continue;
3299 if (!strcmp(direntp->d_name, ".."))
3300 continue;
3301 if (!do_snapshot_destroy(direntp->d_name, path)) {
3302 bret = false;
3303 continue;
3304 }
3305 }
3306
3307 closedir(dir);
3308
3309 if (rmdir(path))
3310 SYSERROR("Error removing directory %s", path);
3311
3312 return bret;
3313}
3314
3315static bool lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
3316{
3317 char clonelxcpath[MAXPATHLEN];
3318
3319 if (!c || !c->name || !c->config_path || !snapname)
3320 return false;
3321
3322 if (!get_snappath_dir(c, clonelxcpath))
3323 return false;
3324
3325 return do_snapshot_destroy(snapname, clonelxcpath);
3326}
3327
3328static bool lxcapi_snapshot_destroy_all(struct lxc_container *c)
3329{
3330 char clonelxcpath[MAXPATHLEN];
3331
3332 if (!c || !c->name || !c->config_path)
3333 return false;
3334
3335 if (!get_snappath_dir(c, clonelxcpath))
3336 return false;
3337
3338 return remove_all_snapshots(clonelxcpath);
771d96b3
ÇO
3339}
3340
b494d2dd
SH
3341static bool lxcapi_may_control(struct lxc_container *c)
3342{
3343 return lxc_try_cmd(c->name, c->config_path) == 0;
3344}
3345
d5aa23e6
SH
3346static bool do_add_remove_node(pid_t init_pid, const char *path, bool add,
3347 struct stat *st)
3348{
3349 char chrootpath[MAXPATHLEN];
3350 char *directory_path = NULL;
3351 pid_t pid;
3352 int ret;
3353
3354 if ((pid = fork()) < 0) {
3355 SYSERROR("failed to fork a child helper");
3356 return false;
3357 }
3358 if (pid) {
3359 if (wait_for_pid(pid) != 0) {
3360 ERROR("Failed to create note in guest");
3361 return false;
3362 }
3363 return true;
3364 }
3365
3366 /* prepare the path */
3367 ret = snprintf(chrootpath, MAXPATHLEN, "/proc/%d/root", init_pid);
3368 if (ret < 0 || ret >= MAXPATHLEN)
3369 return false;
3370
6b9324bd 3371 if (chroot(chrootpath) < 0)
d5aa23e6 3372 exit(1);
6b9324bd 3373 if (chdir("/") < 0)
d5aa23e6
SH
3374 exit(1);
3375 /* remove path if it exists */
3376 if(faccessat(AT_FDCWD, path, F_OK, AT_SYMLINK_NOFOLLOW) == 0) {
3377 if (unlink(path) < 0) {
3378 ERROR("unlink failed");
3379 exit(1);
3380 }
3381 }
3382 if (!add)
3383 exit(0);
3384
3385 /* create any missing directories */
3386 directory_path = dirname(strdup(path));
3387 if (mkdir_p(directory_path, 0755) < 0 && errno != EEXIST) {
3388 ERROR("failed to create directory");
3389 exit(1);
3390 }
3391
3392 /* create the device node */
3393 if (mknod(path, st->st_mode, st->st_rdev) < 0) {
3394 ERROR("mknod failed");
3395 exit(1);
3396 }
3397
3398 exit(0);
3399}
3400
f0ca2726 3401static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
a9a0ed90
ÇO
3402{
3403 int ret;
3404 struct stat st;
a9a0ed90 3405 char value[MAX_BUFFER];
f0ca2726 3406 const char *p;
a9a0ed90
ÇO
3407
3408 /* make sure container is running */
3409 if (!c->is_running(c)) {
3410 ERROR("container is not running");
d5aa23e6 3411 return false;
a9a0ed90
ÇO
3412 }
3413
3414 /* use src_path if dest_path is NULL otherwise use dest_path */
3415 p = dest_path ? dest_path : src_path;
3416
a9a0ed90
ÇO
3417 /* make sure we can access p */
3418 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
d5aa23e6 3419 return false;
a9a0ed90
ÇO
3420
3421 /* continue if path is character device or block device */
c6a9b0d7 3422 if (S_ISCHR(st.st_mode))
a9a0ed90 3423 ret = snprintf(value, MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
c6a9b0d7 3424 else if (S_ISBLK(st.st_mode))
a9a0ed90
ÇO
3425 ret = snprintf(value, MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
3426 else
d5aa23e6 3427 return false;
a9a0ed90
ÇO
3428
3429 /* check snprintf return code */
3430 if (ret < 0 || ret >= MAX_BUFFER)
d5aa23e6 3431 return false;
a9a0ed90 3432
d5aa23e6
SH
3433 if (!do_add_remove_node(c->init_pid(c), p, add, &st))
3434 return false;
a9a0ed90 3435
d5aa23e6 3436 /* add or remove device to/from cgroup access list */
a9a0ed90 3437 if (add) {
a9a0ed90
ÇO
3438 if (!c->set_cgroup_item(c, "devices.allow", value)) {
3439 ERROR("set_cgroup_item failed while adding the device node");
d5aa23e6 3440 return false;
a9a0ed90
ÇO
3441 }
3442 } else {
a9a0ed90
ÇO
3443 if (!c->set_cgroup_item(c, "devices.deny", value)) {
3444 ERROR("set_cgroup_item failed while removing the device node");
d5aa23e6 3445 return false;
a9a0ed90
ÇO
3446 }
3447 }
d5aa23e6 3448
a9a0ed90 3449 return true;
a9a0ed90
ÇO
3450}
3451
f0ca2726 3452static bool lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 3453{
c868b261
ÇO
3454 if (am_unpriv()) {
3455 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3456 return false;
3457 }
a9a0ed90
ÇO
3458 return add_remove_device_node(c, src_path, dest_path, true);
3459}
3460
f0ca2726 3461static bool lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 3462{
c868b261
ÇO
3463 if (am_unpriv()) {
3464 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3465 return false;
3466 }
a9a0ed90
ÇO
3467 return add_remove_device_node(c, src_path, dest_path, false);
3468}
3469
a0e93eeb
CS
3470static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
3471{
3472 va_list ap;
3473 const char **argv;
3474 int ret;
3475
3476 if (!c)
3477 return -1;
3478
3479 va_start(ap, arg);
3480 argv = lxc_va_arg_list_to_argv_const(ap, 1);
3481 va_end(ap);
3482
3483 if (!argv) {
3484 ERROR("Memory allocation error.");
3485 return -1;
3486 }
3487 argv[0] = arg;
3488
3489 ret = lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
3490 free((void*)argv);
3491 return ret;
3492}
3493
afeecbba 3494struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
3495{
3496 struct lxc_container *c;
72d0e1cb 3497
18aa217b
SH
3498 if (!name)
3499 return NULL;
3500
72d0e1cb
SG
3501 c = malloc(sizeof(*c));
3502 if (!c) {
3503 fprintf(stderr, "failed to malloc lxc_container\n");
3504 return NULL;
3505 }
3506 memset(c, 0, sizeof(*c));
3507
afeecbba
SH
3508 if (configpath)
3509 c->config_path = strdup(configpath);
3510 else
593e8478 3511 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
afeecbba 3512
2a59a681 3513 if (!c->config_path) {
03fadd16 3514 fprintf(stderr, "Out of memory\n");
2a59a681
SH
3515 goto err;
3516 }
3517
f5dd1d53 3518 remove_trailing_slashes(c->config_path);
72d0e1cb
SG
3519 c->name = malloc(strlen(name)+1);
3520 if (!c->name) {
3521 fprintf(stderr, "Error allocating lxc_container name\n");
3522 goto err;
3523 }
3524 strcpy(c->name, name);
3525
3526 c->numthreads = 1;
df271a59 3527 if (!(c->slock = lxc_newlock(c->config_path, name))) {
72d0e1cb
SG
3528 fprintf(stderr, "failed to create lock\n");
3529 goto err;
3530 }
3531
df271a59 3532 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
72d0e1cb
SG
3533 fprintf(stderr, "failed to alloc privlock\n");
3534 goto err;
3535 }
3536
afeecbba 3537 if (!set_config_filename(c)) {
72d0e1cb
SG
3538 fprintf(stderr, "Error allocating config file pathname\n");
3539 goto err;
3540 }
72d0e1cb 3541
bac806d1
SH
3542 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL))
3543 goto err;
72d0e1cb 3544
3e625e2d
SH
3545 if (ongoing_create(c) == 2) {
3546 ERROR("Error: %s creation was not completed", c->name);
18aa217b 3547 container_destroy(c);
4df7f012 3548 lxcapi_clear_config(c);
3e625e2d 3549 }
c8ad5f46 3550 c->daemonize = true;
72cf75fa 3551 c->pidfile = NULL;
3e625e2d 3552
72d0e1cb
SG
3553 // assign the member functions
3554 c->is_defined = lxcapi_is_defined;
3555 c->state = lxcapi_state;
3556 c->is_running = lxcapi_is_running;
3557 c->freeze = lxcapi_freeze;
3558 c->unfreeze = lxcapi_unfreeze;
0115f8fd 3559 c->console = lxcapi_console;
b5159817 3560 c->console_getfd = lxcapi_console_getfd;
72d0e1cb
SG
3561 c->init_pid = lxcapi_init_pid;
3562 c->load_config = lxcapi_load_config;
3563 c->want_daemonize = lxcapi_want_daemonize;
130a1888 3564 c->want_close_all_fds = lxcapi_want_close_all_fds;
72d0e1cb
SG
3565 c->start = lxcapi_start;
3566 c->startl = lxcapi_startl;
3567 c->stop = lxcapi_stop;
3568 c->config_file_name = lxcapi_config_file_name;
3569 c->wait = lxcapi_wait;
3570 c->set_config_item = lxcapi_set_config_item;
3571 c->destroy = lxcapi_destroy;
18aa217b 3572 c->destroy_with_snapshots = lxcapi_destroy_with_snapshots;
06e5650e 3573 c->rename = lxcapi_rename;
72d0e1cb
SG
3574 c->save_config = lxcapi_save_config;
3575 c->get_keys = lxcapi_get_keys;
3576 c->create = lxcapi_create;
3577 c->createl = lxcapi_createl;
3578 c->shutdown = lxcapi_shutdown;
3e625e2d 3579 c->reboot = lxcapi_reboot;
4df7f012 3580 c->clear_config = lxcapi_clear_config;
72d0e1cb
SG
3581 c->clear_config_item = lxcapi_clear_config_item;
3582 c->get_config_item = lxcapi_get_config_item;
8ac18377 3583 c->get_running_config_item = lxcapi_get_running_config_item;
794dd120
SH
3584 c->get_cgroup_item = lxcapi_get_cgroup_item;
3585 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
3586 c->get_config_path = lxcapi_get_config_path;
3587 c->set_config_path = lxcapi_set_config_path;
9be53773 3588 c->clone = lxcapi_clone;
799f29ab 3589 c->get_interfaces = lxcapi_get_interfaces;
9c83a661 3590 c->get_ips = lxcapi_get_ips;
a0e93eeb
CS
3591 c->attach = lxcapi_attach;
3592 c->attach_run_wait = lxcapi_attach_run_wait;
3593 c->attach_run_waitl = lxcapi_attach_run_waitl;
f5dd1d53
SH
3594 c->snapshot = lxcapi_snapshot;
3595 c->snapshot_list = lxcapi_snapshot_list;
3596 c->snapshot_restore = lxcapi_snapshot_restore;
771d96b3 3597 c->snapshot_destroy = lxcapi_snapshot_destroy;
18aa217b 3598 c->snapshot_destroy_all = lxcapi_snapshot_destroy_all;
b494d2dd 3599 c->may_control = lxcapi_may_control;
a9a0ed90
ÇO
3600 c->add_device_node = lxcapi_add_device_node;
3601 c->remove_device_node = lxcapi_remove_device_node;
72d0e1cb
SG
3602
3603 /* we'll allow the caller to update these later */
ab1bf971 3604 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
72d0e1cb
SG
3605 fprintf(stderr, "failed to open log\n");
3606 goto err;
3607 }
3608
72d0e1cb
SG
3609 return c;
3610
3611err:
3612 lxc_container_free(c);
3613 return NULL;
3614}
3615
4a7c7daa 3616int lxc_get_wait_states(const char **states)
72d0e1cb
SG
3617{
3618 int i;
3619
3620 if (states)
3621 for (i=0; i<MAX_STATE; i++)
3622 states[i] = lxc_state2str(i);
3623 return MAX_STATE;
3624}
a41f104b 3625
a41f104b
SH
3626/*
3627 * These next two could probably be done smarter with reusing a common function
3628 * with different iterators and tests...
3629 */
3630int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
3631{
3632 DIR *dir;
3633 int i, cfound = 0, nfound = 0;
3634 struct dirent dirent, *direntp;
3635 struct lxc_container *c;
3636
3637 if (!lxcpath)
593e8478 3638 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b 3639
a41f104b 3640 dir = opendir(lxcpath);
a41f104b
SH
3641 if (!dir) {
3642 SYSERROR("opendir on lxcpath");
3643 return -1;
3644 }
3645
3646 if (cret)
3647 *cret = NULL;
3648 if (names)
3649 *names = NULL;
3650
3651 while (!readdir_r(dir, &dirent, &direntp)) {
3652 if (!direntp)
3653 break;
3654 if (!strcmp(direntp->d_name, "."))
3655 continue;
3656 if (!strcmp(direntp->d_name, ".."))
3657 continue;
3658
3659 if (!config_file_exists(lxcpath, direntp->d_name))
3660 continue;
3661
3662 if (names) {
9c88ff1f 3663 if (!add_to_array(names, direntp->d_name, cfound))
a41f104b
SH
3664 goto free_bad;
3665 }
3666 cfound++;
3667
3668 if (!cret) {
3669 nfound++;
3670 continue;
3671 }
3672
3673 c = lxc_container_new(direntp->d_name, lxcpath);
3674 if (!c) {
3675 INFO("Container %s:%s has a config but could not be loaded",
3676 lxcpath, direntp->d_name);
3677 if (names)
9c88ff1f
ÇO
3678 if(!remove_from_array(names, direntp->d_name, cfound--))
3679 goto free_bad;
a41f104b
SH
3680 continue;
3681 }
3682 if (!lxcapi_is_defined(c)) {
3683 INFO("Container %s:%s has a config but is not defined",
3684 lxcpath, direntp->d_name);
3685 if (names)
9c88ff1f
ÇO
3686 if(!remove_from_array(names, direntp->d_name, cfound--))
3687 goto free_bad;
a41f104b
SH
3688 lxc_container_put(c);
3689 continue;
3690 }
3691
2871830a 3692 if (!add_to_clist(cret, c, nfound, true)) {
a41f104b
SH
3693 lxc_container_put(c);
3694 goto free_bad;
3695 }
3696 nfound++;
3697 }
3698
a41f104b 3699 closedir(dir);
a41f104b
SH
3700 return nfound;
3701
3702free_bad:
3703 if (names && *names) {
3704 for (i=0; i<cfound; i++)
3705 free((*names)[i]);
3706 free(*names);
3707 }
3708 if (cret && *cret) {
3709 for (i=0; i<nfound; i++)
3710 lxc_container_put((*cret)[i]);
3711 free(*cret);
3712 }
a41f104b 3713 closedir(dir);
a41f104b
SH
3714 return -1;
3715}
3716
148a9d27
DE
3717int list_active_containers(const char *lxcpath, char ***nret,
3718 struct lxc_container ***cret)
a41f104b 3719{
148a9d27 3720 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
a41f104b
SH
3721 int lxcpath_len;
3722 char *line = NULL;
148a9d27 3723 char **ct_name = NULL;
a41f104b
SH
3724 size_t len = 0;
3725 struct lxc_container *c;
3726
3727 if (!lxcpath)
593e8478 3728 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b
SH
3729 lxcpath_len = strlen(lxcpath);
3730
3731 if (cret)
3732 *cret = NULL;
148a9d27
DE
3733 if (nret)
3734 *nret = NULL;
a41f104b 3735
a41f104b 3736 FILE *f = fopen("/proc/net/unix", "r");
a41f104b
SH
3737 if (!f)
3738 return -1;
3739
3740 while (getline(&line, &len, f) != -1) {
0f8f9c8a 3741 char *p = strrchr(line, ' '), *p2;
a41f104b
SH
3742 if (!p)
3743 continue;
3744 p++;
3745 if (*p != 0x40)
3746 continue;
3747 p++;
3748 if (strncmp(p, lxcpath, lxcpath_len) != 0)
3749 continue;
3750 p += lxcpath_len;
3751 while (*p == '/')
3752 p++;
3753
3754 // Now p is the start of lxc_name
3755 p2 = index(p, '/');
3756 if (!p2 || strncmp(p2, "/command", 8) != 0)
3757 continue;
3758 *p2 = '\0';
3759
148a9d27 3760 if (array_contains(&ct_name, p, ct_name_cnt))
9c88ff1f
ÇO
3761 continue;
3762
148a9d27
DE
3763 if (!add_to_array(&ct_name, p, ct_name_cnt))
3764 goto free_cret_list;
9c88ff1f 3765
148a9d27 3766 ct_name_cnt++;
a41f104b 3767
148a9d27 3768 if (!cret)
a41f104b 3769 continue;
a41f104b
SH
3770
3771 c = lxc_container_new(p, lxcpath);
3772 if (!c) {
3773 INFO("Container %s:%s is running but could not be loaded",
3774 lxcpath, p);
148a9d27 3775 remove_from_array(&ct_name, p, ct_name_cnt--);
a41f104b
SH
3776 continue;
3777 }
3778
3779 /*
3780 * If this is an anonymous container, then is_defined *can*
3781 * return false. So we don't do that check. Count on the
3782 * fact that the command socket exists.
3783 */
3784
148a9d27 3785 if (!add_to_clist(cret, c, cret_cnt, true)) {
a41f104b 3786 lxc_container_put(c);
148a9d27 3787 goto free_cret_list;
a41f104b 3788 }
148a9d27 3789 cret_cnt++;
a41f104b
SH
3790 }
3791
148a9d27
DE
3792 assert(!nret || !cret || cret_cnt == ct_name_cnt);
3793 ret = ct_name_cnt;
3794 if (nret)
3795 *nret = ct_name;
3796 else
3797 goto free_ct_name;
3798 goto out;
a41f104b 3799
148a9d27 3800free_cret_list:
a41f104b 3801 if (cret && *cret) {
148a9d27 3802 for (i = 0; i < cret_cnt; i++)
a41f104b
SH
3803 lxc_container_put((*cret)[i]);
3804 free(*cret);
3805 }
148a9d27
DE
3806
3807free_ct_name:
3808 if (ct_name) {
3809 for (i = 0; i < ct_name_cnt; i++)
3810 free(ct_name[i]);
3811 free(ct_name);
3812 }
3813
3814out:
e853a32d
ÇO
3815 if (line)
3816 free(line);
3817
a41f104b 3818 fclose(f);
148a9d27 3819 return ret;
a41f104b 3820}
2871830a
DE
3821
3822int list_all_containers(const char *lxcpath, char ***nret,
3823 struct lxc_container ***cret)
3824{
3825 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
3826 char **active_name;
3827 char **ct_name;
3828 struct lxc_container **ct_list = NULL;
3829
3830 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
3831 if (ct_cnt < 0)
3832 return ct_cnt;
3833
3834 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
3835 if (active_cnt < 0) {
3836 ret = active_cnt;
3837 goto free_ct_name;
3838 }
3839
3840 for (i = 0; i < active_cnt; i++) {
3841 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
3842 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
3843 ret = -1;
3844 goto free_active_name;
3845 }
3846 ct_cnt++;
3847 }
3848 free(active_name[i]);
3849 active_name[i] = NULL;
3850 }
3851 free(active_name);
3852 active_name = NULL;
3853 active_cnt = 0;
3854
3855 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
3856 struct lxc_container *c;
3857
3858 c = lxc_container_new(ct_name[i], lxcpath);
3859 if (!c) {
3860 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
3861 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
3862 continue;
3863 }
3864
3865 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
3866 lxc_container_put(c);
3867 ret = -1;
3868 goto free_ct_list;
3869 }
3870 ct_list_cnt++;
3871 }
3872
3873 if (cret)
3874 *cret = ct_list;
3875
3876 if (nret)
3877 *nret = ct_name;
3878 else {
3879 ret = ct_cnt;
3880 goto free_ct_name;
3881 }
3882 return ct_cnt;
3883
3884free_ct_list:
3885 for (i = 0; i < ct_list_cnt; i++) {
3886 lxc_container_put(ct_list[i]);
3887 }
3888 if (ct_list)
3889 free(ct_list);
3890
3891free_active_name:
3892 for (i = 0; i < active_cnt; i++) {
3893 if (active_name[i])
3894 free(active_name[i]);
3895 }
3896 if (active_name)
3897 free(active_name);
3898
3899free_ct_name:
3900 for (i = 0; i < ct_cnt; i++) {
3901 free(ct_name[i]);
3902 }
3903 free(ct_name);
3904 return ret;
3905}