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