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