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