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