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