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