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