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