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