]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
clang: Fix build warnings for 3.4
[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 NULL,
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 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) {
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 overlay 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 = overlay_getlower(src+10);
900 if (strncmp(src, "aufs:", 5) == 0)
901 src = overlay_getlower(src+5);
902
903 bdev = bdev_init(src, c->lxc_conf->rootfs.mount, NULL);
904 if (!bdev) {
905 ERROR("Error opening rootfs");
906 exit(1);
907 }
908
909 if (geteuid() == 0) {
910 if (unshare(CLONE_NEWNS) < 0) {
911 ERROR("error unsharing mounts");
912 exit(1);
913 }
914 if (detect_shared_rootfs()) {
915 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
916 SYSERROR("Failed to make / rslave to run template");
917 ERROR("Continuing...");
918 }
919 }
920 }
921 if (strcmp(bdev->type, "dir") != 0) {
922 if (geteuid() != 0) {
923 ERROR("non-root users can only create directory-backed containers");
924 exit(1);
925 }
926 if (bdev->ops->mount(bdev) < 0) {
927 ERROR("Error mounting rootfs");
928 exit(1);
929 }
930 } else { // TODO come up with a better way here!
931 if (bdev->dest)
932 free(bdev->dest);
933 bdev->dest = strdup(bdev->src);
934 }
935
936 /*
937 * create our new array, pre-pend the template name and
938 * base args
939 */
940 if (argv)
941 for (nargs = 0; argv[nargs]; nargs++) ;
942 nargs += 4; // template, path, rootfs and name args
943
944 newargv = malloc(nargs * sizeof(*newargv));
945 if (!newargv)
946 exit(1);
947 newargv[0] = lxcbasename(tpath);
948
949 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
950 patharg = malloc(len);
951 if (!patharg)
952 exit(1);
953 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
954 if (ret < 0 || ret >= len)
955 exit(1);
956 newargv[1] = patharg;
957 len = strlen("--name=") + strlen(c->name) + 1;
958 namearg = malloc(len);
959 if (!namearg)
960 exit(1);
961 ret = snprintf(namearg, len, "--name=%s", c->name);
962 if (ret < 0 || ret >= len)
963 exit(1);
964 newargv[2] = namearg;
965
966 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
967 rootfsarg = malloc(len);
968 if (!rootfsarg)
969 exit(1);
970 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
971 if (ret < 0 || ret >= len)
972 exit(1);
973 newargv[3] = rootfsarg;
974
975 /* add passed-in args */
976 if (argv)
977 for (i = 4; i < nargs; i++)
978 newargv[i] = argv[i-4];
979
980 /* add trailing NULL */
981 nargs++;
982 newargv = realloc(newargv, nargs * sizeof(*newargv));
983 if (!newargv)
984 exit(1);
985 newargv[nargs - 1] = NULL;
986
987 /*
988 * If we're running the template in a mapped userns, then
989 * we prepend the template command with:
990 * lxc-usernsexec <-m map1> ... <-m mapn> --
991 * and we append "--mapped-uid x", where x is the mapped uid
992 * for our geteuid()
993 */
994 if (!lxc_list_empty(&conf->id_map)) {
995 int n2args = 1;
996 char txtuid[20];
997 char txtgid[20];
998 char **n2 = malloc(n2args * sizeof(*n2));
999 struct lxc_list *it;
1000 struct id_map *map;
1001
1002 if (!n2) {
1003 SYSERROR("out of memory");
1004 exit(1);
1005 }
1006 newargv[0] = tpath;
1007 tpath = "lxc-usernsexec";
1008 n2[0] = "lxc-usernsexec";
1009 lxc_list_for_each(it, &conf->id_map) {
1010 map = it->elem;
1011 n2args += 2;
1012 n2 = realloc(n2, n2args * sizeof(char *));
1013 if (!n2)
1014 exit(1);
1015 n2[n2args-2] = "-m";
1016 n2[n2args-1] = malloc(200);
1017 if (!n2[n2args-1])
1018 exit(1);
1019 ret = snprintf(n2[n2args-1], 200, "%c:%lu:%lu:%lu",
1020 map->idtype == ID_TYPE_UID ? 'u' : 'g',
1021 map->nsid, map->hostid, map->range);
1022 if (ret < 0 || ret >= 200)
1023 exit(1);
1024 }
1025 int hostid_mapped = mapped_hostid(geteuid(), conf, ID_TYPE_UID);
1026 int extraargs = hostid_mapped >= 0 ? 1 : 3;
1027 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1028 if (!n2)
1029 exit(1);
1030 if (hostid_mapped < 0) {
1031 hostid_mapped = find_unmapped_nsuid(conf, ID_TYPE_UID);
1032 n2[n2args++] = "-m";
1033 if (hostid_mapped < 0) {
1034 ERROR("Could not find free uid to map");
1035 exit(1);
1036 }
1037 n2[n2args++] = malloc(200);
1038 if (!n2[n2args-1]) {
1039 SYSERROR("out of memory");
1040 exit(1);
1041 }
1042 ret = snprintf(n2[n2args-1], 200, "u:%d:%d:1",
1043 hostid_mapped, geteuid());
1044 if (ret < 0 || ret >= 200) {
1045 ERROR("string too long");
1046 exit(1);
1047 }
1048 }
1049 int hostgid_mapped = mapped_hostid(getegid(), conf, ID_TYPE_GID);
1050 extraargs = hostgid_mapped >= 0 ? 1 : 3;
1051 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1052 if (!n2)
1053 exit(1);
1054 if (hostgid_mapped < 0) {
1055 hostgid_mapped = find_unmapped_nsuid(conf, ID_TYPE_GID);
1056 n2[n2args++] = "-m";
1057 if (hostgid_mapped < 0) {
1058 ERROR("Could not find free uid to map");
1059 exit(1);
1060 }
1061 n2[n2args++] = malloc(200);
1062 if (!n2[n2args-1]) {
1063 SYSERROR("out of memory");
1064 exit(1);
1065 }
1066 ret = snprintf(n2[n2args-1], 200, "g:%d:%d:1",
1067 hostgid_mapped, getegid());
1068 if (ret < 0 || ret >= 200) {
1069 ERROR("string too long");
1070 exit(1);
1071 }
1072 }
1073 n2[n2args++] = "--";
1074 for (i = 0; i < nargs; i++)
1075 n2[i + n2args] = newargv[i];
1076 n2args += nargs;
1077 // Finally add "--mapped-uid $uid" to tell template what to chown
1078 // cached images to
1079 n2args += 4;
1080 n2 = realloc(n2, n2args * sizeof(char *));
1081 if (!n2) {
1082 SYSERROR("out of memory");
1083 exit(1);
1084 }
1085 // note n2[n2args-1] is NULL
1086 n2[n2args-5] = "--mapped-uid";
1087 snprintf(txtuid, 20, "%d", hostid_mapped);
1088 n2[n2args-4] = txtuid;
1089 n2[n2args-3] = "--mapped-gid";
1090 snprintf(txtgid, 20, "%d", hostgid_mapped);
1091 n2[n2args-2] = txtgid;
1092 n2[n2args-1] = NULL;
1093 free(newargv);
1094 newargv = n2;
1095 }
1096 /* execute */
1097 execvp(tpath, newargv);
1098 SYSERROR("failed to execute template %s", tpath);
1099 exit(1);
1100 }
1101
1102 if (wait_for_pid(pid) != 0) {
1103 ERROR("container creation template for %s failed", c->name);
1104 return false;
1105 }
1106
1107 return true;
1108 }
1109
1110 static bool prepend_lxc_header(char *path, const char *t, char *const argv[])
1111 {
1112 long flen;
1113 char *contents;
1114 FILE *f;
1115 int ret = -1;
1116 #if HAVE_LIBGNUTLS
1117 int i;
1118 unsigned char md_value[SHA_DIGEST_LENGTH];
1119 char *tpath;
1120 #endif
1121
1122 f = fopen(path, "r");
1123 if (f == NULL)
1124 return false;
1125
1126 if (fseek(f, 0, SEEK_END) < 0)
1127 goto out_error;
1128 if ((flen = ftell(f)) < 0)
1129 goto out_error;
1130 if (fseek(f, 0, SEEK_SET) < 0)
1131 goto out_error;
1132 if ((contents = malloc(flen + 1)) == NULL)
1133 goto out_error;
1134 if (fread(contents, 1, flen, f) != flen)
1135 goto out_free_contents;
1136
1137 contents[flen] = '\0';
1138 ret = fclose(f);
1139 f = NULL;
1140 if (ret < 0)
1141 goto out_free_contents;
1142
1143 #if HAVE_LIBGNUTLS
1144 tpath = get_template_path(t);
1145 if (!tpath) {
1146 ERROR("bad template: %s", t);
1147 goto out_free_contents;
1148 }
1149
1150 ret = sha1sum_file(tpath, md_value);
1151 if (ret < 0) {
1152 ERROR("Error getting sha1sum of %s", tpath);
1153 free(tpath);
1154 goto out_free_contents;
1155 }
1156 free(tpath);
1157 #endif
1158
1159 f = fopen(path, "w");
1160 if (f == NULL) {
1161 SYSERROR("reopening config for writing");
1162 free(contents);
1163 return false;
1164 }
1165 fprintf(f, "# Template used to create this container: %s\n", t);
1166 if (argv) {
1167 fprintf(f, "# Parameters passed to the template:");
1168 while (*argv) {
1169 fprintf(f, " %s", *argv);
1170 argv++;
1171 }
1172 fprintf(f, "\n");
1173 }
1174 #if HAVE_LIBGNUTLS
1175 fprintf(f, "# Template script checksum (SHA-1): ");
1176 for (i=0; i<SHA_DIGEST_LENGTH; i++)
1177 fprintf(f, "%02x", md_value[i]);
1178 fprintf(f, "\n");
1179 #endif
1180 fprintf(f, "# For additional config options, please look at lxc.conf(5)\n");
1181 if (fwrite(contents, 1, flen, f) != flen) {
1182 SYSERROR("Writing original contents");
1183 free(contents);
1184 fclose(f);
1185 return false;
1186 }
1187 ret = 0;
1188 out_free_contents:
1189 free(contents);
1190 out_error:
1191 if (f) {
1192 int newret;
1193 newret = fclose(f);
1194 if (ret == 0)
1195 ret = newret;
1196 }
1197 if (ret < 0) {
1198 SYSERROR("Error prepending header");
1199 return false;
1200 }
1201 return true;
1202 }
1203
1204 static void lxcapi_clear_config(struct lxc_container *c)
1205 {
1206 if (c && c->lxc_conf) {
1207 lxc_conf_free(c->lxc_conf);
1208 c->lxc_conf = NULL;
1209 }
1210 }
1211
1212 static bool lxcapi_destroy(struct lxc_container *c);
1213 /*
1214 * lxcapi_create:
1215 * create a container with the given parameters.
1216 * @c: container to be created. It has the lxcpath, name, and a starting
1217 * configuration already set
1218 * @t: the template to execute to instantiate the root filesystem and
1219 * adjust the configuration.
1220 * @bdevtype: backing store type to use. If NULL, dir will be used.
1221 * @specs: additional parameters for the backing store, i.e. LVM vg to
1222 * use.
1223 *
1224 * @argv: the arguments to pass to the template, terminated by NULL. If no
1225 * arguments, you can just pass NULL.
1226 */
1227 static bool lxcapi_create(struct lxc_container *c, const char *t,
1228 const char *bdevtype, struct bdev_specs *specs, int flags,
1229 char *const argv[])
1230 {
1231 bool ret = false;
1232 pid_t pid;
1233 char *tpath = NULL;
1234 int partial_fd;
1235
1236 if (!c)
1237 return false;
1238
1239 if (t) {
1240 tpath = get_template_path(t);
1241 if (!tpath) {
1242 ERROR("bad template: %s", t);
1243 goto out;
1244 }
1245 }
1246
1247 /*
1248 * If a template is passed in, and the rootfs already is defined in
1249 * the container config and exists, then * caller is trying to create
1250 * an existing container. Return an error, but do NOT delete the
1251 * container.
1252 */
1253 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
1254 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
1255 ERROR("Container %s:%s already exists", c->config_path, c->name);
1256 goto free_tpath;
1257 }
1258
1259 if (!c->lxc_conf) {
1260 if (!c->load_config(c, lxc_global_config_value("lxc.default_config"))) {
1261 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1262 goto free_tpath;
1263 }
1264 }
1265
1266 if (!create_container_dir(c))
1267 goto free_tpath;
1268
1269 /*
1270 * either template or rootfs.path should be set.
1271 * if both template and rootfs.path are set, template is setup as rootfs.path.
1272 * container is already created if we have a config and rootfs.path is accessible
1273 */
1274 if (!c->lxc_conf->rootfs.path && !tpath)
1275 /* no template passed in and rootfs does not exist: error */
1276 goto out;
1277 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
1278 /* rootfs passed into configuration, but does not exist: error */
1279 goto out;
1280 if (lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
1281 /* Rootfs already existed, user just wanted to save the
1282 * loaded configuration */
1283 ret = true;
1284 goto out;
1285 }
1286
1287 /* Mark that this container is being created */
1288 if ((partial_fd = create_partial(c)) < 0)
1289 goto out;
1290
1291 /* no need to get disk lock bc we have the partial locked */
1292
1293 /*
1294 * Create the backing store
1295 * Note we can't do this in the same task as we use to execute the
1296 * template because of the way zfs works.
1297 * After you 'zfs create', zfs mounts the fs only in the initial
1298 * namespace.
1299 */
1300 pid = fork();
1301 if (pid < 0) {
1302 SYSERROR("failed to fork task for container creation template");
1303 goto out_unlock;
1304 }
1305
1306 if (pid == 0) { // child
1307 struct bdev *bdev = NULL;
1308
1309 if (!(bdev = do_bdev_create(c, bdevtype, specs))) {
1310 ERROR("Error creating backing store type %s for %s",
1311 bdevtype ? bdevtype : "(none)", c->name);
1312 exit(1);
1313 }
1314
1315 /* save config file again to store the new rootfs location */
1316 if (!c->save_config(c, NULL)) {
1317 ERROR("failed to save starting configuration for %s", c->name);
1318 // parent task won't see bdev in config so we delete it
1319 bdev->ops->umount(bdev);
1320 bdev->ops->destroy(bdev);
1321 exit(1);
1322 }
1323 exit(0);
1324 }
1325 if (wait_for_pid(pid) != 0)
1326 goto out_unlock;
1327
1328 /* reload config to get the rootfs */
1329 lxc_conf_free(c->lxc_conf);
1330 c->lxc_conf = NULL;
1331 if (!load_config_locked(c, c->configfile))
1332 goto out_unlock;
1333
1334 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
1335 goto out_unlock;
1336
1337 // now clear out the lxc_conf we have, reload from the created
1338 // container
1339 lxcapi_clear_config(c);
1340
1341 if (t) {
1342 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
1343 ERROR("Error prepending header to configuration file");
1344 goto out_unlock;
1345 }
1346 }
1347 ret = load_config_locked(c, c->configfile);
1348
1349 out_unlock:
1350 if (partial_fd >= 0)
1351 remove_partial(c, partial_fd);
1352 out:
1353 if (!ret && c)
1354 lxcapi_destroy(c);
1355 free_tpath:
1356 if (tpath)
1357 free(tpath);
1358 return ret;
1359 }
1360
1361 static bool lxcapi_reboot(struct lxc_container *c)
1362 {
1363 pid_t pid;
1364
1365 if (!c)
1366 return false;
1367 if (!c->is_running(c))
1368 return false;
1369 pid = c->init_pid(c);
1370 if (pid <= 0)
1371 return false;
1372 if (kill(pid, SIGINT) < 0)
1373 return false;
1374 return true;
1375
1376 }
1377
1378 static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
1379 {
1380 bool retv;
1381 pid_t pid;
1382 int haltsignal = SIGPWR;
1383
1384 if (!c)
1385 return false;
1386
1387 if (!c->is_running(c))
1388 return true;
1389 pid = c->init_pid(c);
1390 if (pid <= 0)
1391 return true;
1392 if (c->lxc_conf && c->lxc_conf->haltsignal)
1393 haltsignal = c->lxc_conf->haltsignal;
1394 kill(pid, haltsignal);
1395 retv = c->wait(c, "STOPPED", timeout);
1396 return retv;
1397 }
1398
1399 static bool lxcapi_createl(struct lxc_container *c, const char *t,
1400 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
1401 {
1402 bool bret = false;
1403 char **args = NULL;
1404 va_list ap;
1405
1406 if (!c)
1407 return false;
1408
1409 /*
1410 * since we're going to wait for create to finish, I don't think we
1411 * need to get a copy of the arguments.
1412 */
1413 va_start(ap, flags);
1414 args = lxc_va_arg_list_to_argv(ap, 0, 0);
1415 va_end(ap);
1416 if (!args) {
1417 ERROR("Memory allocation error.");
1418 goto out;
1419 }
1420
1421 bret = c->create(c, t, bdevtype, specs, flags, args);
1422
1423 out:
1424 free(args);
1425 return bret;
1426 }
1427
1428 static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
1429 {
1430 int ret;
1431
1432 if (!c || !c->lxc_conf)
1433 return false;
1434 if (container_mem_lock(c))
1435 return false;
1436 ret = lxc_clear_config_item(c->lxc_conf, key);
1437 container_mem_unlock(c);
1438 return ret == 0;
1439 }
1440
1441 static inline bool enter_to_ns(struct lxc_container *c) {
1442 int netns, userns, ret = 0, init_pid = 0;;
1443 char new_netns_path[MAXPATHLEN];
1444 char new_userns_path[MAXPATHLEN];
1445
1446 if (!c->is_running(c))
1447 goto out;
1448
1449 init_pid = c->init_pid(c);
1450
1451 /* Switch to new userns */
1452 if ((geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) && access("/proc/self/ns/user", F_OK) == 0) {
1453 ret = snprintf(new_userns_path, MAXPATHLEN, "/proc/%d/ns/user", init_pid);
1454 if (ret < 0 || ret >= MAXPATHLEN)
1455 goto out;
1456
1457 userns = open(new_userns_path, O_RDONLY);
1458 if (userns < 0) {
1459 SYSERROR("failed to open %s", new_userns_path);
1460 goto out;
1461 }
1462
1463 if (setns(userns, CLONE_NEWUSER)) {
1464 SYSERROR("failed to setns for CLONE_NEWUSER");
1465 close(userns);
1466 goto out;
1467 }
1468 close(userns);
1469 }
1470
1471 /* Switch to new netns */
1472 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", init_pid);
1473 if (ret < 0 || ret >= MAXPATHLEN)
1474 goto out;
1475
1476 netns = open(new_netns_path, O_RDONLY);
1477 if (netns < 0) {
1478 SYSERROR("failed to open %s", new_netns_path);
1479 goto out;
1480 }
1481
1482 if (setns(netns, CLONE_NEWNET)) {
1483 SYSERROR("failed to setns for CLONE_NEWNET");
1484 close(netns);
1485 goto out;
1486 }
1487 close(netns);
1488 return true;
1489 out:
1490 return false;
1491 }
1492
1493 // used by qsort and bsearch functions for comparing names
1494 static inline int string_cmp(char **first, char **second)
1495 {
1496 return strcmp(*first, *second);
1497 }
1498
1499 // used by qsort and bsearch functions for comparing container names
1500 static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1501 {
1502 return strcmp((*first)->name, (*second)->name);
1503 }
1504
1505 static bool add_to_array(char ***names, char *cname, int pos)
1506 {
1507 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1508 if (!newnames) {
1509 ERROR("Out of memory");
1510 return false;
1511 }
1512
1513 *names = newnames;
1514 newnames[pos] = strdup(cname);
1515 if (!newnames[pos])
1516 return false;
1517
1518 // sort the arrray as we will use binary search on it
1519 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1520
1521 return true;
1522 }
1523
1524 static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
1525 {
1526 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1527 if (!newlist) {
1528 ERROR("Out of memory");
1529 return false;
1530 }
1531
1532 *list = newlist;
1533 newlist[pos] = c;
1534
1535 // sort the arrray as we will use binary search on it
1536 if (sort)
1537 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
1538
1539 return true;
1540 }
1541
1542 static char** get_from_array(char ***names, char *cname, int size)
1543 {
1544 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1545 }
1546
1547
1548 static bool array_contains(char ***names, char *cname, int size) {
1549 if(get_from_array(names, cname, size) != NULL)
1550 return true;
1551 return false;
1552 }
1553
1554 static bool remove_from_array(char ***names, char *cname, int size)
1555 {
1556 char **result = get_from_array(names, cname, size);
1557 if (result != NULL) {
1558 free(result);
1559 return true;
1560 }
1561 return false;
1562 }
1563
1564 static char** lxcapi_get_interfaces(struct lxc_container *c)
1565 {
1566 pid_t pid;
1567 int i, count = 0, pipefd[2];
1568 char **interfaces = NULL;
1569 char interface[IFNAMSIZ];
1570
1571 if(pipe(pipefd) < 0) {
1572 SYSERROR("pipe failed");
1573 return NULL;
1574 }
1575
1576 pid = fork();
1577 if (pid < 0) {
1578 SYSERROR("failed to fork task to get interfaces information");
1579 close(pipefd[0]);
1580 close(pipefd[1]);
1581 return NULL;
1582 }
1583
1584 if (pid == 0) { // child
1585 int ret = 1, nbytes;
1586 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1587
1588 /* close the read-end of the pipe */
1589 close(pipefd[0]);
1590
1591 if (!enter_to_ns(c)) {
1592 SYSERROR("failed to enter namespace");
1593 goto out;
1594 }
1595
1596 /* Grab the list of interfaces */
1597 if (getifaddrs(&interfaceArray)) {
1598 SYSERROR("failed to get interfaces list");
1599 goto out;
1600 }
1601
1602 /* Iterate through the interfaces */
1603 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1604 nbytes = write(pipefd[1], tempIfAddr->ifa_name, IFNAMSIZ);
1605 if (nbytes < 0) {
1606 ERROR("write failed");
1607 goto out;
1608 }
1609 count++;
1610 }
1611 ret = 0;
1612
1613 out:
1614 if (interfaceArray)
1615 freeifaddrs(interfaceArray);
1616
1617 /* close the write-end of the pipe, thus sending EOF to the reader */
1618 close(pipefd[1]);
1619 exit(ret);
1620 }
1621
1622 /* close the write-end of the pipe */
1623 close(pipefd[1]);
1624
1625 while (read(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
1626 if (array_contains(&interfaces, interface, count))
1627 continue;
1628
1629 if(!add_to_array(&interfaces, interface, count))
1630 ERROR("PARENT: add_to_array failed");
1631 count++;
1632 }
1633
1634 if (wait_for_pid(pid) != 0) {
1635 for(i=0;i<count;i++)
1636 free(interfaces[i]);
1637 free(interfaces);
1638 interfaces = NULL;
1639 }
1640
1641 /* close the read-end of the pipe */
1642 close(pipefd[0]);
1643
1644 /* Append NULL to the array */
1645 if(interfaces)
1646 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
1647
1648 return interfaces;
1649 }
1650
1651 static char** lxcapi_get_ips(struct lxc_container *c, const char* interface, const char* family, int scope)
1652 {
1653 pid_t pid;
1654 int i, count = 0, pipefd[2];
1655 char **addresses = NULL;
1656 char address[INET6_ADDRSTRLEN];
1657
1658 if(pipe(pipefd) < 0) {
1659 SYSERROR("pipe failed");
1660 return NULL;
1661 }
1662
1663 pid = fork();
1664 if (pid < 0) {
1665 SYSERROR("failed to fork task to get container ips");
1666 close(pipefd[0]);
1667 close(pipefd[1]);
1668 return NULL;
1669 }
1670
1671 if (pid == 0) { // child
1672 int ret = 1, nbytes;
1673 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1674 char addressOutputBuffer[INET6_ADDRSTRLEN];
1675 void *tempAddrPtr = NULL;
1676 char *address = NULL;
1677
1678 /* close the read-end of the pipe */
1679 close(pipefd[0]);
1680
1681 if (!enter_to_ns(c)) {
1682 SYSERROR("failed to enter namespace");
1683 goto out;
1684 }
1685
1686 /* Grab the list of interfaces */
1687 if (getifaddrs(&interfaceArray)) {
1688 SYSERROR("failed to get interfaces list");
1689 goto out;
1690 }
1691
1692 /* Iterate through the interfaces */
1693 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
1694 if (tempIfAddr->ifa_addr == NULL)
1695 continue;
1696
1697 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1698 if (family && strcmp(family, "inet"))
1699 continue;
1700 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1701 }
1702 else {
1703 if (family && strcmp(family, "inet6"))
1704 continue;
1705
1706 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1707 continue;
1708
1709 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1710 }
1711
1712 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1713 continue;
1714 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
1715 continue;
1716
1717 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1718 tempAddrPtr,
1719 addressOutputBuffer,
1720 sizeof(addressOutputBuffer));
1721 if (!address)
1722 continue;
1723
1724 nbytes = write(pipefd[1], address, INET6_ADDRSTRLEN);
1725 if (nbytes < 0) {
1726 ERROR("write failed");
1727 goto out;
1728 }
1729 count++;
1730 }
1731 ret = 0;
1732
1733 out:
1734 if(interfaceArray)
1735 freeifaddrs(interfaceArray);
1736
1737 /* close the write-end of the pipe, thus sending EOF to the reader */
1738 close(pipefd[1]);
1739 exit(ret);
1740 }
1741
1742 /* close the write-end of the pipe */
1743 close(pipefd[1]);
1744
1745 while (read(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
1746 if(!add_to_array(&addresses, address, count))
1747 ERROR("PARENT: add_to_array failed");
1748 count++;
1749 }
1750
1751 if (wait_for_pid(pid) != 0) {
1752 for(i=0;i<count;i++)
1753 free(addresses[i]);
1754 free(addresses);
1755 addresses = NULL;
1756 }
1757
1758 /* close the read-end of the pipe */
1759 close(pipefd[0]);
1760
1761 /* Append NULL to the array */
1762 if(addresses)
1763 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
1764
1765 return addresses;
1766 }
1767
1768 static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
1769 {
1770 int ret;
1771
1772 if (!c || !c->lxc_conf)
1773 return -1;
1774 if (container_mem_lock(c))
1775 return -1;
1776 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
1777 container_mem_unlock(c);
1778 return ret;
1779 }
1780
1781 static char* lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
1782 {
1783 char *ret;
1784
1785 if (!c || !c->lxc_conf)
1786 return NULL;
1787 if (container_mem_lock(c))
1788 return NULL;
1789 ret = lxc_cmd_get_config_item(c->name, key, c->get_config_path(c));
1790 container_mem_unlock(c);
1791 return ret;
1792 }
1793
1794 static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
1795 {
1796 if (!key)
1797 return lxc_listconfigs(retv, inlen);
1798 /*
1799 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1800 * This is an intelligent result to show which keys are valid given
1801 * the type of nic it is
1802 */
1803 if (!c || !c->lxc_conf)
1804 return -1;
1805 if (container_mem_lock(c))
1806 return -1;
1807 int ret = -1;
1808 if (strncmp(key, "lxc.network.", 12) == 0)
1809 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
1810 container_mem_unlock(c);
1811 return ret;
1812 }
1813
1814 static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
1815 {
1816 FILE *fout;
1817 bool ret = false, need_disklock = false;
1818 int lret;
1819
1820 if (!alt_file)
1821 alt_file = c->configfile;
1822 if (!alt_file)
1823 return false; // should we write to stdout if no file is specified?
1824
1825 // If we haven't yet loaded a config, load the stock config
1826 if (!c->lxc_conf) {
1827 if (!c->load_config(c, lxc_global_config_value("lxc.default_config"))) {
1828 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c->name);
1829 return false;
1830 }
1831 }
1832
1833 if (!create_container_dir(c))
1834 return false;
1835
1836 /*
1837 * If we're writing to the container's config file, take the
1838 * disk lock. Otherwise just take the memlock to protect the
1839 * struct lxc_container while we're traversing it.
1840 */
1841 if (strcmp(c->configfile, alt_file) == 0)
1842 need_disklock = true;
1843
1844 if (need_disklock)
1845 lret = container_disk_lock(c);
1846 else
1847 lret = container_mem_lock(c);
1848
1849 if (lret)
1850 return false;
1851
1852 fout = fopen(alt_file, "w");
1853 if (!fout)
1854 goto out;
1855 write_config(fout, c->lxc_conf);
1856 fclose(fout);
1857 ret = true;
1858
1859 out:
1860 if (need_disklock)
1861 container_disk_unlock(c);
1862 else
1863 container_mem_unlock(c);
1864 return ret;
1865 }
1866
1867 static bool mod_rdep(struct lxc_container *c, bool inc)
1868 {
1869 char path[MAXPATHLEN];
1870 int ret, v = 0;
1871 FILE *f;
1872 bool bret = false;
1873
1874 if (container_disk_lock(c))
1875 return false;
1876 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1877 c->name);
1878 if (ret < 0 || ret > MAXPATHLEN)
1879 goto out;
1880 f = fopen(path, "r");
1881 if (f) {
1882 ret = fscanf(f, "%d", &v);
1883 fclose(f);
1884 if (ret != 1) {
1885 ERROR("Corrupted file %s", path);
1886 goto out;
1887 }
1888 }
1889 v += inc ? 1 : -1;
1890 f = fopen(path, "w");
1891 if (!f)
1892 goto out;
1893 if (fprintf(f, "%d\n", v) < 0) {
1894 ERROR("Error writing new snapshots value");
1895 fclose(f);
1896 goto out;
1897 }
1898 ret = fclose(f);
1899 if (ret != 0) {
1900 SYSERROR("Error writing to or closing snapshots file");
1901 goto out;
1902 }
1903
1904 bret = true;
1905
1906 out:
1907 container_disk_unlock(c);
1908 return bret;
1909 }
1910
1911 static void strip_newline(char *p)
1912 {
1913 size_t len = strlen(p);
1914 if (len < 1)
1915 return;
1916 if (p[len-1] == '\n')
1917 p[len-1] = '\0';
1918 }
1919
1920 static void mod_all_rdeps(struct lxc_container *c, bool inc)
1921 {
1922 struct lxc_container *p;
1923 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
1924 size_t pathlen = 0, namelen = 0;
1925 FILE *f;
1926 int ret;
1927
1928 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
1929 c->config_path, c->name);
1930 if (ret < 0 || ret >= MAXPATHLEN) {
1931 ERROR("Path name too long");
1932 return;
1933 }
1934 f = fopen(path, "r");
1935 if (f == NULL)
1936 return;
1937 while (getline(&lxcpath, &pathlen, f) != -1) {
1938 if (getline(&lxcname, &namelen, f) == -1) {
1939 ERROR("badly formatted file %s", path);
1940 goto out;
1941 }
1942 strip_newline(lxcpath);
1943 strip_newline(lxcname);
1944 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
1945 ERROR("Unable to find dependent container %s:%s",
1946 lxcpath, lxcname);
1947 continue;
1948 }
1949 if (!mod_rdep(p, inc))
1950 ERROR("Failed to increase numsnapshots for %s:%s",
1951 lxcpath, lxcname);
1952 lxc_container_put(p);
1953 }
1954 out:
1955 if (lxcpath) free(lxcpath);
1956 if (lxcname) free(lxcname);
1957 fclose(f);
1958 }
1959
1960 static bool has_snapshots(struct lxc_container *c)
1961 {
1962 char path[MAXPATHLEN];
1963 int ret, v;
1964 FILE *f;
1965 bool bret = false;
1966
1967 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1968 c->name);
1969 if (ret < 0 || ret > MAXPATHLEN)
1970 goto out;
1971 f = fopen(path, "r");
1972 if (!f)
1973 goto out;
1974 ret = fscanf(f, "%d", &v);
1975 fclose(f);
1976 if (ret != 1)
1977 goto out;
1978 bret = v != 0;
1979
1980 out:
1981 return bret;
1982 }
1983
1984 static int lxc_rmdir_onedev_wrapper(void *data)
1985 {
1986 char *arg = (char *) data;
1987 return lxc_rmdir_onedev(arg);
1988 }
1989
1990 // do we want the api to support --force, or leave that to the caller?
1991 static bool lxcapi_destroy(struct lxc_container *c)
1992 {
1993 struct bdev *r = NULL;
1994 bool bret = false;
1995 int ret;
1996
1997 if (!c || !lxcapi_is_defined(c))
1998 return false;
1999
2000 if (container_disk_lock(c))
2001 return false;
2002
2003 if (!is_stopped(c)) {
2004 // we should queue some sort of error - in c->error_string?
2005 ERROR("container %s is not stopped", c->name);
2006 goto out;
2007 }
2008
2009 if (c->lxc_conf && has_snapshots(c)) {
2010 ERROR("container %s has dependent snapshots", c->name);
2011 goto out;
2012 }
2013
2014 if (!am_unpriv() && c->lxc_conf && c->lxc_conf->rootfs.path && c->lxc_conf->rootfs.mount) {
2015 r = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2016 if (r) {
2017 if (r->ops->destroy(r) < 0) {
2018 bdev_put(r);
2019 ERROR("Error destroying rootfs for %s", c->name);
2020 goto out;
2021 }
2022 bdev_put(r);
2023 }
2024 }
2025
2026 mod_all_rdeps(c, false);
2027
2028 const char *p1 = lxcapi_get_config_path(c);
2029 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
2030 sprintf(path, "%s/%s", p1, c->name);
2031 if (am_unpriv())
2032 ret = userns_exec_1(c->lxc_conf, lxc_rmdir_onedev_wrapper, path);
2033 else
2034 ret = lxc_rmdir_onedev(path);
2035 if (ret < 0) {
2036 ERROR("Error destroying container directory for %s", c->name);
2037 goto out;
2038 }
2039 bret = true;
2040
2041 out:
2042 container_disk_unlock(c);
2043 return bret;
2044 }
2045
2046 static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
2047 {
2048 struct lxc_config_t *config;
2049
2050 if (!c->lxc_conf)
2051 c->lxc_conf = lxc_conf_init();
2052 if (!c->lxc_conf)
2053 return false;
2054 config = lxc_getconfig(key);
2055 if (!config)
2056 return false;
2057 return (0 == config->cb(key, v, c->lxc_conf));
2058 }
2059
2060 static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
2061 {
2062 bool b = false;
2063
2064 if (!c)
2065 return false;
2066
2067 if (container_mem_lock(c))
2068 return false;
2069
2070 b = set_config_item_locked(c, key, v);
2071
2072 container_mem_unlock(c);
2073 return b;
2074 }
2075
2076 static char *lxcapi_config_file_name(struct lxc_container *c)
2077 {
2078 if (!c || !c->configfile)
2079 return NULL;
2080 return strdup(c->configfile);
2081 }
2082
2083 static const char *lxcapi_get_config_path(struct lxc_container *c)
2084 {
2085 if (!c || !c->config_path)
2086 return NULL;
2087 return (const char *)(c->config_path);
2088 }
2089
2090 /*
2091 * not for export
2092 * Just recalculate the c->configfile based on the
2093 * c->config_path, which must be set.
2094 * The lxc_container must be locked or not yet public.
2095 */
2096 static bool set_config_filename(struct lxc_container *c)
2097 {
2098 char *newpath;
2099 int len, ret;
2100
2101 if (!c->config_path)
2102 return false;
2103
2104 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2105 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
2106 newpath = malloc(len);
2107 if (!newpath)
2108 return false;
2109
2110 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
2111 if (ret < 0 || ret >= len) {
2112 fprintf(stderr, "Error printing out config file name\n");
2113 free(newpath);
2114 return false;
2115 }
2116
2117 if (c->configfile)
2118 free(c->configfile);
2119 c->configfile = newpath;
2120
2121 return true;
2122 }
2123
2124 static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
2125 {
2126 char *p;
2127 bool b = false;
2128 char *oldpath = NULL;
2129
2130 if (!c)
2131 return b;
2132
2133 if (container_mem_lock(c))
2134 return b;
2135
2136 p = strdup(path);
2137 if (!p) {
2138 ERROR("Out of memory setting new lxc path");
2139 goto err;
2140 }
2141
2142 b = true;
2143 if (c->config_path)
2144 oldpath = c->config_path;
2145 c->config_path = p;
2146
2147 /* Since we've changed the config path, we have to change the
2148 * config file name too */
2149 if (!set_config_filename(c)) {
2150 ERROR("Out of memory setting new config filename");
2151 b = false;
2152 free(c->config_path);
2153 c->config_path = oldpath;
2154 oldpath = NULL;
2155 }
2156 err:
2157 if (oldpath)
2158 free(oldpath);
2159 container_mem_unlock(c);
2160 return b;
2161 }
2162
2163
2164 static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
2165 {
2166 int ret;
2167
2168 if (!c)
2169 return false;
2170
2171 if (is_stopped(c))
2172 return false;
2173
2174 if (container_disk_lock(c))
2175 return false;
2176
2177 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
2178
2179 container_disk_unlock(c);
2180 return ret == 0;
2181 }
2182
2183 static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
2184 {
2185 int ret;
2186
2187 if (!c)
2188 return -1;
2189
2190 if (is_stopped(c))
2191 return -1;
2192
2193 if (container_disk_lock(c))
2194 return -1;
2195
2196 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
2197
2198 container_disk_unlock(c);
2199 return ret;
2200 }
2201
2202 const char *lxc_get_global_config_item(const char *key)
2203 {
2204 return lxc_global_config_value(key);
2205 }
2206
2207 const char *lxc_get_version(void)
2208 {
2209 return LXC_VERSION;
2210 }
2211
2212 static int copy_file(const char *old, const char *new)
2213 {
2214 int in, out;
2215 ssize_t len, ret;
2216 char buf[8096];
2217 struct stat sbuf;
2218
2219 if (file_exists(new)) {
2220 ERROR("copy destination %s exists", new);
2221 return -1;
2222 }
2223 ret = stat(old, &sbuf);
2224 if (ret < 0) {
2225 INFO("Error stat'ing %s", old);
2226 return -1;
2227 }
2228
2229 in = open(old, O_RDONLY);
2230 if (in < 0) {
2231 SYSERROR("Error opening original file %s", old);
2232 return -1;
2233 }
2234 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
2235 if (out < 0) {
2236 SYSERROR("Error opening new file %s", new);
2237 close(in);
2238 return -1;
2239 }
2240
2241 while (1) {
2242 len = read(in, buf, 8096);
2243 if (len < 0) {
2244 SYSERROR("Error reading old file %s", old);
2245 goto err;
2246 }
2247 if (len == 0)
2248 break;
2249 ret = write(out, buf, len);
2250 if (ret < len) { // should we retry?
2251 SYSERROR("Error: write to new file %s was interrupted", new);
2252 goto err;
2253 }
2254 }
2255 close(in);
2256 close(out);
2257
2258 // we set mode, but not owner/group
2259 ret = chmod(new, sbuf.st_mode);
2260 if (ret) {
2261 SYSERROR("Error setting mode on %s", new);
2262 return -1;
2263 }
2264
2265 return 0;
2266
2267 err:
2268 close(in);
2269 close(out);
2270 return -1;
2271 }
2272
2273 static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2274 {
2275 int i, len, ret;
2276 struct lxc_list *it;
2277 char *cpath;
2278
2279 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
2280 cpath = alloca(len);
2281 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
2282 if (ret < 0 || ret >= len)
2283 return -1;
2284
2285 for (i=0; i<NUM_LXC_HOOKS; i++) {
2286 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2287 char *hookname = it->elem;
2288 char *fname = strrchr(hookname, '/');
2289 char tmppath[MAXPATHLEN];
2290 if (!fname) // relative path - we don't support, but maybe we should
2291 return 0;
2292 if (strncmp(hookname, cpath, len - 1) != 0) {
2293 // this hook is public - ignore
2294 continue;
2295 }
2296 // copy the script, and change the entry in confile
2297 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2298 c->config_path, c->name, fname+1);
2299 if (ret < 0 || ret >= MAXPATHLEN)
2300 return -1;
2301 ret = copy_file(it->elem, tmppath);
2302 if (ret < 0)
2303 return -1;
2304 free(it->elem);
2305 it->elem = strdup(tmppath);
2306 if (!it->elem) {
2307 ERROR("out of memory copying hook path");
2308 return -1;
2309 }
2310 }
2311 }
2312
2313 c->save_config(c, NULL);
2314 return 0;
2315 }
2316
2317 static void new_hwaddr(char *hwaddr)
2318 {
2319 FILE *f;
2320 f = fopen("/dev/urandom", "r");
2321 if (f) {
2322 unsigned int seed;
2323 int ret = fread(&seed, sizeof(seed), 1, f);
2324 if (ret != 1)
2325 seed = time(NULL);
2326 fclose(f);
2327 srand(seed);
2328 } else
2329 srand(time(NULL));
2330 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
2331 rand() % 255, rand() % 255, rand() % 255);
2332 }
2333
2334 static void network_new_hwaddrs(struct lxc_container *c)
2335 {
2336 struct lxc_list *it;
2337
2338 lxc_list_for_each(it, &c->lxc_conf->network) {
2339 struct lxc_netdev *n = it->elem;
2340 if (n->hwaddr)
2341 new_hwaddr(n->hwaddr);
2342 }
2343 }
2344
2345 static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2346 {
2347 char newpath[MAXPATHLEN];
2348 char *oldpath = oldc->lxc_conf->fstab;
2349 int ret;
2350
2351 if (!oldpath)
2352 return 0;
2353
2354 char *p = strrchr(oldpath, '/');
2355 if (!p)
2356 return -1;
2357 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2358 c->config_path, c->name, p);
2359 if (ret < 0 || ret >= MAXPATHLEN) {
2360 ERROR("error printing new path for %s", oldpath);
2361 return -1;
2362 }
2363 if (file_exists(newpath)) {
2364 ERROR("error: fstab file %s exists", newpath);
2365 return -1;
2366 }
2367
2368 if (copy_file(oldpath, newpath) < 0) {
2369 ERROR("error: copying %s to %s", oldpath, newpath);
2370 return -1;
2371 }
2372 free(c->lxc_conf->fstab);
2373 c->lxc_conf->fstab = strdup(newpath);
2374 if (!c->lxc_conf->fstab) {
2375 ERROR("error: allocating pathname");
2376 return -1;
2377 }
2378
2379 return 0;
2380 }
2381
2382 static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2383 {
2384 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2385 int ret;
2386
2387 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2388 c0->name);
2389 if (ret < 0 || ret >= MAXPATHLEN) {
2390 WARN("Error copying reverse dependencies");
2391 return;
2392 }
2393 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2394 c->name);
2395 if (ret < 0 || ret >= MAXPATHLEN) {
2396 WARN("Error copying reverse dependencies");
2397 return;
2398 }
2399 if (copy_file(path0, path1) < 0) {
2400 INFO("Error copying reverse dependencies");
2401 return;
2402 }
2403 }
2404
2405 static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2406 {
2407 int ret;
2408 char path[MAXPATHLEN];
2409 FILE *f;
2410 bool bret;
2411
2412 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2413 c->name);
2414 if (ret < 0 || ret >= MAXPATHLEN)
2415 return false;
2416 f = fopen(path, "a");
2417 if (!f)
2418 return false;
2419 bret = true;
2420 // if anything goes wrong, just return an error
2421 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2422 bret = false;
2423 if (fclose(f) != 0)
2424 bret = false;
2425 return bret;
2426 }
2427
2428 static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
2429 const char *newtype, int flags, const char *bdevdata, uint64_t newsize)
2430 {
2431 struct bdev *bdev;
2432 int need_rdep;
2433
2434 bdev = bdev_copy(c0, c->name, c->config_path, newtype, flags,
2435 bdevdata, newsize, &need_rdep);
2436 if (!bdev) {
2437 ERROR("Error copying storage");
2438 return -1;
2439 }
2440 free(c->lxc_conf->rootfs.path);
2441 c->lxc_conf->rootfs.path = strdup(bdev->src);
2442 bdev_put(bdev);
2443 if (!c->lxc_conf->rootfs.path) {
2444 ERROR("Out of memory while setting storage path");
2445 return -1;
2446 }
2447 if (flags & LXC_CLONE_SNAPSHOT)
2448 copy_rdepends(c, c0);
2449 if (need_rdep) {
2450 if (!add_rdepends(c, c0))
2451 WARN("Error adding reverse dependency from %s to %s",
2452 c->name, c0->name);
2453 }
2454
2455 mod_all_rdeps(c, true);
2456
2457 return 0;
2458 }
2459
2460 struct clone_update_data {
2461 struct lxc_container *c0;
2462 struct lxc_container *c1;
2463 int flags;
2464 char **hookargs;
2465 };
2466
2467 static int clone_update_rootfs(struct clone_update_data *data)
2468 {
2469 struct lxc_container *c0 = data->c0;
2470 struct lxc_container *c = data->c1;
2471 int flags = data->flags;
2472 char **hookargs = data->hookargs;
2473 int ret = -1;
2474 char path[MAXPATHLEN];
2475 struct bdev *bdev;
2476 FILE *fout;
2477 struct lxc_conf *conf = c->lxc_conf;
2478
2479 /* update hostname in rootfs */
2480 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2481
2482 if (setgid(0) < 0) {
2483 ERROR("Failed to setgid to 0");
2484 return -1;
2485 }
2486 if (setuid(0) < 0) {
2487 ERROR("Failed to setuid to 0");
2488 return -1;
2489 }
2490 if (setgroups(0, NULL) < 0)
2491 WARN("Failed to clear groups");
2492
2493 if (unshare(CLONE_NEWNS) < 0)
2494 return -1;
2495 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2496 if (!bdev)
2497 return -1;
2498 if (strcmp(bdev->type, "dir") != 0) {
2499 if (unshare(CLONE_NEWNS) < 0) {
2500 ERROR("error unsharing mounts");
2501 bdev_put(bdev);
2502 return -1;
2503 }
2504 if (detect_shared_rootfs()) {
2505 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
2506 SYSERROR("Failed to make / rslave");
2507 ERROR("Continuing...");
2508 }
2509 }
2510 if (bdev->ops->mount(bdev) < 0) {
2511 bdev_put(bdev);
2512 return -1;
2513 }
2514 } else { // TODO come up with a better way
2515 if (bdev->dest)
2516 free(bdev->dest);
2517 bdev->dest = strdup(bdev->src);
2518 }
2519
2520 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2521 /* Start of environment variable setup for hooks */
2522 if (setenv("LXC_SRC_NAME", c0->name, 1)) {
2523 SYSERROR("failed to set environment variable for source container name");
2524 }
2525 if (setenv("LXC_NAME", c->name, 1)) {
2526 SYSERROR("failed to set environment variable for container name");
2527 }
2528 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
2529 SYSERROR("failed to set environment variable for config path");
2530 }
2531 if (setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1)) {
2532 SYSERROR("failed to set environment variable for rootfs mount");
2533 }
2534 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
2535 SYSERROR("failed to set environment variable for rootfs mount");
2536 }
2537
2538 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
2539 ERROR("Error executing clone hook for %s", c->name);
2540 bdev_put(bdev);
2541 return -1;
2542 }
2543 }
2544
2545 if (!(flags & LXC_CLONE_KEEPNAME)) {
2546 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
2547 bdev_put(bdev);
2548
2549 if (ret < 0 || ret >= MAXPATHLEN)
2550 return -1;
2551 if (!file_exists(path))
2552 return 0;
2553 if (!(fout = fopen(path, "w"))) {
2554 SYSERROR("unable to open %s: ignoring", path);
2555 return 0;
2556 }
2557 if (fprintf(fout, "%s", c->name) < 0) {
2558 fclose(fout);
2559 return -1;
2560 }
2561 if (fclose(fout) < 0)
2562 return -1;
2563 }
2564 else
2565 bdev_put(bdev);
2566
2567 return 0;
2568 }
2569
2570 static int clone_update_rootfs_wrapper(void *data)
2571 {
2572 struct clone_update_data *arg = (struct clone_update_data *) data;
2573 return clone_update_rootfs(arg);
2574 }
2575
2576 /*
2577 * We want to support:
2578 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2579 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2580
2581 -s [ implies overlayfs]
2582 -s -B overlayfs
2583 -s -B aufs
2584
2585 only rootfs gets converted (copied/snapshotted) on clone.
2586 */
2587
2588 static int create_file_dirname(char *path)
2589 {
2590 char *p = strrchr(path, '/');
2591 int ret;
2592
2593 if (!p)
2594 return -1;
2595 *p = '\0';
2596 ret = mkdir(path, 0755);
2597 if (ret && errno != EEXIST)
2598 SYSERROR("creating container path %s", path);
2599 *p = '/';
2600 return ret;
2601 }
2602
2603 static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
2604 const char *lxcpath, int flags,
2605 const char *bdevtype, const char *bdevdata, uint64_t newsize,
2606 char **hookargs)
2607 {
2608 struct lxc_container *c2 = NULL;
2609 char newpath[MAXPATHLEN];
2610 int ret, storage_copied = 0;
2611 const char *n, *l;
2612 char *origroot = NULL;
2613 struct clone_update_data data;
2614 FILE *fout;
2615 pid_t pid;
2616
2617 if (!c || !c->is_defined(c))
2618 return NULL;
2619
2620 if (container_mem_lock(c))
2621 return NULL;
2622
2623 if (!is_stopped(c)) {
2624 ERROR("error: Original container (%s) is running", c->name);
2625 goto out;
2626 }
2627
2628 // Make sure the container doesn't yet exist.
2629 n = newname ? newname : c->name;
2630 l = lxcpath ? lxcpath : c->get_config_path(c);
2631 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
2632 if (ret < 0 || ret >= MAXPATHLEN) {
2633 SYSERROR("clone: failed making config pathname");
2634 goto out;
2635 }
2636 if (file_exists(newpath)) {
2637 ERROR("error: clone: %s exists", newpath);
2638 goto out;
2639 }
2640
2641 ret = create_file_dirname(newpath);
2642 if (ret < 0 && errno != EEXIST) {
2643 ERROR("Error creating container dir for %s", newpath);
2644 goto out;
2645 }
2646
2647 // copy the configuration, tweak it as needed,
2648 if (c->lxc_conf->rootfs.path) {
2649 origroot = c->lxc_conf->rootfs.path;
2650 c->lxc_conf->rootfs.path = NULL;
2651 }
2652 fout = fopen(newpath, "w");
2653 if (!fout) {
2654 SYSERROR("open %s", newpath);
2655 goto out;
2656 }
2657 write_config(fout, c->lxc_conf);
2658 fclose(fout);
2659 c->lxc_conf->rootfs.path = origroot;
2660
2661 sprintf(newpath, "%s/%s/rootfs", l, n);
2662 if (mkdir(newpath, 0755) < 0) {
2663 SYSERROR("error creating %s", newpath);
2664 goto out;
2665 }
2666
2667 if (am_unpriv()) {
2668 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
2669 ERROR("Error chowning %s to container root", newpath);
2670 goto out;
2671 }
2672 }
2673
2674 c2 = lxc_container_new(n, l);
2675 if (!c2) {
2676 ERROR("clone: failed to create new container (%s %s)", n, l);
2677 goto out;
2678 }
2679
2680 // copy/snapshot rootfs's
2681 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
2682 if (ret < 0)
2683 goto out;
2684
2685 // update utsname
2686 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
2687 ERROR("Error setting new hostname");
2688 goto out;
2689 }
2690
2691 // copy hooks
2692 ret = copyhooks(c, c2);
2693 if (ret < 0) {
2694 ERROR("error copying hooks");
2695 goto out;
2696 }
2697
2698 if (copy_fstab(c, c2) < 0) {
2699 ERROR("error copying fstab");
2700 goto out;
2701 }
2702
2703 // update macaddrs
2704 if (!(flags & LXC_CLONE_KEEPMACADDR))
2705 network_new_hwaddrs(c2);
2706
2707 // We've now successfully created c2's storage, so clear it out if we
2708 // fail after this
2709 storage_copied = 1;
2710
2711 if (!c2->save_config(c2, NULL))
2712 goto out;
2713
2714 if ((pid = fork()) < 0) {
2715 SYSERROR("fork");
2716 goto out;
2717 }
2718 if (pid > 0) {
2719 ret = wait_for_pid(pid);
2720 if (ret)
2721 goto out;
2722 container_mem_unlock(c);
2723 return c2;
2724 }
2725 data.c0 = c;
2726 data.c1 = c2;
2727 data.flags = flags;
2728 data.hookargs = hookargs;
2729 if (am_unpriv())
2730 ret = userns_exec_1(c->lxc_conf, clone_update_rootfs_wrapper,
2731 &data);
2732 else
2733 ret = clone_update_rootfs(&data);
2734 if (ret < 0)
2735 exit(1);
2736
2737 container_mem_unlock(c);
2738 exit(0);
2739
2740 out:
2741 container_mem_unlock(c);
2742 if (c2) {
2743 if (!storage_copied)
2744 c2->lxc_conf->rootfs.path = NULL;
2745 c2->destroy(c2);
2746 lxc_container_put(c2);
2747 }
2748
2749 return NULL;
2750 }
2751
2752 static bool lxcapi_rename(struct lxc_container *c, const char *newname)
2753 {
2754 struct bdev *bdev;
2755 struct lxc_container *newc;
2756
2757 if (!c || !c->name || !c->config_path || !c->lxc_conf)
2758 return false;
2759
2760 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2761 if (!bdev) {
2762 ERROR("Failed to find original backing store type");
2763 return false;
2764 }
2765
2766 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
2767 bdev_put(bdev);
2768 if (!newc) {
2769 lxc_container_put(newc);
2770 return false;
2771 }
2772
2773 if (newc && lxcapi_is_defined(newc))
2774 lxc_container_put(newc);
2775
2776 if (!lxcapi_destroy(c)) {
2777 ERROR("Could not destroy existing container %s", c->name);
2778 return false;
2779 }
2780 return true;
2781 }
2782
2783 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)
2784 {
2785 if (!c)
2786 return -1;
2787
2788 return lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
2789 }
2790
2791 static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
2792 {
2793 lxc_attach_command_t command;
2794 pid_t pid;
2795 int r;
2796
2797 if (!c)
2798 return -1;
2799
2800 command.program = (char*)program;
2801 command.argv = (char**)argv;
2802 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
2803 if (r < 0) {
2804 ERROR("ups");
2805 return r;
2806 }
2807 return lxc_wait_for_pid_status(pid);
2808 }
2809
2810 static int get_next_index(const char *lxcpath, char *cname)
2811 {
2812 char *fname;
2813 struct stat sb;
2814 int i = 0, ret;
2815
2816 fname = alloca(strlen(lxcpath) + 20);
2817 while (1) {
2818 sprintf(fname, "%s/snap%d", lxcpath, i);
2819 ret = stat(fname, &sb);
2820 if (ret != 0)
2821 return i;
2822 i++;
2823 }
2824 }
2825
2826 static int lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
2827 {
2828 int i, flags, ret;
2829 struct lxc_container *c2;
2830 char snappath[MAXPATHLEN], newname[20];
2831
2832 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2833 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2834 if (ret < 0 || ret >= MAXPATHLEN)
2835 return -1;
2836 i = get_next_index(snappath, c->name);
2837
2838 if (mkdir_p(snappath, 0755) < 0) {
2839 ERROR("Failed to create snapshot directory %s", snappath);
2840 return -1;
2841 }
2842
2843 ret = snprintf(newname, 20, "snap%d", i);
2844 if (ret < 0 || ret >= 20)
2845 return -1;
2846
2847 /*
2848 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2849 * created in the original container
2850 */
2851 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
2852 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
2853 if (bdev_is_dir(c->lxc_conf->rootfs.path)) {
2854 ERROR("Snapshot of directory-backed container requested.");
2855 ERROR("Making a copy-clone. If you do want snapshots, then");
2856 ERROR("please create an aufs or overlayfs clone first, snapshot that");
2857 ERROR("and keep the original container pristine.");
2858 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
2859 }
2860 c2 = c->clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
2861 if (!c2) {
2862 ERROR("clone of %s:%s failed", c->config_path, c->name);
2863 return -1;
2864 }
2865
2866 lxc_container_put(c2);
2867
2868 // Now write down the creation time
2869 time_t timer;
2870 char buffer[25];
2871 struct tm* tm_info;
2872 FILE *f;
2873
2874 time(&timer);
2875 tm_info = localtime(&timer);
2876
2877 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
2878
2879 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
2880 sprintf(dfnam, "%s/%s/ts", snappath, newname);
2881 f = fopen(dfnam, "w");
2882 if (!f) {
2883 ERROR("Failed to open %s", dfnam);
2884 return -1;
2885 }
2886 if (fprintf(f, "%s", buffer) < 0) {
2887 SYSERROR("Writing timestamp");
2888 fclose(f);
2889 return -1;
2890 }
2891 ret = fclose(f);
2892 if (ret != 0) {
2893 SYSERROR("Writing timestamp");
2894 return -1;
2895 }
2896
2897 if (commentfile) {
2898 // $p / $name / comment \0
2899 int len = strlen(snappath) + strlen(newname) + 10;
2900 char *path = alloca(len);
2901 sprintf(path, "%s/%s/comment", snappath, newname);
2902 return copy_file(commentfile, path) < 0 ? -1 : i;
2903 }
2904
2905 return i;
2906 }
2907
2908 static void lxcsnap_free(struct lxc_snapshot *s)
2909 {
2910 if (s->name)
2911 free(s->name);
2912 if (s->comment_pathname)
2913 free(s->comment_pathname);
2914 if (s->timestamp)
2915 free(s->timestamp);
2916 if (s->lxcpath)
2917 free(s->lxcpath);
2918 }
2919
2920 static char *get_snapcomment_path(char* snappath, char *name)
2921 {
2922 // $snappath/$name/comment
2923 int ret, len = strlen(snappath) + strlen(name) + 10;
2924 char *s = malloc(len);
2925
2926 if (s) {
2927 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
2928 if (ret < 0 || ret >= len) {
2929 free(s);
2930 s = NULL;
2931 }
2932 }
2933 return s;
2934 }
2935
2936 static char *get_timestamp(char* snappath, char *name)
2937 {
2938 char path[MAXPATHLEN], *s = NULL;
2939 int ret, len;
2940 FILE *fin;
2941
2942 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
2943 if (ret < 0 || ret >= MAXPATHLEN)
2944 return NULL;
2945 fin = fopen(path, "r");
2946 if (!fin)
2947 return NULL;
2948 (void) fseek(fin, 0, SEEK_END);
2949 len = ftell(fin);
2950 (void) fseek(fin, 0, SEEK_SET);
2951 if (len > 0) {
2952 s = malloc(len+1);
2953 if (s) {
2954 s[len] = '\0';
2955 if (fread(s, 1, len, fin) != len) {
2956 SYSERROR("reading timestamp");
2957 free(s);
2958 s = NULL;
2959 }
2960 }
2961 }
2962 fclose(fin);
2963 return s;
2964 }
2965
2966 static int lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
2967 {
2968 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
2969 int dirlen, count = 0, ret;
2970 struct dirent dirent, *direntp;
2971 struct lxc_snapshot *snaps =NULL, *nsnaps;
2972 DIR *dir;
2973
2974 if (!c || !lxcapi_is_defined(c))
2975 return -1;
2976
2977 // snappath is ${lxcpath}snaps/${lxcname}/
2978 dirlen = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2979 if (dirlen < 0 || dirlen >= MAXPATHLEN) {
2980 ERROR("path name too long");
2981 return -1;
2982 }
2983 dir = opendir(snappath);
2984 if (!dir) {
2985 INFO("failed to open %s - assuming no snapshots", snappath);
2986 return 0;
2987 }
2988
2989 while (!readdir_r(dir, &dirent, &direntp)) {
2990 if (!direntp)
2991 break;
2992
2993 if (!strcmp(direntp->d_name, "."))
2994 continue;
2995
2996 if (!strcmp(direntp->d_name, ".."))
2997 continue;
2998
2999 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
3000 if (ret < 0 || ret >= MAXPATHLEN) {
3001 ERROR("pathname too long");
3002 goto out_free;
3003 }
3004 if (!file_exists(path2))
3005 continue;
3006 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
3007 if (!nsnaps) {
3008 SYSERROR("Out of memory");
3009 goto out_free;
3010 }
3011 snaps = nsnaps;
3012 snaps[count].free = lxcsnap_free;
3013 snaps[count].name = strdup(direntp->d_name);
3014 if (!snaps[count].name)
3015 goto out_free;
3016 snaps[count].lxcpath = strdup(snappath);
3017 if (!snaps[count].lxcpath) {
3018 free(snaps[count].name);
3019 goto out_free;
3020 }
3021 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
3022 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
3023 count++;
3024 }
3025
3026 if (closedir(dir))
3027 WARN("failed to close directory");
3028
3029 *ret_snaps = snaps;
3030 return count;
3031
3032 out_free:
3033 if (snaps) {
3034 int i;
3035 for (i=0; i<count; i++)
3036 lxcsnap_free(&snaps[i]);
3037 free(snaps);
3038 }
3039 if (closedir(dir))
3040 WARN("failed to close directory");
3041 return -1;
3042 }
3043
3044 static bool lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
3045 {
3046 char clonelxcpath[MAXPATHLEN];
3047 int flags = 0,ret;
3048 struct lxc_container *snap, *rest;
3049 struct bdev *bdev;
3050 bool b = false;
3051
3052 if (!c || !c->name || !c->config_path)
3053 return false;
3054
3055 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
3056 if (!bdev) {
3057 ERROR("Failed to find original backing store type");
3058 return false;
3059 }
3060
3061 if (!newname)
3062 newname = c->name;
3063 if (strcmp(c->name, newname) == 0) {
3064 if (!lxcapi_destroy(c)) {
3065 ERROR("Could not destroy existing container %s", newname);
3066 bdev_put(bdev);
3067 return false;
3068 }
3069 }
3070 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
3071 if (ret < 0 || ret >= MAXPATHLEN) {
3072 bdev_put(bdev);
3073 return false;
3074 }
3075 // how should we lock this?
3076
3077 snap = lxc_container_new(snapname, clonelxcpath);
3078 if (!snap || !lxcapi_is_defined(snap)) {
3079 ERROR("Could not open snapshot %s", snapname);
3080 if (snap) lxc_container_put(snap);
3081 bdev_put(bdev);
3082 return false;
3083 }
3084
3085 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
3086 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3087 rest = lxcapi_clone(snap, newname, c->config_path, flags,
3088 bdev->type, NULL, 0, NULL);
3089 bdev_put(bdev);
3090 if (rest && lxcapi_is_defined(rest))
3091 b = true;
3092 if (rest)
3093 lxc_container_put(rest);
3094 lxc_container_put(snap);
3095 return b;
3096 }
3097
3098 static bool lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
3099 {
3100 int ret;
3101 char clonelxcpath[MAXPATHLEN];
3102 struct lxc_container *snap = NULL;
3103
3104 if (!c || !c->name || !c->config_path)
3105 return false;
3106
3107 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
3108 if (ret < 0 || ret >= MAXPATHLEN)
3109 goto err;
3110
3111 snap = lxc_container_new(snapname, clonelxcpath);
3112 if (!snap || !lxcapi_is_defined(snap)) {
3113 ERROR("Could not find snapshot %s", snapname);
3114 goto err;
3115 }
3116
3117 if (!lxcapi_destroy(snap)) {
3118 ERROR("Could not destroy snapshot %s", snapname);
3119 goto err;
3120 }
3121 lxc_container_put(snap);
3122
3123 return true;
3124 err:
3125 if (snap)
3126 lxc_container_put(snap);
3127 return false;
3128 }
3129
3130 static bool lxcapi_may_control(struct lxc_container *c)
3131 {
3132 return lxc_try_cmd(c->name, c->config_path) == 0;
3133 }
3134
3135 static bool do_add_remove_node(pid_t init_pid, const char *path, bool add,
3136 struct stat *st)
3137 {
3138 char chrootpath[MAXPATHLEN];
3139 char *directory_path = NULL;
3140 pid_t pid;
3141 int ret;
3142
3143 if ((pid = fork()) < 0) {
3144 SYSERROR("failed to fork a child helper");
3145 return false;
3146 }
3147 if (pid) {
3148 if (wait_for_pid(pid) != 0) {
3149 ERROR("Failed to create note in guest");
3150 return false;
3151 }
3152 return true;
3153 }
3154
3155 /* prepare the path */
3156 ret = snprintf(chrootpath, MAXPATHLEN, "/proc/%d/root", init_pid);
3157 if (ret < 0 || ret >= MAXPATHLEN)
3158 return false;
3159
3160 if (chroot(chrootpath) < 0)
3161 exit(1);
3162 if (chdir("/") < 0)
3163 exit(1);
3164 /* remove path if it exists */
3165 if(faccessat(AT_FDCWD, path, F_OK, AT_SYMLINK_NOFOLLOW) == 0) {
3166 if (unlink(path) < 0) {
3167 ERROR("unlink failed");
3168 exit(1);
3169 }
3170 }
3171 if (!add)
3172 exit(0);
3173
3174 /* create any missing directories */
3175 directory_path = dirname(strdup(path));
3176 if (mkdir_p(directory_path, 0755) < 0 && errno != EEXIST) {
3177 ERROR("failed to create directory");
3178 exit(1);
3179 }
3180
3181 /* create the device node */
3182 if (mknod(path, st->st_mode, st->st_rdev) < 0) {
3183 ERROR("mknod failed");
3184 exit(1);
3185 }
3186
3187 exit(0);
3188 }
3189
3190 static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
3191 {
3192 int ret;
3193 struct stat st;
3194 char value[MAX_BUFFER];
3195 const char *p;
3196
3197 /* make sure container is running */
3198 if (!c->is_running(c)) {
3199 ERROR("container is not running");
3200 return false;
3201 }
3202
3203 /* use src_path if dest_path is NULL otherwise use dest_path */
3204 p = dest_path ? dest_path : src_path;
3205
3206 /* make sure we can access p */
3207 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
3208 return false;
3209
3210 /* continue if path is character device or block device */
3211 if (S_ISCHR(st.st_mode))
3212 ret = snprintf(value, MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
3213 else if (S_ISBLK(st.st_mode))
3214 ret = snprintf(value, MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
3215 else
3216 return false;
3217
3218 /* check snprintf return code */
3219 if (ret < 0 || ret >= MAX_BUFFER)
3220 return false;
3221
3222 if (!do_add_remove_node(c->init_pid(c), p, add, &st))
3223 return false;
3224
3225 /* add or remove device to/from cgroup access list */
3226 if (add) {
3227 if (!c->set_cgroup_item(c, "devices.allow", value)) {
3228 ERROR("set_cgroup_item failed while adding the device node");
3229 return false;
3230 }
3231 } else {
3232 if (!c->set_cgroup_item(c, "devices.deny", value)) {
3233 ERROR("set_cgroup_item failed while removing the device node");
3234 return false;
3235 }
3236 }
3237
3238 return true;
3239 }
3240
3241 static bool lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
3242 {
3243 if (am_unpriv()) {
3244 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3245 return false;
3246 }
3247 return add_remove_device_node(c, src_path, dest_path, true);
3248 }
3249
3250 static bool lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
3251 {
3252 if (am_unpriv()) {
3253 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
3254 return false;
3255 }
3256 return add_remove_device_node(c, src_path, dest_path, false);
3257 }
3258
3259 static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
3260 {
3261 va_list ap;
3262 const char **argv;
3263 int ret;
3264
3265 if (!c)
3266 return -1;
3267
3268 va_start(ap, arg);
3269 argv = lxc_va_arg_list_to_argv_const(ap, 1);
3270 va_end(ap);
3271
3272 if (!argv) {
3273 ERROR("Memory allocation error.");
3274 return -1;
3275 }
3276 argv[0] = arg;
3277
3278 ret = lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
3279 free((void*)argv);
3280 return ret;
3281 }
3282
3283 struct lxc_container *lxc_container_new(const char *name, const char *configpath)
3284 {
3285 struct lxc_container *c;
3286
3287 c = malloc(sizeof(*c));
3288 if (!c) {
3289 fprintf(stderr, "failed to malloc lxc_container\n");
3290 return NULL;
3291 }
3292 memset(c, 0, sizeof(*c));
3293
3294 if (configpath)
3295 c->config_path = strdup(configpath);
3296 else
3297 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
3298
3299 if (!c->config_path) {
3300 fprintf(stderr, "Out of memory\n");
3301 goto err;
3302 }
3303
3304 remove_trailing_slashes(c->config_path);
3305 c->name = malloc(strlen(name)+1);
3306 if (!c->name) {
3307 fprintf(stderr, "Error allocating lxc_container name\n");
3308 goto err;
3309 }
3310 strcpy(c->name, name);
3311
3312 c->numthreads = 1;
3313 if (!(c->slock = lxc_newlock(c->config_path, name))) {
3314 fprintf(stderr, "failed to create lock\n");
3315 goto err;
3316 }
3317
3318 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
3319 fprintf(stderr, "failed to alloc privlock\n");
3320 goto err;
3321 }
3322
3323 if (!set_config_filename(c)) {
3324 fprintf(stderr, "Error allocating config file pathname\n");
3325 goto err;
3326 }
3327
3328 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL))
3329 goto err;
3330
3331 if (ongoing_create(c) == 2) {
3332 ERROR("Error: %s creation was not completed", c->name);
3333 lxcapi_destroy(c);
3334 lxcapi_clear_config(c);
3335 }
3336 c->daemonize = true;
3337 c->pidfile = NULL;
3338
3339 // assign the member functions
3340 c->is_defined = lxcapi_is_defined;
3341 c->state = lxcapi_state;
3342 c->is_running = lxcapi_is_running;
3343 c->freeze = lxcapi_freeze;
3344 c->unfreeze = lxcapi_unfreeze;
3345 c->console = lxcapi_console;
3346 c->console_getfd = lxcapi_console_getfd;
3347 c->init_pid = lxcapi_init_pid;
3348 c->load_config = lxcapi_load_config;
3349 c->want_daemonize = lxcapi_want_daemonize;
3350 c->want_close_all_fds = lxcapi_want_close_all_fds;
3351 c->start = lxcapi_start;
3352 c->startl = lxcapi_startl;
3353 c->stop = lxcapi_stop;
3354 c->config_file_name = lxcapi_config_file_name;
3355 c->wait = lxcapi_wait;
3356 c->set_config_item = lxcapi_set_config_item;
3357 c->destroy = lxcapi_destroy;
3358 c->rename = lxcapi_rename;
3359 c->save_config = lxcapi_save_config;
3360 c->get_keys = lxcapi_get_keys;
3361 c->create = lxcapi_create;
3362 c->createl = lxcapi_createl;
3363 c->shutdown = lxcapi_shutdown;
3364 c->reboot = lxcapi_reboot;
3365 c->clear_config = lxcapi_clear_config;
3366 c->clear_config_item = lxcapi_clear_config_item;
3367 c->get_config_item = lxcapi_get_config_item;
3368 c->get_running_config_item = lxcapi_get_running_config_item;
3369 c->get_cgroup_item = lxcapi_get_cgroup_item;
3370 c->set_cgroup_item = lxcapi_set_cgroup_item;
3371 c->get_config_path = lxcapi_get_config_path;
3372 c->set_config_path = lxcapi_set_config_path;
3373 c->clone = lxcapi_clone;
3374 c->get_interfaces = lxcapi_get_interfaces;
3375 c->get_ips = lxcapi_get_ips;
3376 c->attach = lxcapi_attach;
3377 c->attach_run_wait = lxcapi_attach_run_wait;
3378 c->attach_run_waitl = lxcapi_attach_run_waitl;
3379 c->snapshot = lxcapi_snapshot;
3380 c->snapshot_list = lxcapi_snapshot_list;
3381 c->snapshot_restore = lxcapi_snapshot_restore;
3382 c->snapshot_destroy = lxcapi_snapshot_destroy;
3383 c->may_control = lxcapi_may_control;
3384 c->add_device_node = lxcapi_add_device_node;
3385 c->remove_device_node = lxcapi_remove_device_node;
3386
3387 /* we'll allow the caller to update these later */
3388 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
3389 fprintf(stderr, "failed to open log\n");
3390 goto err;
3391 }
3392
3393 return c;
3394
3395 err:
3396 lxc_container_free(c);
3397 return NULL;
3398 }
3399
3400 int lxc_get_wait_states(const char **states)
3401 {
3402 int i;
3403
3404 if (states)
3405 for (i=0; i<MAX_STATE; i++)
3406 states[i] = lxc_state2str(i);
3407 return MAX_STATE;
3408 }
3409
3410 /*
3411 * These next two could probably be done smarter with reusing a common function
3412 * with different iterators and tests...
3413 */
3414 int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
3415 {
3416 DIR *dir;
3417 int i, cfound = 0, nfound = 0;
3418 struct dirent dirent, *direntp;
3419 struct lxc_container *c;
3420
3421 if (!lxcpath)
3422 lxcpath = lxc_global_config_value("lxc.lxcpath");
3423
3424 dir = opendir(lxcpath);
3425 if (!dir) {
3426 SYSERROR("opendir on lxcpath");
3427 return -1;
3428 }
3429
3430 if (cret)
3431 *cret = NULL;
3432 if (names)
3433 *names = NULL;
3434
3435 while (!readdir_r(dir, &dirent, &direntp)) {
3436 if (!direntp)
3437 break;
3438 if (!strcmp(direntp->d_name, "."))
3439 continue;
3440 if (!strcmp(direntp->d_name, ".."))
3441 continue;
3442
3443 if (!config_file_exists(lxcpath, direntp->d_name))
3444 continue;
3445
3446 if (names) {
3447 if (!add_to_array(names, direntp->d_name, cfound))
3448 goto free_bad;
3449 }
3450 cfound++;
3451
3452 if (!cret) {
3453 nfound++;
3454 continue;
3455 }
3456
3457 c = lxc_container_new(direntp->d_name, lxcpath);
3458 if (!c) {
3459 INFO("Container %s:%s has a config but could not be loaded",
3460 lxcpath, direntp->d_name);
3461 if (names)
3462 if(!remove_from_array(names, direntp->d_name, cfound--))
3463 goto free_bad;
3464 continue;
3465 }
3466 if (!lxcapi_is_defined(c)) {
3467 INFO("Container %s:%s has a config but is not defined",
3468 lxcpath, direntp->d_name);
3469 if (names)
3470 if(!remove_from_array(names, direntp->d_name, cfound--))
3471 goto free_bad;
3472 lxc_container_put(c);
3473 continue;
3474 }
3475
3476 if (!add_to_clist(cret, c, nfound, true)) {
3477 lxc_container_put(c);
3478 goto free_bad;
3479 }
3480 nfound++;
3481 }
3482
3483 closedir(dir);
3484 return nfound;
3485
3486 free_bad:
3487 if (names && *names) {
3488 for (i=0; i<cfound; i++)
3489 free((*names)[i]);
3490 free(*names);
3491 }
3492 if (cret && *cret) {
3493 for (i=0; i<nfound; i++)
3494 lxc_container_put((*cret)[i]);
3495 free(*cret);
3496 }
3497 closedir(dir);
3498 return -1;
3499 }
3500
3501 int list_active_containers(const char *lxcpath, char ***nret,
3502 struct lxc_container ***cret)
3503 {
3504 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
3505 int lxcpath_len;
3506 char *line = NULL;
3507 char **ct_name = NULL;
3508 size_t len = 0;
3509 struct lxc_container *c;
3510
3511 if (!lxcpath)
3512 lxcpath = lxc_global_config_value("lxc.lxcpath");
3513 lxcpath_len = strlen(lxcpath);
3514
3515 if (cret)
3516 *cret = NULL;
3517 if (nret)
3518 *nret = NULL;
3519
3520 FILE *f = fopen("/proc/net/unix", "r");
3521 if (!f)
3522 return -1;
3523
3524 while (getline(&line, &len, f) != -1) {
3525 char *p = strrchr(line, ' '), *p2;
3526 if (!p)
3527 continue;
3528 p++;
3529 if (*p != 0x40)
3530 continue;
3531 p++;
3532 if (strncmp(p, lxcpath, lxcpath_len) != 0)
3533 continue;
3534 p += lxcpath_len;
3535 while (*p == '/')
3536 p++;
3537
3538 // Now p is the start of lxc_name
3539 p2 = index(p, '/');
3540 if (!p2 || strncmp(p2, "/command", 8) != 0)
3541 continue;
3542 *p2 = '\0';
3543
3544 if (array_contains(&ct_name, p, ct_name_cnt))
3545 continue;
3546
3547 if (!add_to_array(&ct_name, p, ct_name_cnt))
3548 goto free_cret_list;
3549
3550 ct_name_cnt++;
3551
3552 if (!cret)
3553 continue;
3554
3555 c = lxc_container_new(p, lxcpath);
3556 if (!c) {
3557 INFO("Container %s:%s is running but could not be loaded",
3558 lxcpath, p);
3559 remove_from_array(&ct_name, p, ct_name_cnt--);
3560 continue;
3561 }
3562
3563 /*
3564 * If this is an anonymous container, then is_defined *can*
3565 * return false. So we don't do that check. Count on the
3566 * fact that the command socket exists.
3567 */
3568
3569 if (!add_to_clist(cret, c, cret_cnt, true)) {
3570 lxc_container_put(c);
3571 goto free_cret_list;
3572 }
3573 cret_cnt++;
3574 }
3575
3576 assert(!nret || !cret || cret_cnt == ct_name_cnt);
3577 ret = ct_name_cnt;
3578 if (nret)
3579 *nret = ct_name;
3580 else
3581 goto free_ct_name;
3582 goto out;
3583
3584 free_cret_list:
3585 if (cret && *cret) {
3586 for (i = 0; i < cret_cnt; i++)
3587 lxc_container_put((*cret)[i]);
3588 free(*cret);
3589 }
3590
3591 free_ct_name:
3592 if (ct_name) {
3593 for (i = 0; i < ct_name_cnt; i++)
3594 free(ct_name[i]);
3595 free(ct_name);
3596 }
3597
3598 out:
3599 if (line)
3600 free(line);
3601
3602 fclose(f);
3603 return ret;
3604 }
3605
3606 int list_all_containers(const char *lxcpath, char ***nret,
3607 struct lxc_container ***cret)
3608 {
3609 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
3610 char **active_name;
3611 char **ct_name;
3612 struct lxc_container **ct_list = NULL;
3613
3614 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
3615 if (ct_cnt < 0)
3616 return ct_cnt;
3617
3618 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
3619 if (active_cnt < 0) {
3620 ret = active_cnt;
3621 goto free_ct_name;
3622 }
3623
3624 for (i = 0; i < active_cnt; i++) {
3625 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
3626 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
3627 ret = -1;
3628 goto free_active_name;
3629 }
3630 ct_cnt++;
3631 }
3632 free(active_name[i]);
3633 active_name[i] = NULL;
3634 }
3635 free(active_name);
3636 active_name = NULL;
3637 active_cnt = 0;
3638
3639 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
3640 struct lxc_container *c;
3641
3642 c = lxc_container_new(ct_name[i], lxcpath);
3643 if (!c) {
3644 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
3645 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
3646 continue;
3647 }
3648
3649 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
3650 lxc_container_put(c);
3651 ret = -1;
3652 goto free_ct_list;
3653 }
3654 ct_list_cnt++;
3655 }
3656
3657 if (cret)
3658 *cret = ct_list;
3659
3660 if (nret)
3661 *nret = ct_name;
3662 else {
3663 ret = ct_cnt;
3664 goto free_ct_name;
3665 }
3666 return ct_cnt;
3667
3668 free_ct_list:
3669 for (i = 0; i < ct_list_cnt; i++) {
3670 lxc_container_put(ct_list[i]);
3671 }
3672 if (ct_list)
3673 free(ct_list);
3674
3675 free_active_name:
3676 for (i = 0; i < active_cnt; i++) {
3677 if (active_name[i])
3678 free(active_name[i]);
3679 }
3680 if (active_name)
3681 free(active_name);
3682
3683 free_ct_name:
3684 for (i = 0; i < ct_cnt; i++) {
3685 free(ct_name[i]);
3686 }
3687 free(ct_name);
3688 return ret;
3689 }