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