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