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