]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
prune_init_cgroup: don't dereference NULL
[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
0ea055b3 22#include <sys/mman.h>
148a9d27 23#include <assert.h>
a0e93eeb 24#include <stdarg.h>
71454076 25#include <pthread.h>
9be53773
SH
26#include <unistd.h>
27#include <sys/types.h>
28#include <sys/wait.h>
4de2791f 29#include <sys/mount.h>
9be53773 30#include <errno.h>
93dc5327 31#include <fcntl.h>
9be53773 32#include <sched.h>
f5dd1d53 33#include <dirent.h>
f2363e38
ÇO
34#include <sched.h>
35#include <arpa/inet.h>
36#include <libgen.h>
d659597e 37#include <stdint.h>
c476bdce 38#include <grp.h>
9fc7f8c0 39#include <stdio.h>
5f7eba0b 40#include <sys/syscall.h>
f2363e38
ÇO
41
42#include <lxc/lxccontainer.h>
43#include <lxc/version.h>
e58fae8f 44#include <lxc/network.h>
f2363e38 45
9be53773 46#include "config.h"
72d0e1cb
SG
47#include "lxc.h"
48#include "state.h"
72d0e1cb 49#include "conf.h"
72d0e1cb 50#include "confile.h"
b5159817 51#include "console.h"
72d0e1cb
SG
52#include "cgroup.h"
53#include "commands.h"
e29fe1dd 54#include "criu.h"
72d0e1cb 55#include "log.h"
9be53773 56#include "bdev.h"
6a44839f 57#include "utils.h"
a0e93eeb 58#include "attach.h"
f2363e38
ÇO
59#include "monitor.h"
60#include "namespace.h"
fed29fad 61#include "network.h"
95ee490b 62#include "lxclock.h"
735f2c6e 63#include "sync.h"
4ba0d9af
SG
64
65#if HAVE_IFADDRS_H
9c83a661 66#include <ifaddrs.h>
4ba0d9af
SG
67#else
68#include <../include/ifaddrs.h>
69#endif
72d0e1cb 70
684f79a5
SG
71#if IS_BIONIC
72#include <../include/lxcmntent.h>
73#else
74#include <mntent.h>
75#endif
76
a9a0ed90
ÇO
77#define MAX_BUFFER 4096
78
c868b261
ÇO
79#define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
80
5f7eba0b
SG
81/* Define faccessat() if missing from the C library */
82#ifndef HAVE_FACCESSAT
83static int faccessat(int __fd, const char *__file, int __type, int __flag)
84{
85#ifdef __NR_faccessat
86return syscall(__NR_faccessat, __fd, __file, __type, __flag);
87#else
88errno = ENOSYS;
89return -1;
90#endif
91}
92#endif
93
72d0e1cb
SG
94lxc_log_define(lxc_container, lxc);
95
858377e4
SH
96static bool do_lxcapi_destroy(struct lxc_container *c);
97static const char *lxcapi_get_config_path(struct lxc_container *c);
98#define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
99static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v);
100static bool container_destroy(struct lxc_container *c);
101static bool get_snappath_dir(struct lxc_container *c, char *snappath);
102static bool lxcapi_snapshot_destroy_all(struct lxc_container *c);
103static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file);
104
a41f104b
SH
105static bool config_file_exists(const char *lxcpath, const char *cname)
106{
107 /* $lxcpath + '/' + $cname + '/config' + \0 */
108 int ret, len = strlen(lxcpath) + strlen(cname) + 9;
109 char *fname = alloca(len);
110
111 ret = snprintf(fname, len, "%s/%s/config", lxcpath, cname);
112 if (ret < 0 || ret >= len)
113 return false;
114
115 return file_exists(fname);
116}
117
3e625e2d
SH
118/*
119 * A few functions to help detect when a container creation failed.
120 * If a container creation was killed partway through, then trying
121 * to actually start that container could harm the host. We detect
122 * this by creating a 'partial' file under the container directory,
123 * and keeping an advisory lock. When container creation completes,
124 * we remove that file. When we load or try to start a container, if
125 * we find that file, without a flock, we remove the container.
126 */
74a3920a 127static int ongoing_create(struct lxc_container *c)
3e625e2d
SH
128{
129 int len = strlen(c->config_path) + strlen(c->name) + 10;
130 char *path = alloca(len);
131 int fd, ret;
93dc5327
SH
132 struct flock lk;
133
3e625e2d
SH
134 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
135 if (ret < 0 || ret >= len) {
136 ERROR("Error writing partial pathname");
137 return -1;
138 }
139
140 if (!file_exists(path))
141 return 0;
025ed0f3 142 fd = open(path, O_RDWR);
025ed0f3 143 if (fd < 0) {
3e625e2d
SH
144 // give benefit of the doubt
145 SYSERROR("Error opening partial file");
3e625e2d
SH
146 return 0;
147 }
93dc5327
SH
148 lk.l_type = F_WRLCK;
149 lk.l_whence = SEEK_SET;
150 lk.l_start = 0;
151 lk.l_len = 0;
152 lk.l_pid = -1;
153 if (fcntl(fd, F_GETLK, &lk) == 0 && lk.l_pid != -1) {
3e625e2d
SH
154 // create is still ongoing
155 close(fd);
3e625e2d
SH
156 return 1;
157 }
158 // create completed but partial is still there.
159 close(fd);
3e625e2d
SH
160 return 2;
161}
162
74a3920a 163static int create_partial(struct lxc_container *c)
3e625e2d
SH
164{
165 // $lxcpath + '/' + $name + '/partial' + \0
166 int len = strlen(c->config_path) + strlen(c->name) + 10;
167 char *path = alloca(len);
168 int fd, ret;
93dc5327
SH
169 struct flock lk;
170
3e625e2d
SH
171 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
172 if (ret < 0 || ret >= len) {
173 ERROR("Error writing partial pathname");
174 return -1;
175 }
93dc5327 176 if ((fd=open(path, O_RDWR | O_CREAT | O_EXCL, 0755)) < 0) {
3e625e2d 177 SYSERROR("Erorr creating partial file");
3e625e2d
SH
178 return -1;
179 }
93dc5327
SH
180 lk.l_type = F_WRLCK;
181 lk.l_whence = SEEK_SET;
182 lk.l_start = 0;
183 lk.l_len = 0;
184 if (fcntl(fd, F_SETLKW, &lk) < 0) {
3e625e2d
SH
185 SYSERROR("Error locking partial file %s", path);
186 close(fd);
3e625e2d
SH
187 return -1;
188 }
3e625e2d
SH
189
190 return fd;
191}
192
74a3920a 193static void remove_partial(struct lxc_container *c, int fd)
3e625e2d
SH
194{
195 // $lxcpath + '/' + $name + '/partial' + \0
196 int len = strlen(c->config_path) + strlen(c->name) + 10;
197 char *path = alloca(len);
198 int ret;
199
200 close(fd);
201 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
202 if (ret < 0 || ret >= len) {
203 ERROR("Error writing partial pathname");
204 return;
205 }
3e625e2d
SH
206 if (unlink(path) < 0)
207 SYSERROR("Error unlink partial file %s", path);
3e625e2d
SH
208}
209
72d0e1cb 210/* LOCKING
3bc449ed
SH
211 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
212 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
213 * container configuration file.
214 * The container_disk_lock also takes the container_mem_lock.
215 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
72d0e1cb
SG
216 * NOTHING mutexes two independent programs with their own struct
217 * lxc_container for the same c->name, between API calls. For instance,
218 * c->config_read(); c->start(); Between those calls, data on disk
219 * could change (which shouldn't bother the caller unless for instance
220 * the rootfs get moved). c->config_read(); update; c->config_write();
221 * Two such updaters could race. The callers should therefore check their
222 * results. Trying to prevent that would necessarily expose us to deadlocks
223 * due to hung callers. So I prefer to keep the locks only within our own
224 * functions, not across functions.
225 *
3bc449ed 226 * If you're going to clone while holding a lxccontainer, increment
72d0e1cb
SG
227 * c->numthreads (under privlock) before forking. When deleting,
228 * decrement numthreads under privlock, then if it hits 0 you can delete.
229 * Do not ever use a lxccontainer whose numthreads you did not bump.
230 */
231
232static void lxc_container_free(struct lxc_container *c)
233{
234 if (!c)
235 return;
236
f10fad2f
ME
237 free(c->configfile);
238 c->configfile = NULL;
239 free(c->error_string);
240 c->error_string = NULL;
d95db067 241 if (c->slock) {
df271a59 242 lxc_putlock(c->slock);
d95db067
DE
243 c->slock = NULL;
244 }
72d0e1cb 245 if (c->privlock) {
df271a59 246 lxc_putlock(c->privlock);
72d0e1cb
SG
247 c->privlock = NULL;
248 }
f10fad2f
ME
249 free(c->name);
250 c->name = NULL;
d95db067
DE
251 if (c->lxc_conf) {
252 lxc_conf_free(c->lxc_conf);
253 c->lxc_conf = NULL;
254 }
f10fad2f
ME
255 free(c->config_path);
256 c->config_path = NULL;
72cf75fa 257
72d0e1cb
SG
258 free(c);
259}
260
43d1aa34
SH
261/*
262 * Consider the following case:
263freer | racing get()er
264==================================================================
265lxc_container_put() | lxc_container_get()
266\ lxclock(c->privlock) | c->numthreads < 1? (no)
267\ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
268\ lxcunlock() | \
269\ lxc_container_free() | \ lxclock() returns
270 | \ c->numthreads < 1 -> return 0
271\ \ (free stuff) |
272\ \ sem_destroy(privlock) |
273
274 * When the get()er checks numthreads the first time, one of the following
275 * is true:
276 * 1. freer has set numthreads = 0. get() returns 0
277 * 2. freer is between lxclock and setting numthreads to 0. get()er will
278 * sem_wait on privlock, get lxclock after freer() drops it, then see
279 * numthreads is 0 and exit without touching lxclock again..
280 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
281 * will see --numthreads = 1 and not call lxc_container_free().
282*/
283
72d0e1cb
SG
284int lxc_container_get(struct lxc_container *c)
285{
286 if (!c)
287 return 0;
288
43d1aa34
SH
289 // if someone else has already started freeing the container, don't
290 // try to take the lock, which may be invalid
291 if (c->numthreads < 1)
292 return 0;
293
5cee8c50 294 if (container_mem_lock(c))
72d0e1cb
SG
295 return 0;
296 if (c->numthreads < 1) {
297 // bail without trying to unlock, bc the privlock is now probably
298 // in freed memory
299 return 0;
300 }
301 c->numthreads++;
5cee8c50 302 container_mem_unlock(c);
72d0e1cb
SG
303 return 1;
304}
305
306int lxc_container_put(struct lxc_container *c)
307{
308 if (!c)
309 return -1;
5cee8c50 310 if (container_mem_lock(c))
72d0e1cb
SG
311 return -1;
312 if (--c->numthreads < 1) {
5cee8c50 313 container_mem_unlock(c);
72d0e1cb
SG
314 lxc_container_free(c);
315 return 1;
316 }
5cee8c50 317 container_mem_unlock(c);
72d0e1cb
SG
318 return 0;
319}
320
858377e4 321static bool do_lxcapi_is_defined(struct lxc_container *c)
72d0e1cb
SG
322{
323 struct stat statbuf;
324 bool ret = false;
325 int statret;
326
327 if (!c)
328 return false;
329
5cee8c50 330 if (container_mem_lock(c))
72d0e1cb
SG
331 return false;
332 if (!c->configfile)
333 goto out;
334 statret = stat(c->configfile, &statbuf);
335 if (statret != 0)
336 goto out;
337 ret = true;
338
339out:
5cee8c50 340 container_mem_unlock(c);
72d0e1cb
SG
341 return ret;
342}
343
858377e4
SH
344#define WRAP_API(rettype, fnname) \
345static rettype fnname(struct lxc_container *c) \
346{ \
347 rettype ret; \
348 current_config = c ? c->lxc_conf : NULL; \
349 ret = do_##fnname(c); \
350 current_config = NULL; \
351 return ret; \
352}
353
354#define WRAP_API_1(rettype, fnname, t1) \
355static rettype fnname(struct lxc_container *c, t1 a1) \
356{ \
357 rettype ret; \
358 current_config = c ? c->lxc_conf : NULL; \
359 ret = do_##fnname(c, a1); \
360 current_config = NULL; \
361 return ret; \
362}
363
364#define WRAP_API_2(rettype, fnname, t1, t2) \
365static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
366{ \
367 rettype ret; \
368 current_config = c ? c->lxc_conf : NULL; \
369 ret = do_##fnname(c, a1, a2); \
370 current_config = NULL; \
371 return ret; \
372}
373
374#define WRAP_API_3(rettype, fnname, t1, t2, t3) \
375static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
376{ \
377 rettype ret; \
378 current_config = c ? c->lxc_conf : NULL; \
379 ret = do_##fnname(c, a1, a2, a3); \
380 current_config = NULL; \
381 return ret; \
382}
383
384WRAP_API(bool, lxcapi_is_defined)
385
386static const char *do_lxcapi_state(struct lxc_container *c)
72d0e1cb 387{
72d0e1cb
SG
388 lxc_state_t s;
389
390 if (!c)
391 return NULL;
13f5be62 392 s = lxc_getstate(c->name, c->config_path);
39dc698c 393 return lxc_state2str(s);
72d0e1cb
SG
394}
395
858377e4
SH
396WRAP_API(const char *, lxcapi_state)
397
39dc698c 398static bool is_stopped(struct lxc_container *c)
794dd120
SH
399{
400 lxc_state_t s;
13f5be62 401 s = lxc_getstate(c->name, c->config_path);
794dd120
SH
402 return (s == STOPPED);
403}
404
858377e4 405static bool do_lxcapi_is_running(struct lxc_container *c)
72d0e1cb
SG
406{
407 const char *s;
408
409 if (!c)
410 return false;
858377e4 411 s = do_lxcapi_state(c);
72d0e1cb
SG
412 if (!s || strcmp(s, "STOPPED") == 0)
413 return false;
414 return true;
415}
416
858377e4
SH
417WRAP_API(bool, lxcapi_is_running)
418
419static bool do_lxcapi_freeze(struct lxc_container *c)
72d0e1cb
SG
420{
421 int ret;
422 if (!c)
423 return false;
424
9123e471 425 ret = lxc_freeze(c->name, c->config_path);
72d0e1cb
SG
426 if (ret)
427 return false;
428 return true;
429}
430
858377e4
SH
431WRAP_API(bool, lxcapi_freeze)
432
433static bool do_lxcapi_unfreeze(struct lxc_container *c)
72d0e1cb
SG
434{
435 int ret;
436 if (!c)
437 return false;
438
9123e471 439 ret = lxc_unfreeze(c->name, c->config_path);
72d0e1cb
SG
440 if (ret)
441 return false;
442 return true;
443}
444
858377e4
SH
445WRAP_API(bool, lxcapi_unfreeze)
446
447static int do_lxcapi_console_getfd(struct lxc_container *c, int *ttynum, int *masterfd)
0115f8fd
DE
448{
449 int ttyfd;
450 if (!c)
451 return -1;
452
b5159817 453 ttyfd = lxc_console_getfd(c, ttynum, masterfd);
0115f8fd
DE
454 return ttyfd;
455}
456
858377e4
SH
457WRAP_API_2(int, lxcapi_console_getfd, int *, int *)
458
b5159817
DE
459static int lxcapi_console(struct lxc_container *c, int ttynum, int stdinfd,
460 int stdoutfd, int stderrfd, int escape)
461{
858377e4
SH
462 int ret;
463
464 if (!c)
465 return -1;
466
467 current_config = c->lxc_conf;
468 ret = lxc_console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape);
469 current_config = NULL;
470 return ret;
b5159817
DE
471}
472
858377e4 473static pid_t do_lxcapi_init_pid(struct lxc_container *c)
72d0e1cb 474{
72d0e1cb
SG
475 if (!c)
476 return -1;
477
5cee8c50 478 return lxc_cmd_get_init_pid(c->name, c->config_path);
72d0e1cb
SG
479}
480
858377e4
SH
481WRAP_API(pid_t, lxcapi_init_pid)
482
12a50cc6 483static bool load_config_locked(struct lxc_container *c, const char *fname)
8eb5694b
SH
484{
485 if (!c->lxc_conf)
486 c->lxc_conf = lxc_conf_init();
6b0d5538
SH
487 if (!c->lxc_conf)
488 return false;
d08779d4
SH
489 if (lxc_config_read(fname, c->lxc_conf, false) != 0)
490 return false;
d08779d4 491 return true;
8eb5694b
SH
492}
493
858377e4 494static bool do_lxcapi_load_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 495{
39dc698c
SH
496 bool ret = false, need_disklock = false;
497 int lret;
12a50cc6 498 const char *fname;
72d0e1cb
SG
499 if (!c)
500 return false;
501
502 fname = c->configfile;
503 if (alt_file)
504 fname = alt_file;
505 if (!fname)
506 return false;
39dc698c
SH
507 /*
508 * If we're reading something other than the container's config,
509 * we only need to lock the in-memory container. If loading the
510 * container's config file, take the disk lock.
511 */
512 if (strcmp(fname, c->configfile) == 0)
513 need_disklock = true;
514
515 if (need_disklock)
516 lret = container_disk_lock(c);
517 else
518 lret = container_mem_lock(c);
519 if (lret)
72d0e1cb 520 return false;
39dc698c 521
8eb5694b 522 ret = load_config_locked(c, fname);
39dc698c
SH
523
524 if (need_disklock)
525 container_disk_unlock(c);
526 else
527 container_mem_unlock(c);
72d0e1cb
SG
528 return ret;
529}
530
858377e4
SH
531WRAP_API_1(bool, lxcapi_load_config, const char *)
532
533static bool do_lxcapi_want_daemonize(struct lxc_container *c, bool state)
72d0e1cb 534{
497a2995 535 if (!c || !c->lxc_conf)
540f932a 536 return false;
f02abefe 537 if (container_mem_lock(c)) {
3bc449ed 538 ERROR("Error getting mem lock");
540f932a 539 return false;
3bc449ed 540 }
a2739df5 541 c->daemonize = state;
3bc449ed 542 container_mem_unlock(c);
540f932a 543 return true;
72d0e1cb
SG
544}
545
858377e4
SH
546WRAP_API_1(bool, lxcapi_want_daemonize, bool)
547
548static bool do_lxcapi_want_close_all_fds(struct lxc_container *c, bool state)
130a1888
ÇO
549{
550 if (!c || !c->lxc_conf)
49badbbe 551 return false;
130a1888
ÇO
552 if (container_mem_lock(c)) {
553 ERROR("Error getting mem lock");
49badbbe 554 return false;
130a1888 555 }
540f932a 556 c->lxc_conf->close_all_fds = state;
130a1888 557 container_mem_unlock(c);
49badbbe 558 return true;
130a1888
ÇO
559}
560
858377e4
SH
561WRAP_API_1(bool, lxcapi_want_close_all_fds, bool)
562
563static bool do_lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
7a44c8b4
SG
564{
565 int ret;
566
567 if (!c)
568 return false;
569
67e571de 570 ret = lxc_wait(c->name, state, timeout, c->config_path);
7a44c8b4
SG
571 return ret == 0;
572}
573
858377e4 574WRAP_API_2(bool, lxcapi_wait, const char *, int)
7a44c8b4 575
858377e4 576static bool do_wait_on_daemonized_start(struct lxc_container *c, int pid)
7a44c8b4
SG
577{
578 /* we'll probably want to make this timeout configurable? */
697fa639 579 int timeout = 5, ret, status;
7a44c8b4 580
697fa639
SH
581 /*
582 * our child is going to fork again, then exit. reap the
583 * child
584 */
03f064ff 585 ret = waitpid(pid, &status, 0);
697fa639
SH
586 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
587 DEBUG("failed waiting for first dual-fork child");
858377e4 588 return do_lxcapi_wait(c, "RUNNING", timeout);
7a44c8b4
SG
589}
590
858377e4
SH
591WRAP_API_1(bool, wait_on_daemonized_start, int)
592
2d834aa8
SH
593static bool am_single_threaded(void)
594{
595 struct dirent dirent, *direntp;
596 DIR *dir;
597 int count=0;
598
2d834aa8 599 dir = opendir("/proc/self/task");
2d834aa8
SH
600 if (!dir) {
601 INFO("failed to open /proc/self/task");
602 return false;
603 }
604
605 while (!readdir_r(dir, &dirent, &direntp)) {
606 if (!direntp)
607 break;
608
609 if (!strcmp(direntp->d_name, "."))
610 continue;
611
612 if (!strcmp(direntp->d_name, ".."))
613 continue;
614 if (++count > 1)
615 break;
616 }
2d834aa8 617 closedir(dir);
2d834aa8
SH
618 return count == 1;
619}
620
fd51a89b
SH
621static void push_arg(char ***argp, char *arg, int *nargs)
622{
623 char **argv;
624 char *copy;
625
626 do {
627 copy = strdup(arg);
628 } while (!copy);
629 do {
630 argv = realloc(*argp, (*nargs + 2) * sizeof(char *));
631 } while (!argv);
632 *argp = argv;
633 argv[*nargs] = copy;
634 (*nargs)++;
635 argv[*nargs] = NULL;
636}
637
638static char **split_init_cmd(const char *incmd)
639{
640 size_t len;
641 int nargs = 0;
642 char *copy, *p, *saveptr;
643 char **argv;
644
645 if (!incmd)
646 return NULL;
647
648 len = strlen(incmd) + 1;
649 copy = alloca(len);
650 strncpy(copy, incmd, len);
651 copy[len-1] = '\0';
652
653 do {
654 argv = malloc(sizeof(char *));
655 } while (!argv);
656 argv[0] = NULL;
657 for (p = strtok_r(copy, " ", &saveptr); p != NULL;
658 p = strtok_r(NULL, " ", &saveptr))
659 push_arg(&argv, p, &nargs);
660
661 if (nargs == 0) {
662 free(argv);
663 return NULL;
664 }
665 return argv;
666}
667
668static void free_init_cmd(char **argv)
669{
670 int i = 0;
671
672 if (!argv)
673 return;
674 while (argv[i])
675 free(argv[i++]);
676 free(argv);
677}
678
858377e4 679static bool do_lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
72d0e1cb
SG
680{
681 int ret;
682 struct lxc_conf *conf;
540f932a 683 bool daemonize = false;
6eaac303 684 FILE *pid_fp = NULL;
72d0e1cb
SG
685 char *default_args[] = {
686 "/sbin/init",
13aad0ae 687 NULL,
72d0e1cb 688 };
fd51a89b 689 char **init_cmd = NULL;
72d0e1cb
SG
690
691 /* container exists */
692 if (!c)
693 return false;
120146b9
SG
694
695 /* If anything fails before we set error_num, we want an error in there */
696 c->error_num = 1;
697
72d0e1cb
SG
698 /* container has been setup */
699 if (!c->lxc_conf)
700 return false;
701
3e625e2d
SH
702 if ((ret = ongoing_create(c)) < 0) {
703 ERROR("Error checking for incomplete creation");
704 return false;
705 }
706 if (ret == 2) {
707 ERROR("Error: %s creation was not completed", c->name);
858377e4 708 do_lxcapi_destroy(c);
3e625e2d
SH
709 return false;
710 } else if (ret == 1) {
711 ERROR("Error: creation of %s is ongoing", c->name);
712 return false;
713 }
714
72d0e1cb
SG
715 /* is this app meant to be run through lxcinit, as in lxc-execute? */
716 if (useinit && !argv)
717 return false;
718
5cee8c50 719 if (container_mem_lock(c))
72d0e1cb
SG
720 return false;
721 conf = c->lxc_conf;
722 daemonize = c->daemonize;
5cee8c50 723 container_mem_unlock(c);
72d0e1cb
SG
724
725 if (useinit) {
507cee36 726 ret = lxc_execute(c->name, argv, 1, conf, c->config_path, daemonize);
72d0e1cb
SG
727 return ret == 0 ? true : false;
728 }
729
fd51a89b
SH
730 /* if no argv was passed in, use lxc.init_cmd if provided in
731 * configuration */
732 if (!argv)
733 argv = init_cmd = split_init_cmd(conf->init_cmd);
734
735 /* ... and otherwise use default_args */
736 if (!argv)
737 argv = default_args;
72d0e1cb
SG
738
739 /*
740 * say, I'm not sure - what locks do we want here? Any?
741 * Is liblxc's locking enough here to protect the on disk
742 * container? We don't want to exclude things like lxc_info
743 * while container is running...
744 */
745 if (daemonize) {
0a4be28d 746 char title[2048];
e51d4895 747 lxc_monitord_spawn(c->config_path);
71454076 748
72d0e1cb 749 pid_t pid = fork();
844f7a38 750 if (pid < 0)
72d0e1cb 751 return false;
6eaac303
QH
752
753 if (pid != 0) {
754 /* Set to NULL because we don't want father unlink
755 * the PID file, child will do the free and unlink.
756 */
757 c->pidfile = NULL;
03f064ff 758 return wait_on_daemonized_start(c, pid);
6eaac303 759 }
025ed0f3 760
0a4be28d
TA
761 /* We don't really care if this doesn't print all the
762 * characters; all that it means is that the proctitle will be
763 * ugly. Similarly, we also don't care if setproctitle()
764 * fails. */
765 snprintf(title, sizeof(title), "[lxc monitor] %s %s", c->config_path, c->name);
766 INFO("Attempting to set proc title to %s", title);
767 setproctitle(title);
768
697fa639
SH
769 /* second fork to be reparented by init */
770 pid = fork();
771 if (pid < 0) {
772 SYSERROR("Error doing dual-fork");
13353dc4 773 exit(1);
697fa639
SH
774 }
775 if (pid != 0)
776 exit(0);
72d0e1cb 777 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
c278cef2
SH
778 if (chdir("/")) {
779 SYSERROR("Error chdir()ing to /.");
13353dc4 780 exit(1);
c278cef2 781 }
d2cf4c37 782 lxc_check_inherited(conf, true, -1);
69aeabac
TA
783 if (null_stdfds() < 0) {
784 ERROR("failed to close fds");
13353dc4 785 exit(1);
69aeabac 786 }
72d0e1cb 787 setsid();
2d834aa8
SH
788 } else {
789 if (!am_single_threaded()) {
790 ERROR("Cannot start non-daemonized container when threaded");
791 return false;
792 }
72d0e1cb
SG
793 }
794
6eaac303
QH
795 /* We need to write PID file after daeminize, so we always
796 * write the right PID.
797 */
798 if (c->pidfile) {
799 pid_fp = fopen(c->pidfile, "w");
800 if (pid_fp == NULL) {
801 SYSERROR("Failed to create pidfile '%s' for '%s'",
802 c->pidfile, c->name);
13353dc4
SH
803 if (daemonize)
804 exit(1);
6eaac303
QH
805 return false;
806 }
807
808 if (fprintf(pid_fp, "%d\n", getpid()) < 0) {
809 SYSERROR("Failed to write '%s'", c->pidfile);
810 fclose(pid_fp);
811 pid_fp = NULL;
13353dc4
SH
812 if (daemonize)
813 exit(1);
6eaac303
QH
814 return false;
815 }
816
817 fclose(pid_fp);
818 pid_fp = NULL;
819 }
820
72d0e1cb 821 conf->reboot = 0;
d2cf4c37 822
a8dfe4e0
WB
823 /* Unshare the mount namespace if requested */
824 if (conf->monitor_unshare) {
825 if (unshare(CLONE_NEWNS)) {
826 SYSERROR("failed to unshare mount namespace");
827 return false;
828 }
829 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
830 SYSERROR("Failed to make / rslave at startup");
831 return false;
832 }
833 }
834
8bee8851 835reboot:
d2cf4c37
SH
836 if (lxc_check_inherited(conf, daemonize, -1)) {
837 ERROR("Inherited fds found");
838 ret = 1;
839 goto out;
840 }
841
507cee36 842 ret = lxc_start(c->name, argv, conf, c->config_path, daemonize);
d4ef230c 843 c->error_num = ret;
72d0e1cb 844
8bee8851 845 if (conf->reboot == 1) {
72d0e1cb 846 INFO("container requested reboot");
8bee8851 847 conf->reboot = 2;
72d0e1cb
SG
848 goto reboot;
849 }
850
d2cf4c37 851out:
487d8008
QH
852 if (c->pidfile) {
853 unlink(c->pidfile);
854 free(c->pidfile);
855 c->pidfile = NULL;
856 }
857
fd51a89b
SH
858 free_init_cmd(init_cmd);
859
844f7a38 860 if (daemonize)
05e5d7dc 861 exit (ret == 0 ? true : false);
844f7a38 862 else
05e5d7dc 863 return (ret == 0 ? true : false);
72d0e1cb
SG
864}
865
858377e4
SH
866static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
867{
868 bool ret;
869 current_config = c ? c->lxc_conf : NULL;
870 ret = do_lxcapi_start(c, useinit, argv);
871 current_config = NULL;
872 return ret;
873}
874
72d0e1cb
SG
875/*
876 * note there MUST be an ending NULL
877 */
878static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
879{
880 va_list ap;
a0e93eeb 881 char **inargs = NULL;
72d0e1cb
SG
882 bool bret = false;
883
884 /* container exists */
885 if (!c)
886 return false;
887
858377e4
SH
888 current_config = c->lxc_conf;
889
72d0e1cb 890 va_start(ap, useinit);
a0e93eeb 891 inargs = lxc_va_arg_list_to_argv(ap, 0, 1);
72d0e1cb
SG
892 va_end(ap);
893
a0e93eeb
CS
894 if (!inargs) {
895 ERROR("Memory allocation error.");
896 goto out;
72d0e1cb
SG
897 }
898
a0e93eeb 899 /* pass NULL if no arguments were supplied */
858377e4 900 bret = do_lxcapi_start(c, useinit, *inargs ? inargs : NULL);
72d0e1cb
SG
901
902out:
903 if (inargs) {
4e03ae57
DE
904 char **arg;
905 for (arg = inargs; *arg; arg++)
906 free(*arg);
72d0e1cb
SG
907 free(inargs);
908 }
909
858377e4 910 current_config = NULL;
72d0e1cb
SG
911 return bret;
912}
913
858377e4 914static bool do_lxcapi_stop(struct lxc_container *c)
72d0e1cb
SG
915{
916 int ret;
917
918 if (!c)
919 return false;
920
ef6e34ee 921 ret = lxc_cmd_stop(c->name, c->config_path);
72d0e1cb 922
d775f21b 923 return ret == 0;
72d0e1cb
SG
924}
925
858377e4
SH
926WRAP_API(bool, lxcapi_stop)
927
d5752559
SH
928static int do_create_container_dir(const char *path, struct lxc_conf *conf)
929{
930 int ret = -1, lasterr;
931 char *p = alloca(strlen(path)+1);
932 mode_t mask = umask(0002);
933 ret = mkdir(path, 0770);
934 lasterr = errno;
935 umask(mask);
936 errno = lasterr;
937 if (ret) {
938 if (errno == EEXIST)
939 ret = 0;
940 else {
941 SYSERROR("failed to create container path %s", path);
942 return -1;
943 }
944 }
945 strcpy(p, path);
946 if (!lxc_list_empty(&conf->id_map) && chown_mapped_root(p, conf) != 0) {
947 ERROR("Failed to chown container dir");
948 ret = -1;
949 }
950 return ret;
951}
952
72d0e1cb
SG
953/*
954 * create the standard expected container dir
955 */
956static bool create_container_dir(struct lxc_container *c)
957{
958 char *s;
959 int len, ret;
960
2a59a681 961 len = strlen(c->config_path) + strlen(c->name) + 2;
72d0e1cb
SG
962 s = malloc(len);
963 if (!s)
964 return false;
2a59a681 965 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
72d0e1cb
SG
966 if (ret < 0 || ret >= len) {
967 free(s);
968 return false;
969 }
d5752559 970 ret = do_create_container_dir(s, c->lxc_conf);
72d0e1cb
SG
971 free(s);
972 return ret == 0;
973}
974
975/*
1897e3bc
SH
976 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
977 * it returns a mounted bdev on success, NULL on error.
72d0e1cb 978 */
1897e3bc
SH
979static struct bdev *do_bdev_create(struct lxc_container *c, const char *type,
980 struct bdev_specs *specs)
981{
982 char *dest;
1897e3bc
SH
983 size_t len;
984 struct bdev *bdev;
985 int ret;
986
cd219ae6
SY
987 /* rootfs.path or lxcpath/lxcname/rootfs */
988 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0) {
cf465fe4
SH
989 const char *rpath = c->lxc_conf->rootfs.path;
990 len = strlen(rpath) + 1;
cd219ae6 991 dest = alloca(len);
cf465fe4 992 ret = snprintf(dest, len, "%s", rpath);
cd219ae6 993 } else {
858377e4 994 const char *lxcpath = do_lxcapi_get_config_path(c);
cd219ae6
SY
995 len = strlen(c->name) + strlen(lxcpath) + 9;
996 dest = alloca(len);
997 ret = snprintf(dest, len, "%s/%s/rootfs", lxcpath, c->name);
998 }
1897e3bc
SH
999 if (ret < 0 || ret >= len)
1000 return NULL;
1001
1002 bdev = bdev_create(dest, type, c->name, specs);
d44e88c2 1003 if (!bdev) {
959aee9c 1004 ERROR("Failed to create backing store type %s", type);
1897e3bc 1005 return NULL;
d44e88c2
SH
1006 }
1007
858377e4 1008 do_lxcapi_set_config_item(c, "lxc.rootfs", bdev->src);
cf3ef16d
SH
1009
1010 /* if we are not root, chown the rootfs dir to root in the
1011 * target uidmap */
1012
0e6e3a41 1013 if (geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) {
c4d10a05 1014 if (chown_mapped_root(bdev->dest, c->lxc_conf) < 0) {
959aee9c 1015 ERROR("Error chowning %s to container root", bdev->dest);
97e9cfa0 1016 suggest_default_idmap();
cf3ef16d
SH
1017 bdev_put(bdev);
1018 return NULL;
1019 }
1020 }
1021
1897e3bc
SH
1022 return bdev;
1023}
1024
96b3cb40 1025static char *lxcbasename(char *path)
72d0e1cb 1026{
96b3cb40
SH
1027 char *p = path + strlen(path) - 1;
1028 while (*p != '/' && p > path)
1029 p--;
1030 return p;
1031}
72d0e1cb 1032
69aeabac 1033static bool create_run_template(struct lxc_container *c, char *tpath, bool need_null_stdfds,
96b3cb40
SH
1034 char *const argv[])
1035{
1036 pid_t pid;
72d0e1cb 1037
72d0e1cb 1038 if (!tpath)
96b3cb40 1039 return true;
72d0e1cb
SG
1040
1041 pid = fork();
1042 if (pid < 0) {
959aee9c 1043 SYSERROR("failed to fork task for container creation template");
96b3cb40 1044 return false;
72d0e1cb
SG
1045 }
1046
1047 if (pid == 0) { // child
1897e3bc
SH
1048 char *patharg, *namearg, *rootfsarg, *src;
1049 struct bdev *bdev = NULL;
72d0e1cb 1050 int i;
96b3cb40
SH
1051 int ret, len, nargs = 0;
1052 char **newargv;
cf3ef16d 1053 struct lxc_conf *conf = c->lxc_conf;
72d0e1cb 1054
69aeabac
TA
1055 if (need_null_stdfds && null_stdfds() < 0) {
1056 exit(1);
dc23c1c8 1057 }
1897e3bc
SH
1058
1059 src = c->lxc_conf->rootfs.path;
1060 /*
1f92162d 1061 * for an overlay create, what the user wants is the template to fill
1897e3bc
SH
1062 * in what will become the readonly lower layer. So don't mount for
1063 * the template
1064 */
1f92162d
SG
1065 if (strncmp(src, "overlayfs:", 10) == 0)
1066 src = overlay_getlower(src+10);
1067 if (strncmp(src, "aufs:", 5) == 0)
1068 src = overlay_getlower(src+5);
1069
76a26f55 1070 bdev = bdev_init(c->lxc_conf, src, c->lxc_conf->rootfs.mount, NULL);
1897e3bc
SH
1071 if (!bdev) {
1072 ERROR("Error opening rootfs");
1073 exit(1);
1074 }
1075
4de2791f 1076 if (geteuid() == 0) {
cf3ef16d
SH
1077 if (unshare(CLONE_NEWNS) < 0) {
1078 ERROR("error unsharing mounts");
1079 exit(1);
1080 }
4de2791f 1081 if (detect_shared_rootfs()) {
c597baa8 1082 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
4de2791f
SH
1083 SYSERROR("Failed to make / rslave to run template");
1084 ERROR("Continuing...");
1085 }
1086 }
1087 }
2659c7cb 1088 if (strcmp(bdev->type, "dir") && strcmp(bdev->type, "btrfs")) {
4de2791f 1089 if (geteuid() != 0) {
2659c7cb 1090 ERROR("non-root users can only create btrfs and directory-backed containers");
4de2791f
SH
1091 exit(1);
1092 }
cf3ef16d
SH
1093 if (bdev->ops->mount(bdev) < 0) {
1094 ERROR("Error mounting rootfs");
1095 exit(1);
1096 }
1097 } else { // TODO come up with a better way here!
f10fad2f 1098 free(bdev->dest);
cf3ef16d 1099 bdev->dest = strdup(bdev->src);
1897e3bc
SH
1100 }
1101
72d0e1cb
SG
1102 /*
1103 * create our new array, pre-pend the template name and
1104 * base args
1105 */
1106 if (argv)
1897e3bc 1107 for (nargs = 0; argv[nargs]; nargs++) ;
6849cb5b 1108 nargs += 4; // template, path, rootfs and name args
cf3ef16d 1109
72d0e1cb
SG
1110 newargv = malloc(nargs * sizeof(*newargv));
1111 if (!newargv)
1112 exit(1);
96b3cb40 1113 newargv[0] = lxcbasename(tpath);
72d0e1cb 1114
2a59a681 1115 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
72d0e1cb
SG
1116 patharg = malloc(len);
1117 if (!patharg)
1118 exit(1);
2a59a681 1119 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
72d0e1cb
SG
1120 if (ret < 0 || ret >= len)
1121 exit(1);
1122 newargv[1] = patharg;
1123 len = strlen("--name=") + strlen(c->name) + 1;
1124 namearg = malloc(len);
1125 if (!namearg)
1126 exit(1);
1127 ret = snprintf(namearg, len, "--name=%s", c->name);
1128 if (ret < 0 || ret >= len)
1129 exit(1);
1130 newargv[2] = namearg;
1131
1897e3bc
SH
1132 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
1133 rootfsarg = malloc(len);
1134 if (!rootfsarg)
1135 exit(1);
1136 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
1137 if (ret < 0 || ret >= len)
1138 exit(1);
1139 newargv[3] = rootfsarg;
1140
72d0e1cb
SG
1141 /* add passed-in args */
1142 if (argv)
1897e3bc
SH
1143 for (i = 4; i < nargs; i++)
1144 newargv[i] = argv[i-4];
72d0e1cb
SG
1145
1146 /* add trailing NULL */
1147 nargs++;
1148 newargv = realloc(newargv, nargs * sizeof(*newargv));
1149 if (!newargv)
1150 exit(1);
1151 newargv[nargs - 1] = NULL;
1152
cf3ef16d
SH
1153 /*
1154 * If we're running the template in a mapped userns, then
1155 * we prepend the template command with:
1156 * lxc-usernsexec <-m map1> ... <-m mapn> --
57d116ab
SH
1157 * and we append "--mapped-uid x", where x is the mapped uid
1158 * for our geteuid()
cf3ef16d 1159 */
0e6e3a41 1160 if (!lxc_list_empty(&conf->id_map)) {
cf3ef16d 1161 int n2args = 1;
57d116ab 1162 char txtuid[20];
2133f58c 1163 char txtgid[20];
cf3ef16d
SH
1164 char **n2 = malloc(n2args * sizeof(*n2));
1165 struct lxc_list *it;
1166 struct id_map *map;
1167
57d116ab
SH
1168 if (!n2) {
1169 SYSERROR("out of memory");
1170 exit(1);
1171 }
cf3ef16d
SH
1172 newargv[0] = tpath;
1173 tpath = "lxc-usernsexec";
1174 n2[0] = "lxc-usernsexec";
1175 lxc_list_for_each(it, &conf->id_map) {
1176 map = it->elem;
1177 n2args += 2;
57d116ab 1178 n2 = realloc(n2, n2args * sizeof(char *));
cf3ef16d
SH
1179 if (!n2)
1180 exit(1);
1181 n2[n2args-2] = "-m";
1182 n2[n2args-1] = malloc(200);
1183 if (!n2[n2args-1])
1184 exit(1);
1185 ret = snprintf(n2[n2args-1], 200, "%c:%lu:%lu:%lu",
1186 map->idtype == ID_TYPE_UID ? 'u' : 'g',
1187 map->nsid, map->hostid, map->range);
1188 if (ret < 0 || ret >= 200)
1189 exit(1);
1190 }
2133f58c 1191 int hostid_mapped = mapped_hostid(geteuid(), conf, ID_TYPE_UID);
6849cb5b 1192 int extraargs = hostid_mapped >= 0 ? 1 : 3;
57d116ab 1193 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
cf3ef16d
SH
1194 if (!n2)
1195 exit(1);
57d116ab 1196 if (hostid_mapped < 0) {
2133f58c 1197 hostid_mapped = find_unmapped_nsuid(conf, ID_TYPE_UID);
cf3ef16d 1198 n2[n2args++] = "-m";
57d116ab 1199 if (hostid_mapped < 0) {
cf3ef16d
SH
1200 ERROR("Could not find free uid to map");
1201 exit(1);
1202 }
1203 n2[n2args++] = malloc(200);
1204 if (!n2[n2args-1]) {
1205 SYSERROR("out of memory");
1206 exit(1);
1207 }
1208 ret = snprintf(n2[n2args-1], 200, "u:%d:%d:1",
57d116ab 1209 hostid_mapped, geteuid());
cf3ef16d
SH
1210 if (ret < 0 || ret >= 200) {
1211 ERROR("string too long");
1212 exit(1);
1213 }
1214 }
2133f58c
SH
1215 int hostgid_mapped = mapped_hostid(getegid(), conf, ID_TYPE_GID);
1216 extraargs = hostgid_mapped >= 0 ? 1 : 3;
1217 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1218 if (!n2)
1219 exit(1);
1220 if (hostgid_mapped < 0) {
1221 hostgid_mapped = find_unmapped_nsuid(conf, ID_TYPE_GID);
1222 n2[n2args++] = "-m";
1223 if (hostgid_mapped < 0) {
1224 ERROR("Could not find free uid to map");
1225 exit(1);
1226 }
1227 n2[n2args++] = malloc(200);
1228 if (!n2[n2args-1]) {
1229 SYSERROR("out of memory");
1230 exit(1);
1231 }
1232 ret = snprintf(n2[n2args-1], 200, "g:%d:%d:1",
1233 hostgid_mapped, getegid());
1234 if (ret < 0 || ret >= 200) {
1235 ERROR("string too long");
1236 exit(1);
1237 }
1238 }
cf3ef16d
SH
1239 n2[n2args++] = "--";
1240 for (i = 0; i < nargs; i++)
1241 n2[i + n2args] = newargv[i];
57d116ab
SH
1242 n2args += nargs;
1243 // Finally add "--mapped-uid $uid" to tell template what to chown
1244 // cached images to
2133f58c 1245 n2args += 4;
57d116ab
SH
1246 n2 = realloc(n2, n2args * sizeof(char *));
1247 if (!n2) {
1248 SYSERROR("out of memory");
1249 exit(1);
1250 }
1251 // note n2[n2args-1] is NULL
2133f58c 1252 n2[n2args-5] = "--mapped-uid";
57d116ab 1253 snprintf(txtuid, 20, "%d", hostid_mapped);
2133f58c
SH
1254 n2[n2args-4] = txtuid;
1255 n2[n2args-3] = "--mapped-gid";
1256 snprintf(txtgid, 20, "%d", hostgid_mapped);
1257 n2[n2args-2] = txtgid;
57d116ab 1258 n2[n2args-1] = NULL;
cf3ef16d
SH
1259 free(newargv);
1260 newargv = n2;
1261 }
72d0e1cb 1262 /* execute */
cf3ef16d 1263 execvp(tpath, newargv);
72d0e1cb
SG
1264 SYSERROR("failed to execute template %s", tpath);
1265 exit(1);
1266 }
1267
9be53773 1268 if (wait_for_pid(pid) != 0) {
959aee9c 1269 ERROR("container creation template for %s failed", c->name);
96b3cb40
SH
1270 return false;
1271 }
1272
1273 return true;
1274}
1275
74a3920a 1276static bool prepend_lxc_header(char *path, const char *t, char *const argv[])
3ce74686 1277{
1fd9bd50 1278 long flen;
b4569e93 1279 char *contents;
3ce74686 1280 FILE *f;
025ed0f3 1281 int ret = -1;
52026772 1282#if HAVE_LIBGNUTLS
025ed0f3 1283 int i;
3ce74686 1284 unsigned char md_value[SHA_DIGEST_LENGTH];
b4569e93 1285 char *tpath;
52026772 1286#endif
3ce74686 1287
025ed0f3 1288 f = fopen(path, "r");
025ed0f3 1289 if (f == NULL)
3ce74686 1290 return false;
025ed0f3
SH
1291
1292 if (fseek(f, 0, SEEK_END) < 0)
1293 goto out_error;
1294 if ((flen = ftell(f)) < 0)
1295 goto out_error;
1296 if (fseek(f, 0, SEEK_SET) < 0)
1297 goto out_error;
1298 if ((contents = malloc(flen + 1)) == NULL)
1299 goto out_error;
1300 if (fread(contents, 1, flen, f) != flen)
1301 goto out_free_contents;
1302
3ce74686 1303 contents[flen] = '\0';
025ed0f3 1304 ret = fclose(f);
025ed0f3
SH
1305 f = NULL;
1306 if (ret < 0)
1307 goto out_free_contents;
3ce74686 1308
b4569e93 1309#if HAVE_LIBGNUTLS
01efd4d3 1310 tpath = get_template_path(t);
85db5535 1311 if (!tpath) {
959aee9c 1312 ERROR("bad template: %s", t);
025ed0f3 1313 goto out_free_contents;
3ce74686
SH
1314 }
1315
85db5535
DE
1316 ret = sha1sum_file(tpath, md_value);
1317 if (ret < 0) {
1318 ERROR("Error getting sha1sum of %s", tpath);
3ce74686 1319 free(tpath);
85db5535 1320 goto out_free_contents;
3ce74686 1321 }
85db5535 1322 free(tpath);
3ce74686
SH
1323#endif
1324
025ed0f3 1325 f = fopen(path, "w");
025ed0f3 1326 if (f == NULL) {
3ce74686
SH
1327 SYSERROR("reopening config for writing");
1328 free(contents);
1329 return false;
1330 }
1331 fprintf(f, "# Template used to create this container: %s\n", t);
1332 if (argv) {
1333 fprintf(f, "# Parameters passed to the template:");
1334 while (*argv) {
1335 fprintf(f, " %s", *argv);
1336 argv++;
1337 }
1338 fprintf(f, "\n");
1339 }
1340#if HAVE_LIBGNUTLS
56698177
SH
1341 fprintf(f, "# Template script checksum (SHA-1): ");
1342 for (i=0; i<SHA_DIGEST_LENGTH; i++)
1343 fprintf(f, "%02x", md_value[i]);
1344 fprintf(f, "\n");
3ce74686 1345#endif
0520c252 1346 fprintf(f, "# For additional config options, please look at lxc.container.conf(5)\n");
3ce74686
SH
1347 if (fwrite(contents, 1, flen, f) != flen) {
1348 SYSERROR("Writing original contents");
1349 free(contents);
1350 fclose(f);
1351 return false;
1352 }
025ed0f3
SH
1353 ret = 0;
1354out_free_contents:
3ce74686 1355 free(contents);
025ed0f3
SH
1356out_error:
1357 if (f) {
1358 int newret;
025ed0f3 1359 newret = fclose(f);
025ed0f3
SH
1360 if (ret == 0)
1361 ret = newret;
1362 }
1363 if (ret < 0) {
1364 SYSERROR("Error prepending header");
3ce74686
SH
1365 return false;
1366 }
1367 return true;
1368}
1369
4df7f012
SH
1370static void lxcapi_clear_config(struct lxc_container *c)
1371{
f979ac15
SH
1372 if (c) {
1373 if (c->lxc_conf) {
1374 lxc_conf_free(c->lxc_conf);
1375 c->lxc_conf = NULL;
1376 }
4df7f012
SH
1377 }
1378}
1379
858377e4
SH
1380#define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1381
96b3cb40
SH
1382/*
1383 * lxcapi_create:
1384 * create a container with the given parameters.
1385 * @c: container to be created. It has the lxcpath, name, and a starting
1386 * configuration already set
1387 * @t: the template to execute to instantiate the root filesystem and
1388 * adjust the configuration.
1389 * @bdevtype: backing store type to use. If NULL, dir will be used.
1390 * @specs: additional parameters for the backing store, i.e. LVM vg to
1391 * use.
1392 *
1393 * @argv: the arguments to pass to the template, terminated by NULL. If no
1394 * arguments, you can just pass NULL.
1395 */
858377e4 1396static bool do_lxcapi_create(struct lxc_container *c, const char *t,
dc23c1c8 1397 const char *bdevtype, struct bdev_specs *specs, int flags,
96b3cb40
SH
1398 char *const argv[])
1399{
a69aad27 1400 bool ret = false;
96b3cb40 1401 pid_t pid;
85db5535 1402 char *tpath = NULL;
cbee8106 1403 int partial_fd;
96b3cb40
SH
1404
1405 if (!c)
1406 return false;
1407
85db5535
DE
1408 if (t) {
1409 tpath = get_template_path(t);
1410 if (!tpath) {
959aee9c 1411 ERROR("bad template: %s", t);
85db5535
DE
1412 goto out;
1413 }
96b3cb40
SH
1414 }
1415
cf465fe4
SH
1416 /*
1417 * If a template is passed in, and the rootfs already is defined in
1418 * the container config and exists, then * caller is trying to create
1419 * an existing container. Return an error, but do NOT delete the
1420 * container.
1421 */
858377e4 1422 if (do_lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
cf465fe4
SH
1423 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
1424 ERROR("Container %s:%s already exists", c->config_path, c->name);
6c6892b5 1425 goto free_tpath;
cf465fe4
SH
1426 }
1427
6c6892b5 1428 if (!c->lxc_conf) {
858377e4 1429 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
959aee9c 1430 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
6c6892b5
DE
1431 goto free_tpath;
1432 }
96b3cb40
SH
1433 }
1434
6c6892b5
DE
1435 if (!create_container_dir(c))
1436 goto free_tpath;
1437
0590e82c 1438 /*
0590e82c
SH
1439 * if both template and rootfs.path are set, template is setup as rootfs.path.
1440 * container is already created if we have a config and rootfs.path is accessible
1441 */
00370edd
DW
1442 if (!c->lxc_conf->rootfs.path && !tpath) {
1443 /* no template passed in and rootfs does not exist */
1444 if (!c->save_config(c, NULL)) {
1445 ERROR("failed to save starting configuration for %s\n", c->name);
1446 goto out;
1447 }
1448 ret = true;
0590e82c 1449 goto out;
00370edd 1450 }
0590e82c
SH
1451 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
1452 /* rootfs passed into configuration, but does not exist: error */
1453 goto out;
858377e4 1454 if (do_lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
0590e82c
SH
1455 /* Rootfs already existed, user just wanted to save the
1456 * loaded configuration */
0f4cdd77
DW
1457 if (!c->save_config(c, NULL))
1458 ERROR("failed to save starting configuration for %s\n", c->name);
0590e82c
SH
1459 ret = true;
1460 goto out;
a69aad27 1461 }
96b3cb40
SH
1462
1463 /* Mark that this container is being created */
1464 if ((partial_fd = create_partial(c)) < 0)
1465 goto out;
1466
1467 /* no need to get disk lock bc we have the partial locked */
1468
1469 /*
1470 * Create the backing store
1471 * Note we can't do this in the same task as we use to execute the
1472 * template because of the way zfs works.
1473 * After you 'zfs create', zfs mounts the fs only in the initial
1474 * namespace.
1475 */
1476 pid = fork();
1477 if (pid < 0) {
959aee9c 1478 SYSERROR("failed to fork task for container creation template");
8eb5694b
SH
1479 goto out_unlock;
1480 }
1481
96b3cb40
SH
1482 if (pid == 0) { // child
1483 struct bdev *bdev = NULL;
1484
1485 if (!(bdev = do_bdev_create(c, bdevtype, specs))) {
1486 ERROR("Error creating backing store type %s for %s",
1487 bdevtype ? bdevtype : "(none)", c->name);
1488 exit(1);
1489 }
1490
1491 /* save config file again to store the new rootfs location */
858377e4 1492 if (!do_lxcapi_save_config(c, NULL)) {
959aee9c 1493 ERROR("failed to save starting configuration for %s", c->name);
96b3cb40
SH
1494 // parent task won't see bdev in config so we delete it
1495 bdev->ops->umount(bdev);
1496 bdev->ops->destroy(bdev);
1497 exit(1);
1498 }
1499 exit(0);
1500 }
1501 if (wait_for_pid(pid) != 0)
a09295f8 1502 goto out_unlock;
96b3cb40
SH
1503
1504 /* reload config to get the rootfs */
a3b47c09 1505 lxc_conf_free(c->lxc_conf);
96b3cb40
SH
1506 c->lxc_conf = NULL;
1507 if (!load_config_locked(c, c->configfile))
a09295f8 1508 goto out_unlock;
96b3cb40 1509
dc23c1c8 1510 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
96b3cb40
SH
1511 goto out_unlock;
1512
8eb5694b
SH
1513 // now clear out the lxc_conf we have, reload from the created
1514 // container
858377e4 1515 do_lxcapi_clear_config(c);
3ce74686 1516
9d65a487
KY
1517 if (t) {
1518 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
1519 ERROR("Error prepending header to configuration file");
1520 goto out_unlock;
1521 }
3ce74686 1522 }
a69aad27 1523 ret = load_config_locked(c, c->configfile);
72d0e1cb
SG
1524
1525out_unlock:
3e625e2d
SH
1526 if (partial_fd >= 0)
1527 remove_partial(c, partial_fd);
72d0e1cb 1528out:
c55d4505 1529 if (!ret)
18aa217b 1530 container_destroy(c);
6c6892b5 1531free_tpath:
f10fad2f 1532 free(tpath);
a69aad27 1533 return ret;
72d0e1cb
SG
1534}
1535
858377e4
SH
1536static bool lxcapi_create(struct lxc_container *c, const char *t,
1537 const char *bdevtype, struct bdev_specs *specs, int flags,
1538 char *const argv[])
1539{
1540 bool ret;
1541 current_config = c ? c->lxc_conf : NULL;
1542 ret = do_lxcapi_create(c, t, bdevtype, specs, flags, argv);
1543 current_config = NULL;
1544 return ret;
1545}
1546
1547static bool do_lxcapi_reboot(struct lxc_container *c)
3e625e2d
SH
1548{
1549 pid_t pid;
dd267776 1550 int rebootsignal = SIGINT;
3e625e2d
SH
1551
1552 if (!c)
1553 return false;
858377e4 1554 if (!do_lxcapi_is_running(c))
3e625e2d 1555 return false;
858377e4 1556 pid = do_lxcapi_init_pid(c);
3e625e2d
SH
1557 if (pid <= 0)
1558 return false;
dd267776
BP
1559 if (c->lxc_conf && c->lxc_conf->rebootsignal)
1560 rebootsignal = c->lxc_conf->rebootsignal;
1561 if (kill(pid, rebootsignal) < 0)
3e625e2d
SH
1562 return false;
1563 return true;
1564
1565}
1566
858377e4
SH
1567WRAP_API(bool, lxcapi_reboot)
1568
1569static bool do_lxcapi_shutdown(struct lxc_container *c, int timeout)
72d0e1cb
SG
1570{
1571 bool retv;
1572 pid_t pid;
f0f1d8c0 1573 int haltsignal = SIGPWR;
72d0e1cb
SG
1574
1575 if (!c)
1576 return false;
1577
858377e4 1578 if (!do_lxcapi_is_running(c))
72d0e1cb 1579 return true;
858377e4 1580 pid = do_lxcapi_init_pid(c);
72d0e1cb
SG
1581 if (pid <= 0)
1582 return true;
b0227444 1583 if (c->lxc_conf && c->lxc_conf->haltsignal)
f0f1d8c0
DE
1584 haltsignal = c->lxc_conf->haltsignal;
1585 kill(pid, haltsignal);
858377e4 1586 retv = do_lxcapi_wait(c, "STOPPED", timeout);
72d0e1cb
SG
1587 return retv;
1588}
1589
858377e4
SH
1590WRAP_API_1(bool, lxcapi_shutdown, int)
1591
1897e3bc 1592static bool lxcapi_createl(struct lxc_container *c, const char *t,
dc23c1c8 1593 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
72d0e1cb
SG
1594{
1595 bool bret = false;
a0e93eeb 1596 char **args = NULL;
72d0e1cb 1597 va_list ap;
72d0e1cb
SG
1598
1599 if (!c)
1600 return false;
1601
858377e4
SH
1602 current_config = c->lxc_conf;
1603
72d0e1cb
SG
1604 /*
1605 * since we're going to wait for create to finish, I don't think we
1606 * need to get a copy of the arguments.
1607 */
dc23c1c8 1608 va_start(ap, flags);
a0e93eeb 1609 args = lxc_va_arg_list_to_argv(ap, 0, 0);
72d0e1cb 1610 va_end(ap);
a0e93eeb
CS
1611 if (!args) {
1612 ERROR("Memory allocation error.");
1613 goto out;
1614 }
72d0e1cb 1615
858377e4 1616 bret = do_lxcapi_create(c, t, bdevtype, specs, flags, args);
72d0e1cb
SG
1617
1618out:
a0e93eeb 1619 free(args);
858377e4 1620 current_config = NULL;
72d0e1cb
SG
1621 return bret;
1622}
1623
6b0d5538
SH
1624static void do_clear_unexp_config_line(struct lxc_conf *conf, const char *key)
1625{
1626 if (strcmp(key, "lxc.cgroup") == 0)
1627 clear_unexp_config_line(conf, key, true);
1628 else if (strcmp(key, "lxc.network") == 0)
1629 clear_unexp_config_line(conf, key, true);
1630 else if (strcmp(key, "lxc.hook") == 0)
1631 clear_unexp_config_line(conf, key, true);
1632 else
1633 clear_unexp_config_line(conf, key, false);
1634 if (!do_append_unexp_config_line(conf, key, ""))
1635 WARN("Error clearing configuration for %s", key);
1636}
1637
858377e4 1638static bool do_lxcapi_clear_config_item(struct lxc_container *c, const char *key)
72d0e1cb
SG
1639{
1640 int ret;
1641
1642 if (!c || !c->lxc_conf)
1643 return false;
5cee8c50 1644 if (container_mem_lock(c))
72d0e1cb 1645 return false;
72d0e1cb 1646 ret = lxc_clear_config_item(c->lxc_conf, key);
6b0d5538
SH
1647 if (!ret)
1648 do_clear_unexp_config_line(c->lxc_conf, key);
5cee8c50 1649 container_mem_unlock(c);
72d0e1cb
SG
1650 return ret == 0;
1651}
1652
858377e4
SH
1653WRAP_API_1(bool, lxcapi_clear_config_item, const char *)
1654
e0f59189 1655static inline bool enter_net_ns(struct lxc_container *c)
51d0854c 1656{
858377e4 1657 pid_t pid = do_lxcapi_init_pid(c);
ae22a220 1658
0e6e3a41 1659 if ((geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) && access("/proc/self/ns/user", F_OK) == 0) {
51d0854c
DY
1660 if (!switch_to_ns(pid, "user"))
1661 return false;
9c83a661 1662 }
51d0854c 1663 return switch_to_ns(pid, "net");
799f29ab
ÇO
1664}
1665
9c88ff1f
ÇO
1666// used by qsort and bsearch functions for comparing names
1667static inline int string_cmp(char **first, char **second)
1668{
1669 return strcmp(*first, *second);
1670}
1671
1672// used by qsort and bsearch functions for comparing container names
1673static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1674{
1675 return strcmp((*first)->name, (*second)->name);
1676}
1677
1678static bool add_to_array(char ***names, char *cname, int pos)
1679{
1680 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1681 if (!newnames) {
1682 ERROR("Out of memory");
1683 return false;
1684 }
1685
1686 *names = newnames;
1687 newnames[pos] = strdup(cname);
1688 if (!newnames[pos])
1689 return false;
1690
1691 // sort the arrray as we will use binary search on it
1692 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1693
1694 return true;
1695}
1696
2871830a 1697static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
9c88ff1f
ÇO
1698{
1699 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1700 if (!newlist) {
1701 ERROR("Out of memory");
1702 return false;
1703 }
1704
1705 *list = newlist;
1706 newlist[pos] = c;
1707
1708 // sort the arrray as we will use binary search on it
2871830a
DE
1709 if (sort)
1710 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
9c88ff1f
ÇO
1711
1712 return true;
1713}
1714
1715static char** get_from_array(char ***names, char *cname, int size)
1716{
1717 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1718}
1719
1720
1721static bool array_contains(char ***names, char *cname, int size) {
1722 if(get_from_array(names, cname, size) != NULL)
1723 return true;
1724 return false;
1725}
1726
1727static bool remove_from_array(char ***names, char *cname, int size)
1728{
1729 char **result = get_from_array(names, cname, size);
1730 if (result != NULL) {
1731 free(result);
1732 return true;
1733 }
1734 return false;
1735}
1736
858377e4 1737static char ** do_lxcapi_get_interfaces(struct lxc_container *c)
799f29ab 1738{
ae22a220
ÇO
1739 pid_t pid;
1740 int i, count = 0, pipefd[2];
9c88ff1f 1741 char **interfaces = NULL;
ae22a220 1742 char interface[IFNAMSIZ];
799f29ab 1743
ae22a220
ÇO
1744 if(pipe(pipefd) < 0) {
1745 SYSERROR("pipe failed");
1746 return NULL;
c868b261
ÇO
1747 }
1748
ae22a220
ÇO
1749 pid = fork();
1750 if (pid < 0) {
959aee9c 1751 SYSERROR("failed to fork task to get interfaces information");
ae22a220
ÇO
1752 close(pipefd[0]);
1753 close(pipefd[1]);
1754 return NULL;
1755 }
799f29ab 1756
ae22a220
ÇO
1757 if (pid == 0) { // child
1758 int ret = 1, nbytes;
1759 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1760
1761 /* close the read-end of the pipe */
1762 close(pipefd[0]);
1763
e0f59189 1764 if (!enter_net_ns(c)) {
ae22a220
ÇO
1765 SYSERROR("failed to enter namespace");
1766 goto out;
1767 }
1768
1769 /* Grab the list of interfaces */
1770 if (getifaddrs(&interfaceArray)) {
1771 SYSERROR("failed to get interfaces list");
1772 goto out;
1773 }
1774
1775 /* Iterate through the interfaces */
1776 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1777 nbytes = write(pipefd[1], tempIfAddr->ifa_name, IFNAMSIZ);
1778 if (nbytes < 0) {
1779 ERROR("write failed");
1780 goto out;
1781 }
1782 count++;
1783 }
1784 ret = 0;
1785
1786 out:
1787 if (interfaceArray)
1788 freeifaddrs(interfaceArray);
1789
1790 /* close the write-end of the pipe, thus sending EOF to the reader */
1791 close(pipefd[1]);
1792 exit(ret);
799f29ab
ÇO
1793 }
1794
ae22a220
ÇO
1795 /* close the write-end of the pipe */
1796 close(pipefd[1]);
1797
358afd84 1798 while (read(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
ae22a220
ÇO
1799 if (array_contains(&interfaces, interface, count))
1800 continue;
799f29ab 1801
ae22a220
ÇO
1802 if(!add_to_array(&interfaces, interface, count))
1803 ERROR("PARENT: add_to_array failed");
9c88ff1f
ÇO
1804 count++;
1805 }
799f29ab 1806
ae22a220
ÇO
1807 if (wait_for_pid(pid) != 0) {
1808 for(i=0;i<count;i++)
1809 free(interfaces[i]);
1810 free(interfaces);
1811 interfaces = NULL;
1812 }
9c88ff1f 1813
ae22a220
ÇO
1814 /* close the read-end of the pipe */
1815 close(pipefd[0]);
799f29ab 1816
9c88ff1f
ÇO
1817 /* Append NULL to the array */
1818 if(interfaces)
1819 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
799f29ab 1820
9c88ff1f 1821 return interfaces;
799f29ab
ÇO
1822}
1823
858377e4
SH
1824WRAP_API(char **, lxcapi_get_interfaces)
1825
1826static char** do_lxcapi_get_ips(struct lxc_container *c, const char* interface, const char* family, int scope)
799f29ab 1827{
ae22a220
ÇO
1828 pid_t pid;
1829 int i, count = 0, pipefd[2];
9c88ff1f 1830 char **addresses = NULL;
ae22a220 1831 char address[INET6_ADDRSTRLEN];
799f29ab 1832
ae22a220
ÇO
1833 if(pipe(pipefd) < 0) {
1834 SYSERROR("pipe failed");
1835 return NULL;
c868b261
ÇO
1836 }
1837
ae22a220
ÇO
1838 pid = fork();
1839 if (pid < 0) {
959aee9c 1840 SYSERROR("failed to fork task to get container ips");
ae22a220
ÇO
1841 close(pipefd[0]);
1842 close(pipefd[1]);
1843 return NULL;
9c83a661
SG
1844 }
1845
ae22a220
ÇO
1846 if (pid == 0) { // child
1847 int ret = 1, nbytes;
1848 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1849 char addressOutputBuffer[INET6_ADDRSTRLEN];
1850 void *tempAddrPtr = NULL;
1851 char *address = NULL;
fe218ca3 1852
ae22a220
ÇO
1853 /* close the read-end of the pipe */
1854 close(pipefd[0]);
1855
e0f59189 1856 if (!enter_net_ns(c)) {
ae22a220
ÇO
1857 SYSERROR("failed to enter namespace");
1858 goto out;
9c83a661 1859 }
ae22a220
ÇO
1860
1861 /* Grab the list of interfaces */
1862 if (getifaddrs(&interfaceArray)) {
1863 SYSERROR("failed to get interfaces list");
1864 goto out;
1865 }
1866
1867 /* Iterate through the interfaces */
1868 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1869 if (tempIfAddr->ifa_addr == NULL)
9c83a661
SG
1870 continue;
1871
ae22a220
ÇO
1872 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1873 if (family && strcmp(family, "inet"))
1874 continue;
1875 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1876 }
1877 else {
1878 if (family && strcmp(family, "inet6"))
1879 continue;
1880
1881 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1882 continue;
1883
1884 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1885 }
1886
1887 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1888 continue;
1889 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
9c83a661
SG
1890 continue;
1891
ae22a220
ÇO
1892 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1893 tempAddrPtr,
1894 addressOutputBuffer,
1895 sizeof(addressOutputBuffer));
1896 if (!address)
1897 continue;
1898
1899 nbytes = write(pipefd[1], address, INET6_ADDRSTRLEN);
1900 if (nbytes < 0) {
1901 ERROR("write failed");
1902 goto out;
1903 }
1904 count++;
9c83a661 1905 }
ae22a220 1906 ret = 0;
9c83a661 1907
ae22a220
ÇO
1908 out:
1909 if(interfaceArray)
1910 freeifaddrs(interfaceArray);
9c83a661 1911
ae22a220
ÇO
1912 /* close the write-end of the pipe, thus sending EOF to the reader */
1913 close(pipefd[1]);
1914 exit(ret);
6849cb5b 1915 }
9c83a661 1916
ae22a220
ÇO
1917 /* close the write-end of the pipe */
1918 close(pipefd[1]);
1919
358afd84 1920 while (read(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
9c88ff1f 1921 if(!add_to_array(&addresses, address, count))
ae22a220 1922 ERROR("PARENT: add_to_array failed");
9c88ff1f 1923 count++;
9c83a661
SG
1924 }
1925
ae22a220
ÇO
1926 if (wait_for_pid(pid) != 0) {
1927 for(i=0;i<count;i++)
1928 free(addresses[i]);
1929 free(addresses);
1930 addresses = NULL;
1931 }
9c83a661 1932
ae22a220
ÇO
1933 /* close the read-end of the pipe */
1934 close(pipefd[0]);
9c83a661
SG
1935
1936 /* Append NULL to the array */
9c88ff1f
ÇO
1937 if(addresses)
1938 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
9c83a661
SG
1939
1940 return addresses;
1941}
1942
858377e4
SH
1943WRAP_API_3(char **, lxcapi_get_ips, const char *, const char *, int)
1944
1945static int do_lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1946{
1947 int ret;
1948
1949 if (!c || !c->lxc_conf)
1950 return -1;
5cee8c50 1951 if (container_mem_lock(c))
72d0e1cb 1952 return -1;
72d0e1cb 1953 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
5cee8c50 1954 container_mem_unlock(c);
72d0e1cb
SG
1955 return ret;
1956}
1957
858377e4
SH
1958WRAP_API_3(int, lxcapi_get_config_item, const char *, char *, int)
1959
1960static char* do_lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
8ac18377
ÇO
1961{
1962 char *ret;
1963
1964 if (!c || !c->lxc_conf)
1965 return NULL;
1966 if (container_mem_lock(c))
1967 return NULL;
858377e4 1968 ret = lxc_cmd_get_config_item(c->name, key, do_lxcapi_get_config_path(c));
8ac18377
ÇO
1969 container_mem_unlock(c);
1970 return ret;
1971}
1972
858377e4
SH
1973WRAP_API_1(char *, lxcapi_get_running_config_item, const char *)
1974
1975static int do_lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1976{
1977 if (!key)
1978 return lxc_listconfigs(retv, inlen);
1979 /*
1980 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1981 * This is an intelligent result to show which keys are valid given
1982 * the type of nic it is
1983 */
1984 if (!c || !c->lxc_conf)
1985 return -1;
5cee8c50 1986 if (container_mem_lock(c))
72d0e1cb
SG
1987 return -1;
1988 int ret = -1;
1989 if (strncmp(key, "lxc.network.", 12) == 0)
6849cb5b 1990 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
5cee8c50 1991 container_mem_unlock(c);
72d0e1cb
SG
1992 return ret;
1993}
1994
858377e4
SH
1995WRAP_API_3(int, lxcapi_get_keys, const char *, char *, int)
1996
1997static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 1998{
39dc698c
SH
1999 FILE *fout;
2000 bool ret = false, need_disklock = false;
2001 int lret;
2002
72d0e1cb
SG
2003 if (!alt_file)
2004 alt_file = c->configfile;
2005 if (!alt_file)
6849cb5b 2006 return false; // should we write to stdout if no file is specified?
39dc698c
SH
2007
2008 // If we haven't yet loaded a config, load the stock config
2009 if (!c->lxc_conf) {
858377e4 2010 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
959aee9c 2011 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c->name);
72d0e1cb
SG
2012 return false;
2013 }
39dc698c 2014 }
72d0e1cb 2015
5a3d2e1e
SG
2016 if (!create_container_dir(c))
2017 return false;
2018
39dc698c
SH
2019 /*
2020 * If we're writing to the container's config file, take the
2021 * disk lock. Otherwise just take the memlock to protect the
2022 * struct lxc_container while we're traversing it.
2023 */
2024 if (strcmp(c->configfile, alt_file) == 0)
2025 need_disklock = true;
2026
2027 if (need_disklock)
2028 lret = container_disk_lock(c);
2029 else
2030 lret = container_mem_lock(c);
2031
2032 if (lret)
72d0e1cb 2033 return false;
39dc698c
SH
2034
2035 fout = fopen(alt_file, "w");
2036 if (!fout)
2037 goto out;
6b0d5538 2038 write_config(fout, c->lxc_conf);
72d0e1cb 2039 fclose(fout);
39dc698c
SH
2040 ret = true;
2041
2042out:
2043 if (need_disklock)
2044 container_disk_unlock(c);
2045 else
2046 container_mem_unlock(c);
2047 return ret;
72d0e1cb
SG
2048}
2049
858377e4
SH
2050WRAP_API_1(bool, lxcapi_save_config, const char *)
2051
0ea055b3
CB
2052
2053static bool mod_rdep(struct lxc_container *c0, struct lxc_container *c, bool inc)
dfb31b25 2054{
0ea055b3
CB
2055 FILE *f1;
2056 struct stat fbuf;
42342bed
CB
2057 void *buf = NULL;
2058 char *del = NULL;
dfb31b25 2059 char path[MAXPATHLEN];
0ea055b3
CB
2060 char newpath[MAXPATHLEN];
2061 int fd, ret, n = 0, v = 0;
dfb31b25 2062 bool bret = false;
42342bed 2063 size_t len = 0, bytes = 0;
dfb31b25 2064
0ea055b3 2065 if (container_disk_lock(c0))
dfb31b25 2066 return false;
0ea055b3
CB
2067
2068 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c0->config_path, c0->name);
dfb31b25
SH
2069 if (ret < 0 || ret > MAXPATHLEN)
2070 goto out;
0ea055b3
CB
2071 ret = snprintf(newpath, MAXPATHLEN, "%s\n%s\n", c->config_path, c->name);
2072 if (ret < 0 || ret > MAXPATHLEN)
dfb31b25 2073 goto out;
0ea055b3
CB
2074
2075 /* If we find an lxc-snapshot file using the old format only listing the
2076 * number of snapshots we will keep using it. */
2077 f1 = fopen(path, "r");
2078 if (f1) {
2079 n = fscanf(f1, "%d", &v);
2080 fclose(f1);
2081 if (n == 1 && v == 0) {
2082 remove(path);
2083 n = 0;
2084 }
dfb31b25 2085 }
0ea055b3
CB
2086 if (n == 1) {
2087 v += inc ? 1 : -1;
2088 f1 = fopen(path, "w");
2089 if (!f1)
2090 goto out;
2091 if (fprintf(f1, "%d\n", v) < 0) {
2092 ERROR("Error writing new snapshots value");
2093 fclose(f1);
2094 goto out;
2095 }
2096 ret = fclose(f1);
2097 if (ret != 0) {
2098 SYSERROR("Error writing to or closing snapshots file");
2099 goto out;
2100 }
2101 } else {
2102 /* Here we know that we have or can use an lxc-snapshot file
2103 * using the new format. */
2104 if (inc) {
2105 f1 = fopen(path, "a");
2106 if (!f1)
2107 goto out;
2108
2109 if (fprintf(f1, "%s", newpath) < 0) {
2110 ERROR("Error writing new snapshots entry");
2111 ret = fclose(f1);
2112 if (ret != 0)
2113 SYSERROR("Error writing to or closing snapshots file");
2114 goto out;
2115 }
2116
2117 ret = fclose(f1);
2118 if (ret != 0) {
2119 SYSERROR("Error writing to or closing snapshots file");
2120 goto out;
2121 }
2122 } else if (!inc) {
d028235d
SG
2123 if ((fd = open(path, O_RDWR | O_CLOEXEC)) < 0)
2124 goto out;
2125
2126 if (fstat(fd, &fbuf) < 0) {
2127 close(fd);
2128 goto out;
2129 }
2130
2131 if (fbuf.st_size != 0) {
2132 /* write terminating \0-byte to file */
2133 if (pwrite(fd, "", 1, fbuf.st_size) <= 0) {
2134 close(fd);
2135 goto out;
2136 }
2137
2138 buf = mmap(NULL, fbuf.st_size + 1, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2139 if (buf == MAP_FAILED) {
2140 SYSERROR("Failed to create mapping %s", path);
2141 close(fd);
2142 goto out;
2143 }
2144
2145 len = strlen(newpath);
2146 while ((del = strstr((char *)buf, newpath))) {
2147 memmove(del, del + len, strlen(del) - len + 1);
2148 bytes += len;
2149 }
2150
2151 munmap(buf, fbuf.st_size + 1);
2152 if (ftruncate(fd, fbuf.st_size - bytes) < 0) {
2153 SYSERROR("Failed to truncate file %s", path);
2154 close(fd);
2155 goto out;
2156 }
2157 }
2158 close(fd);
2159 }
0ea055b3
CB
2160
2161 /* If the lxc-snapshot file is empty, remove it. */
2162 if (stat(path, &fbuf) < 0)
2163 goto out;
d028235d
SG
2164 if (!fbuf.st_size) {
2165 remove(path);
0ea055b3 2166 }
dfb31b25
SH
2167 }
2168
2169 bret = true;
2170
2171out:
0ea055b3 2172 container_disk_unlock(c0);
dfb31b25
SH
2173 return bret;
2174}
2175
2176static void strip_newline(char *p)
2177{
2178 size_t len = strlen(p);
2179 if (len < 1)
2180 return;
2181 if (p[len-1] == '\n')
2182 p[len-1] = '\0';
2183}
2184
d825fff3 2185void mod_all_rdeps(struct lxc_container *c, bool inc)
dfb31b25
SH
2186{
2187 struct lxc_container *p;
2188 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
2189 size_t pathlen = 0, namelen = 0;
2190 FILE *f;
2191 int ret;
2192
2193 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
2194 c->config_path, c->name);
2195 if (ret < 0 || ret >= MAXPATHLEN) {
2196 ERROR("Path name too long");
2197 return;
2198 }
025ed0f3 2199 f = fopen(path, "r");
025ed0f3 2200 if (f == NULL)
dfb31b25
SH
2201 return;
2202 while (getline(&lxcpath, &pathlen, f) != -1) {
2203 if (getline(&lxcname, &namelen, f) == -1) {
959aee9c 2204 ERROR("badly formatted file %s", path);
dfb31b25
SH
2205 goto out;
2206 }
2207 strip_newline(lxcpath);
2208 strip_newline(lxcname);
2209 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
2210 ERROR("Unable to find dependent container %s:%s",
2211 lxcpath, lxcname);
2212 continue;
2213 }
0ea055b3
CB
2214 if (!mod_rdep(p, c, inc))
2215 ERROR("Failed to update snapshots file for %s:%s",
dfb31b25
SH
2216 lxcpath, lxcname);
2217 lxc_container_put(p);
2218 }
2219out:
f10fad2f
ME
2220 free(lxcpath);
2221 free(lxcname);
dfb31b25
SH
2222 fclose(f);
2223}
2224
18aa217b 2225static bool has_fs_snapshots(struct lxc_container *c)
dfb31b25 2226{
0ea055b3 2227 FILE *f;
dfb31b25
SH
2228 char path[MAXPATHLEN];
2229 int ret, v;
0ea055b3 2230 struct stat fbuf;
dfb31b25
SH
2231 bool bret = false;
2232
2233 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
2234 c->name);
2235 if (ret < 0 || ret > MAXPATHLEN)
2236 goto out;
0ea055b3
CB
2237 /* If the file doesn't exist there are no snapshots. */
2238 if (stat(path, &fbuf) < 0)
dfb31b25 2239 goto out;
0ea055b3
CB
2240 v = fbuf.st_size;
2241 if (v != 0) {
2242 f = fopen(path, "r");
2243 if (!f)
2244 goto out;
2245 ret = fscanf(f, "%d", &v);
2246 fclose(f);
2247 // TODO: Figure out what to do with the return value of fscanf.
2248 if (ret != 1)
2249 INFO("Container uses new lxc-snapshots format %s", path);
2250 }
dfb31b25
SH
2251 bret = v != 0;
2252
2253out:
2254 return bret;
2255}
2256
18aa217b
SH
2257static bool has_snapshots(struct lxc_container *c)
2258{
2259 char path[MAXPATHLEN];
2260 struct dirent dirent, *direntp;
2261 int count=0;
2262 DIR *dir;
2263
2264 if (!get_snappath_dir(c, path))
2265 return false;
2266 dir = opendir(path);
2267 if (!dir)
2268 return false;
2269 while (!readdir_r(dir, &dirent, &direntp)) {
2270 if (!direntp)
2271 break;
2272
2273 if (!strcmp(direntp->d_name, "."))
2274 continue;
2275
2276 if (!strcmp(direntp->d_name, ".."))
2277 continue;
2278 count++;
2279 break;
2280 }
2281 closedir(dir);
2282 return count > 0;
2283}
2284
297c2d58 2285static bool do_destroy_container(struct lxc_conf *conf) {
d028235d
SG
2286 if (am_unpriv()) {
2287 if (userns_exec_1(conf, bdev_destroy_wrapper, conf) < 0)
2288 return false;
2289 return true;
2290 }
2291 return bdev_destroy(conf);
297c2d58
CB
2292}
2293
4355ab5f
SH
2294static int lxc_rmdir_onedev_wrapper(void *data)
2295{
2296 char *arg = (char *) data;
18aa217b 2297 return lxc_rmdir_onedev(arg, "snaps");
4355ab5f
SH
2298}
2299
18aa217b 2300static bool container_destroy(struct lxc_container *c)
72d0e1cb 2301{
c868b261 2302 bool bret = false;
297c2d58 2303 int ret = 0;
a70a69e8 2304 struct lxc_conf *conf;
72d0e1cb 2305
858377e4 2306 if (!c || !do_lxcapi_is_defined(c))
5a3d2e1e
SG
2307 return false;
2308
a70a69e8 2309 conf = c->lxc_conf;
3bc449ed 2310 if (container_disk_lock(c))
72d0e1cb 2311 return false;
72d0e1cb 2312
39dc698c 2313 if (!is_stopped(c)) {
60bf62d4
SH
2314 // we should queue some sort of error - in c->error_string?
2315 ERROR("container %s is not stopped", c->name);
2316 goto out;
72d0e1cb
SG
2317 }
2318
a70a69e8 2319 if (conf && !lxc_list_empty(&conf->hooks[LXCHOOK_DESTROY])) {
37cf711b 2320 /* Start of environment variable setup for hooks */
ab7efcf5 2321 if (c->name && setenv("LXC_NAME", c->name, 1)) {
37cf711b
SY
2322 SYSERROR("failed to set environment variable for container name");
2323 }
ab7efcf5 2324 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
37cf711b
SY
2325 SYSERROR("failed to set environment variable for config path");
2326 }
ab7efcf5 2327 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
37cf711b
SY
2328 SYSERROR("failed to set environment variable for rootfs mount");
2329 }
ab7efcf5 2330 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
37cf711b
SY
2331 SYSERROR("failed to set environment variable for rootfs mount");
2332 }
2333 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1)) {
2334 SYSERROR("failed to set environment variable for console path");
2335 }
2336 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1)) {
2337 SYSERROR("failed to set environment variable for console log");
2338 }
2339 /* End of environment variable setup for hooks */
2340
2341 if (run_lxc_hooks(c->name, "destroy", conf, c->get_config_path(c), NULL)) {
2342 ERROR("Error executing clone hook for %s", c->name);
2343 goto out;
2344 }
2345 }
2346
2347 if (current_config && conf == current_config) {
858377e4 2348 current_config = NULL;
37cf711b
SY
2349 if (conf->logfd != -1) {
2350 close(conf->logfd);
2351 conf->logfd = -1;
858377e4
SH
2352 }
2353 }
2354
d028235d
SG
2355 if (conf && conf->rootfs.path && conf->rootfs.mount) {
2356 if (!do_destroy_container(conf)) {
2357 ERROR("Error destroying rootfs for %s", c->name);
2358 goto out;
2359 }
2360 INFO("Destroyed rootfs for %s", c->name);
2361 }
60bf62d4 2362
dfb31b25
SH
2363 mod_all_rdeps(c, false);
2364
858377e4 2365 const char *p1 = do_lxcapi_get_config_path(c);
60bf62d4
SH
2366 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
2367 sprintf(path, "%s/%s", p1, c->name);
c868b261 2368 if (am_unpriv())
37cf711b 2369 ret = userns_exec_1(conf, lxc_rmdir_onedev_wrapper, path);
4355ab5f 2370 else
18aa217b 2371 ret = lxc_rmdir_onedev(path, "snaps");
4355ab5f 2372 if (ret < 0) {
60bf62d4
SH
2373 ERROR("Error destroying container directory for %s", c->name);
2374 goto out;
2375 }
d028235d 2376 INFO("Destroyed directory for %s", c->name);
297c2d58 2377
fef48dc9 2378 bret = true;
60bf62d4
SH
2379
2380out:
3bc449ed 2381 container_disk_unlock(c);
fef48dc9 2382 return bret;
72d0e1cb
SG
2383}
2384
858377e4 2385static bool do_lxcapi_destroy(struct lxc_container *c)
18aa217b
SH
2386{
2387 if (!c || !lxcapi_is_defined(c))
2388 return false;
2389 if (has_snapshots(c)) {
2390 ERROR("Container %s has snapshots; not removing", c->name);
2391 return false;
2392 }
2393
2394 if (has_fs_snapshots(c)) {
2395 ERROR("container %s has snapshots on its rootfs", c->name);
2396 return false;
2397 }
2398
2399 return container_destroy(c);
2400}
2401
858377e4 2402WRAP_API(bool, lxcapi_destroy)
18aa217b 2403
858377e4 2404static bool do_lxcapi_destroy_with_snapshots(struct lxc_container *c)
18aa217b
SH
2405{
2406 if (!c || !lxcapi_is_defined(c))
2407 return false;
2408 if (!lxcapi_snapshot_destroy_all(c)) {
2409 ERROR("Error deleting all snapshots");
2410 return false;
2411 }
2412 return lxcapi_destroy(c);
2413}
2414
858377e4
SH
2415WRAP_API(bool, lxcapi_destroy_with_snapshots)
2416
96532523
SH
2417static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
2418{
2419 struct lxc_config_t *config;
2420
2421 if (!c->lxc_conf)
2422 c->lxc_conf = lxc_conf_init();
6b0d5538 2423 if (!c->lxc_conf)
96532523
SH
2424 return false;
2425 config = lxc_getconfig(key);
2426 if (!config)
2427 return false;
6b0d5538 2428 if (config->cb(key, v, c->lxc_conf) != 0)
f979ac15 2429 return false;
6b0d5538 2430 return do_append_unexp_config_line(c->lxc_conf, key, v);
96532523
SH
2431}
2432
858377e4 2433static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb 2434{
72d0e1cb 2435 bool b = false;
72d0e1cb
SG
2436
2437 if (!c)
2438 return false;
2439
5cee8c50 2440 if (container_mem_lock(c))
72d0e1cb
SG
2441 return false;
2442
96532523 2443 b = set_config_item_locked(c, key, v);
72d0e1cb 2444
5cee8c50 2445 container_mem_unlock(c);
72d0e1cb
SG
2446 return b;
2447}
2448
858377e4
SH
2449WRAP_API_2(bool, lxcapi_set_config_item, const char *, const char *)
2450
72d0e1cb
SG
2451static char *lxcapi_config_file_name(struct lxc_container *c)
2452{
2453 if (!c || !c->configfile)
2454 return NULL;
2455 return strdup(c->configfile);
2456}
2457
2a59a681
SH
2458static const char *lxcapi_get_config_path(struct lxc_container *c)
2459{
2460 if (!c || !c->config_path)
2461 return NULL;
2462 return (const char *)(c->config_path);
2463}
2464
afeecbba
SH
2465/*
2466 * not for export
2467 * Just recalculate the c->configfile based on the
2468 * c->config_path, which must be set.
2469 * The lxc_container must be locked or not yet public.
2470 */
2471static bool set_config_filename(struct lxc_container *c)
2472{
2473 char *newpath;
2474 int len, ret;
2475
2476 if (!c->config_path)
2477 return false;
2478
2479 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2480 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
2481 newpath = malloc(len);
2482 if (!newpath)
2483 return false;
2484
2485 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
2486 if (ret < 0 || ret >= len) {
2487 fprintf(stderr, "Error printing out config file name\n");
2488 free(newpath);
2489 return false;
2490 }
2491
f10fad2f 2492 free(c->configfile);
afeecbba
SH
2493 c->configfile = newpath;
2494
2495 return true;
2496}
2497
858377e4 2498static bool do_lxcapi_set_config_path(struct lxc_container *c, const char *path)
2a59a681
SH
2499{
2500 char *p;
2501 bool b = false;
afeecbba 2502 char *oldpath = NULL;
2a59a681
SH
2503
2504 if (!c)
2505 return b;
2506
5cee8c50 2507 if (container_mem_lock(c))
2a59a681
SH
2508 return b;
2509
2510 p = strdup(path);
afeecbba
SH
2511 if (!p) {
2512 ERROR("Out of memory setting new lxc path");
2a59a681 2513 goto err;
afeecbba
SH
2514 }
2515
2a59a681
SH
2516 b = true;
2517 if (c->config_path)
afeecbba 2518 oldpath = c->config_path;
2a59a681 2519 c->config_path = p;
afeecbba
SH
2520
2521 /* Since we've changed the config path, we have to change the
2522 * config file name too */
2523 if (!set_config_filename(c)) {
2524 ERROR("Out of memory setting new config filename");
2525 b = false;
2526 free(c->config_path);
2527 c->config_path = oldpath;
2528 oldpath = NULL;
2529 }
2a59a681 2530err:
f10fad2f 2531 free(oldpath);
5cee8c50 2532 container_mem_unlock(c);
2a59a681
SH
2533 return b;
2534}
2535
858377e4 2536WRAP_API_1(bool, lxcapi_set_config_path, const char *)
2a59a681 2537
858377e4 2538static bool do_lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
794dd120
SH
2539{
2540 int ret;
794dd120
SH
2541
2542 if (!c)
2543 return false;
2544
3bc449ed 2545 if (is_stopped(c))
794dd120
SH
2546 return false;
2547
3bc449ed
SH
2548 if (container_disk_lock(c))
2549 return false;
794dd120 2550
33ad9f1a 2551 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
3bc449ed
SH
2552
2553 container_disk_unlock(c);
2554 return ret == 0;
794dd120
SH
2555}
2556
858377e4
SH
2557WRAP_API_2(bool, lxcapi_set_cgroup_item, const char *, const char *)
2558
2559static int do_lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
794dd120 2560{
3bc449ed 2561 int ret;
794dd120 2562
6502006a 2563 if (!c)
794dd120
SH
2564 return -1;
2565
3bc449ed 2566 if (is_stopped(c))
794dd120
SH
2567 return -1;
2568
3bc449ed
SH
2569 if (container_disk_lock(c))
2570 return -1;
794dd120 2571
33ad9f1a 2572 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
794dd120 2573
3bc449ed 2574 container_disk_unlock(c);
794dd120
SH
2575 return ret;
2576}
2577
858377e4
SH
2578WRAP_API_3(int, lxcapi_get_cgroup_item, const char *, char *, int)
2579
593e8478 2580const char *lxc_get_global_config_item(const char *key)
83c98d82 2581{
593e8478 2582 return lxc_global_config_value(key);
a8428dfa
SH
2583}
2584
b6b918a1
SG
2585const char *lxc_get_version(void)
2586{
95ee490b 2587 return LXC_VERSION;
b6b918a1
SG
2588}
2589
f0ca2726 2590static int copy_file(const char *old, const char *new)
9be53773
SH
2591{
2592 int in, out;
2593 ssize_t len, ret;
2594 char buf[8096];
2595 struct stat sbuf;
2596
2597 if (file_exists(new)) {
2598 ERROR("copy destination %s exists", new);
2599 return -1;
2600 }
2601 ret = stat(old, &sbuf);
2602 if (ret < 0) {
dfb31b25 2603 INFO("Error stat'ing %s", old);
9be53773
SH
2604 return -1;
2605 }
2606
2607 in = open(old, O_RDONLY);
2608 if (in < 0) {
dfb31b25 2609 SYSERROR("Error opening original file %s", old);
9be53773
SH
2610 return -1;
2611 }
2612 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
2613 if (out < 0) {
dfb31b25 2614 SYSERROR("Error opening new file %s", new);
9be53773
SH
2615 close(in);
2616 return -1;
2617 }
2618
2619 while (1) {
2620 len = read(in, buf, 8096);
2621 if (len < 0) {
dfb31b25 2622 SYSERROR("Error reading old file %s", old);
9be53773
SH
2623 goto err;
2624 }
2625 if (len == 0)
2626 break;
2627 ret = write(out, buf, len);
6849cb5b 2628 if (ret < len) { // should we retry?
dfb31b25 2629 SYSERROR("Error: write to new file %s was interrupted", new);
9be53773
SH
2630 goto err;
2631 }
2632 }
2633 close(in);
2634 close(out);
2635
2636 // we set mode, but not owner/group
2637 ret = chmod(new, sbuf.st_mode);
2638 if (ret) {
dfb31b25 2639 SYSERROR("Error setting mode on %s", new);
9be53773
SH
2640 return -1;
2641 }
2642
2643 return 0;
2644
2645err:
2646 close(in);
2647 close(out);
2648 return -1;
2649}
2650
9be53773
SH
2651static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2652{
619256b5 2653 int i, len, ret;
9be53773 2654 struct lxc_list *it;
619256b5
ÇO
2655 char *cpath;
2656
2657 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
2658 cpath = alloca(len);
2659 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
2660 if (ret < 0 || ret >= len)
2661 return -1;
9be53773
SH
2662
2663 for (i=0; i<NUM_LXC_HOOKS; i++) {
2664 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2665 char *hookname = it->elem;
c32981c3 2666 char *fname = strrchr(hookname, '/');
9be53773
SH
2667 char tmppath[MAXPATHLEN];
2668 if (!fname) // relative path - we don't support, but maybe we should
2669 return 0;
619256b5
ÇO
2670 if (strncmp(hookname, cpath, len - 1) != 0) {
2671 // this hook is public - ignore
2672 continue;
2673 }
9be53773
SH
2674 // copy the script, and change the entry in confile
2675 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2676 c->config_path, c->name, fname+1);
2677 if (ret < 0 || ret >= MAXPATHLEN)
2678 return -1;
2679 ret = copy_file(it->elem, tmppath);
2680 if (ret < 0)
2681 return -1;
2682 free(it->elem);
2683 it->elem = strdup(tmppath);
2684 if (!it->elem) {
2685 ERROR("out of memory copying hook path");
2686 return -1;
2687 }
9be53773
SH
2688 }
2689 }
2690
67702c21
SH
2691 if (!clone_update_unexp_hooks(c->lxc_conf, oldc->config_path,
2692 c->config_path, oldc->name, c->name)) {
6b0d5538
SH
2693 ERROR("Error saving new hooks in clone");
2694 return -1;
2695 }
858377e4 2696 do_lxcapi_save_config(c, NULL);
9be53773
SH
2697 return 0;
2698}
2699
9be53773
SH
2700
2701static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2702{
2703 char newpath[MAXPATHLEN];
2704 char *oldpath = oldc->lxc_conf->fstab;
2705 int ret;
2706
2707 if (!oldpath)
2708 return 0;
2709
6b0d5538
SH
2710 clear_unexp_config_line(c->lxc_conf, "lxc.mount", false);
2711
c32981c3 2712 char *p = strrchr(oldpath, '/');
9be53773
SH
2713 if (!p)
2714 return -1;
2715 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2716 c->config_path, c->name, p);
2717 if (ret < 0 || ret >= MAXPATHLEN) {
2718 ERROR("error printing new path for %s", oldpath);
2719 return -1;
2720 }
2721 if (file_exists(newpath)) {
2722 ERROR("error: fstab file %s exists", newpath);
2723 return -1;
2724 }
2725
2726 if (copy_file(oldpath, newpath) < 0) {
2727 ERROR("error: copying %s to %s", oldpath, newpath);
2728 return -1;
2729 }
2730 free(c->lxc_conf->fstab);
2731 c->lxc_conf->fstab = strdup(newpath);
2732 if (!c->lxc_conf->fstab) {
2733 ERROR("error: allocating pathname");
2734 return -1;
2735 }
6b0d5538
SH
2736 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.mount", newpath)) {
2737 ERROR("error saving new lxctab");
2738 return -1;
2739 }
9be53773
SH
2740
2741 return 0;
2742}
2743
dfb31b25
SH
2744static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2745{
2746 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2747 int ret;
2748
2749 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2750 c0->name);
2751 if (ret < 0 || ret >= MAXPATHLEN) {
2752 WARN("Error copying reverse dependencies");
2753 return;
2754 }
2755 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2756 c->name);
2757 if (ret < 0 || ret >= MAXPATHLEN) {
2758 WARN("Error copying reverse dependencies");
2759 return;
2760 }
2761 if (copy_file(path0, path1) < 0) {
2762 INFO("Error copying reverse dependencies");
2763 return;
2764 }
2765}
2766
2767static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2768{
2769 int ret;
2770 char path[MAXPATHLEN];
2771 FILE *f;
2772 bool bret;
2773
2774 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2775 c->name);
2776 if (ret < 0 || ret >= MAXPATHLEN)
2777 return false;
2778 f = fopen(path, "a");
2779 if (!f)
2780 return false;
2781 bret = true;
2782 // if anything goes wrong, just return an error
2783 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2784 bret = false;
2785 if (fclose(f) != 0)
2786 bret = false;
2787 return bret;
2788}
2789
9be53773 2790static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
d659597e 2791 const char *newtype, int flags, const char *bdevdata, uint64_t newsize)
9be53773
SH
2792{
2793 struct bdev *bdev;
dfb31b25 2794 int need_rdep;
9be53773 2795
1354955b 2796 bdev = bdev_copy(c0, c->name, c->config_path, newtype, flags,
dfb31b25 2797 bdevdata, newsize, &need_rdep);
9be53773 2798 if (!bdev) {
dfb31b25 2799 ERROR("Error copying storage");
9be53773
SH
2800 return -1;
2801 }
2802 free(c->lxc_conf->rootfs.path);
2803 c->lxc_conf->rootfs.path = strdup(bdev->src);
2804 bdev_put(bdev);
dfb31b25
SH
2805 if (!c->lxc_conf->rootfs.path) {
2806 ERROR("Out of memory while setting storage path");
9be53773 2807 return -1;
dfb31b25 2808 }
6b0d5538
SH
2809 // We will simply append a new lxc.rootfs entry to the unexpanded config
2810 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs", false);
2811 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs", c->lxc_conf->rootfs.path)) {
222dc581 2812 ERROR("Error saving new rootfs to cloned config");
d0218321
SH
2813 return -1;
2814 }
eee59f94
SH
2815 if (flags & LXC_CLONE_SNAPSHOT)
2816 copy_rdepends(c, c0);
dfb31b25
SH
2817 if (need_rdep) {
2818 if (!add_rdepends(c, c0))
2819 WARN("Error adding reverse dependency from %s to %s",
2820 c->name, c0->name);
2821 }
2822
2823 mod_all_rdeps(c, true);
2824
9be53773
SH
2825 return 0;
2826}
2827
1354955b
SH
2828struct clone_update_data {
2829 struct lxc_container *c0;
2830 struct lxc_container *c1;
2831 int flags;
2832 char **hookargs;
2833};
2834
2835static int clone_update_rootfs(struct clone_update_data *data)
9be53773 2836{
1354955b
SH
2837 struct lxc_container *c0 = data->c0;
2838 struct lxc_container *c = data->c1;
2839 int flags = data->flags;
2840 char **hookargs = data->hookargs;
9be53773
SH
2841 int ret = -1;
2842 char path[MAXPATHLEN];
2843 struct bdev *bdev;
2844 FILE *fout;
148e91f5 2845 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
2846
2847 /* update hostname in rootfs */
2848 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2849
1354955b
SH
2850 if (setgid(0) < 0) {
2851 ERROR("Failed to setgid to 0");
2852 return -1;
2853 }
2854 if (setuid(0) < 0) {
2855 ERROR("Failed to setuid to 0");
9be53773 2856 return -1;
1354955b 2857 }
c476bdce
SH
2858 if (setgroups(0, NULL) < 0)
2859 WARN("Failed to clear groups");
9be53773 2860
1354955b
SH
2861 if (unshare(CLONE_NEWNS) < 0)
2862 return -1;
76a26f55 2863 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
9be53773 2864 if (!bdev)
1354955b 2865 return -1;
cf3ef16d
SH
2866 if (strcmp(bdev->type, "dir") != 0) {
2867 if (unshare(CLONE_NEWNS) < 0) {
2868 ERROR("error unsharing mounts");
e7de366c 2869 bdev_put(bdev);
1354955b 2870 return -1;
cf3ef16d 2871 }
2c6f3fc9
SH
2872 if (detect_shared_rootfs()) {
2873 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
2874 SYSERROR("Failed to make / rslave");
2875 ERROR("Continuing...");
2876 }
2877 }
e7de366c
SG
2878 if (bdev->ops->mount(bdev) < 0) {
2879 bdev_put(bdev);
1354955b 2880 return -1;
e7de366c 2881 }
cf3ef16d 2882 } else { // TODO come up with a better way
f10fad2f 2883 free(bdev->dest);
cf3ef16d
SH
2884 bdev->dest = strdup(bdev->src);
2885 }
148e91f5
SH
2886
2887 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2888 /* Start of environment variable setup for hooks */
ab7efcf5 2889 if (c0->name && setenv("LXC_SRC_NAME", c0->name, 1)) {
1143ed39
DE
2890 SYSERROR("failed to set environment variable for source container name");
2891 }
ab7efcf5 2892 if (c->name && setenv("LXC_NAME", c->name, 1)) {
148e91f5
SH
2893 SYSERROR("failed to set environment variable for container name");
2894 }
ab7efcf5 2895 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
148e91f5
SH
2896 SYSERROR("failed to set environment variable for config path");
2897 }
ab7efcf5 2898 if (bdev->dest && setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1)) {
148e91f5
SH
2899 SYSERROR("failed to set environment variable for rootfs mount");
2900 }
ab7efcf5 2901 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
148e91f5
SH
2902 SYSERROR("failed to set environment variable for rootfs mount");
2903 }
2904
283678ed 2905 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
148e91f5 2906 ERROR("Error executing clone hook for %s", c->name);
e7de366c 2907 bdev_put(bdev);
1354955b 2908 return -1;
148e91f5
SH
2909 }
2910 }
2911
2912 if (!(flags & LXC_CLONE_KEEPNAME)) {
2913 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
e7de366c
SG
2914 bdev_put(bdev);
2915
148e91f5 2916 if (ret < 0 || ret >= MAXPATHLEN)
1354955b 2917 return -1;
8058be39 2918 if (!file_exists(path))
1354955b 2919 return 0;
148e91f5 2920 if (!(fout = fopen(path, "w"))) {
959aee9c 2921 SYSERROR("unable to open %s: ignoring", path);
1354955b 2922 return 0;
148e91f5 2923 }
a684f0b7
ÇO
2924 if (fprintf(fout, "%s", c->name) < 0) {
2925 fclose(fout);
1354955b 2926 return -1;
6849cb5b 2927 }
148e91f5 2928 if (fclose(fout) < 0)
1354955b 2929 return -1;
9be53773 2930 }
e7de366c
SG
2931 else
2932 bdev_put(bdev);
2933
1354955b
SH
2934 return 0;
2935}
2936
2937static int clone_update_rootfs_wrapper(void *data)
2938{
2939 struct clone_update_data *arg = (struct clone_update_data *) data;
2940 return clone_update_rootfs(arg);
9be53773
SH
2941}
2942
2943/*
2944 * We want to support:
2945sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2946 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2947
2948-s [ implies overlayfs]
2949-s -B overlayfs
2950-s -B aufs
2951
2952only rootfs gets converted (copied/snapshotted) on clone.
2953*/
2954
d5752559 2955static int create_file_dirname(char *path, struct lxc_conf *conf)
9be53773 2956{
c32981c3 2957 char *p = strrchr(path, '/');
d5752559 2958 int ret = -1;
9be53773
SH
2959
2960 if (!p)
2961 return -1;
2962 *p = '\0';
d028235d 2963 ret = do_create_container_dir(path, conf);
9be53773
SH
2964 *p = '/';
2965 return ret;
2966}
2967
030ce9a9
CB
2968/* When we clone a container with overlay lxc.mount.entry entries we need to
2969* update absolute paths for upper- and workdir. This update is done in two
2970* locations: lxc_conf->unexpanded_config and lxc_conf->mount_list. Both updates
2971* are done independent of each other since lxc_conf->mountlist may container
2972* more mount entries (e.g. from other included files) than
2973* lxc_conf->unexpanded_config . */
2974static int update_ovl_paths(struct lxc_conf *lxc_conf, const char *lxc_path,
2975 const char *lxc_name, const char *newpath,
2976 const char *newname)
2977{
2978 char new_upper[MAXPATHLEN];
2979 char new_work[MAXPATHLEN];
2980 char old_upper[MAXPATHLEN];
2981 char old_work[MAXPATHLEN];
2982 char *cleanpath = NULL;
2983 int i;
2984 int fret = -1;
2985 int ret = 0;
2986 struct lxc_list *iterator;
2987 const char *ovl_dirs[] = {"br", "upperdir", "workdir"};
2988
2989 cleanpath = strdup(newpath);
2990 if (!cleanpath)
2991 goto err;
2992
2993 remove_trailing_slashes(cleanpath);
2994
2995 /* We have to update lxc_conf->unexpanded_config separately from
2996 * lxc_conf->mount_list. */
2997 for (i = 0; i < sizeof(ovl_dirs) / sizeof(ovl_dirs[0]); i++) {
2998 if (!clone_update_unexp_ovl_paths(lxc_conf, lxc_path, newpath,
2999 lxc_name, newname,
3000 ovl_dirs[i]))
3001 goto err;
3002 }
3003
3004 ret = snprintf(old_work, MAXPATHLEN, "workdir=%s/%s", lxc_path, lxc_name);
3005 if (ret < 0 || ret >= MAXPATHLEN)
3006 goto err;
3007
3008 ret = snprintf(new_work, MAXPATHLEN, "workdir=%s/%s", cleanpath, newname);
3009 if (ret < 0 || ret >= MAXPATHLEN)
3010 goto err;
3011
3012 lxc_list_for_each(iterator, &lxc_conf->mount_list) {
3013 char *mnt_entry = NULL;
3014 char *new_mnt_entry = NULL;
3015 char *tmp = NULL;
3016 char *tmp_mnt_entry = NULL;
3017 mnt_entry = iterator->elem;
3018
3019 if (strstr(mnt_entry, "overlay"))
3020 tmp = "upperdir";
3021 else if (strstr(mnt_entry, "aufs"))
3022 tmp = "br";
3023
3024 if (!tmp)
3025 continue;
3026
3027 ret = snprintf(old_upper, MAXPATHLEN, "%s=%s/%s", tmp, lxc_path, lxc_name);
3028 if (ret < 0 || ret >= MAXPATHLEN)
3029 goto err;
3030
3031 ret = snprintf(new_upper, MAXPATHLEN, "%s=%s/%s", tmp, cleanpath, newname);
3032 if (ret < 0 || ret >= MAXPATHLEN)
3033 goto err;
3034
3035 if (strstr(mnt_entry, old_upper)) {
3036 tmp_mnt_entry = lxc_string_replace(old_upper, new_upper, mnt_entry);
3037 }
3038
3039 if (strstr(mnt_entry, old_work)) {
3040 if (tmp_mnt_entry)
3041 new_mnt_entry = lxc_string_replace(old_work, new_work, tmp_mnt_entry);
3042 else
3043 new_mnt_entry = lxc_string_replace(old_work, new_work, mnt_entry);
3044 }
3045
3046 if (new_mnt_entry) {
3047 free(iterator->elem);
3048 iterator->elem = strdup(new_mnt_entry);
3049 } else if (tmp_mnt_entry) {
3050 free(iterator->elem);
3051 iterator->elem = strdup(tmp_mnt_entry);
3052 }
3053
3054 free(new_mnt_entry);
3055 free(tmp_mnt_entry);
3056 }
3057
3058 fret = 0;
3059err:
3060 free(cleanpath);
3061 return fret;
3062}
3063
858377e4 3064static struct lxc_container *do_lxcapi_clone(struct lxc_container *c, const char *newname,
9be53773 3065 const char *lxcpath, int flags,
d659597e 3066 const char *bdevtype, const char *bdevdata, uint64_t newsize,
148e91f5 3067 char **hookargs)
9be53773
SH
3068{
3069 struct lxc_container *c2 = NULL;
3070 char newpath[MAXPATHLEN];
176d9acb 3071 int ret, storage_copied = 0;
5eea90e8 3072 char *origroot = NULL, *saved_unexp_conf = NULL;
1354955b 3073 struct clone_update_data data;
3b392519 3074 size_t saved_unexp_len;
9be53773 3075 FILE *fout;
1354955b 3076 pid_t pid;
9be53773 3077
858377e4 3078 if (!c || !do_lxcapi_is_defined(c))
9be53773
SH
3079 return NULL;
3080
5cee8c50 3081 if (container_mem_lock(c))
9be53773
SH
3082 return NULL;
3083
39dc698c 3084 if (!is_stopped(c)) {
9be53773
SH
3085 ERROR("error: Original container (%s) is running", c->name);
3086 goto out;
3087 }
3088
3089 // Make sure the container doesn't yet exist.
05d53f4c
SH
3090 if (!newname)
3091 newname = c->name;
3092 if (!lxcpath)
858377e4 3093 lxcpath = do_lxcapi_get_config_path(c);
05d53f4c 3094 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", lxcpath, newname);
6849cb5b 3095 if (ret < 0 || ret >= MAXPATHLEN) {
9be53773
SH
3096 SYSERROR("clone: failed making config pathname");
3097 goto out;
3098 }
3099 if (file_exists(newpath)) {
3100 ERROR("error: clone: %s exists", newpath);
3101 goto out;
3102 }
3103
d5752559 3104 ret = create_file_dirname(newpath, c->lxc_conf);
96532523 3105 if (ret < 0 && errno != EEXIST) {
9be53773
SH
3106 ERROR("Error creating container dir for %s", newpath);
3107 goto out;
3108 }
3109
3110 // copy the configuration, tweak it as needed,
8d2efe40
SH
3111 if (c->lxc_conf->rootfs.path) {
3112 origroot = c->lxc_conf->rootfs.path;
3113 c->lxc_conf->rootfs.path = NULL;
3114 }
9be53773
SH
3115 fout = fopen(newpath, "w");
3116 if (!fout) {
3117 SYSERROR("open %s", newpath);
3118 goto out;
3119 }
5eea90e8
SH
3120
3121 saved_unexp_conf = c->lxc_conf->unexpanded_config;
3b392519 3122 saved_unexp_len = c->lxc_conf->unexpanded_len;
5eea90e8
SH
3123 c->lxc_conf->unexpanded_config = strdup(saved_unexp_conf);
3124 if (!c->lxc_conf->unexpanded_config) {
3125 ERROR("Out of memory");
3126 goto out;
3127 }
3128 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs", false);
6b0d5538 3129 write_config(fout, c->lxc_conf);
9be53773 3130 fclose(fout);
8d2efe40 3131 c->lxc_conf->rootfs.path = origroot;
5eea90e8
SH
3132 free(c->lxc_conf->unexpanded_config);
3133 c->lxc_conf->unexpanded_config = saved_unexp_conf;
3134 saved_unexp_conf = NULL;
3b392519 3135 c->lxc_conf->unexpanded_len = saved_unexp_len;
9be53773 3136
05d53f4c 3137 sprintf(newpath, "%s/%s/rootfs", lxcpath, newname);
9be53773
SH
3138 if (mkdir(newpath, 0755) < 0) {
3139 SYSERROR("error creating %s", newpath);
3140 goto out;
3141 }
3142
1354955b
SH
3143 if (am_unpriv()) {
3144 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
959aee9c 3145 ERROR("Error chowning %s to container root", newpath);
1354955b
SH
3146 goto out;
3147 }
3148 }
3149
05d53f4c 3150 c2 = lxc_container_new(newname, lxcpath);
375c2258 3151 if (!c2) {
05d53f4c
SH
3152 ERROR("clone: failed to create new container (%s %s)", newname,
3153 lxcpath);
9be53773
SH
3154 goto out;
3155 }
8d2efe40
SH
3156
3157 // copy/snapshot rootfs's
3158 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
3159 if (ret < 0)
3160 goto out;
9be53773 3161
6b0d5538 3162
96532523 3163 // update utsname
3d7ad474
CB
3164 if (!(flags & LXC_CLONE_KEEPNAME)) {
3165 clear_unexp_config_line(c2->lxc_conf, "lxc.utsname", false);
3166
3167 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
3168 ERROR("Error setting new hostname");
3169 goto out;
3170 }
96532523
SH
3171 }
3172
619256b5
ÇO
3173 // copy hooks
3174 ret = copyhooks(c, c2);
3175 if (ret < 0) {
3176 ERROR("error copying hooks");
3177 goto out;
9be53773
SH
3178 }
3179
3180 if (copy_fstab(c, c2) < 0) {
3181 ERROR("error copying fstab");
9be53773
SH
3182 goto out;
3183 }
3184
3185 // update macaddrs
6b0d5538 3186 if (!(flags & LXC_CLONE_KEEPMACADDR)) {
67702c21
SH
3187 if (!network_new_hwaddrs(c2->lxc_conf)) {
3188 ERROR("Error updating mac addresses");
6b0d5538
SH
3189 goto out;
3190 }
3191 }
9be53773 3192
030ce9a9
CB
3193 // update absolute paths for overlay mount directories
3194 if (update_ovl_paths(c2->lxc_conf, c->config_path, c->name, lxcpath, newname) < 0)
3195 goto out;
3196
176d9acb
SH
3197 // We've now successfully created c2's storage, so clear it out if we
3198 // fail after this
3199 storage_copied = 1;
3200
375c2258 3201 if (!c2->save_config(c2, NULL))
9be53773 3202 goto out;
9be53773 3203
1354955b
SH
3204 if ((pid = fork()) < 0) {
3205 SYSERROR("fork");
9be53773 3206 goto out;
1354955b
SH
3207 }
3208 if (pid > 0) {
3209 ret = wait_for_pid(pid);
3210 if (ret)
3211 goto out;
3212 container_mem_unlock(c);
3213 return c2;
3214 }
3215 data.c0 = c;
3216 data.c1 = c2;
3217 data.flags = flags;
3218 data.hookargs = hookargs;
3219 if (am_unpriv())
3220 ret = userns_exec_1(c->lxc_conf, clone_update_rootfs_wrapper,
3221 &data);
3222 else
3223 ret = clone_update_rootfs(&data);
3224 if (ret < 0)
3225 exit(1);
9be53773 3226
5cee8c50 3227 container_mem_unlock(c);
1354955b 3228 exit(0);
9be53773
SH
3229
3230out:
5cee8c50 3231 container_mem_unlock(c);
375c2258 3232 if (c2) {
176d9acb
SH
3233 if (!storage_copied)
3234 c2->lxc_conf->rootfs.path = NULL;
375c2258 3235 c2->destroy(c2);
9be53773 3236 lxc_container_put(c2);
375c2258 3237 }
9be53773
SH
3238
3239 return NULL;
3240}
3241
858377e4
SH
3242static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
3243 const char *lxcpath, int flags,
3244 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3245 char **hookargs)
3246{
3247 struct lxc_container * ret;
3248 current_config = c ? c->lxc_conf : NULL;
3249 ret = do_lxcapi_clone(c, newname, lxcpath, flags, bdevtype, bdevdata, newsize, hookargs);
3250 current_config = NULL;
3251 return ret;
3252}
3253
3254static bool do_lxcapi_rename(struct lxc_container *c, const char *newname)
06e5650e
ÇO
3255{
3256 struct bdev *bdev;
3257 struct lxc_container *newc;
06e5650e 3258
d693cf93 3259 if (!c || !c->name || !c->config_path || !c->lxc_conf)
06e5650e
ÇO
3260 return false;
3261
18aa217b
SH
3262 if (has_fs_snapshots(c) || has_snapshots(c)) {
3263 ERROR("Renaming a container with snapshots is not supported");
3264 return false;
3265 }
76a26f55 3266 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
06e5650e
ÇO
3267 if (!bdev) {
3268 ERROR("Failed to find original backing store type");
3269 return false;
3270 }
3271
619256b5 3272 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
06e5650e
ÇO
3273 bdev_put(bdev);
3274 if (!newc) {
3275 lxc_container_put(newc);
3276 return false;
3277 }
3278
3279 if (newc && lxcapi_is_defined(newc))
3280 lxc_container_put(newc);
3281
18aa217b 3282 if (!container_destroy(c)) {
06e5650e
ÇO
3283 ERROR("Could not destroy existing container %s", c->name);
3284 return false;
3285 }
3286 return true;
3287}
3288
858377e4
SH
3289WRAP_API_1(bool, lxcapi_rename, const char *)
3290
a0e93eeb
CS
3291static 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)
3292{
858377e4
SH
3293 int ret;
3294
a0e93eeb
CS
3295 if (!c)
3296 return -1;
3297
858377e4
SH
3298 current_config = c->lxc_conf;
3299
3300 ret = lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
3301 current_config = NULL;
3302 return ret;
a0e93eeb
CS
3303}
3304
858377e4 3305static int do_lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
a0e93eeb
CS
3306{
3307 lxc_attach_command_t command;
3308 pid_t pid;
3309 int r;
3310
3311 if (!c)
3312 return -1;
3313
3314 command.program = (char*)program;
3315 command.argv = (char**)argv;
3316 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
3317 if (r < 0) {
3318 ERROR("ups");
3319 return r;
3320 }
3321 return lxc_wait_for_pid_status(pid);
3322}
3323
858377e4
SH
3324static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
3325{
3326 int ret;
3327 current_config = c ? c->lxc_conf : NULL;
3328 ret = do_lxcapi_attach_run_wait(c, options, program, argv);
3329 current_config = NULL;
3330 return ret;
3331}
3332
74a3920a 3333static int get_next_index(const char *lxcpath, char *cname)
f5dd1d53
SH
3334{
3335 char *fname;
3336 struct stat sb;
3337 int i = 0, ret;
3338
3339 fname = alloca(strlen(lxcpath) + 20);
3340 while (1) {
3341 sprintf(fname, "%s/snap%d", lxcpath, i);
3342 ret = stat(fname, &sb);
3343 if (ret != 0)
3344 return i;
3345 i++;
3346 }
3347}
3348
18aa217b
SH
3349static bool get_snappath_dir(struct lxc_container *c, char *snappath)
3350{
3351 int ret;
3352 /*
3353 * If the old style snapshot path exists, use it
3354 * /var/lib/lxc -> /var/lib/lxcsnaps
3355 */
3356 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps", c->config_path);
3357 if (ret < 0 || ret >= MAXPATHLEN)
3358 return false;
3359 if (dir_exists(snappath)) {
3360 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
3361 if (ret < 0 || ret >= MAXPATHLEN)
3362 return false;
3363 return true;
3364 }
3365
3366 /*
3367 * Use the new style path
3368 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3369 */
3370 ret = snprintf(snappath, MAXPATHLEN, "%s/%s/snaps", c->config_path, c->name);
3371 if (ret < 0 || ret >= MAXPATHLEN)
3372 return false;
3373 return true;
3374}
3375
858377e4 3376static int do_lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
f5dd1d53
SH
3377{
3378 int i, flags, ret;
3379 struct lxc_container *c2;
3380 char snappath[MAXPATHLEN], newname[20];
3381
840f05df
SH
3382 if (!c || !lxcapi_is_defined(c))
3383 return -1;
3384
cdd01be2
SH
3385 if (!bdev_can_backup(c->lxc_conf)) {
3386 ERROR("%s's backing store cannot be backed up.", c->name);
3387 ERROR("Your container must use another backing store type.");
3388 return -1;
3389 }
3390
18aa217b 3391 if (!get_snappath_dir(c, snappath))
f5dd1d53 3392 return -1;
18aa217b 3393
f5dd1d53
SH
3394 i = get_next_index(snappath, c->name);
3395
3396 if (mkdir_p(snappath, 0755) < 0) {
3397 ERROR("Failed to create snapshot directory %s", snappath);
3398 return -1;
3399 }
3400
3401 ret = snprintf(newname, 20, "snap%d", i);
3402 if (ret < 0 || ret >= 20)
3403 return -1;
3404
0a83cbbb
SH
3405 /*
3406 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3407 * created in the original container
3408 */
3409 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
3410 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
76a26f55 3411 if (bdev_is_dir(c->lxc_conf, c->lxc_conf->rootfs.path)) {
8c39f7a4
SH
3412 ERROR("Snapshot of directory-backed container requested.");
3413 ERROR("Making a copy-clone. If you do want snapshots, then");
1f92162d 3414 ERROR("please create an aufs or overlayfs clone first, snapshot that");
8c39f7a4
SH
3415 ERROR("and keep the original container pristine.");
3416 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3417 }
858377e4 3418 c2 = do_lxcapi_clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
f5dd1d53 3419 if (!c2) {
959aee9c 3420 ERROR("clone of %s:%s failed", c->config_path, c->name);
f5dd1d53
SH
3421 return -1;
3422 }
3423
3424 lxc_container_put(c2);
3425
3426 // Now write down the creation time
3427 time_t timer;
3428 char buffer[25];
3429 struct tm* tm_info;
025ed0f3 3430 FILE *f;
f5dd1d53
SH
3431
3432 time(&timer);
3433 tm_info = localtime(&timer);
3434
3435 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
3436
3437 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
3438 sprintf(dfnam, "%s/%s/ts", snappath, newname);
025ed0f3 3439 f = fopen(dfnam, "w");
f5dd1d53 3440 if (!f) {
959aee9c 3441 ERROR("Failed to open %s", dfnam);
f5dd1d53
SH
3442 return -1;
3443 }
3444 if (fprintf(f, "%s", buffer) < 0) {
3445 SYSERROR("Writing timestamp");
3446 fclose(f);
3447 return -1;
3448 }
025ed0f3 3449 ret = fclose(f);
025ed0f3 3450 if (ret != 0) {
f5dd1d53
SH
3451 SYSERROR("Writing timestamp");
3452 return -1;
3453 }
3454
3455 if (commentfile) {
3456 // $p / $name / comment \0
3457 int len = strlen(snappath) + strlen(newname) + 10;
3458 char *path = alloca(len);
3459 sprintf(path, "%s/%s/comment", snappath, newname);
3460 return copy_file(commentfile, path) < 0 ? -1 : i;
3461 }
3462
3463 return i;
3464}
3465
858377e4
SH
3466WRAP_API_1(int, lxcapi_snapshot, const char *)
3467
f5dd1d53
SH
3468static void lxcsnap_free(struct lxc_snapshot *s)
3469{
f10fad2f
ME
3470 free(s->name);
3471 free(s->comment_pathname);
3472 free(s->timestamp);
3473 free(s->lxcpath);
f5dd1d53
SH
3474}
3475
3476static char *get_snapcomment_path(char* snappath, char *name)
3477{
3478 // $snappath/$name/comment
3479 int ret, len = strlen(snappath) + strlen(name) + 10;
3480 char *s = malloc(len);
3481
3482 if (s) {
3483 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
3484 if (ret < 0 || ret >= len) {
3485 free(s);
3486 s = NULL;
3487 }
3488 }
3489 return s;
3490}
3491
3492static char *get_timestamp(char* snappath, char *name)
3493{
3494 char path[MAXPATHLEN], *s = NULL;
3495 int ret, len;
3496 FILE *fin;
3497
3498 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
3499 if (ret < 0 || ret >= MAXPATHLEN)
3500 return NULL;
025ed0f3 3501 fin = fopen(path, "r");
025ed0f3 3502 if (!fin)
f5dd1d53
SH
3503 return NULL;
3504 (void) fseek(fin, 0, SEEK_END);
3505 len = ftell(fin);
3506 (void) fseek(fin, 0, SEEK_SET);
3507 if (len > 0) {
3508 s = malloc(len+1);
3509 if (s) {
3510 s[len] = '\0';
3511 if (fread(s, 1, len, fin) != len) {
3512 SYSERROR("reading timestamp");
3513 free(s);
3514 s = NULL;
3515 }
3516 }
3517 }
3518 fclose(fin);
3519 return s;
3520}
3521
858377e4 3522static int do_lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
f5dd1d53
SH
3523{
3524 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
18aa217b 3525 int count = 0, ret;
f5dd1d53
SH
3526 struct dirent dirent, *direntp;
3527 struct lxc_snapshot *snaps =NULL, *nsnaps;
3528 DIR *dir;
3529
3530 if (!c || !lxcapi_is_defined(c))
3531 return -1;
c868b261 3532
18aa217b 3533 if (!get_snappath_dir(c, snappath)) {
f5dd1d53
SH
3534 ERROR("path name too long");
3535 return -1;
3536 }
025ed0f3 3537 dir = opendir(snappath);
025ed0f3 3538 if (!dir) {
f5dd1d53
SH
3539 INFO("failed to open %s - assuming no snapshots", snappath);
3540 return 0;
3541 }
3542
3543 while (!readdir_r(dir, &dirent, &direntp)) {
3544 if (!direntp)
3545 break;
3546
3547 if (!strcmp(direntp->d_name, "."))
3548 continue;
3549
3550 if (!strcmp(direntp->d_name, ".."))
3551 continue;
3552
3553 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
3554 if (ret < 0 || ret >= MAXPATHLEN) {
3555 ERROR("pathname too long");
3556 goto out_free;
3557 }
3558 if (!file_exists(path2))
3559 continue;
3560 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
3561 if (!nsnaps) {
3562 SYSERROR("Out of memory");
3563 goto out_free;
3564 }
3565 snaps = nsnaps;
3566 snaps[count].free = lxcsnap_free;
3567 snaps[count].name = strdup(direntp->d_name);
3568 if (!snaps[count].name)
3569 goto out_free;
3570 snaps[count].lxcpath = strdup(snappath);
3571 if (!snaps[count].lxcpath) {
3572 free(snaps[count].name);
3573 goto out_free;
3574 }
3575 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
3576 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
3577 count++;
3578 }
3579
3580 if (closedir(dir))
3581 WARN("failed to close directory");
3582
3583 *ret_snaps = snaps;
3584 return count;
3585
3586out_free:
3587 if (snaps) {
3588 int i;
3589 for (i=0; i<count; i++)
3590 lxcsnap_free(&snaps[i]);
3591 free(snaps);
3592 }
9baa57bd
SH
3593 if (closedir(dir))
3594 WARN("failed to close directory");
f5dd1d53
SH
3595 return -1;
3596}
3597
858377e4
SH
3598WRAP_API_1(int, lxcapi_snapshot_list, struct lxc_snapshot **)
3599
3600static bool do_lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
f5dd1d53
SH
3601{
3602 char clonelxcpath[MAXPATHLEN];
18aa217b 3603 int flags = 0;
f5dd1d53
SH
3604 struct lxc_container *snap, *rest;
3605 struct bdev *bdev;
3606 bool b = false;
3607
3608 if (!c || !c->name || !c->config_path)
3609 return false;
3610
18aa217b
SH
3611 if (has_fs_snapshots(c)) {
3612 ERROR("container rootfs has dependent snapshots");
3613 return false;
3614 }
3615
76a26f55 3616 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
f5dd1d53
SH
3617 if (!bdev) {
3618 ERROR("Failed to find original backing store type");
3619 return false;
3620 }
3621
3622 if (!newname)
3623 newname = c->name;
7e36f87e 3624
18aa217b 3625 if (!get_snappath_dir(c, clonelxcpath)) {
f5dd1d53
SH
3626 bdev_put(bdev);
3627 return false;
3628 }
3629 // how should we lock this?
3630
3631 snap = lxc_container_new(snapname, clonelxcpath);
3632 if (!snap || !lxcapi_is_defined(snap)) {
3633 ERROR("Could not open snapshot %s", snapname);
3634 if (snap) lxc_container_put(snap);
3635 bdev_put(bdev);
3636 return false;
3637 }
3638
7e36f87e 3639 if (strcmp(c->name, newname) == 0) {
18aa217b 3640 if (!container_destroy(c)) {
7e36f87e
ÇO
3641 ERROR("Could not destroy existing container %s", newname);
3642 lxc_container_put(snap);
3643 bdev_put(bdev);
3644 return false;
3645 }
3646 }
3647
de269ee8
SH
3648 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
3649 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3650 rest = lxcapi_clone(snap, newname, c->config_path, flags,
3651 bdev->type, NULL, 0, NULL);
f5dd1d53
SH
3652 bdev_put(bdev);
3653 if (rest && lxcapi_is_defined(rest))
3654 b = true;
3655 if (rest)
3656 lxc_container_put(rest);
3657 lxc_container_put(snap);
3658 return b;
3659}
3660
858377e4
SH
3661WRAP_API_2(bool, lxcapi_snapshot_restore, const char *, const char *)
3662
18aa217b 3663static bool do_snapshot_destroy(const char *snapname, const char *clonelxcpath)
771d96b3 3664{
771d96b3 3665 struct lxc_container *snap = NULL;
18aa217b 3666 bool bret = false;
771d96b3
ÇO
3667
3668 snap = lxc_container_new(snapname, clonelxcpath);
18aa217b 3669 if (!snap) {
771d96b3
ÇO
3670 ERROR("Could not find snapshot %s", snapname);
3671 goto err;
3672 }
3673
858377e4 3674 if (!do_lxcapi_destroy(snap)) {
771d96b3
ÇO
3675 ERROR("Could not destroy snapshot %s", snapname);
3676 goto err;
3677 }
18aa217b 3678 bret = true;
771d96b3 3679
771d96b3
ÇO
3680err:
3681 if (snap)
3682 lxc_container_put(snap);
18aa217b
SH
3683 return bret;
3684}
3685
3686static bool remove_all_snapshots(const char *path)
3687{
3688 DIR *dir;
3689 struct dirent dirent, *direntp;
3690 bool bret = true;
3691
3692 dir = opendir(path);
3693 if (!dir) {
3694 SYSERROR("opendir on snapshot path %s", path);
3695 return false;
3696 }
3697 while (!readdir_r(dir, &dirent, &direntp)) {
3698 if (!direntp)
3699 break;
3700 if (!strcmp(direntp->d_name, "."))
3701 continue;
3702 if (!strcmp(direntp->d_name, ".."))
3703 continue;
3704 if (!do_snapshot_destroy(direntp->d_name, path)) {
3705 bret = false;
3706 continue;
3707 }
3708 }
3709
3710 closedir(dir);
3711
3712 if (rmdir(path))
3713 SYSERROR("Error removing directory %s", path);
3714
3715 return bret;
3716}
3717
858377e4 3718static bool do_lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
18aa217b
SH
3719{
3720 char clonelxcpath[MAXPATHLEN];
3721
3722 if (!c || !c->name || !c->config_path || !snapname)
3723 return false;
3724
3725 if (!get_snappath_dir(c, clonelxcpath))
3726 return false;
3727
3728 return do_snapshot_destroy(snapname, clonelxcpath);
3729}
3730
858377e4
SH
3731WRAP_API_1(bool, lxcapi_snapshot_destroy, const char *)
3732
3733static bool do_lxcapi_snapshot_destroy_all(struct lxc_container *c)
18aa217b
SH
3734{
3735 char clonelxcpath[MAXPATHLEN];
3736
3737 if (!c || !c->name || !c->config_path)
3738 return false;
3739
3740 if (!get_snappath_dir(c, clonelxcpath))
3741 return false;
3742
3743 return remove_all_snapshots(clonelxcpath);
771d96b3
ÇO
3744}
3745
858377e4
SH
3746WRAP_API(bool, lxcapi_snapshot_destroy_all)
3747
3748static bool do_lxcapi_may_control(struct lxc_container *c)
b494d2dd
SH
3749{
3750 return lxc_try_cmd(c->name, c->config_path) == 0;
3751}
3752
858377e4
SH
3753WRAP_API(bool, lxcapi_may_control)
3754
d5aa23e6
SH
3755static bool do_add_remove_node(pid_t init_pid, const char *path, bool add,
3756 struct stat *st)
3757{
3758 char chrootpath[MAXPATHLEN];
3759 char *directory_path = NULL;
3760 pid_t pid;
3761 int ret;
3762
3763 if ((pid = fork()) < 0) {
3764 SYSERROR("failed to fork a child helper");
3765 return false;
3766 }
3767 if (pid) {
3768 if (wait_for_pid(pid) != 0) {
3769 ERROR("Failed to create note in guest");
3770 return false;
3771 }
3772 return true;
3773 }
3774
3775 /* prepare the path */
3776 ret = snprintf(chrootpath, MAXPATHLEN, "/proc/%d/root", init_pid);
3777 if (ret < 0 || ret >= MAXPATHLEN)
3778 return false;
3779
6b9324bd 3780 if (chroot(chrootpath) < 0)
d5aa23e6 3781 exit(1);
6b9324bd 3782 if (chdir("/") < 0)
d5aa23e6
SH
3783 exit(1);
3784 /* remove path if it exists */
3785 if(faccessat(AT_FDCWD, path, F_OK, AT_SYMLINK_NOFOLLOW) == 0) {
3786 if (unlink(path) < 0) {
3787 ERROR("unlink failed");
3788 exit(1);
3789 }
3790 }
3791 if (!add)
3792 exit(0);
3793
3794 /* create any missing directories */
3795 directory_path = dirname(strdup(path));
3796 if (mkdir_p(directory_path, 0755) < 0 && errno != EEXIST) {
3797 ERROR("failed to create directory");
3798 exit(1);
3799 }
3800
3801 /* create the device node */
3802 if (mknod(path, st->st_mode, st->st_rdev) < 0) {
3803 ERROR("mknod failed");
3804 exit(1);
3805 }
3806
3807 exit(0);
3808}
3809
f0ca2726 3810static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
a9a0ed90
ÇO
3811{
3812 int ret;
3813 struct stat st;
a9a0ed90 3814 char value[MAX_BUFFER];
f0ca2726 3815 const char *p;
a9a0ed90
ÇO
3816
3817 /* make sure container is running */
858377e4 3818 if (!do_lxcapi_is_running(c)) {
a9a0ed90 3819 ERROR("container is not running");
d5aa23e6 3820 return false;
a9a0ed90
ÇO
3821 }
3822
3823 /* use src_path if dest_path is NULL otherwise use dest_path */
3824 p = dest_path ? dest_path : src_path;
3825
a9a0ed90
ÇO
3826 /* make sure we can access p */
3827 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
d5aa23e6 3828 return false;
a9a0ed90
ÇO
3829
3830 /* continue if path is character device or block device */
c6a9b0d7 3831 if (S_ISCHR(st.st_mode))
a9a0ed90 3832 ret = snprintf(value, MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
c6a9b0d7 3833 else if (S_ISBLK(st.st_mode))
a9a0ed90
ÇO
3834 ret = snprintf(value, MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
3835 else
d5aa23e6 3836 return false;
a9a0ed90
ÇO
3837
3838 /* check snprintf return code */
3839 if (ret < 0 || ret >= MAX_BUFFER)
d5aa23e6 3840 return false;
a9a0ed90 3841
858377e4 3842 if (!do_add_remove_node(do_lxcapi_init_pid(c), p, add, &st))
d5aa23e6 3843 return false;
a9a0ed90 3844
d5aa23e6 3845 /* add or remove device to/from cgroup access list */
a9a0ed90 3846 if (add) {
858377e4 3847 if (!do_lxcapi_set_cgroup_item(c, "devices.allow", value)) {
a9a0ed90 3848 ERROR("set_cgroup_item failed while adding the device node");
d5aa23e6 3849 return false;
a9a0ed90
ÇO
3850 }
3851 } else {
858377e4 3852 if (!do_lxcapi_set_cgroup_item(c, "devices.deny", value)) {
a9a0ed90 3853 ERROR("set_cgroup_item failed while removing the device node");
d5aa23e6 3854 return false;
a9a0ed90
ÇO
3855 }
3856 }
d5aa23e6 3857
a9a0ed90 3858 return true;
a9a0ed90
ÇO
3859}
3860
858377e4 3861static bool do_lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 3862{
c868b261
ÇO
3863 if (am_unpriv()) {
3864 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3865 return false;
3866 }
a9a0ed90
ÇO
3867 return add_remove_device_node(c, src_path, dest_path, true);
3868}
3869
858377e4
SH
3870WRAP_API_2(bool, lxcapi_add_device_node, const char *, const char *)
3871
3872static bool do_lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 3873{
c868b261
ÇO
3874 if (am_unpriv()) {
3875 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3876 return false;
3877 }
a9a0ed90
ÇO
3878 return add_remove_device_node(c, src_path, dest_path, false);
3879}
3880
858377e4
SH
3881WRAP_API_2(bool, lxcapi_remove_device_node, const char *, const char *)
3882
3883static bool do_lxcapi_attach_interface(struct lxc_container *c, const char *ifname,
e58fae8f
DY
3884 const char *dst_ifname)
3885{
3886 int ret = 0;
3887 if (am_unpriv()) {
3888 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3889 return false;
3890 }
3891
3892 if (!ifname) {
3893 ERROR("No source interface name given");
3894 return false;
3895 }
3896
3897 ret = lxc_netdev_isup(ifname);
e58fae8f 3898
e5848d39
SH
3899 if (ret > 0) {
3900 /* netdev of ifname is up. */
e58fae8f
DY
3901 ret = lxc_netdev_down(ifname);
3902 if (ret)
3903 goto err;
3904 }
3905
858377e4 3906 ret = lxc_netdev_move_by_name(ifname, do_lxcapi_init_pid(c), dst_ifname);
e58fae8f
DY
3907 if (ret)
3908 goto err;
3909
3910 return true;
e5848d39 3911
e58fae8f 3912err:
e58fae8f
DY
3913 return false;
3914}
3915
858377e4
SH
3916WRAP_API_2(bool, lxcapi_attach_interface, const char *, const char *)
3917
3918static bool do_lxcapi_detach_interface(struct lxc_container *c, const char *ifname,
e58fae8f
DY
3919 const char *dst_ifname)
3920{
3921 pid_t pid, pid_outside;
3922
3923 if (am_unpriv()) {
3924 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3925 return false;
3926 }
3927
3928 if (!ifname) {
3929 ERROR("No source interface name given");
3930 return false;
3931 }
3932
3933 pid_outside = getpid();
3934 pid = fork();
3935 if (pid < 0) {
3936 ERROR("failed to fork task to get interfaces information");
3937 return false;
3938 }
3939
3940 if (pid == 0) { // child
3941 int ret = 0;
e0f59189 3942 if (!enter_net_ns(c)) {
e58fae8f
DY
3943 ERROR("failed to enter namespace");
3944 exit(-1);
3945 }
3946
3947 ret = lxc_netdev_isup(ifname);
3948 if (ret < 0)
3949 exit(ret);
3950
3951 /* netdev of ifname is up. */
3952 if (ret) {
3953 ret = lxc_netdev_down(ifname);
3954 if (ret)
3955 exit(ret);
3956 }
3957
3958 ret = lxc_netdev_move_by_name(ifname, pid_outside, dst_ifname);
3959
3960 /* -EINVAL means there is no netdev named as ifanme. */
3961 if (ret == -EINVAL) {
3962 ERROR("No network device named as %s.", ifname);
3963 }
3964 exit(ret);
3965 }
3966
3967 if (wait_for_pid(pid) != 0)
3968 return false;
3969
3970 return true;
3971}
3972
858377e4
SH
3973WRAP_API_2(bool, lxcapi_detach_interface, const char *, const char *)
3974
3975static bool do_lxcapi_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose)
bbd4e13e
TA
3976{
3977 pid_t pid;
3978 int status;
85c50991 3979 char path[PATH_MAX];
bbd4e13e
TA
3980
3981 if (!criu_ok(c))
3982 return false;
3983
3984 if (mkdir(directory, 0700) < 0 && errno != EEXIST)
3985 return false;
3986
85c50991
TA
3987 status = snprintf(path, sizeof(path), "%s/inventory.img", directory);
3988 if (status < 0 || status >= sizeof(path))
3989 return false;
3990
3991 if (access(path, F_OK) == 0) {
3992 ERROR("please use a fresh directory for the dump directory\n");
3993 return false;
3994 }
3995
735f2c6e
TA
3996 pid = fork();
3997 if (pid < 0)
3998 return false;
3999
4000 if (pid == 0) {
4001 struct criu_opts os;
4002
4003 os.action = "dump";
4004 os.directory = directory;
4005 os.c = c;
4006 os.stop = stop;
4007 os.verbose = verbose;
4008
4009 /* exec_criu() returning is an error */
4010 exec_criu(&os);
4011 exit(1);
4012 } else {
4013 pid_t w = waitpid(pid, &status, 0);
4014 if (w == -1) {
3fdf4a73 4015 SYSERROR("waitpid");
735f2c6e
TA
4016 return false;
4017 }
4018
4019 if (WIFEXITED(status)) {
4020 return !WEXITSTATUS(status);
4021 }
4022
4023 return false;
4024 }
4025}
4026
858377e4
SH
4027WRAP_API_3(bool, lxcapi_checkpoint, char *, bool, bool)
4028
4029static bool do_lxcapi_restore(struct lxc_container *c, char *directory, bool verbose)
c9d8f2ee
TA
4030{
4031 pid_t pid;
4032 int status, nread;
4033 int pipefd[2];
4034
4035 if (!criu_ok(c))
4036 return false;
4037
4038 if (geteuid()) {
4039 ERROR("Must be root to restore\n");
4040 return false;
4041 }
4042
4043 if (pipe(pipefd)) {
4044 ERROR("failed to create pipe");
4045 return false;
4046 }
4047
4048 pid = fork();
4049 if (pid < 0) {
4050 close(pipefd[0]);
4051 close(pipefd[1]);
4052 return false;
4053 }
4054
4055 if (pid == 0) {
4056 close(pipefd[0]);
4057 // this never returns
4058 do_restore(c, pipefd[1], directory, verbose);
4059 }
4060
4061 close(pipefd[1]);
4062
4063 nread = read(pipefd[0], &status, sizeof(status));
4064 close(pipefd[0]);
4065 if (sizeof(status) != nread) {
4066 ERROR("reading status from pipe failed");
4067 goto err_wait;
4068 }
4069
4070 // If the criu process was killed or exited nonzero, wait() for the
4071 // handler, since the restore process died. Otherwise, we don't need to
4072 // wait, since the child becomes the monitor process.
4073 if (!WIFEXITED(status) || WEXITSTATUS(status))
4074 goto err_wait;
4075 return true;
4076
4077err_wait:
4078 if (wait_for_pid(pid))
4079 ERROR("restore process died");
4080 return false;
735f2c6e
TA
4081}
4082
858377e4
SH
4083WRAP_API_2(bool, lxcapi_restore, char *, bool)
4084
a0e93eeb
CS
4085static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
4086{
4087 va_list ap;
4088 const char **argv;
4089 int ret;
4090
4091 if (!c)
4092 return -1;
4093
858377e4
SH
4094 current_config = c->lxc_conf;
4095
a0e93eeb
CS
4096 va_start(ap, arg);
4097 argv = lxc_va_arg_list_to_argv_const(ap, 1);
4098 va_end(ap);
4099
4100 if (!argv) {
4101 ERROR("Memory allocation error.");
858377e4
SH
4102 ret = -1;
4103 goto out;
a0e93eeb
CS
4104 }
4105 argv[0] = arg;
4106
858377e4 4107 ret = do_lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
a0e93eeb 4108 free((void*)argv);
858377e4
SH
4109out:
4110 current_config = NULL;
a0e93eeb
CS
4111 return ret;
4112}
4113
afeecbba 4114struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
4115{
4116 struct lxc_container *c;
72d0e1cb 4117
18aa217b
SH
4118 if (!name)
4119 return NULL;
4120
72d0e1cb
SG
4121 c = malloc(sizeof(*c));
4122 if (!c) {
4123 fprintf(stderr, "failed to malloc lxc_container\n");
4124 return NULL;
4125 }
4126 memset(c, 0, sizeof(*c));
4127
afeecbba
SH
4128 if (configpath)
4129 c->config_path = strdup(configpath);
4130 else
593e8478 4131 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
afeecbba 4132
2a59a681 4133 if (!c->config_path) {
03fadd16 4134 fprintf(stderr, "Out of memory\n");
2a59a681
SH
4135 goto err;
4136 }
4137
f5dd1d53 4138 remove_trailing_slashes(c->config_path);
72d0e1cb
SG
4139 c->name = malloc(strlen(name)+1);
4140 if (!c->name) {
4141 fprintf(stderr, "Error allocating lxc_container name\n");
4142 goto err;
4143 }
4144 strcpy(c->name, name);
4145
4146 c->numthreads = 1;
df271a59 4147 if (!(c->slock = lxc_newlock(c->config_path, name))) {
72d0e1cb
SG
4148 fprintf(stderr, "failed to create lock\n");
4149 goto err;
4150 }
4151
df271a59 4152 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
72d0e1cb
SG
4153 fprintf(stderr, "failed to alloc privlock\n");
4154 goto err;
4155 }
4156
afeecbba 4157 if (!set_config_filename(c)) {
72d0e1cb
SG
4158 fprintf(stderr, "Error allocating config file pathname\n");
4159 goto err;
4160 }
72d0e1cb 4161
bac806d1
SH
4162 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL))
4163 goto err;
72d0e1cb 4164
3e625e2d
SH
4165 if (ongoing_create(c) == 2) {
4166 ERROR("Error: %s creation was not completed", c->name);
18aa217b 4167 container_destroy(c);
4df7f012 4168 lxcapi_clear_config(c);
3e625e2d 4169 }
a2739df5 4170 c->daemonize = true;
72cf75fa 4171 c->pidfile = NULL;
3e625e2d 4172
72d0e1cb
SG
4173 // assign the member functions
4174 c->is_defined = lxcapi_is_defined;
4175 c->state = lxcapi_state;
4176 c->is_running = lxcapi_is_running;
4177 c->freeze = lxcapi_freeze;
4178 c->unfreeze = lxcapi_unfreeze;
0115f8fd 4179 c->console = lxcapi_console;
b5159817 4180 c->console_getfd = lxcapi_console_getfd;
72d0e1cb
SG
4181 c->init_pid = lxcapi_init_pid;
4182 c->load_config = lxcapi_load_config;
4183 c->want_daemonize = lxcapi_want_daemonize;
130a1888 4184 c->want_close_all_fds = lxcapi_want_close_all_fds;
72d0e1cb
SG
4185 c->start = lxcapi_start;
4186 c->startl = lxcapi_startl;
4187 c->stop = lxcapi_stop;
4188 c->config_file_name = lxcapi_config_file_name;
4189 c->wait = lxcapi_wait;
4190 c->set_config_item = lxcapi_set_config_item;
4191 c->destroy = lxcapi_destroy;
18aa217b 4192 c->destroy_with_snapshots = lxcapi_destroy_with_snapshots;
06e5650e 4193 c->rename = lxcapi_rename;
72d0e1cb
SG
4194 c->save_config = lxcapi_save_config;
4195 c->get_keys = lxcapi_get_keys;
4196 c->create = lxcapi_create;
4197 c->createl = lxcapi_createl;
4198 c->shutdown = lxcapi_shutdown;
3e625e2d 4199 c->reboot = lxcapi_reboot;
4df7f012 4200 c->clear_config = lxcapi_clear_config;
72d0e1cb
SG
4201 c->clear_config_item = lxcapi_clear_config_item;
4202 c->get_config_item = lxcapi_get_config_item;
8ac18377 4203 c->get_running_config_item = lxcapi_get_running_config_item;
794dd120
SH
4204 c->get_cgroup_item = lxcapi_get_cgroup_item;
4205 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
4206 c->get_config_path = lxcapi_get_config_path;
4207 c->set_config_path = lxcapi_set_config_path;
9be53773 4208 c->clone = lxcapi_clone;
799f29ab 4209 c->get_interfaces = lxcapi_get_interfaces;
9c83a661 4210 c->get_ips = lxcapi_get_ips;
a0e93eeb
CS
4211 c->attach = lxcapi_attach;
4212 c->attach_run_wait = lxcapi_attach_run_wait;
4213 c->attach_run_waitl = lxcapi_attach_run_waitl;
f5dd1d53
SH
4214 c->snapshot = lxcapi_snapshot;
4215 c->snapshot_list = lxcapi_snapshot_list;
4216 c->snapshot_restore = lxcapi_snapshot_restore;
771d96b3 4217 c->snapshot_destroy = lxcapi_snapshot_destroy;
18aa217b 4218 c->snapshot_destroy_all = lxcapi_snapshot_destroy_all;
b494d2dd 4219 c->may_control = lxcapi_may_control;
a9a0ed90
ÇO
4220 c->add_device_node = lxcapi_add_device_node;
4221 c->remove_device_node = lxcapi_remove_device_node;
e58fae8f
DY
4222 c->attach_interface = lxcapi_attach_interface;
4223 c->detach_interface = lxcapi_detach_interface;
735f2c6e
TA
4224 c->checkpoint = lxcapi_checkpoint;
4225 c->restore = lxcapi_restore;
72d0e1cb 4226
72d0e1cb
SG
4227 return c;
4228
4229err:
4230 lxc_container_free(c);
4231 return NULL;
4232}
4233
4a7c7daa 4234int lxc_get_wait_states(const char **states)
72d0e1cb
SG
4235{
4236 int i;
4237
4238 if (states)
4239 for (i=0; i<MAX_STATE; i++)
4240 states[i] = lxc_state2str(i);
4241 return MAX_STATE;
4242}
a41f104b 4243
a41f104b
SH
4244/*
4245 * These next two could probably be done smarter with reusing a common function
4246 * with different iterators and tests...
4247 */
4248int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
4249{
4250 DIR *dir;
4251 int i, cfound = 0, nfound = 0;
4252 struct dirent dirent, *direntp;
4253 struct lxc_container *c;
4254
4255 if (!lxcpath)
593e8478 4256 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b 4257
a41f104b 4258 dir = opendir(lxcpath);
a41f104b
SH
4259 if (!dir) {
4260 SYSERROR("opendir on lxcpath");
4261 return -1;
4262 }
4263
4264 if (cret)
4265 *cret = NULL;
4266 if (names)
4267 *names = NULL;
4268
4269 while (!readdir_r(dir, &dirent, &direntp)) {
4270 if (!direntp)
4271 break;
4272 if (!strcmp(direntp->d_name, "."))
4273 continue;
4274 if (!strcmp(direntp->d_name, ".."))
4275 continue;
4276
4277 if (!config_file_exists(lxcpath, direntp->d_name))
4278 continue;
4279
4280 if (names) {
9c88ff1f 4281 if (!add_to_array(names, direntp->d_name, cfound))
a41f104b
SH
4282 goto free_bad;
4283 }
4284 cfound++;
4285
4286 if (!cret) {
4287 nfound++;
4288 continue;
4289 }
4290
4291 c = lxc_container_new(direntp->d_name, lxcpath);
4292 if (!c) {
4293 INFO("Container %s:%s has a config but could not be loaded",
4294 lxcpath, direntp->d_name);
4295 if (names)
9c88ff1f
ÇO
4296 if(!remove_from_array(names, direntp->d_name, cfound--))
4297 goto free_bad;
a41f104b
SH
4298 continue;
4299 }
858377e4 4300 if (!do_lxcapi_is_defined(c)) {
a41f104b
SH
4301 INFO("Container %s:%s has a config but is not defined",
4302 lxcpath, direntp->d_name);
4303 if (names)
9c88ff1f
ÇO
4304 if(!remove_from_array(names, direntp->d_name, cfound--))
4305 goto free_bad;
a41f104b
SH
4306 lxc_container_put(c);
4307 continue;
4308 }
4309
2871830a 4310 if (!add_to_clist(cret, c, nfound, true)) {
a41f104b
SH
4311 lxc_container_put(c);
4312 goto free_bad;
4313 }
4314 nfound++;
4315 }
4316
a41f104b 4317 closedir(dir);
a41f104b
SH
4318 return nfound;
4319
4320free_bad:
4321 if (names && *names) {
4322 for (i=0; i<cfound; i++)
4323 free((*names)[i]);
4324 free(*names);
4325 }
4326 if (cret && *cret) {
4327 for (i=0; i<nfound; i++)
4328 lxc_container_put((*cret)[i]);
4329 free(*cret);
4330 }
a41f104b 4331 closedir(dir);
a41f104b
SH
4332 return -1;
4333}
4334
148a9d27
DE
4335int list_active_containers(const char *lxcpath, char ***nret,
4336 struct lxc_container ***cret)
a41f104b 4337{
148a9d27 4338 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
a41f104b
SH
4339 int lxcpath_len;
4340 char *line = NULL;
148a9d27 4341 char **ct_name = NULL;
a41f104b
SH
4342 size_t len = 0;
4343 struct lxc_container *c;
88556fd7 4344 bool is_hashed;
a41f104b
SH
4345
4346 if (!lxcpath)
593e8478 4347 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b
SH
4348 lxcpath_len = strlen(lxcpath);
4349
4350 if (cret)
4351 *cret = NULL;
148a9d27
DE
4352 if (nret)
4353 *nret = NULL;
a41f104b 4354
a41f104b 4355 FILE *f = fopen("/proc/net/unix", "r");
a41f104b
SH
4356 if (!f)
4357 return -1;
4358
4359 while (getline(&line, &len, f) != -1) {
88556fd7 4360
0f8f9c8a 4361 char *p = strrchr(line, ' '), *p2;
a41f104b
SH
4362 if (!p)
4363 continue;
4364 p++;
4365 if (*p != 0x40)
4366 continue;
4367 p++;
88556fd7
ÇO
4368
4369 is_hashed = false;
4370 if (strncmp(p, lxcpath, lxcpath_len) == 0) {
4371 p += lxcpath_len;
4372 } else if (strncmp(p, "lxc/", 4) == 0) {
4373 p += 4;
4374 is_hashed = true;
4375 } else {
a41f104b 4376 continue;
88556fd7
ÇO
4377 }
4378
a41f104b
SH
4379 while (*p == '/')
4380 p++;
4381
4382 // Now p is the start of lxc_name
46cd2845 4383 p2 = strchr(p, '/');
a41f104b
SH
4384 if (!p2 || strncmp(p2, "/command", 8) != 0)
4385 continue;
4386 *p2 = '\0';
4387
88556fd7
ÇO
4388 if (is_hashed) {
4389 if (strncmp(lxcpath, lxc_cmd_get_lxcpath(p), lxcpath_len) != 0)
4390 continue;
4391 p = lxc_cmd_get_name(p);
4392 }
4393
148a9d27 4394 if (array_contains(&ct_name, p, ct_name_cnt))
9c88ff1f
ÇO
4395 continue;
4396
148a9d27
DE
4397 if (!add_to_array(&ct_name, p, ct_name_cnt))
4398 goto free_cret_list;
9c88ff1f 4399
148a9d27 4400 ct_name_cnt++;
a41f104b 4401
148a9d27 4402 if (!cret)
a41f104b 4403 continue;
a41f104b
SH
4404
4405 c = lxc_container_new(p, lxcpath);
4406 if (!c) {
4407 INFO("Container %s:%s is running but could not be loaded",
4408 lxcpath, p);
148a9d27 4409 remove_from_array(&ct_name, p, ct_name_cnt--);
a41f104b
SH
4410 continue;
4411 }
4412
4413 /*
4414 * If this is an anonymous container, then is_defined *can*
4415 * return false. So we don't do that check. Count on the
4416 * fact that the command socket exists.
4417 */
4418
148a9d27 4419 if (!add_to_clist(cret, c, cret_cnt, true)) {
a41f104b 4420 lxc_container_put(c);
148a9d27 4421 goto free_cret_list;
a41f104b 4422 }
148a9d27 4423 cret_cnt++;
a41f104b
SH
4424 }
4425
148a9d27
DE
4426 assert(!nret || !cret || cret_cnt == ct_name_cnt);
4427 ret = ct_name_cnt;
4428 if (nret)
4429 *nret = ct_name;
4430 else
4431 goto free_ct_name;
4432 goto out;
a41f104b 4433
148a9d27 4434free_cret_list:
a41f104b 4435 if (cret && *cret) {
148a9d27 4436 for (i = 0; i < cret_cnt; i++)
a41f104b
SH
4437 lxc_container_put((*cret)[i]);
4438 free(*cret);
4439 }
148a9d27
DE
4440
4441free_ct_name:
4442 if (ct_name) {
4443 for (i = 0; i < ct_name_cnt; i++)
4444 free(ct_name[i]);
4445 free(ct_name);
4446 }
4447
4448out:
f10fad2f 4449 free(line);
e853a32d 4450
a41f104b 4451 fclose(f);
148a9d27 4452 return ret;
a41f104b 4453}
2871830a
DE
4454
4455int list_all_containers(const char *lxcpath, char ***nret,
4456 struct lxc_container ***cret)
4457{
4458 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
4459 char **active_name;
4460 char **ct_name;
4461 struct lxc_container **ct_list = NULL;
4462
4463 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
4464 if (ct_cnt < 0)
4465 return ct_cnt;
4466
4467 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
4468 if (active_cnt < 0) {
4469 ret = active_cnt;
4470 goto free_ct_name;
4471 }
4472
4473 for (i = 0; i < active_cnt; i++) {
4474 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
4475 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
4476 ret = -1;
4477 goto free_active_name;
4478 }
4479 ct_cnt++;
4480 }
4481 free(active_name[i]);
4482 active_name[i] = NULL;
4483 }
4484 free(active_name);
4485 active_name = NULL;
4486 active_cnt = 0;
4487
4488 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
4489 struct lxc_container *c;
4490
4491 c = lxc_container_new(ct_name[i], lxcpath);
4492 if (!c) {
4493 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
4494 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
4495 continue;
4496 }
4497
4498 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
4499 lxc_container_put(c);
4500 ret = -1;
4501 goto free_ct_list;
4502 }
4503 ct_list_cnt++;
4504 }
4505
4506 if (cret)
4507 *cret = ct_list;
4508
4509 if (nret)
4510 *nret = ct_name;
4511 else {
4512 ret = ct_cnt;
4513 goto free_ct_name;
4514 }
4515 return ct_cnt;
4516
4517free_ct_list:
4518 for (i = 0; i < ct_list_cnt; i++) {
4519 lxc_container_put(ct_list[i]);
4520 }
f10fad2f 4521 free(ct_list);
2871830a
DE
4522
4523free_active_name:
4524 for (i = 0; i < active_cnt; i++) {
f10fad2f 4525 free(active_name[i]);
2871830a 4526 }
f10fad2f 4527 free(active_name);
2871830a
DE
4528
4529free_ct_name:
4530 for (i = 0; i < ct_cnt; i++) {
4531 free(ct_name[i]);
4532 }
4533 free(ct_name);
4534 return ret;
4535}