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