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