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