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