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