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