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