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