]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
Merge pull request #1374 from brauner/2017-01-03/fix_suggest_default_idmap
[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 41#include "attach.h"
d8e48992
CB
42#include "bdev.h"
43#include "lxcoverlay.h"
44#include "lxcbtrfs.h"
38683db4 45#include "cgroup.h"
72d0e1cb 46#include "conf.h"
38683db4
CB
47#include "config.h"
48#include "commands.h"
72d0e1cb 49#include "confile.h"
b5159817 50#include "console.h"
e29fe1dd 51#include "criu.h"
72d0e1cb 52#include "log.h"
38683db4
CB
53#include "lxc.h"
54#include "lxccontainer.h"
55#include "lxclock.h"
f2363e38
ÇO
56#include "monitor.h"
57#include "namespace.h"
fed29fad 58#include "network.h"
735f2c6e 59#include "sync.h"
38683db4
CB
60#include "state.h"
61#include "utils.h"
62#include "version.h"
4ba0d9af
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{
74f96976 626 struct dirent *direntp;
2d834aa8
SH
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
74f96976 636 while ((direntp = readdir(dir))) {
2d834aa8
SH
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;
5590a671 673 char *copy, *p, *saveptr = NULL;
fd51a89b
SH
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;
591614a7
CB
1585 if (kill(pid, rebootsignal) < 0) {
1586 WARN("Could not send signal %d to pid %d.", rebootsignal, pid);
3e625e2d 1587 return false;
591614a7 1588 }
3e625e2d
SH
1589 return true;
1590
1591}
1592
858377e4
SH
1593WRAP_API(bool, lxcapi_reboot)
1594
1595static bool do_lxcapi_shutdown(struct lxc_container *c, int timeout)
72d0e1cb
SG
1596{
1597 bool retv;
1598 pid_t pid;
f0f1d8c0 1599 int haltsignal = SIGPWR;
72d0e1cb
SG
1600
1601 if (!c)
1602 return false;
1603
858377e4 1604 if (!do_lxcapi_is_running(c))
72d0e1cb 1605 return true;
858377e4 1606 pid = do_lxcapi_init_pid(c);
72d0e1cb
SG
1607 if (pid <= 0)
1608 return true;
330ae3d3
CB
1609
1610 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
1611 if (task_blocking_signal(pid, (SIGRTMIN + 3)))
1612 haltsignal = (SIGRTMIN + 3);
1613
b0227444 1614 if (c->lxc_conf && c->lxc_conf->haltsignal)
f0f1d8c0 1615 haltsignal = c->lxc_conf->haltsignal;
330ae3d3
CB
1616
1617 INFO("Using signal number '%d' as halt signal.", haltsignal);
1618
591614a7
CB
1619 if (kill(pid, haltsignal) < 0)
1620 WARN("Could not send signal %d to pid %d.", haltsignal, pid);
1621
858377e4 1622 retv = do_lxcapi_wait(c, "STOPPED", timeout);
72d0e1cb
SG
1623 return retv;
1624}
1625
858377e4
SH
1626WRAP_API_1(bool, lxcapi_shutdown, int)
1627
1897e3bc 1628static bool lxcapi_createl(struct lxc_container *c, const char *t,
dc23c1c8 1629 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
72d0e1cb
SG
1630{
1631 bool bret = false;
a0e93eeb 1632 char **args = NULL;
72d0e1cb 1633 va_list ap;
72d0e1cb
SG
1634
1635 if (!c)
1636 return false;
1637
858377e4
SH
1638 current_config = c->lxc_conf;
1639
72d0e1cb
SG
1640 /*
1641 * since we're going to wait for create to finish, I don't think we
1642 * need to get a copy of the arguments.
1643 */
dc23c1c8 1644 va_start(ap, flags);
a0e93eeb 1645 args = lxc_va_arg_list_to_argv(ap, 0, 0);
72d0e1cb 1646 va_end(ap);
a0e93eeb
CS
1647 if (!args) {
1648 ERROR("Memory allocation error.");
1649 goto out;
1650 }
72d0e1cb 1651
858377e4 1652 bret = do_lxcapi_create(c, t, bdevtype, specs, flags, args);
72d0e1cb
SG
1653
1654out:
a0e93eeb 1655 free(args);
858377e4 1656 current_config = NULL;
72d0e1cb
SG
1657 return bret;
1658}
1659
6b0d5538
SH
1660static void do_clear_unexp_config_line(struct lxc_conf *conf, const char *key)
1661{
1662 if (strcmp(key, "lxc.cgroup") == 0)
1663 clear_unexp_config_line(conf, key, true);
1664 else if (strcmp(key, "lxc.network") == 0)
1665 clear_unexp_config_line(conf, key, true);
1666 else if (strcmp(key, "lxc.hook") == 0)
1667 clear_unexp_config_line(conf, key, true);
1668 else
1669 clear_unexp_config_line(conf, key, false);
1670 if (!do_append_unexp_config_line(conf, key, ""))
1671 WARN("Error clearing configuration for %s", key);
1672}
1673
858377e4 1674static bool do_lxcapi_clear_config_item(struct lxc_container *c, const char *key)
72d0e1cb
SG
1675{
1676 int ret;
1677
1678 if (!c || !c->lxc_conf)
1679 return false;
5cee8c50 1680 if (container_mem_lock(c))
72d0e1cb 1681 return false;
72d0e1cb 1682 ret = lxc_clear_config_item(c->lxc_conf, key);
6b0d5538
SH
1683 if (!ret)
1684 do_clear_unexp_config_line(c->lxc_conf, key);
5cee8c50 1685 container_mem_unlock(c);
72d0e1cb
SG
1686 return ret == 0;
1687}
1688
858377e4
SH
1689WRAP_API_1(bool, lxcapi_clear_config_item, const char *)
1690
e0f59189 1691static inline bool enter_net_ns(struct lxc_container *c)
51d0854c 1692{
858377e4 1693 pid_t pid = do_lxcapi_init_pid(c);
ae22a220 1694
0e6e3a41 1695 if ((geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) && access("/proc/self/ns/user", F_OK) == 0) {
51d0854c
DY
1696 if (!switch_to_ns(pid, "user"))
1697 return false;
9c83a661 1698 }
51d0854c 1699 return switch_to_ns(pid, "net");
799f29ab
ÇO
1700}
1701
9c88ff1f
ÇO
1702// used by qsort and bsearch functions for comparing names
1703static inline int string_cmp(char **first, char **second)
1704{
1705 return strcmp(*first, *second);
1706}
1707
1708// used by qsort and bsearch functions for comparing container names
1709static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1710{
1711 return strcmp((*first)->name, (*second)->name);
1712}
1713
1714static bool add_to_array(char ***names, char *cname, int pos)
1715{
1716 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1717 if (!newnames) {
1718 ERROR("Out of memory");
1719 return false;
1720 }
1721
1722 *names = newnames;
1723 newnames[pos] = strdup(cname);
1724 if (!newnames[pos])
1725 return false;
1726
1727 // sort the arrray as we will use binary search on it
1728 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1729
1730 return true;
1731}
1732
2871830a 1733static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
9c88ff1f
ÇO
1734{
1735 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1736 if (!newlist) {
1737 ERROR("Out of memory");
1738 return false;
1739 }
1740
1741 *list = newlist;
1742 newlist[pos] = c;
1743
1744 // sort the arrray as we will use binary search on it
2871830a
DE
1745 if (sort)
1746 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
9c88ff1f
ÇO
1747
1748 return true;
1749}
1750
1751static char** get_from_array(char ***names, char *cname, int size)
1752{
1753 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1754}
1755
1756
1757static bool array_contains(char ***names, char *cname, int size) {
1758 if(get_from_array(names, cname, size) != NULL)
1759 return true;
1760 return false;
1761}
1762
1763static bool remove_from_array(char ***names, char *cname, int size)
1764{
1765 char **result = get_from_array(names, cname, size);
1766 if (result != NULL) {
1767 free(result);
1768 return true;
1769 }
1770 return false;
1771}
1772
858377e4 1773static char ** do_lxcapi_get_interfaces(struct lxc_container *c)
799f29ab 1774{
ae22a220
ÇO
1775 pid_t pid;
1776 int i, count = 0, pipefd[2];
9c88ff1f 1777 char **interfaces = NULL;
ae22a220 1778 char interface[IFNAMSIZ];
799f29ab 1779
ae22a220
ÇO
1780 if(pipe(pipefd) < 0) {
1781 SYSERROR("pipe failed");
1782 return NULL;
c868b261
ÇO
1783 }
1784
ae22a220
ÇO
1785 pid = fork();
1786 if (pid < 0) {
959aee9c 1787 SYSERROR("failed to fork task to get interfaces information");
ae22a220
ÇO
1788 close(pipefd[0]);
1789 close(pipefd[1]);
1790 return NULL;
1791 }
799f29ab 1792
ae22a220
ÇO
1793 if (pid == 0) { // child
1794 int ret = 1, nbytes;
1795 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1796
1797 /* close the read-end of the pipe */
1798 close(pipefd[0]);
1799
e0f59189 1800 if (!enter_net_ns(c)) {
ae22a220
ÇO
1801 SYSERROR("failed to enter namespace");
1802 goto out;
1803 }
1804
1805 /* Grab the list of interfaces */
1806 if (getifaddrs(&interfaceArray)) {
1807 SYSERROR("failed to get interfaces list");
1808 goto out;
1809 }
1810
1811 /* Iterate through the interfaces */
1812 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1813 nbytes = write(pipefd[1], tempIfAddr->ifa_name, IFNAMSIZ);
1814 if (nbytes < 0) {
1815 ERROR("write failed");
1816 goto out;
1817 }
1818 count++;
1819 }
1820 ret = 0;
1821
1822 out:
1823 if (interfaceArray)
1824 freeifaddrs(interfaceArray);
1825
1826 /* close the write-end of the pipe, thus sending EOF to the reader */
1827 close(pipefd[1]);
1828 exit(ret);
799f29ab
ÇO
1829 }
1830
ae22a220
ÇO
1831 /* close the write-end of the pipe */
1832 close(pipefd[1]);
1833
358afd84 1834 while (read(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
ae22a220
ÇO
1835 if (array_contains(&interfaces, interface, count))
1836 continue;
799f29ab 1837
ae22a220
ÇO
1838 if(!add_to_array(&interfaces, interface, count))
1839 ERROR("PARENT: add_to_array failed");
9c88ff1f
ÇO
1840 count++;
1841 }
799f29ab 1842
ae22a220
ÇO
1843 if (wait_for_pid(pid) != 0) {
1844 for(i=0;i<count;i++)
1845 free(interfaces[i]);
1846 free(interfaces);
1847 interfaces = NULL;
1848 }
9c88ff1f 1849
ae22a220
ÇO
1850 /* close the read-end of the pipe */
1851 close(pipefd[0]);
799f29ab 1852
9c88ff1f
ÇO
1853 /* Append NULL to the array */
1854 if(interfaces)
1855 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
799f29ab 1856
9c88ff1f 1857 return interfaces;
799f29ab
ÇO
1858}
1859
858377e4
SH
1860WRAP_API(char **, lxcapi_get_interfaces)
1861
1862static char** do_lxcapi_get_ips(struct lxc_container *c, const char* interface, const char* family, int scope)
799f29ab 1863{
ae22a220
ÇO
1864 pid_t pid;
1865 int i, count = 0, pipefd[2];
9c88ff1f 1866 char **addresses = NULL;
ae22a220 1867 char address[INET6_ADDRSTRLEN];
799f29ab 1868
ae22a220
ÇO
1869 if(pipe(pipefd) < 0) {
1870 SYSERROR("pipe failed");
1871 return NULL;
c868b261
ÇO
1872 }
1873
ae22a220
ÇO
1874 pid = fork();
1875 if (pid < 0) {
959aee9c 1876 SYSERROR("failed to fork task to get container ips");
ae22a220
ÇO
1877 close(pipefd[0]);
1878 close(pipefd[1]);
1879 return NULL;
9c83a661
SG
1880 }
1881
ae22a220
ÇO
1882 if (pid == 0) { // child
1883 int ret = 1, nbytes;
1884 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1885 char addressOutputBuffer[INET6_ADDRSTRLEN];
1886 void *tempAddrPtr = NULL;
1887 char *address = NULL;
fe218ca3 1888
ae22a220
ÇO
1889 /* close the read-end of the pipe */
1890 close(pipefd[0]);
1891
e0f59189 1892 if (!enter_net_ns(c)) {
ae22a220
ÇO
1893 SYSERROR("failed to enter namespace");
1894 goto out;
9c83a661 1895 }
ae22a220
ÇO
1896
1897 /* Grab the list of interfaces */
1898 if (getifaddrs(&interfaceArray)) {
1899 SYSERROR("failed to get interfaces list");
1900 goto out;
1901 }
1902
1903 /* Iterate through the interfaces */
1904 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1905 if (tempIfAddr->ifa_addr == NULL)
9c83a661
SG
1906 continue;
1907
ae22a220
ÇO
1908 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1909 if (family && strcmp(family, "inet"))
1910 continue;
1911 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1912 }
1913 else {
1914 if (family && strcmp(family, "inet6"))
1915 continue;
1916
1917 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1918 continue;
1919
1920 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1921 }
1922
1923 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1924 continue;
1925 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
9c83a661
SG
1926 continue;
1927
ae22a220
ÇO
1928 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1929 tempAddrPtr,
1930 addressOutputBuffer,
1931 sizeof(addressOutputBuffer));
1932 if (!address)
1933 continue;
1934
1935 nbytes = write(pipefd[1], address, INET6_ADDRSTRLEN);
1936 if (nbytes < 0) {
1937 ERROR("write failed");
1938 goto out;
1939 }
1940 count++;
9c83a661 1941 }
ae22a220 1942 ret = 0;
9c83a661 1943
ae22a220
ÇO
1944 out:
1945 if(interfaceArray)
1946 freeifaddrs(interfaceArray);
9c83a661 1947
ae22a220
ÇO
1948 /* close the write-end of the pipe, thus sending EOF to the reader */
1949 close(pipefd[1]);
1950 exit(ret);
6849cb5b 1951 }
9c83a661 1952
ae22a220
ÇO
1953 /* close the write-end of the pipe */
1954 close(pipefd[1]);
1955
358afd84 1956 while (read(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
9c88ff1f 1957 if(!add_to_array(&addresses, address, count))
ae22a220 1958 ERROR("PARENT: add_to_array failed");
9c88ff1f 1959 count++;
9c83a661
SG
1960 }
1961
ae22a220
ÇO
1962 if (wait_for_pid(pid) != 0) {
1963 for(i=0;i<count;i++)
1964 free(addresses[i]);
1965 free(addresses);
1966 addresses = NULL;
1967 }
9c83a661 1968
ae22a220
ÇO
1969 /* close the read-end of the pipe */
1970 close(pipefd[0]);
9c83a661
SG
1971
1972 /* Append NULL to the array */
9c88ff1f
ÇO
1973 if(addresses)
1974 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
9c83a661
SG
1975
1976 return addresses;
1977}
1978
858377e4
SH
1979WRAP_API_3(char **, lxcapi_get_ips, const char *, const char *, int)
1980
1981static int do_lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1982{
1983 int ret;
1984
1985 if (!c || !c->lxc_conf)
1986 return -1;
5cee8c50 1987 if (container_mem_lock(c))
72d0e1cb 1988 return -1;
72d0e1cb 1989 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
5cee8c50 1990 container_mem_unlock(c);
72d0e1cb
SG
1991 return ret;
1992}
1993
858377e4
SH
1994WRAP_API_3(int, lxcapi_get_config_item, const char *, char *, int)
1995
1996static char* do_lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
8ac18377
ÇO
1997{
1998 char *ret;
1999
2000 if (!c || !c->lxc_conf)
2001 return NULL;
2002 if (container_mem_lock(c))
2003 return NULL;
858377e4 2004 ret = lxc_cmd_get_config_item(c->name, key, do_lxcapi_get_config_path(c));
8ac18377
ÇO
2005 container_mem_unlock(c);
2006 return ret;
2007}
2008
858377e4
SH
2009WRAP_API_1(char *, lxcapi_get_running_config_item, const char *)
2010
2011static int do_lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
2012{
2013 if (!key)
2014 return lxc_listconfigs(retv, inlen);
2015 /*
2016 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
2017 * This is an intelligent result to show which keys are valid given
2018 * the type of nic it is
2019 */
2020 if (!c || !c->lxc_conf)
2021 return -1;
5cee8c50 2022 if (container_mem_lock(c))
72d0e1cb
SG
2023 return -1;
2024 int ret = -1;
2025 if (strncmp(key, "lxc.network.", 12) == 0)
6849cb5b 2026 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
5cee8c50 2027 container_mem_unlock(c);
72d0e1cb
SG
2028 return ret;
2029}
2030
858377e4
SH
2031WRAP_API_3(int, lxcapi_get_keys, const char *, char *, int)
2032
2033static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 2034{
39dc698c
SH
2035 FILE *fout;
2036 bool ret = false, need_disklock = false;
2037 int lret;
2038
72d0e1cb
SG
2039 if (!alt_file)
2040 alt_file = c->configfile;
2041 if (!alt_file)
6849cb5b 2042 return false; // should we write to stdout if no file is specified?
39dc698c
SH
2043
2044 // If we haven't yet loaded a config, load the stock config
2045 if (!c->lxc_conf) {
858377e4 2046 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
959aee9c 2047 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c->name);
72d0e1cb
SG
2048 return false;
2049 }
39dc698c 2050 }
72d0e1cb 2051
5a3d2e1e
SG
2052 if (!create_container_dir(c))
2053 return false;
2054
39dc698c
SH
2055 /*
2056 * If we're writing to the container's config file, take the
2057 * disk lock. Otherwise just take the memlock to protect the
2058 * struct lxc_container while we're traversing it.
2059 */
2060 if (strcmp(c->configfile, alt_file) == 0)
2061 need_disklock = true;
2062
2063 if (need_disklock)
2064 lret = container_disk_lock(c);
2065 else
2066 lret = container_mem_lock(c);
2067
2068 if (lret)
72d0e1cb 2069 return false;
39dc698c
SH
2070
2071 fout = fopen(alt_file, "w");
2072 if (!fout)
2073 goto out;
6b0d5538 2074 write_config(fout, c->lxc_conf);
72d0e1cb 2075 fclose(fout);
39dc698c
SH
2076 ret = true;
2077
2078out:
2079 if (need_disklock)
2080 container_disk_unlock(c);
2081 else
2082 container_mem_unlock(c);
2083 return ret;
72d0e1cb
SG
2084}
2085
858377e4
SH
2086WRAP_API_1(bool, lxcapi_save_config, const char *)
2087
0ea055b3
CB
2088
2089static bool mod_rdep(struct lxc_container *c0, struct lxc_container *c, bool inc)
dfb31b25 2090{
0ea055b3
CB
2091 FILE *f1;
2092 struct stat fbuf;
42342bed
CB
2093 void *buf = NULL;
2094 char *del = NULL;
dfb31b25 2095 char path[MAXPATHLEN];
0ea055b3
CB
2096 char newpath[MAXPATHLEN];
2097 int fd, ret, n = 0, v = 0;
dfb31b25 2098 bool bret = false;
42342bed 2099 size_t len = 0, bytes = 0;
dfb31b25 2100
0ea055b3 2101 if (container_disk_lock(c0))
dfb31b25 2102 return false;
0ea055b3
CB
2103
2104 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c0->config_path, c0->name);
dfb31b25
SH
2105 if (ret < 0 || ret > MAXPATHLEN)
2106 goto out;
0ea055b3
CB
2107 ret = snprintf(newpath, MAXPATHLEN, "%s\n%s\n", c->config_path, c->name);
2108 if (ret < 0 || ret > MAXPATHLEN)
dfb31b25 2109 goto out;
0ea055b3
CB
2110
2111 /* If we find an lxc-snapshot file using the old format only listing the
2112 * number of snapshots we will keep using it. */
2113 f1 = fopen(path, "r");
2114 if (f1) {
2115 n = fscanf(f1, "%d", &v);
2116 fclose(f1);
2117 if (n == 1 && v == 0) {
2118 remove(path);
2119 n = 0;
2120 }
dfb31b25 2121 }
0ea055b3
CB
2122 if (n == 1) {
2123 v += inc ? 1 : -1;
2124 f1 = fopen(path, "w");
2125 if (!f1)
2126 goto out;
2127 if (fprintf(f1, "%d\n", v) < 0) {
2128 ERROR("Error writing new snapshots value");
2129 fclose(f1);
2130 goto out;
2131 }
2132 ret = fclose(f1);
2133 if (ret != 0) {
2134 SYSERROR("Error writing to or closing snapshots file");
2135 goto out;
2136 }
2137 } else {
2138 /* Here we know that we have or can use an lxc-snapshot file
2139 * using the new format. */
2140 if (inc) {
2141 f1 = fopen(path, "a");
2142 if (!f1)
2143 goto out;
2144
2145 if (fprintf(f1, "%s", newpath) < 0) {
2146 ERROR("Error writing new snapshots entry");
2147 ret = fclose(f1);
2148 if (ret != 0)
2149 SYSERROR("Error writing to or closing snapshots file");
2150 goto out;
2151 }
2152
2153 ret = fclose(f1);
2154 if (ret != 0) {
2155 SYSERROR("Error writing to or closing snapshots file");
2156 goto out;
2157 }
2158 } else if (!inc) {
d028235d
SG
2159 if ((fd = open(path, O_RDWR | O_CLOEXEC)) < 0)
2160 goto out;
2161
2162 if (fstat(fd, &fbuf) < 0) {
2163 close(fd);
2164 goto out;
2165 }
2166
2167 if (fbuf.st_size != 0) {
d028235d 2168
25086a5f 2169 buf = lxc_strmmap(NULL, fbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
d028235d
SG
2170 if (buf == MAP_FAILED) {
2171 SYSERROR("Failed to create mapping %s", path);
2172 close(fd);
2173 goto out;
2174 }
2175
2176 len = strlen(newpath);
2177 while ((del = strstr((char *)buf, newpath))) {
2178 memmove(del, del + len, strlen(del) - len + 1);
2179 bytes += len;
2180 }
2181
25086a5f 2182 lxc_strmunmap(buf, fbuf.st_size);
d028235d
SG
2183 if (ftruncate(fd, fbuf.st_size - bytes) < 0) {
2184 SYSERROR("Failed to truncate file %s", path);
2185 close(fd);
2186 goto out;
2187 }
2188 }
2189 close(fd);
2190 }
0ea055b3
CB
2191
2192 /* If the lxc-snapshot file is empty, remove it. */
2193 if (stat(path, &fbuf) < 0)
2194 goto out;
d028235d
SG
2195 if (!fbuf.st_size) {
2196 remove(path);
0ea055b3 2197 }
dfb31b25
SH
2198 }
2199
2200 bret = true;
2201
2202out:
0ea055b3 2203 container_disk_unlock(c0);
dfb31b25
SH
2204 return bret;
2205}
2206
2207static void strip_newline(char *p)
2208{
2209 size_t len = strlen(p);
2210 if (len < 1)
2211 return;
2212 if (p[len-1] == '\n')
2213 p[len-1] = '\0';
2214}
2215
d825fff3 2216void mod_all_rdeps(struct lxc_container *c, bool inc)
dfb31b25
SH
2217{
2218 struct lxc_container *p;
2219 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
2220 size_t pathlen = 0, namelen = 0;
2221 FILE *f;
2222 int ret;
2223
2224 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
2225 c->config_path, c->name);
2226 if (ret < 0 || ret >= MAXPATHLEN) {
2227 ERROR("Path name too long");
2228 return;
2229 }
025ed0f3 2230 f = fopen(path, "r");
025ed0f3 2231 if (f == NULL)
dfb31b25
SH
2232 return;
2233 while (getline(&lxcpath, &pathlen, f) != -1) {
2234 if (getline(&lxcname, &namelen, f) == -1) {
959aee9c 2235 ERROR("badly formatted file %s", path);
dfb31b25
SH
2236 goto out;
2237 }
2238 strip_newline(lxcpath);
2239 strip_newline(lxcname);
2240 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
2241 ERROR("Unable to find dependent container %s:%s",
2242 lxcpath, lxcname);
2243 continue;
2244 }
0ea055b3
CB
2245 if (!mod_rdep(p, c, inc))
2246 ERROR("Failed to update snapshots file for %s:%s",
dfb31b25
SH
2247 lxcpath, lxcname);
2248 lxc_container_put(p);
2249 }
2250out:
f10fad2f
ME
2251 free(lxcpath);
2252 free(lxcname);
dfb31b25
SH
2253 fclose(f);
2254}
2255
18aa217b 2256static bool has_fs_snapshots(struct lxc_container *c)
dfb31b25 2257{
0ea055b3 2258 FILE *f;
dfb31b25
SH
2259 char path[MAXPATHLEN];
2260 int ret, v;
0ea055b3 2261 struct stat fbuf;
dfb31b25
SH
2262 bool bret = false;
2263
2264 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
2265 c->name);
2266 if (ret < 0 || ret > MAXPATHLEN)
2267 goto out;
0ea055b3
CB
2268 /* If the file doesn't exist there are no snapshots. */
2269 if (stat(path, &fbuf) < 0)
dfb31b25 2270 goto out;
0ea055b3
CB
2271 v = fbuf.st_size;
2272 if (v != 0) {
2273 f = fopen(path, "r");
2274 if (!f)
2275 goto out;
2276 ret = fscanf(f, "%d", &v);
2277 fclose(f);
2278 // TODO: Figure out what to do with the return value of fscanf.
2279 if (ret != 1)
2280 INFO("Container uses new lxc-snapshots format %s", path);
2281 }
dfb31b25
SH
2282 bret = v != 0;
2283
2284out:
2285 return bret;
2286}
2287
18aa217b
SH
2288static bool has_snapshots(struct lxc_container *c)
2289{
2290 char path[MAXPATHLEN];
74f96976 2291 struct dirent *direntp;
18aa217b
SH
2292 int count=0;
2293 DIR *dir;
2294
2295 if (!get_snappath_dir(c, path))
2296 return false;
2297 dir = opendir(path);
2298 if (!dir)
2299 return false;
74f96976 2300 while ((direntp = readdir(dir))) {
18aa217b
SH
2301 if (!direntp)
2302 break;
2303
2304 if (!strcmp(direntp->d_name, "."))
2305 continue;
2306
2307 if (!strcmp(direntp->d_name, ".."))
2308 continue;
2309 count++;
2310 break;
2311 }
2312 closedir(dir);
2313 return count > 0;
2314}
2315
297c2d58 2316static bool do_destroy_container(struct lxc_conf *conf) {
d028235d
SG
2317 if (am_unpriv()) {
2318 if (userns_exec_1(conf, bdev_destroy_wrapper, conf) < 0)
2319 return false;
2320 return true;
2321 }
2322 return bdev_destroy(conf);
297c2d58
CB
2323}
2324
4355ab5f
SH
2325static int lxc_rmdir_onedev_wrapper(void *data)
2326{
2327 char *arg = (char *) data;
18aa217b 2328 return lxc_rmdir_onedev(arg, "snaps");
4355ab5f
SH
2329}
2330
18aa217b 2331static bool container_destroy(struct lxc_container *c)
72d0e1cb 2332{
c868b261 2333 bool bret = false;
297c2d58 2334 int ret = 0;
a70a69e8 2335 struct lxc_conf *conf;
72d0e1cb 2336
858377e4 2337 if (!c || !do_lxcapi_is_defined(c))
5a3d2e1e
SG
2338 return false;
2339
a70a69e8 2340 conf = c->lxc_conf;
3bc449ed 2341 if (container_disk_lock(c))
72d0e1cb 2342 return false;
72d0e1cb 2343
39dc698c 2344 if (!is_stopped(c)) {
60bf62d4
SH
2345 // we should queue some sort of error - in c->error_string?
2346 ERROR("container %s is not stopped", c->name);
2347 goto out;
72d0e1cb
SG
2348 }
2349
a70a69e8 2350 if (conf && !lxc_list_empty(&conf->hooks[LXCHOOK_DESTROY])) {
37cf711b 2351 /* Start of environment variable setup for hooks */
ab7efcf5 2352 if (c->name && setenv("LXC_NAME", c->name, 1)) {
37cf711b
SY
2353 SYSERROR("failed to set environment variable for container name");
2354 }
ab7efcf5 2355 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
37cf711b
SY
2356 SYSERROR("failed to set environment variable for config path");
2357 }
ab7efcf5 2358 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
37cf711b
SY
2359 SYSERROR("failed to set environment variable for rootfs mount");
2360 }
ab7efcf5 2361 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
37cf711b
SY
2362 SYSERROR("failed to set environment variable for rootfs mount");
2363 }
2364 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1)) {
2365 SYSERROR("failed to set environment variable for console path");
2366 }
2367 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1)) {
2368 SYSERROR("failed to set environment variable for console log");
2369 }
2370 /* End of environment variable setup for hooks */
2371
2372 if (run_lxc_hooks(c->name, "destroy", conf, c->get_config_path(c), NULL)) {
2373 ERROR("Error executing clone hook for %s", c->name);
2374 goto out;
2375 }
2376 }
2377
2378 if (current_config && conf == current_config) {
858377e4 2379 current_config = NULL;
37cf711b
SY
2380 if (conf->logfd != -1) {
2381 close(conf->logfd);
2382 conf->logfd = -1;
858377e4
SH
2383 }
2384 }
2385
d028235d
SG
2386 if (conf && conf->rootfs.path && conf->rootfs.mount) {
2387 if (!do_destroy_container(conf)) {
2388 ERROR("Error destroying rootfs for %s", c->name);
2389 goto out;
2390 }
2391 INFO("Destroyed rootfs for %s", c->name);
2392 }
60bf62d4 2393
dfb31b25
SH
2394 mod_all_rdeps(c, false);
2395
858377e4 2396 const char *p1 = do_lxcapi_get_config_path(c);
60bf62d4
SH
2397 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
2398 sprintf(path, "%s/%s", p1, c->name);
c868b261 2399 if (am_unpriv())
37cf711b 2400 ret = userns_exec_1(conf, lxc_rmdir_onedev_wrapper, path);
4355ab5f 2401 else
18aa217b 2402 ret = lxc_rmdir_onedev(path, "snaps");
4355ab5f 2403 if (ret < 0) {
60bf62d4
SH
2404 ERROR("Error destroying container directory for %s", c->name);
2405 goto out;
2406 }
d028235d 2407 INFO("Destroyed directory for %s", c->name);
297c2d58 2408
fef48dc9 2409 bret = true;
60bf62d4
SH
2410
2411out:
3bc449ed 2412 container_disk_unlock(c);
fef48dc9 2413 return bret;
72d0e1cb
SG
2414}
2415
858377e4 2416static bool do_lxcapi_destroy(struct lxc_container *c)
18aa217b
SH
2417{
2418 if (!c || !lxcapi_is_defined(c))
2419 return false;
2420 if (has_snapshots(c)) {
2421 ERROR("Container %s has snapshots; not removing", c->name);
2422 return false;
2423 }
2424
2425 if (has_fs_snapshots(c)) {
2426 ERROR("container %s has snapshots on its rootfs", c->name);
2427 return false;
2428 }
2429
2430 return container_destroy(c);
2431}
2432
858377e4 2433WRAP_API(bool, lxcapi_destroy)
18aa217b 2434
858377e4 2435static bool do_lxcapi_destroy_with_snapshots(struct lxc_container *c)
18aa217b
SH
2436{
2437 if (!c || !lxcapi_is_defined(c))
2438 return false;
2439 if (!lxcapi_snapshot_destroy_all(c)) {
2440 ERROR("Error deleting all snapshots");
2441 return false;
2442 }
2443 return lxcapi_destroy(c);
2444}
2445
858377e4
SH
2446WRAP_API(bool, lxcapi_destroy_with_snapshots)
2447
96532523
SH
2448static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
2449{
2450 struct lxc_config_t *config;
2451
2452 if (!c->lxc_conf)
2453 c->lxc_conf = lxc_conf_init();
6b0d5538 2454 if (!c->lxc_conf)
96532523
SH
2455 return false;
2456 config = lxc_getconfig(key);
2457 if (!config)
2458 return false;
6b0d5538 2459 if (config->cb(key, v, c->lxc_conf) != 0)
f979ac15 2460 return false;
6b0d5538 2461 return do_append_unexp_config_line(c->lxc_conf, key, v);
96532523
SH
2462}
2463
858377e4 2464static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb 2465{
72d0e1cb 2466 bool b = false;
72d0e1cb
SG
2467
2468 if (!c)
2469 return false;
2470
5cee8c50 2471 if (container_mem_lock(c))
72d0e1cb
SG
2472 return false;
2473
96532523 2474 b = set_config_item_locked(c, key, v);
72d0e1cb 2475
5cee8c50 2476 container_mem_unlock(c);
72d0e1cb
SG
2477 return b;
2478}
2479
858377e4
SH
2480WRAP_API_2(bool, lxcapi_set_config_item, const char *, const char *)
2481
72d0e1cb
SG
2482static char *lxcapi_config_file_name(struct lxc_container *c)
2483{
2484 if (!c || !c->configfile)
2485 return NULL;
2486 return strdup(c->configfile);
2487}
2488
2a59a681
SH
2489static const char *lxcapi_get_config_path(struct lxc_container *c)
2490{
2491 if (!c || !c->config_path)
2492 return NULL;
2493 return (const char *)(c->config_path);
2494}
2495
afeecbba
SH
2496/*
2497 * not for export
2498 * Just recalculate the c->configfile based on the
2499 * c->config_path, which must be set.
2500 * The lxc_container must be locked or not yet public.
2501 */
2502static bool set_config_filename(struct lxc_container *c)
2503{
2504 char *newpath;
2505 int len, ret;
2506
2507 if (!c->config_path)
2508 return false;
2509
2510 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2511 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
2512 newpath = malloc(len);
2513 if (!newpath)
2514 return false;
2515
2516 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
2517 if (ret < 0 || ret >= len) {
2518 fprintf(stderr, "Error printing out config file name\n");
2519 free(newpath);
2520 return false;
2521 }
2522
f10fad2f 2523 free(c->configfile);
afeecbba
SH
2524 c->configfile = newpath;
2525
2526 return true;
2527}
2528
858377e4 2529static bool do_lxcapi_set_config_path(struct lxc_container *c, const char *path)
2a59a681
SH
2530{
2531 char *p;
2532 bool b = false;
afeecbba 2533 char *oldpath = NULL;
2a59a681
SH
2534
2535 if (!c)
2536 return b;
2537
5cee8c50 2538 if (container_mem_lock(c))
2a59a681
SH
2539 return b;
2540
2541 p = strdup(path);
afeecbba
SH
2542 if (!p) {
2543 ERROR("Out of memory setting new lxc path");
2a59a681 2544 goto err;
afeecbba
SH
2545 }
2546
2a59a681
SH
2547 b = true;
2548 if (c->config_path)
afeecbba 2549 oldpath = c->config_path;
2a59a681 2550 c->config_path = p;
afeecbba
SH
2551
2552 /* Since we've changed the config path, we have to change the
2553 * config file name too */
2554 if (!set_config_filename(c)) {
2555 ERROR("Out of memory setting new config filename");
2556 b = false;
2557 free(c->config_path);
2558 c->config_path = oldpath;
2559 oldpath = NULL;
2560 }
2a59a681 2561err:
f10fad2f 2562 free(oldpath);
5cee8c50 2563 container_mem_unlock(c);
2a59a681
SH
2564 return b;
2565}
2566
858377e4 2567WRAP_API_1(bool, lxcapi_set_config_path, const char *)
2a59a681 2568
858377e4 2569static bool do_lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
794dd120
SH
2570{
2571 int ret;
794dd120
SH
2572
2573 if (!c)
2574 return false;
2575
3bc449ed 2576 if (is_stopped(c))
794dd120
SH
2577 return false;
2578
3bc449ed
SH
2579 if (container_disk_lock(c))
2580 return false;
794dd120 2581
33ad9f1a 2582 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
3bc449ed
SH
2583
2584 container_disk_unlock(c);
2585 return ret == 0;
794dd120
SH
2586}
2587
858377e4
SH
2588WRAP_API_2(bool, lxcapi_set_cgroup_item, const char *, const char *)
2589
2590static int do_lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
794dd120 2591{
3bc449ed 2592 int ret;
794dd120 2593
6502006a 2594 if (!c)
794dd120
SH
2595 return -1;
2596
3bc449ed 2597 if (is_stopped(c))
794dd120
SH
2598 return -1;
2599
3bc449ed
SH
2600 if (container_disk_lock(c))
2601 return -1;
794dd120 2602
33ad9f1a 2603 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
794dd120 2604
3bc449ed 2605 container_disk_unlock(c);
794dd120
SH
2606 return ret;
2607}
2608
858377e4
SH
2609WRAP_API_3(int, lxcapi_get_cgroup_item, const char *, char *, int)
2610
593e8478 2611const char *lxc_get_global_config_item(const char *key)
83c98d82 2612{
593e8478 2613 return lxc_global_config_value(key);
a8428dfa
SH
2614}
2615
b6b918a1
SG
2616const char *lxc_get_version(void)
2617{
95ee490b 2618 return LXC_VERSION;
b6b918a1
SG
2619}
2620
f0ca2726 2621static int copy_file(const char *old, const char *new)
9be53773
SH
2622{
2623 int in, out;
2624 ssize_t len, ret;
2625 char buf[8096];
2626 struct stat sbuf;
2627
2628 if (file_exists(new)) {
2629 ERROR("copy destination %s exists", new);
2630 return -1;
2631 }
2632 ret = stat(old, &sbuf);
2633 if (ret < 0) {
dfb31b25 2634 INFO("Error stat'ing %s", old);
9be53773
SH
2635 return -1;
2636 }
2637
2638 in = open(old, O_RDONLY);
2639 if (in < 0) {
dfb31b25 2640 SYSERROR("Error opening original file %s", old);
9be53773
SH
2641 return -1;
2642 }
2643 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
2644 if (out < 0) {
dfb31b25 2645 SYSERROR("Error opening new file %s", new);
9be53773
SH
2646 close(in);
2647 return -1;
2648 }
2649
2650 while (1) {
2651 len = read(in, buf, 8096);
2652 if (len < 0) {
dfb31b25 2653 SYSERROR("Error reading old file %s", old);
9be53773
SH
2654 goto err;
2655 }
2656 if (len == 0)
2657 break;
2658 ret = write(out, buf, len);
6849cb5b 2659 if (ret < len) { // should we retry?
dfb31b25 2660 SYSERROR("Error: write to new file %s was interrupted", new);
9be53773
SH
2661 goto err;
2662 }
2663 }
2664 close(in);
2665 close(out);
2666
2667 // we set mode, but not owner/group
2668 ret = chmod(new, sbuf.st_mode);
2669 if (ret) {
dfb31b25 2670 SYSERROR("Error setting mode on %s", new);
9be53773
SH
2671 return -1;
2672 }
2673
2674 return 0;
2675
2676err:
2677 close(in);
2678 close(out);
2679 return -1;
2680}
2681
9be53773
SH
2682static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2683{
619256b5 2684 int i, len, ret;
9be53773 2685 struct lxc_list *it;
619256b5
ÇO
2686 char *cpath;
2687
2688 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
2689 cpath = alloca(len);
2690 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
2691 if (ret < 0 || ret >= len)
2692 return -1;
9be53773
SH
2693
2694 for (i=0; i<NUM_LXC_HOOKS; i++) {
2695 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2696 char *hookname = it->elem;
c32981c3 2697 char *fname = strrchr(hookname, '/');
9be53773
SH
2698 char tmppath[MAXPATHLEN];
2699 if (!fname) // relative path - we don't support, but maybe we should
2700 return 0;
619256b5
ÇO
2701 if (strncmp(hookname, cpath, len - 1) != 0) {
2702 // this hook is public - ignore
2703 continue;
2704 }
9be53773
SH
2705 // copy the script, and change the entry in confile
2706 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2707 c->config_path, c->name, fname+1);
2708 if (ret < 0 || ret >= MAXPATHLEN)
2709 return -1;
2710 ret = copy_file(it->elem, tmppath);
2711 if (ret < 0)
2712 return -1;
2713 free(it->elem);
2714 it->elem = strdup(tmppath);
2715 if (!it->elem) {
2716 ERROR("out of memory copying hook path");
2717 return -1;
2718 }
9be53773
SH
2719 }
2720 }
2721
67702c21
SH
2722 if (!clone_update_unexp_hooks(c->lxc_conf, oldc->config_path,
2723 c->config_path, oldc->name, c->name)) {
6b0d5538
SH
2724 ERROR("Error saving new hooks in clone");
2725 return -1;
2726 }
858377e4 2727 do_lxcapi_save_config(c, NULL);
9be53773
SH
2728 return 0;
2729}
2730
9be53773
SH
2731
2732static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2733{
2734 char newpath[MAXPATHLEN];
2735 char *oldpath = oldc->lxc_conf->fstab;
2736 int ret;
2737
2738 if (!oldpath)
2739 return 0;
2740
6b0d5538
SH
2741 clear_unexp_config_line(c->lxc_conf, "lxc.mount", false);
2742
c32981c3 2743 char *p = strrchr(oldpath, '/');
9be53773
SH
2744 if (!p)
2745 return -1;
2746 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2747 c->config_path, c->name, p);
2748 if (ret < 0 || ret >= MAXPATHLEN) {
2749 ERROR("error printing new path for %s", oldpath);
2750 return -1;
2751 }
2752 if (file_exists(newpath)) {
2753 ERROR("error: fstab file %s exists", newpath);
2754 return -1;
2755 }
2756
2757 if (copy_file(oldpath, newpath) < 0) {
2758 ERROR("error: copying %s to %s", oldpath, newpath);
2759 return -1;
2760 }
2761 free(c->lxc_conf->fstab);
2762 c->lxc_conf->fstab = strdup(newpath);
2763 if (!c->lxc_conf->fstab) {
2764 ERROR("error: allocating pathname");
2765 return -1;
2766 }
6b0d5538
SH
2767 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.mount", newpath)) {
2768 ERROR("error saving new lxctab");
2769 return -1;
2770 }
9be53773
SH
2771
2772 return 0;
2773}
2774
dfb31b25
SH
2775static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2776{
2777 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2778 int ret;
2779
2780 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2781 c0->name);
2782 if (ret < 0 || ret >= MAXPATHLEN) {
2783 WARN("Error copying reverse dependencies");
2784 return;
2785 }
2786 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2787 c->name);
2788 if (ret < 0 || ret >= MAXPATHLEN) {
2789 WARN("Error copying reverse dependencies");
2790 return;
2791 }
2792 if (copy_file(path0, path1) < 0) {
2793 INFO("Error copying reverse dependencies");
2794 return;
2795 }
2796}
2797
2798static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2799{
2800 int ret;
2801 char path[MAXPATHLEN];
2802 FILE *f;
2803 bool bret;
2804
2805 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2806 c->name);
2807 if (ret < 0 || ret >= MAXPATHLEN)
2808 return false;
2809 f = fopen(path, "a");
2810 if (!f)
2811 return false;
2812 bret = true;
2813 // if anything goes wrong, just return an error
2814 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2815 bret = false;
2816 if (fclose(f) != 0)
2817 bret = false;
2818 return bret;
2819}
2820
15a90a10
SH
2821/*
2822 * If the fs natively supports snapshot clones with no penalty,
2823 * then default to those even if not requested.
2824 * Currently we only do this for btrfs.
2825 */
2826bool should_default_to_snapshot(struct lxc_container *c0,
2827 struct lxc_container *c1)
2828{
2829 size_t l0 = strlen(c0->config_path) + strlen(c0->name) + 2;
2830 size_t l1 = strlen(c1->config_path) + strlen(c1->name) + 2;
2831 char *p0 = alloca(l0 + 1);
2832 char *p1 = alloca(l1 + 1);
6e0fa6a0 2833 char *rootfs = c0->lxc_conf->rootfs.path;
15a90a10
SH
2834
2835 snprintf(p0, l0, "%s/%s", c0->config_path, c0->name);
2836 snprintf(p1, l1, "%s/%s", c1->config_path, c1->name);
9a09badc
CB
2837
2838 if (!is_btrfs_fs(p0) || !is_btrfs_fs(p1))
2839 return false;
2840
6e0fa6a0
CB
2841 if (is_btrfs_subvol(rootfs) <= 0)
2842 return false;
2843
15a90a10
SH
2844 return btrfs_same_fs(p0, p1) == 0;
2845}
2846
9be53773 2847static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
763429b6
CB
2848 const char *newtype, int flags, const char *bdevdata,
2849 uint64_t newsize)
9be53773
SH
2850{
2851 struct bdev *bdev;
dfb31b25 2852 int need_rdep;
9be53773 2853
15a90a10
SH
2854 if (should_default_to_snapshot(c0, c))
2855 flags |= LXC_CLONE_SNAPSHOT;
2856
763429b6
CB
2857 bdev = bdev_copy(c0, c->name, c->config_path, newtype, flags, bdevdata,
2858 newsize, &need_rdep);
9be53773 2859 if (!bdev) {
763429b6 2860 ERROR("Error copying storage.");
9be53773
SH
2861 return -1;
2862 }
763429b6
CB
2863
2864 /* Set new rootfs. */
9be53773
SH
2865 free(c->lxc_conf->rootfs.path);
2866 c->lxc_conf->rootfs.path = strdup(bdev->src);
763429b6
CB
2867
2868 /* Set new bdev type. */
8869eb5f
CB
2869 free(c->lxc_conf->rootfs.bdev_type);
2870 c->lxc_conf->rootfs.bdev_type = strdup(bdev->type);
9be53773 2871 bdev_put(bdev);
763429b6 2872
dfb31b25 2873 if (!c->lxc_conf->rootfs.path) {
763429b6
CB
2874 ERROR("Out of memory while setting storage path.");
2875 return -1;
2876 }
2877 if (!c->lxc_conf->rootfs.bdev_type) {
2878 ERROR("Out of memory while setting rootfs backend.");
9be53773 2879 return -1;
dfb31b25 2880 }
763429b6
CB
2881
2882 /* Append a new lxc.rootfs entry to the unexpanded config. */
6b0d5538 2883 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs", false);
763429b6
CB
2884 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs",
2885 c->lxc_conf->rootfs.path)) {
2886 ERROR("Error saving new rootfs to cloned config.");
d0218321
SH
2887 return -1;
2888 }
763429b6
CB
2889
2890 /* Append a new lxc.rootfs.backend entry to the unexpanded config. */
8869eb5f 2891 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.backend", false);
763429b6
CB
2892 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs.backend",
2893 c->lxc_conf->rootfs.bdev_type)) {
2894 ERROR("Error saving new rootfs backend to cloned config.");
8869eb5f
CB
2895 return -1;
2896 }
763429b6 2897
eee59f94
SH
2898 if (flags & LXC_CLONE_SNAPSHOT)
2899 copy_rdepends(c, c0);
dfb31b25
SH
2900 if (need_rdep) {
2901 if (!add_rdepends(c, c0))
2902 WARN("Error adding reverse dependency from %s to %s",
763429b6 2903 c->name, c0->name);
dfb31b25
SH
2904 }
2905
2906 mod_all_rdeps(c, true);
2907
9be53773
SH
2908 return 0;
2909}
2910
1354955b
SH
2911struct clone_update_data {
2912 struct lxc_container *c0;
2913 struct lxc_container *c1;
2914 int flags;
2915 char **hookargs;
2916};
2917
2918static int clone_update_rootfs(struct clone_update_data *data)
9be53773 2919{
1354955b
SH
2920 struct lxc_container *c0 = data->c0;
2921 struct lxc_container *c = data->c1;
2922 int flags = data->flags;
2923 char **hookargs = data->hookargs;
9be53773
SH
2924 int ret = -1;
2925 char path[MAXPATHLEN];
2926 struct bdev *bdev;
2927 FILE *fout;
148e91f5 2928 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
2929
2930 /* update hostname in rootfs */
2931 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2932
1354955b
SH
2933 if (setgid(0) < 0) {
2934 ERROR("Failed to setgid to 0");
2935 return -1;
2936 }
2937 if (setuid(0) < 0) {
2938 ERROR("Failed to setuid to 0");
9be53773 2939 return -1;
1354955b 2940 }
c476bdce
SH
2941 if (setgroups(0, NULL) < 0)
2942 WARN("Failed to clear groups");
9be53773 2943
1354955b
SH
2944 if (unshare(CLONE_NEWNS) < 0)
2945 return -1;
76a26f55 2946 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
9be53773 2947 if (!bdev)
1354955b 2948 return -1;
cf3ef16d
SH
2949 if (strcmp(bdev->type, "dir") != 0) {
2950 if (unshare(CLONE_NEWNS) < 0) {
2951 ERROR("error unsharing mounts");
e7de366c 2952 bdev_put(bdev);
1354955b 2953 return -1;
cf3ef16d 2954 }
2c6f3fc9
SH
2955 if (detect_shared_rootfs()) {
2956 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
2957 SYSERROR("Failed to make / rslave");
2958 ERROR("Continuing...");
2959 }
2960 }
e7de366c
SG
2961 if (bdev->ops->mount(bdev) < 0) {
2962 bdev_put(bdev);
1354955b 2963 return -1;
e7de366c 2964 }
cf3ef16d 2965 } else { // TODO come up with a better way
f10fad2f 2966 free(bdev->dest);
cf3ef16d
SH
2967 bdev->dest = strdup(bdev->src);
2968 }
148e91f5
SH
2969
2970 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2971 /* Start of environment variable setup for hooks */
ab7efcf5 2972 if (c0->name && setenv("LXC_SRC_NAME", c0->name, 1)) {
1143ed39
DE
2973 SYSERROR("failed to set environment variable for source container name");
2974 }
ab7efcf5 2975 if (c->name && setenv("LXC_NAME", c->name, 1)) {
148e91f5
SH
2976 SYSERROR("failed to set environment variable for container name");
2977 }
ab7efcf5 2978 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
148e91f5
SH
2979 SYSERROR("failed to set environment variable for config path");
2980 }
ab7efcf5 2981 if (bdev->dest && setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1)) {
148e91f5
SH
2982 SYSERROR("failed to set environment variable for rootfs mount");
2983 }
ab7efcf5 2984 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
148e91f5
SH
2985 SYSERROR("failed to set environment variable for rootfs mount");
2986 }
2987
283678ed 2988 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
148e91f5 2989 ERROR("Error executing clone hook for %s", c->name);
e7de366c 2990 bdev_put(bdev);
1354955b 2991 return -1;
148e91f5
SH
2992 }
2993 }
2994
2995 if (!(flags & LXC_CLONE_KEEPNAME)) {
2996 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
e7de366c
SG
2997 bdev_put(bdev);
2998
148e91f5 2999 if (ret < 0 || ret >= MAXPATHLEN)
1354955b 3000 return -1;
8058be39 3001 if (!file_exists(path))
1354955b 3002 return 0;
148e91f5 3003 if (!(fout = fopen(path, "w"))) {
959aee9c 3004 SYSERROR("unable to open %s: ignoring", path);
1354955b 3005 return 0;
148e91f5 3006 }
a684f0b7
ÇO
3007 if (fprintf(fout, "%s", c->name) < 0) {
3008 fclose(fout);
1354955b 3009 return -1;
6849cb5b 3010 }
148e91f5 3011 if (fclose(fout) < 0)
1354955b 3012 return -1;
9be53773 3013 }
e7de366c
SG
3014 else
3015 bdev_put(bdev);
3016
1354955b
SH
3017 return 0;
3018}
3019
3020static int clone_update_rootfs_wrapper(void *data)
3021{
3022 struct clone_update_data *arg = (struct clone_update_data *) data;
3023 return clone_update_rootfs(arg);
9be53773
SH
3024}
3025
3026/*
3027 * We want to support:
3028sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3029 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3030
3031-s [ implies overlayfs]
3032-s -B overlayfs
3033-s -B aufs
3034
3035only rootfs gets converted (copied/snapshotted) on clone.
3036*/
3037
d5752559 3038static int create_file_dirname(char *path, struct lxc_conf *conf)
9be53773 3039{
c32981c3 3040 char *p = strrchr(path, '/');
d5752559 3041 int ret = -1;
9be53773
SH
3042
3043 if (!p)
3044 return -1;
3045 *p = '\0';
d028235d 3046 ret = do_create_container_dir(path, conf);
9be53773
SH
3047 *p = '/';
3048 return ret;
3049}
3050
858377e4 3051static struct lxc_container *do_lxcapi_clone(struct lxc_container *c, const char *newname,
9be53773 3052 const char *lxcpath, int flags,
d659597e 3053 const char *bdevtype, const char *bdevdata, uint64_t newsize,
148e91f5 3054 char **hookargs)
9be53773
SH
3055{
3056 struct lxc_container *c2 = NULL;
3057 char newpath[MAXPATHLEN];
176d9acb 3058 int ret, storage_copied = 0;
5eea90e8 3059 char *origroot = NULL, *saved_unexp_conf = NULL;
1354955b 3060 struct clone_update_data data;
3b392519 3061 size_t saved_unexp_len;
9be53773 3062 FILE *fout;
1354955b 3063 pid_t pid;
9be53773 3064
858377e4 3065 if (!c || !do_lxcapi_is_defined(c))
9be53773
SH
3066 return NULL;
3067
5cee8c50 3068 if (container_mem_lock(c))
9be53773
SH
3069 return NULL;
3070
39dc698c 3071 if (!is_stopped(c)) {
9be53773
SH
3072 ERROR("error: Original container (%s) is running", c->name);
3073 goto out;
3074 }
3075
3076 // Make sure the container doesn't yet exist.
05d53f4c
SH
3077 if (!newname)
3078 newname = c->name;
3079 if (!lxcpath)
858377e4 3080 lxcpath = do_lxcapi_get_config_path(c);
05d53f4c 3081 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", lxcpath, newname);
6849cb5b 3082 if (ret < 0 || ret >= MAXPATHLEN) {
9be53773
SH
3083 SYSERROR("clone: failed making config pathname");
3084 goto out;
3085 }
3086 if (file_exists(newpath)) {
3087 ERROR("error: clone: %s exists", newpath);
3088 goto out;
3089 }
3090
d5752559 3091 ret = create_file_dirname(newpath, c->lxc_conf);
96532523 3092 if (ret < 0 && errno != EEXIST) {
9be53773
SH
3093 ERROR("Error creating container dir for %s", newpath);
3094 goto out;
3095 }
3096
3097 // copy the configuration, tweak it as needed,
8d2efe40
SH
3098 if (c->lxc_conf->rootfs.path) {
3099 origroot = c->lxc_conf->rootfs.path;
3100 c->lxc_conf->rootfs.path = NULL;
3101 }
9be53773
SH
3102 fout = fopen(newpath, "w");
3103 if (!fout) {
3104 SYSERROR("open %s", newpath);
3105 goto out;
3106 }
5eea90e8
SH
3107
3108 saved_unexp_conf = c->lxc_conf->unexpanded_config;
3b392519 3109 saved_unexp_len = c->lxc_conf->unexpanded_len;
5eea90e8
SH
3110 c->lxc_conf->unexpanded_config = strdup(saved_unexp_conf);
3111 if (!c->lxc_conf->unexpanded_config) {
3112 ERROR("Out of memory");
7d72b959 3113 fclose(fout);
5eea90e8
SH
3114 goto out;
3115 }
3116 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs", false);
6b0d5538 3117 write_config(fout, c->lxc_conf);
9be53773 3118 fclose(fout);
8d2efe40 3119 c->lxc_conf->rootfs.path = origroot;
5eea90e8
SH
3120 free(c->lxc_conf->unexpanded_config);
3121 c->lxc_conf->unexpanded_config = saved_unexp_conf;
3122 saved_unexp_conf = NULL;
3b392519 3123 c->lxc_conf->unexpanded_len = saved_unexp_len;
9be53773 3124
05d53f4c 3125 sprintf(newpath, "%s/%s/rootfs", lxcpath, newname);
9be53773
SH
3126 if (mkdir(newpath, 0755) < 0) {
3127 SYSERROR("error creating %s", newpath);
3128 goto out;
3129 }
3130
1354955b
SH
3131 if (am_unpriv()) {
3132 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
959aee9c 3133 ERROR("Error chowning %s to container root", newpath);
1354955b
SH
3134 goto out;
3135 }
3136 }
3137
05d53f4c 3138 c2 = lxc_container_new(newname, lxcpath);
375c2258 3139 if (!c2) {
05d53f4c
SH
3140 ERROR("clone: failed to create new container (%s %s)", newname,
3141 lxcpath);
9be53773
SH
3142 goto out;
3143 }
8d2efe40
SH
3144
3145 // copy/snapshot rootfs's
3146 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
3147 if (ret < 0)
3148 goto out;
9be53773 3149
6b0d5538 3150
96532523 3151 // update utsname
3d7ad474
CB
3152 if (!(flags & LXC_CLONE_KEEPNAME)) {
3153 clear_unexp_config_line(c2->lxc_conf, "lxc.utsname", false);
3154
3155 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
3156 ERROR("Error setting new hostname");
3157 goto out;
3158 }
96532523
SH
3159 }
3160
619256b5
ÇO
3161 // copy hooks
3162 ret = copyhooks(c, c2);
3163 if (ret < 0) {
3164 ERROR("error copying hooks");
3165 goto out;
9be53773
SH
3166 }
3167
3168 if (copy_fstab(c, c2) < 0) {
3169 ERROR("error copying fstab");
9be53773
SH
3170 goto out;
3171 }
3172
3173 // update macaddrs
6b0d5538 3174 if (!(flags & LXC_CLONE_KEEPMACADDR)) {
67702c21
SH
3175 if (!network_new_hwaddrs(c2->lxc_conf)) {
3176 ERROR("Error updating mac addresses");
6b0d5538
SH
3177 goto out;
3178 }
3179 }
9be53773 3180
030ce9a9 3181 // update absolute paths for overlay mount directories
83e79752 3182 if (ovl_update_abs_paths(c2->lxc_conf, c->config_path, c->name, lxcpath, newname) < 0)
030ce9a9
CB
3183 goto out;
3184
176d9acb
SH
3185 // We've now successfully created c2's storage, so clear it out if we
3186 // fail after this
3187 storage_copied = 1;
3188
375c2258 3189 if (!c2->save_config(c2, NULL))
9be53773 3190 goto out;
9be53773 3191
1354955b
SH
3192 if ((pid = fork()) < 0) {
3193 SYSERROR("fork");
9be53773 3194 goto out;
1354955b
SH
3195 }
3196 if (pid > 0) {
3197 ret = wait_for_pid(pid);
3198 if (ret)
3199 goto out;
3200 container_mem_unlock(c);
3201 return c2;
3202 }
3203 data.c0 = c;
3204 data.c1 = c2;
3205 data.flags = flags;
3206 data.hookargs = hookargs;
3207 if (am_unpriv())
3208 ret = userns_exec_1(c->lxc_conf, clone_update_rootfs_wrapper,
3209 &data);
3210 else
3211 ret = clone_update_rootfs(&data);
3212 if (ret < 0)
3213 exit(1);
9be53773 3214
5cee8c50 3215 container_mem_unlock(c);
1354955b 3216 exit(0);
9be53773
SH
3217
3218out:
5cee8c50 3219 container_mem_unlock(c);
375c2258 3220 if (c2) {
176d9acb
SH
3221 if (!storage_copied)
3222 c2->lxc_conf->rootfs.path = NULL;
375c2258 3223 c2->destroy(c2);
9be53773 3224 lxc_container_put(c2);
375c2258 3225 }
9be53773
SH
3226
3227 return NULL;
3228}
3229
858377e4
SH
3230static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
3231 const char *lxcpath, int flags,
3232 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3233 char **hookargs)
3234{
3235 struct lxc_container * ret;
3236 current_config = c ? c->lxc_conf : NULL;
3237 ret = do_lxcapi_clone(c, newname, lxcpath, flags, bdevtype, bdevdata, newsize, hookargs);
3238 current_config = NULL;
3239 return ret;
3240}
3241
3242static bool do_lxcapi_rename(struct lxc_container *c, const char *newname)
06e5650e
ÇO
3243{
3244 struct bdev *bdev;
3245 struct lxc_container *newc;
06e5650e 3246
d693cf93 3247 if (!c || !c->name || !c->config_path || !c->lxc_conf)
06e5650e
ÇO
3248 return false;
3249
18aa217b
SH
3250 if (has_fs_snapshots(c) || has_snapshots(c)) {
3251 ERROR("Renaming a container with snapshots is not supported");
3252 return false;
3253 }
76a26f55 3254 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
06e5650e
ÇO
3255 if (!bdev) {
3256 ERROR("Failed to find original backing store type");
3257 return false;
3258 }
3259
619256b5 3260 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
06e5650e
ÇO
3261 bdev_put(bdev);
3262 if (!newc) {
3263 lxc_container_put(newc);
3264 return false;
3265 }
3266
3267 if (newc && lxcapi_is_defined(newc))
3268 lxc_container_put(newc);
3269
18aa217b 3270 if (!container_destroy(c)) {
06e5650e
ÇO
3271 ERROR("Could not destroy existing container %s", c->name);
3272 return false;
3273 }
3274 return true;
3275}
3276
858377e4
SH
3277WRAP_API_1(bool, lxcapi_rename, const char *)
3278
a0e93eeb
CS
3279static int lxcapi_attach(struct lxc_container *c, lxc_attach_exec_t exec_function, void *exec_payload, lxc_attach_options_t *options, pid_t *attached_process)
3280{
858377e4
SH
3281 int ret;
3282
a0e93eeb
CS
3283 if (!c)
3284 return -1;
3285
858377e4
SH
3286 current_config = c->lxc_conf;
3287
3288 ret = lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
3289 current_config = NULL;
3290 return ret;
a0e93eeb
CS
3291}
3292
858377e4 3293static int do_lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
a0e93eeb
CS
3294{
3295 lxc_attach_command_t command;
3296 pid_t pid;
3297 int r;
3298
3299 if (!c)
3300 return -1;
3301
3302 command.program = (char*)program;
3303 command.argv = (char**)argv;
3304 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
3305 if (r < 0) {
3306 ERROR("ups");
3307 return r;
3308 }
3309 return lxc_wait_for_pid_status(pid);
3310}
3311
858377e4
SH
3312static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
3313{
3314 int ret;
3315 current_config = c ? c->lxc_conf : NULL;
3316 ret = do_lxcapi_attach_run_wait(c, options, program, argv);
3317 current_config = NULL;
3318 return ret;
3319}
3320
74a3920a 3321static int get_next_index(const char *lxcpath, char *cname)
f5dd1d53
SH
3322{
3323 char *fname;
3324 struct stat sb;
3325 int i = 0, ret;
3326
3327 fname = alloca(strlen(lxcpath) + 20);
3328 while (1) {
3329 sprintf(fname, "%s/snap%d", lxcpath, i);
3330 ret = stat(fname, &sb);
3331 if (ret != 0)
3332 return i;
3333 i++;
3334 }
3335}
3336
18aa217b
SH
3337static bool get_snappath_dir(struct lxc_container *c, char *snappath)
3338{
3339 int ret;
3340 /*
3341 * If the old style snapshot path exists, use it
3342 * /var/lib/lxc -> /var/lib/lxcsnaps
3343 */
3344 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps", c->config_path);
3345 if (ret < 0 || ret >= MAXPATHLEN)
3346 return false;
3347 if (dir_exists(snappath)) {
3348 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
3349 if (ret < 0 || ret >= MAXPATHLEN)
3350 return false;
3351 return true;
3352 }
3353
3354 /*
3355 * Use the new style path
3356 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3357 */
3358 ret = snprintf(snappath, MAXPATHLEN, "%s/%s/snaps", c->config_path, c->name);
3359 if (ret < 0 || ret >= MAXPATHLEN)
3360 return false;
3361 return true;
3362}
3363
858377e4 3364static int do_lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
f5dd1d53
SH
3365{
3366 int i, flags, ret;
3367 struct lxc_container *c2;
3368 char snappath[MAXPATHLEN], newname[20];
3369
840f05df
SH
3370 if (!c || !lxcapi_is_defined(c))
3371 return -1;
3372
cdd01be2
SH
3373 if (!bdev_can_backup(c->lxc_conf)) {
3374 ERROR("%s's backing store cannot be backed up.", c->name);
3375 ERROR("Your container must use another backing store type.");
3376 return -1;
3377 }
3378
18aa217b 3379 if (!get_snappath_dir(c, snappath))
f5dd1d53 3380 return -1;
18aa217b 3381
f5dd1d53
SH
3382 i = get_next_index(snappath, c->name);
3383
3384 if (mkdir_p(snappath, 0755) < 0) {
3385 ERROR("Failed to create snapshot directory %s", snappath);
3386 return -1;
3387 }
3388
3389 ret = snprintf(newname, 20, "snap%d", i);
3390 if (ret < 0 || ret >= 20)
3391 return -1;
3392
0a83cbbb
SH
3393 /*
3394 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3395 * created in the original container
3396 */
3397 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
3398 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
76a26f55 3399 if (bdev_is_dir(c->lxc_conf, c->lxc_conf->rootfs.path)) {
8c39f7a4
SH
3400 ERROR("Snapshot of directory-backed container requested.");
3401 ERROR("Making a copy-clone. If you do want snapshots, then");
1f92162d 3402 ERROR("please create an aufs or overlayfs clone first, snapshot that");
8c39f7a4
SH
3403 ERROR("and keep the original container pristine.");
3404 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3405 }
858377e4 3406 c2 = do_lxcapi_clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
f5dd1d53 3407 if (!c2) {
959aee9c 3408 ERROR("clone of %s:%s failed", c->config_path, c->name);
f5dd1d53
SH
3409 return -1;
3410 }
3411
3412 lxc_container_put(c2);
3413
3414 // Now write down the creation time
3415 time_t timer;
3416 char buffer[25];
3417 struct tm* tm_info;
025ed0f3 3418 FILE *f;
f5dd1d53
SH
3419
3420 time(&timer);
3421 tm_info = localtime(&timer);
3422
3423 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
3424
3425 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
3426 sprintf(dfnam, "%s/%s/ts", snappath, newname);
025ed0f3 3427 f = fopen(dfnam, "w");
f5dd1d53 3428 if (!f) {
959aee9c 3429 ERROR("Failed to open %s", dfnam);
f5dd1d53
SH
3430 return -1;
3431 }
3432 if (fprintf(f, "%s", buffer) < 0) {
3433 SYSERROR("Writing timestamp");
3434 fclose(f);
3435 return -1;
3436 }
025ed0f3 3437 ret = fclose(f);
025ed0f3 3438 if (ret != 0) {
f5dd1d53
SH
3439 SYSERROR("Writing timestamp");
3440 return -1;
3441 }
3442
3443 if (commentfile) {
3444 // $p / $name / comment \0
3445 int len = strlen(snappath) + strlen(newname) + 10;
3446 char *path = alloca(len);
3447 sprintf(path, "%s/%s/comment", snappath, newname);
3448 return copy_file(commentfile, path) < 0 ? -1 : i;
3449 }
3450
3451 return i;
3452}
3453
858377e4
SH
3454WRAP_API_1(int, lxcapi_snapshot, const char *)
3455
f5dd1d53
SH
3456static void lxcsnap_free(struct lxc_snapshot *s)
3457{
f10fad2f
ME
3458 free(s->name);
3459 free(s->comment_pathname);
3460 free(s->timestamp);
3461 free(s->lxcpath);
f5dd1d53
SH
3462}
3463
3464static char *get_snapcomment_path(char* snappath, char *name)
3465{
3466 // $snappath/$name/comment
3467 int ret, len = strlen(snappath) + strlen(name) + 10;
3468 char *s = malloc(len);
3469
3470 if (s) {
3471 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
3472 if (ret < 0 || ret >= len) {
3473 free(s);
3474 s = NULL;
3475 }
3476 }
3477 return s;
3478}
3479
3480static char *get_timestamp(char* snappath, char *name)
3481{
3482 char path[MAXPATHLEN], *s = NULL;
3483 int ret, len;
3484 FILE *fin;
3485
3486 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
3487 if (ret < 0 || ret >= MAXPATHLEN)
3488 return NULL;
025ed0f3 3489 fin = fopen(path, "r");
025ed0f3 3490 if (!fin)
f5dd1d53
SH
3491 return NULL;
3492 (void) fseek(fin, 0, SEEK_END);
3493 len = ftell(fin);
3494 (void) fseek(fin, 0, SEEK_SET);
3495 if (len > 0) {
3496 s = malloc(len+1);
3497 if (s) {
3498 s[len] = '\0';
3499 if (fread(s, 1, len, fin) != len) {
3500 SYSERROR("reading timestamp");
3501 free(s);
3502 s = NULL;
3503 }
3504 }
3505 }
3506 fclose(fin);
3507 return s;
3508}
3509
858377e4 3510static int do_lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
f5dd1d53
SH
3511{
3512 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
18aa217b 3513 int count = 0, ret;
74f96976 3514 struct dirent *direntp;
f5dd1d53
SH
3515 struct lxc_snapshot *snaps =NULL, *nsnaps;
3516 DIR *dir;
3517
3518 if (!c || !lxcapi_is_defined(c))
3519 return -1;
c868b261 3520
18aa217b 3521 if (!get_snappath_dir(c, snappath)) {
f5dd1d53
SH
3522 ERROR("path name too long");
3523 return -1;
3524 }
025ed0f3 3525 dir = opendir(snappath);
025ed0f3 3526 if (!dir) {
f5dd1d53
SH
3527 INFO("failed to open %s - assuming no snapshots", snappath);
3528 return 0;
3529 }
3530
74f96976 3531 while ((direntp = readdir(dir))) {
f5dd1d53
SH
3532 if (!direntp)
3533 break;
3534
3535 if (!strcmp(direntp->d_name, "."))
3536 continue;
3537
3538 if (!strcmp(direntp->d_name, ".."))
3539 continue;
3540
3541 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
3542 if (ret < 0 || ret >= MAXPATHLEN) {
3543 ERROR("pathname too long");
3544 goto out_free;
3545 }
3546 if (!file_exists(path2))
3547 continue;
3548 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
3549 if (!nsnaps) {
3550 SYSERROR("Out of memory");
3551 goto out_free;
3552 }
3553 snaps = nsnaps;
3554 snaps[count].free = lxcsnap_free;
3555 snaps[count].name = strdup(direntp->d_name);
3556 if (!snaps[count].name)
3557 goto out_free;
3558 snaps[count].lxcpath = strdup(snappath);
3559 if (!snaps[count].lxcpath) {
3560 free(snaps[count].name);
3561 goto out_free;
3562 }
3563 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
3564 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
3565 count++;
3566 }
3567
3568 if (closedir(dir))
3569 WARN("failed to close directory");
3570
3571 *ret_snaps = snaps;
3572 return count;
3573
3574out_free:
3575 if (snaps) {
3576 int i;
3577 for (i=0; i<count; i++)
3578 lxcsnap_free(&snaps[i]);
3579 free(snaps);
3580 }
9baa57bd
SH
3581 if (closedir(dir))
3582 WARN("failed to close directory");
f5dd1d53
SH
3583 return -1;
3584}
3585
858377e4
SH
3586WRAP_API_1(int, lxcapi_snapshot_list, struct lxc_snapshot **)
3587
3588static bool do_lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
f5dd1d53
SH
3589{
3590 char clonelxcpath[MAXPATHLEN];
18aa217b 3591 int flags = 0;
f5dd1d53
SH
3592 struct lxc_container *snap, *rest;
3593 struct bdev *bdev;
3594 bool b = false;
3595
3596 if (!c || !c->name || !c->config_path)
3597 return false;
3598
18aa217b
SH
3599 if (has_fs_snapshots(c)) {
3600 ERROR("container rootfs has dependent snapshots");
3601 return false;
3602 }
3603
76a26f55 3604 bdev = bdev_init(c->lxc_conf, c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
f5dd1d53
SH
3605 if (!bdev) {
3606 ERROR("Failed to find original backing store type");
3607 return false;
3608 }
3609
3610 if (!newname)
3611 newname = c->name;
7e36f87e 3612
18aa217b 3613 if (!get_snappath_dir(c, clonelxcpath)) {
f5dd1d53
SH
3614 bdev_put(bdev);
3615 return false;
3616 }
3617 // how should we lock this?
3618
3619 snap = lxc_container_new(snapname, clonelxcpath);
3620 if (!snap || !lxcapi_is_defined(snap)) {
3621 ERROR("Could not open snapshot %s", snapname);
3622 if (snap) lxc_container_put(snap);
3623 bdev_put(bdev);
3624 return false;
3625 }
3626
7e36f87e 3627 if (strcmp(c->name, newname) == 0) {
18aa217b 3628 if (!container_destroy(c)) {
7e36f87e
ÇO
3629 ERROR("Could not destroy existing container %s", newname);
3630 lxc_container_put(snap);
3631 bdev_put(bdev);
3632 return false;
3633 }
3634 }
3635
de269ee8
SH
3636 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
3637 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3638 rest = lxcapi_clone(snap, newname, c->config_path, flags,
3639 bdev->type, NULL, 0, NULL);
f5dd1d53
SH
3640 bdev_put(bdev);
3641 if (rest && lxcapi_is_defined(rest))
3642 b = true;
3643 if (rest)
3644 lxc_container_put(rest);
3645 lxc_container_put(snap);
3646 return b;
3647}
3648
858377e4
SH
3649WRAP_API_2(bool, lxcapi_snapshot_restore, const char *, const char *)
3650
18aa217b 3651static bool do_snapshot_destroy(const char *snapname, const char *clonelxcpath)
771d96b3 3652{
771d96b3 3653 struct lxc_container *snap = NULL;
18aa217b 3654 bool bret = false;
771d96b3
ÇO
3655
3656 snap = lxc_container_new(snapname, clonelxcpath);
18aa217b 3657 if (!snap) {
771d96b3
ÇO
3658 ERROR("Could not find snapshot %s", snapname);
3659 goto err;
3660 }
3661
858377e4 3662 if (!do_lxcapi_destroy(snap)) {
771d96b3
ÇO
3663 ERROR("Could not destroy snapshot %s", snapname);
3664 goto err;
3665 }
18aa217b 3666 bret = true;
771d96b3 3667
771d96b3
ÇO
3668err:
3669 if (snap)
3670 lxc_container_put(snap);
18aa217b
SH
3671 return bret;
3672}
3673
3674static bool remove_all_snapshots(const char *path)
3675{
3676 DIR *dir;
74f96976 3677 struct dirent *direntp;
18aa217b
SH
3678 bool bret = true;
3679
3680 dir = opendir(path);
3681 if (!dir) {
3682 SYSERROR("opendir on snapshot path %s", path);
3683 return false;
3684 }
74f96976 3685 while ((direntp = readdir(dir))) {
18aa217b
SH
3686 if (!direntp)
3687 break;
3688 if (!strcmp(direntp->d_name, "."))
3689 continue;
3690 if (!strcmp(direntp->d_name, ".."))
3691 continue;
3692 if (!do_snapshot_destroy(direntp->d_name, path)) {
3693 bret = false;
3694 continue;
3695 }
3696 }
3697
3698 closedir(dir);
3699
3700 if (rmdir(path))
3701 SYSERROR("Error removing directory %s", path);
3702
3703 return bret;
3704}
3705
858377e4 3706static bool do_lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
18aa217b
SH
3707{
3708 char clonelxcpath[MAXPATHLEN];
3709
3710 if (!c || !c->name || !c->config_path || !snapname)
3711 return false;
3712
3713 if (!get_snappath_dir(c, clonelxcpath))
3714 return false;
3715
3716 return do_snapshot_destroy(snapname, clonelxcpath);
3717}
3718
858377e4
SH
3719WRAP_API_1(bool, lxcapi_snapshot_destroy, const char *)
3720
3721static bool do_lxcapi_snapshot_destroy_all(struct lxc_container *c)
18aa217b
SH
3722{
3723 char clonelxcpath[MAXPATHLEN];
3724
3725 if (!c || !c->name || !c->config_path)
3726 return false;
3727
3728 if (!get_snappath_dir(c, clonelxcpath))
3729 return false;
3730
3731 return remove_all_snapshots(clonelxcpath);
771d96b3
ÇO
3732}
3733
858377e4
SH
3734WRAP_API(bool, lxcapi_snapshot_destroy_all)
3735
3736static bool do_lxcapi_may_control(struct lxc_container *c)
b494d2dd
SH
3737{
3738 return lxc_try_cmd(c->name, c->config_path) == 0;
3739}
3740
858377e4
SH
3741WRAP_API(bool, lxcapi_may_control)
3742
d5aa23e6
SH
3743static bool do_add_remove_node(pid_t init_pid, const char *path, bool add,
3744 struct stat *st)
3745{
3746 char chrootpath[MAXPATHLEN];
3747 char *directory_path = NULL;
3748 pid_t pid;
3749 int ret;
3750
3751 if ((pid = fork()) < 0) {
3752 SYSERROR("failed to fork a child helper");
3753 return false;
3754 }
3755 if (pid) {
3756 if (wait_for_pid(pid) != 0) {
3757 ERROR("Failed to create note in guest");
3758 return false;
3759 }
3760 return true;
3761 }
3762
3763 /* prepare the path */
3764 ret = snprintf(chrootpath, MAXPATHLEN, "/proc/%d/root", init_pid);
3765 if (ret < 0 || ret >= MAXPATHLEN)
3766 return false;
3767
6b9324bd 3768 if (chroot(chrootpath) < 0)
d5aa23e6 3769 exit(1);
6b9324bd 3770 if (chdir("/") < 0)
d5aa23e6
SH
3771 exit(1);
3772 /* remove path if it exists */
3773 if(faccessat(AT_FDCWD, path, F_OK, AT_SYMLINK_NOFOLLOW) == 0) {
3774 if (unlink(path) < 0) {
3775 ERROR("unlink failed");
3776 exit(1);
3777 }
3778 }
3779 if (!add)
3780 exit(0);
3781
3782 /* create any missing directories */
3783 directory_path = dirname(strdup(path));
3784 if (mkdir_p(directory_path, 0755) < 0 && errno != EEXIST) {
3785 ERROR("failed to create directory");
3786 exit(1);
3787 }
3788
3789 /* create the device node */
3790 if (mknod(path, st->st_mode, st->st_rdev) < 0) {
3791 ERROR("mknod failed");
3792 exit(1);
3793 }
3794
3795 exit(0);
3796}
3797
f0ca2726 3798static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
a9a0ed90
ÇO
3799{
3800 int ret;
3801 struct stat st;
a9a0ed90 3802 char value[MAX_BUFFER];
f0ca2726 3803 const char *p;
a9a0ed90
ÇO
3804
3805 /* make sure container is running */
858377e4 3806 if (!do_lxcapi_is_running(c)) {
a9a0ed90 3807 ERROR("container is not running");
d5aa23e6 3808 return false;
a9a0ed90
ÇO
3809 }
3810
3811 /* use src_path if dest_path is NULL otherwise use dest_path */
3812 p = dest_path ? dest_path : src_path;
3813
a9a0ed90
ÇO
3814 /* make sure we can access p */
3815 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
d5aa23e6 3816 return false;
a9a0ed90
ÇO
3817
3818 /* continue if path is character device or block device */
c6a9b0d7 3819 if (S_ISCHR(st.st_mode))
a9a0ed90 3820 ret = snprintf(value, MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
c6a9b0d7 3821 else if (S_ISBLK(st.st_mode))
a9a0ed90
ÇO
3822 ret = snprintf(value, MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
3823 else
d5aa23e6 3824 return false;
a9a0ed90
ÇO
3825
3826 /* check snprintf return code */
3827 if (ret < 0 || ret >= MAX_BUFFER)
d5aa23e6 3828 return false;
a9a0ed90 3829
858377e4 3830 if (!do_add_remove_node(do_lxcapi_init_pid(c), p, add, &st))
d5aa23e6 3831 return false;
a9a0ed90 3832
d5aa23e6 3833 /* add or remove device to/from cgroup access list */
a9a0ed90 3834 if (add) {
858377e4 3835 if (!do_lxcapi_set_cgroup_item(c, "devices.allow", value)) {
a9a0ed90 3836 ERROR("set_cgroup_item failed while adding the device node");
d5aa23e6 3837 return false;
a9a0ed90
ÇO
3838 }
3839 } else {
858377e4 3840 if (!do_lxcapi_set_cgroup_item(c, "devices.deny", value)) {
a9a0ed90 3841 ERROR("set_cgroup_item failed while removing the device node");
d5aa23e6 3842 return false;
a9a0ed90
ÇO
3843 }
3844 }
d5aa23e6 3845
a9a0ed90 3846 return true;
a9a0ed90
ÇO
3847}
3848
858377e4 3849static bool do_lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 3850{
c868b261
ÇO
3851 if (am_unpriv()) {
3852 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3853 return false;
3854 }
a9a0ed90
ÇO
3855 return add_remove_device_node(c, src_path, dest_path, true);
3856}
3857
858377e4
SH
3858WRAP_API_2(bool, lxcapi_add_device_node, const char *, const char *)
3859
3860static bool do_lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
a9a0ed90 3861{
c868b261
ÇO
3862 if (am_unpriv()) {
3863 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3864 return false;
3865 }
a9a0ed90
ÇO
3866 return add_remove_device_node(c, src_path, dest_path, false);
3867}
3868
858377e4
SH
3869WRAP_API_2(bool, lxcapi_remove_device_node, const char *, const char *)
3870
3871static bool do_lxcapi_attach_interface(struct lxc_container *c, const char *ifname,
e58fae8f
DY
3872 const char *dst_ifname)
3873{
3874 int ret = 0;
3875 if (am_unpriv()) {
3876 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3877 return false;
3878 }
3879
3880 if (!ifname) {
3881 ERROR("No source interface name given");
3882 return false;
3883 }
3884
3885 ret = lxc_netdev_isup(ifname);
e58fae8f 3886
e5848d39
SH
3887 if (ret > 0) {
3888 /* netdev of ifname is up. */
e58fae8f
DY
3889 ret = lxc_netdev_down(ifname);
3890 if (ret)
3891 goto err;
3892 }
3893
858377e4 3894 ret = lxc_netdev_move_by_name(ifname, do_lxcapi_init_pid(c), dst_ifname);
e58fae8f
DY
3895 if (ret)
3896 goto err;
3897
3898 return true;
e5848d39 3899
e58fae8f 3900err:
e58fae8f
DY
3901 return false;
3902}
3903
858377e4
SH
3904WRAP_API_2(bool, lxcapi_attach_interface, const char *, const char *)
3905
3906static bool do_lxcapi_detach_interface(struct lxc_container *c, const char *ifname,
e58fae8f
DY
3907 const char *dst_ifname)
3908{
3909 pid_t pid, pid_outside;
3910
3911 if (am_unpriv()) {
3912 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3913 return false;
3914 }
3915
3916 if (!ifname) {
3917 ERROR("No source interface name given");
3918 return false;
3919 }
3920
3921 pid_outside = getpid();
3922 pid = fork();
3923 if (pid < 0) {
3924 ERROR("failed to fork task to get interfaces information");
3925 return false;
3926 }
3927
3928 if (pid == 0) { // child
3929 int ret = 0;
e0f59189 3930 if (!enter_net_ns(c)) {
e58fae8f
DY
3931 ERROR("failed to enter namespace");
3932 exit(-1);
3933 }
3934
3935 ret = lxc_netdev_isup(ifname);
3936 if (ret < 0)
3937 exit(ret);
3938
3939 /* netdev of ifname is up. */
3940 if (ret) {
3941 ret = lxc_netdev_down(ifname);
3942 if (ret)
3943 exit(ret);
3944 }
3945
3946 ret = lxc_netdev_move_by_name(ifname, pid_outside, dst_ifname);
3947
3948 /* -EINVAL means there is no netdev named as ifanme. */
3949 if (ret == -EINVAL) {
3950 ERROR("No network device named as %s.", ifname);
3951 }
3952 exit(ret);
3953 }
3954
3955 if (wait_for_pid(pid) != 0)
3956 return false;
3957
3958 return true;
3959}
3960
858377e4
SH
3961WRAP_API_2(bool, lxcapi_detach_interface, const char *, const char *)
3962
aef3d51e
TA
3963static int do_lxcapi_migrate(struct lxc_container *c, unsigned int cmd,
3964 struct migrate_opts *opts, unsigned int size)
bbd4e13e 3965{
aef3d51e 3966 int ret;
2cb80427 3967 struct migrate_opts *valid_opts = opts;
85c50991 3968
aef3d51e
TA
3969 /* If the caller has a bigger (newer) struct migrate_opts, let's make
3970 * sure that the stuff on the end is zero, i.e. that they didn't ask us
3971 * to do anything special.
3972 */
3973 if (size > sizeof(*opts)) {
3974 unsigned char *addr;
3975 unsigned char *end;
3976
3977 addr = (void *)opts + sizeof(*opts);
3978 end = (void *)opts + size;
3979 for (; addr < end; addr++) {
3980 if (*addr) {
3981 return -E2BIG;
3982 }
3983 }
85c50991
TA
3984 }
3985
2cb80427
TA
3986 /* If the caller has a smaller struct, let's zero out the end for them
3987 * so we don't accidentally use bits of it that they didn't know about
3988 * to initialize.
3989 */
3990 if (size < sizeof(*opts)) {
3991 valid_opts = malloc(sizeof(*opts));
3992 if (!valid_opts)
3993 return -ENOMEM;
3994
3995 memset(valid_opts, 0, sizeof(*opts));
3996 memcpy(valid_opts, opts, size);
3997 }
3998
aef3d51e
TA
3999 switch (cmd) {
4000 case MIGRATE_PRE_DUMP:
7ad13c91
TA
4001 if (!do_lxcapi_is_running(c)) {
4002 ERROR("container is not running");
4003 return false;
4004 }
2cb80427 4005 ret = !__criu_pre_dump(c, valid_opts);
aef3d51e
TA
4006 break;
4007 case MIGRATE_DUMP:
7ad13c91
TA
4008 if (!do_lxcapi_is_running(c)) {
4009 ERROR("container is not running");
4010 return false;
4011 }
2cb80427 4012 ret = !__criu_dump(c, valid_opts);
aef3d51e
TA
4013 break;
4014 case MIGRATE_RESTORE:
7ad13c91
TA
4015 if (do_lxcapi_is_running(c)) {
4016 ERROR("container is already running");
4017 return false;
4018 }
2cb80427 4019 ret = !__criu_restore(c, valid_opts);
aef3d51e
TA
4020 break;
4021 default:
4022 ERROR("invalid migrate command %u", cmd);
4023 ret = -EINVAL;
4024 }
735f2c6e 4025
f686506d
TA
4026 if (size < sizeof(*opts))
4027 free(valid_opts);
4028
aef3d51e
TA
4029 return ret;
4030}
735f2c6e 4031
aef3d51e 4032WRAP_API_3(int, lxcapi_migrate, unsigned int, struct migrate_opts *, unsigned int)
735f2c6e 4033
aef3d51e
TA
4034static bool do_lxcapi_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose)
4035{
ebb088e1
AR
4036 struct migrate_opts opts;
4037
4038 memset(&opts, 0, sizeof(opts));
4039
4040 opts.directory = directory;
4041 opts.stop = stop;
4042 opts.verbose = verbose;
735f2c6e 4043
aef3d51e 4044 return !do_lxcapi_migrate(c, MIGRATE_DUMP, &opts, sizeof(opts));
735f2c6e
TA
4045}
4046
858377e4
SH
4047WRAP_API_3(bool, lxcapi_checkpoint, char *, bool, bool)
4048
4049static bool do_lxcapi_restore(struct lxc_container *c, char *directory, bool verbose)
c9d8f2ee 4050{
ebb088e1
AR
4051 struct migrate_opts opts;
4052
4053 memset(&opts, 0, sizeof(opts));
4054
4055 opts.directory = directory;
4056 opts.verbose = verbose;
c9d8f2ee 4057
aef3d51e 4058 return !do_lxcapi_migrate(c, MIGRATE_RESTORE, &opts, sizeof(opts));
735f2c6e
TA
4059}
4060
858377e4
SH
4061WRAP_API_2(bool, lxcapi_restore, char *, bool)
4062
a0e93eeb
CS
4063static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
4064{
4065 va_list ap;
4066 const char **argv;
4067 int ret;
4068
4069 if (!c)
4070 return -1;
4071
858377e4
SH
4072 current_config = c->lxc_conf;
4073
a0e93eeb
CS
4074 va_start(ap, arg);
4075 argv = lxc_va_arg_list_to_argv_const(ap, 1);
4076 va_end(ap);
4077
4078 if (!argv) {
4079 ERROR("Memory allocation error.");
858377e4
SH
4080 ret = -1;
4081 goto out;
a0e93eeb
CS
4082 }
4083 argv[0] = arg;
4084
858377e4 4085 ret = do_lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
a0e93eeb 4086 free((void*)argv);
858377e4
SH
4087out:
4088 current_config = NULL;
a0e93eeb
CS
4089 return ret;
4090}
4091
afeecbba 4092struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
4093{
4094 struct lxc_container *c;
72d0e1cb 4095
18aa217b
SH
4096 if (!name)
4097 return NULL;
4098
72d0e1cb
SG
4099 c = malloc(sizeof(*c));
4100 if (!c) {
4101 fprintf(stderr, "failed to malloc lxc_container\n");
4102 return NULL;
4103 }
4104 memset(c, 0, sizeof(*c));
4105
afeecbba
SH
4106 if (configpath)
4107 c->config_path = strdup(configpath);
4108 else
593e8478 4109 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
afeecbba 4110
2a59a681 4111 if (!c->config_path) {
03fadd16 4112 fprintf(stderr, "Out of memory\n");
2a59a681
SH
4113 goto err;
4114 }
4115
f5dd1d53 4116 remove_trailing_slashes(c->config_path);
72d0e1cb
SG
4117 c->name = malloc(strlen(name)+1);
4118 if (!c->name) {
4119 fprintf(stderr, "Error allocating lxc_container name\n");
4120 goto err;
4121 }
4122 strcpy(c->name, name);
4123
4124 c->numthreads = 1;
df271a59 4125 if (!(c->slock = lxc_newlock(c->config_path, name))) {
72d0e1cb
SG
4126 fprintf(stderr, "failed to create lock\n");
4127 goto err;
4128 }
4129
df271a59 4130 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
72d0e1cb
SG
4131 fprintf(stderr, "failed to alloc privlock\n");
4132 goto err;
4133 }
4134
afeecbba 4135 if (!set_config_filename(c)) {
72d0e1cb
SG
4136 fprintf(stderr, "Error allocating config file pathname\n");
4137 goto err;
4138 }
72d0e1cb 4139
bac806d1
SH
4140 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL))
4141 goto err;
72d0e1cb 4142
3e625e2d
SH
4143 if (ongoing_create(c) == 2) {
4144 ERROR("Error: %s creation was not completed", c->name);
18aa217b 4145 container_destroy(c);
4df7f012 4146 lxcapi_clear_config(c);
3e625e2d 4147 }
a2739df5 4148 c->daemonize = true;
72cf75fa 4149 c->pidfile = NULL;
3e625e2d 4150
72d0e1cb
SG
4151 // assign the member functions
4152 c->is_defined = lxcapi_is_defined;
4153 c->state = lxcapi_state;
4154 c->is_running = lxcapi_is_running;
4155 c->freeze = lxcapi_freeze;
4156 c->unfreeze = lxcapi_unfreeze;
0115f8fd 4157 c->console = lxcapi_console;
b5159817 4158 c->console_getfd = lxcapi_console_getfd;
72d0e1cb
SG
4159 c->init_pid = lxcapi_init_pid;
4160 c->load_config = lxcapi_load_config;
4161 c->want_daemonize = lxcapi_want_daemonize;
130a1888 4162 c->want_close_all_fds = lxcapi_want_close_all_fds;
72d0e1cb
SG
4163 c->start = lxcapi_start;
4164 c->startl = lxcapi_startl;
4165 c->stop = lxcapi_stop;
4166 c->config_file_name = lxcapi_config_file_name;
4167 c->wait = lxcapi_wait;
4168 c->set_config_item = lxcapi_set_config_item;
4169 c->destroy = lxcapi_destroy;
18aa217b 4170 c->destroy_with_snapshots = lxcapi_destroy_with_snapshots;
06e5650e 4171 c->rename = lxcapi_rename;
72d0e1cb
SG
4172 c->save_config = lxcapi_save_config;
4173 c->get_keys = lxcapi_get_keys;
4174 c->create = lxcapi_create;
4175 c->createl = lxcapi_createl;
4176 c->shutdown = lxcapi_shutdown;
3e625e2d 4177 c->reboot = lxcapi_reboot;
4df7f012 4178 c->clear_config = lxcapi_clear_config;
72d0e1cb
SG
4179 c->clear_config_item = lxcapi_clear_config_item;
4180 c->get_config_item = lxcapi_get_config_item;
8ac18377 4181 c->get_running_config_item = lxcapi_get_running_config_item;
794dd120
SH
4182 c->get_cgroup_item = lxcapi_get_cgroup_item;
4183 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
4184 c->get_config_path = lxcapi_get_config_path;
4185 c->set_config_path = lxcapi_set_config_path;
9be53773 4186 c->clone = lxcapi_clone;
799f29ab 4187 c->get_interfaces = lxcapi_get_interfaces;
9c83a661 4188 c->get_ips = lxcapi_get_ips;
a0e93eeb
CS
4189 c->attach = lxcapi_attach;
4190 c->attach_run_wait = lxcapi_attach_run_wait;
4191 c->attach_run_waitl = lxcapi_attach_run_waitl;
f5dd1d53
SH
4192 c->snapshot = lxcapi_snapshot;
4193 c->snapshot_list = lxcapi_snapshot_list;
4194 c->snapshot_restore = lxcapi_snapshot_restore;
771d96b3 4195 c->snapshot_destroy = lxcapi_snapshot_destroy;
18aa217b 4196 c->snapshot_destroy_all = lxcapi_snapshot_destroy_all;
b494d2dd 4197 c->may_control = lxcapi_may_control;
a9a0ed90
ÇO
4198 c->add_device_node = lxcapi_add_device_node;
4199 c->remove_device_node = lxcapi_remove_device_node;
e58fae8f
DY
4200 c->attach_interface = lxcapi_attach_interface;
4201 c->detach_interface = lxcapi_detach_interface;
735f2c6e
TA
4202 c->checkpoint = lxcapi_checkpoint;
4203 c->restore = lxcapi_restore;
aef3d51e 4204 c->migrate = lxcapi_migrate;
72d0e1cb 4205
72d0e1cb
SG
4206 return c;
4207
4208err:
4209 lxc_container_free(c);
4210 return NULL;
4211}
4212
4a7c7daa 4213int lxc_get_wait_states(const char **states)
72d0e1cb
SG
4214{
4215 int i;
4216
4217 if (states)
4218 for (i=0; i<MAX_STATE; i++)
4219 states[i] = lxc_state2str(i);
4220 return MAX_STATE;
4221}
a41f104b 4222
a41f104b
SH
4223/*
4224 * These next two could probably be done smarter with reusing a common function
4225 * with different iterators and tests...
4226 */
4227int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
4228{
4229 DIR *dir;
4230 int i, cfound = 0, nfound = 0;
74f96976 4231 struct dirent *direntp;
a41f104b
SH
4232 struct lxc_container *c;
4233
4234 if (!lxcpath)
593e8478 4235 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b 4236
a41f104b 4237 dir = opendir(lxcpath);
a41f104b
SH
4238 if (!dir) {
4239 SYSERROR("opendir on lxcpath");
4240 return -1;
4241 }
4242
4243 if (cret)
4244 *cret = NULL;
4245 if (names)
4246 *names = NULL;
4247
74f96976 4248 while ((direntp = readdir(dir))) {
a41f104b
SH
4249 if (!direntp)
4250 break;
e4ebeab1
CALP
4251
4252 // Ignore '.', '..' and any hidden directory
4253 if (!strncmp(direntp->d_name, ".", 1))
a41f104b
SH
4254 continue;
4255
4256 if (!config_file_exists(lxcpath, direntp->d_name))
4257 continue;
4258
4259 if (names) {
9c88ff1f 4260 if (!add_to_array(names, direntp->d_name, cfound))
a41f104b
SH
4261 goto free_bad;
4262 }
4263 cfound++;
4264
4265 if (!cret) {
4266 nfound++;
4267 continue;
4268 }
4269
4270 c = lxc_container_new(direntp->d_name, lxcpath);
4271 if (!c) {
4272 INFO("Container %s:%s has a config but could not be loaded",
4273 lxcpath, direntp->d_name);
4274 if (names)
9c88ff1f
ÇO
4275 if(!remove_from_array(names, direntp->d_name, cfound--))
4276 goto free_bad;
a41f104b
SH
4277 continue;
4278 }
858377e4 4279 if (!do_lxcapi_is_defined(c)) {
a41f104b
SH
4280 INFO("Container %s:%s has a config but is not defined",
4281 lxcpath, direntp->d_name);
4282 if (names)
9c88ff1f
ÇO
4283 if(!remove_from_array(names, direntp->d_name, cfound--))
4284 goto free_bad;
a41f104b
SH
4285 lxc_container_put(c);
4286 continue;
4287 }
4288
2871830a 4289 if (!add_to_clist(cret, c, nfound, true)) {
a41f104b
SH
4290 lxc_container_put(c);
4291 goto free_bad;
4292 }
4293 nfound++;
4294 }
4295
a41f104b 4296 closedir(dir);
a41f104b
SH
4297 return nfound;
4298
4299free_bad:
4300 if (names && *names) {
4301 for (i=0; i<cfound; i++)
4302 free((*names)[i]);
4303 free(*names);
4304 }
4305 if (cret && *cret) {
4306 for (i=0; i<nfound; i++)
4307 lxc_container_put((*cret)[i]);
4308 free(*cret);
4309 }
a41f104b 4310 closedir(dir);
a41f104b
SH
4311 return -1;
4312}
4313
148a9d27
DE
4314int list_active_containers(const char *lxcpath, char ***nret,
4315 struct lxc_container ***cret)
a41f104b 4316{
148a9d27 4317 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
a41f104b
SH
4318 int lxcpath_len;
4319 char *line = NULL;
148a9d27 4320 char **ct_name = NULL;
a41f104b
SH
4321 size_t len = 0;
4322 struct lxc_container *c;
88556fd7 4323 bool is_hashed;
a41f104b
SH
4324
4325 if (!lxcpath)
593e8478 4326 lxcpath = lxc_global_config_value("lxc.lxcpath");
a41f104b
SH
4327 lxcpath_len = strlen(lxcpath);
4328
4329 if (cret)
4330 *cret = NULL;
148a9d27
DE
4331 if (nret)
4332 *nret = NULL;
a41f104b 4333
a41f104b 4334 FILE *f = fopen("/proc/net/unix", "r");
a41f104b
SH
4335 if (!f)
4336 return -1;
4337
4338 while (getline(&line, &len, f) != -1) {
88556fd7 4339
0f8f9c8a 4340 char *p = strrchr(line, ' '), *p2;
a41f104b
SH
4341 if (!p)
4342 continue;
4343 p++;
4344 if (*p != 0x40)
4345 continue;
4346 p++;
88556fd7
ÇO
4347
4348 is_hashed = false;
4349 if (strncmp(p, lxcpath, lxcpath_len) == 0) {
4350 p += lxcpath_len;
4351 } else if (strncmp(p, "lxc/", 4) == 0) {
4352 p += 4;
4353 is_hashed = true;
4354 } else {
a41f104b 4355 continue;
88556fd7
ÇO
4356 }
4357
a41f104b
SH
4358 while (*p == '/')
4359 p++;
4360
4361 // Now p is the start of lxc_name
46cd2845 4362 p2 = strchr(p, '/');
a41f104b
SH
4363 if (!p2 || strncmp(p2, "/command", 8) != 0)
4364 continue;
4365 *p2 = '\0';
4366
88556fd7
ÇO
4367 if (is_hashed) {
4368 if (strncmp(lxcpath, lxc_cmd_get_lxcpath(p), lxcpath_len) != 0)
4369 continue;
4370 p = lxc_cmd_get_name(p);
4371 }
4372
148a9d27 4373 if (array_contains(&ct_name, p, ct_name_cnt))
9c88ff1f
ÇO
4374 continue;
4375
148a9d27
DE
4376 if (!add_to_array(&ct_name, p, ct_name_cnt))
4377 goto free_cret_list;
9c88ff1f 4378
148a9d27 4379 ct_name_cnt++;
a41f104b 4380
148a9d27 4381 if (!cret)
a41f104b 4382 continue;
a41f104b
SH
4383
4384 c = lxc_container_new(p, lxcpath);
4385 if (!c) {
4386 INFO("Container %s:%s is running but could not be loaded",
4387 lxcpath, p);
148a9d27 4388 remove_from_array(&ct_name, p, ct_name_cnt--);
a41f104b
SH
4389 continue;
4390 }
4391
4392 /*
4393 * If this is an anonymous container, then is_defined *can*
4394 * return false. So we don't do that check. Count on the
4395 * fact that the command socket exists.
4396 */
4397
148a9d27 4398 if (!add_to_clist(cret, c, cret_cnt, true)) {
a41f104b 4399 lxc_container_put(c);
148a9d27 4400 goto free_cret_list;
a41f104b 4401 }
148a9d27 4402 cret_cnt++;
a41f104b
SH
4403 }
4404
148a9d27
DE
4405 assert(!nret || !cret || cret_cnt == ct_name_cnt);
4406 ret = ct_name_cnt;
4407 if (nret)
4408 *nret = ct_name;
4409 else
4410 goto free_ct_name;
4411 goto out;
a41f104b 4412
148a9d27 4413free_cret_list:
a41f104b 4414 if (cret && *cret) {
148a9d27 4415 for (i = 0; i < cret_cnt; i++)
a41f104b
SH
4416 lxc_container_put((*cret)[i]);
4417 free(*cret);
4418 }
148a9d27
DE
4419
4420free_ct_name:
4421 if (ct_name) {
4422 for (i = 0; i < ct_name_cnt; i++)
4423 free(ct_name[i]);
4424 free(ct_name);
4425 }
4426
4427out:
f10fad2f 4428 free(line);
e853a32d 4429
a41f104b 4430 fclose(f);
148a9d27 4431 return ret;
a41f104b 4432}
2871830a
DE
4433
4434int list_all_containers(const char *lxcpath, char ***nret,
4435 struct lxc_container ***cret)
4436{
4437 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
4438 char **active_name;
4439 char **ct_name;
4440 struct lxc_container **ct_list = NULL;
4441
4442 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
4443 if (ct_cnt < 0)
4444 return ct_cnt;
4445
4446 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
4447 if (active_cnt < 0) {
4448 ret = active_cnt;
4449 goto free_ct_name;
4450 }
4451
4452 for (i = 0; i < active_cnt; i++) {
4453 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
4454 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
4455 ret = -1;
4456 goto free_active_name;
4457 }
4458 ct_cnt++;
4459 }
4460 free(active_name[i]);
4461 active_name[i] = NULL;
4462 }
4463 free(active_name);
4464 active_name = NULL;
4465 active_cnt = 0;
4466
4467 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
4468 struct lxc_container *c;
4469
4470 c = lxc_container_new(ct_name[i], lxcpath);
4471 if (!c) {
4472 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
4473 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
4474 continue;
4475 }
4476
4477 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
4478 lxc_container_put(c);
4479 ret = -1;
4480 goto free_ct_list;
4481 }
4482 ct_list_cnt++;
4483 }
4484
4485 if (cret)
4486 *cret = ct_list;
4487
4488 if (nret)
4489 *nret = ct_name;
4490 else {
4491 ret = ct_cnt;
4492 goto free_ct_name;
4493 }
4494 return ct_cnt;
4495
4496free_ct_list:
4497 for (i = 0; i < ct_list_cnt; i++) {
4498 lxc_container_put(ct_list[i]);
4499 }
f10fad2f 4500 free(ct_list);
2871830a
DE
4501
4502free_active_name:
4503 for (i = 0; i < active_cnt; i++) {
f10fad2f 4504 free(active_name[i]);
2871830a 4505 }
f10fad2f 4506 free(active_name);
2871830a
DE
4507
4508free_ct_name:
4509 for (i = 0; i < ct_cnt; i++) {
4510 free(ct_name[i]);
4511 }
4512 free(ct_name);
4513 return ret;
4514}