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