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