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