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