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