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