]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
lxccontainer: do_lxcapi_create()
[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 <dirent.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <grp.h>
26 #include <libgen.h>
27 #include <pthread.h>
28 #include <sched.h>
29 #include <stdarg.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <arpa/inet.h>
34 #include <sys/sysmacros.h>
35 #include <sys/mman.h>
36 #include <sys/mount.h>
37 #include <sys/syscall.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40
41 #include "af_unix.h"
42 #include "attach.h"
43 #include "cgroup.h"
44 #include "conf.h"
45 #include "config.h"
46 #include "commands.h"
47 #include "commands_utils.h"
48 #include "confile.h"
49 #include "confile_utils.h"
50 #include "console.h"
51 #include "criu.h"
52 #include "initutils.h"
53 #include "log.h"
54 #include "lxc.h"
55 #include "lxccontainer.h"
56 #include "lxclock.h"
57 #include "monitor.h"
58 #include "namespace.h"
59 #include "network.h"
60 #include "parse.h"
61 #include "start.h"
62 #include "state.h"
63 #include "storage.h"
64 #include "storage_utils.h"
65 #include "storage/btrfs.h"
66 #include "storage/overlay.h"
67 #include "sync.h"
68 #include "utils.h"
69 #include "version.h"
70
71 /* major()/minor() */
72 #ifdef MAJOR_IN_MKDEV
73 # include <sys/mkdev.h>
74 #endif
75
76 #if HAVE_IFADDRS_H
77 #include <ifaddrs.h>
78 #else
79 #include <../include/ifaddrs.h>
80 #endif
81
82 #if IS_BIONIC
83 #include <../include/lxcmntent.h>
84 #else
85 #include <mntent.h>
86 #endif
87
88 #define MAX_BUFFER 4096
89
90 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
91
92 /* Define faccessat() if missing from the C library */
93 #ifndef HAVE_FACCESSAT
94 static int faccessat(int __fd, const char *__file, int __type, int __flag)
95 {
96 #ifdef __NR_faccessat
97 return syscall(__NR_faccessat, __fd, __file, __type, __flag);
98 #else
99 errno = ENOSYS;
100 return -1;
101 #endif
102 }
103 #endif
104
105 lxc_log_define(lxc_container, lxc);
106
107 static bool do_lxcapi_destroy(struct lxc_container *c);
108 static const char *lxcapi_get_config_path(struct lxc_container *c);
109 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
110 static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v);
111 static bool container_destroy(struct lxc_container *c,
112 struct lxc_storage *storage);
113 static bool get_snappath_dir(struct lxc_container *c, char *snappath);
114 static bool lxcapi_snapshot_destroy_all(struct lxc_container *c);
115 static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file);
116
117 static bool config_file_exists(const char *lxcpath, const char *cname)
118 {
119 /* $lxcpath + '/' + $cname + '/config' + \0 */
120 int ret, len = strlen(lxcpath) + strlen(cname) + 9;
121 char *fname = alloca(len);
122
123 ret = snprintf(fname, len, "%s/%s/config", lxcpath, cname);
124 if (ret < 0 || ret >= len)
125 return false;
126
127 return file_exists(fname);
128 }
129
130 /*
131 * A few functions to help detect when a container creation failed.
132 * If a container creation was killed partway through, then trying
133 * to actually start that container could harm the host. We detect
134 * this by creating a 'partial' file under the container directory,
135 * and keeping an advisory lock. When container creation completes,
136 * we remove that file. When we load or try to start a container, if
137 * we find that file, without a flock, we remove the container.
138 */
139 static int ongoing_create(struct lxc_container *c)
140 {
141 int len = strlen(c->config_path) + strlen(c->name) + 10;
142 char *path = alloca(len);
143 int fd, ret;
144 struct flock lk;
145
146 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
147 if (ret < 0 || ret >= len) {
148 ERROR("Error writing partial pathname");
149 return -1;
150 }
151
152 if (!file_exists(path))
153 return 0;
154 fd = open(path, O_RDWR);
155 if (fd < 0) {
156 /* give benefit of the doubt */
157 SYSERROR("Error opening partial file");
158 return 0;
159 }
160 lk.l_type = F_WRLCK;
161 lk.l_whence = SEEK_SET;
162 lk.l_start = 0;
163 lk.l_len = 0;
164 lk.l_pid = -1;
165 if (fcntl(fd, F_GETLK, &lk) == 0 && lk.l_pid != -1) {
166 /* create is still ongoing */
167 close(fd);
168 return 1;
169 }
170 /* create completed but partial is still there. */
171 close(fd);
172 return 2;
173 }
174
175 static int create_partial(struct lxc_container *c)
176 {
177 /* $lxcpath + '/' + $name + '/partial' + \0 */
178 int len = strlen(c->config_path) + strlen(c->name) + 10;
179 char *path = alloca(len);
180 int fd, ret;
181 struct flock lk;
182
183 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
184 if (ret < 0 || ret >= len) {
185 ERROR("Error writing partial pathname");
186 return -1;
187 }
188 if ((fd=open(path, O_RDWR | O_CREAT | O_EXCL, 0755)) < 0) {
189 SYSERROR("Error creating partial file");
190 return -1;
191 }
192 lk.l_type = F_WRLCK;
193 lk.l_whence = SEEK_SET;
194 lk.l_start = 0;
195 lk.l_len = 0;
196 if (fcntl(fd, F_SETLKW, &lk) < 0) {
197 SYSERROR("Error locking partial file %s", path);
198 close(fd);
199 return -1;
200 }
201
202 return fd;
203 }
204
205 static void remove_partial(struct lxc_container *c, int fd)
206 {
207 /* $lxcpath + '/' + $name + '/partial' + \0 */
208 int len = strlen(c->config_path) + strlen(c->name) + 10;
209 char *path = alloca(len);
210 int ret;
211
212 close(fd);
213 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
214 if (ret < 0 || ret >= len) {
215 ERROR("Error writing partial pathname");
216 return;
217 }
218 if (unlink(path) < 0)
219 SYSERROR("Error unlink partial file %s", path);
220 }
221
222 /* LOCKING
223 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
224 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
225 * container configuration file.
226 * The container_disk_lock also takes the container_mem_lock.
227 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
228 * NOTHING mutexes two independent programs with their own struct
229 * lxc_container for the same c->name, between API calls. For instance,
230 * c->config_read(); c->start(); Between those calls, data on disk
231 * could change (which shouldn't bother the caller unless for instance
232 * the rootfs get moved). c->config_read(); update; c->config_write();
233 * Two such updaters could race. The callers should therefore check their
234 * results. Trying to prevent that would necessarily expose us to deadlocks
235 * due to hung callers. So I prefer to keep the locks only within our own
236 * functions, not across functions.
237 *
238 * If you're going to clone while holding a lxccontainer, increment
239 * c->numthreads (under privlock) before forking. When deleting,
240 * decrement numthreads under privlock, then if it hits 0 you can delete.
241 * Do not ever use a lxccontainer whose numthreads you did not bump.
242 */
243
244 static void lxc_container_free(struct lxc_container *c)
245 {
246 if (!c)
247 return;
248
249 free(c->configfile);
250 c->configfile = NULL;
251 free(c->error_string);
252 c->error_string = NULL;
253 if (c->slock) {
254 lxc_putlock(c->slock);
255 c->slock = NULL;
256 }
257 if (c->privlock) {
258 lxc_putlock(c->privlock);
259 c->privlock = NULL;
260 }
261 free(c->name);
262 c->name = NULL;
263 if (c->lxc_conf) {
264 lxc_conf_free(c->lxc_conf);
265 c->lxc_conf = NULL;
266 }
267 free(c->config_path);
268 c->config_path = NULL;
269
270 free(c);
271 }
272
273 /*
274 * Consider the following case:
275 freer | racing get()er
276 ==================================================================
277 lxc_container_put() | lxc_container_get()
278 \ lxclock(c->privlock) | c->numthreads < 1? (no)
279 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
280 \ lxcunlock() | \
281 \ lxc_container_free() | \ lxclock() returns
282 | \ c->numthreads < 1 -> return 0
283 \ \ (free stuff) |
284 \ \ sem_destroy(privlock) |
285
286 * When the get()er checks numthreads the first time, one of the following
287 * is true:
288 * 1. freer has set numthreads = 0. get() returns 0
289 * 2. freer is between lxclock and setting numthreads to 0. get()er will
290 * sem_wait on privlock, get lxclock after freer() drops it, then see
291 * numthreads is 0 and exit without touching lxclock again..
292 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
293 * will see --numthreads = 1 and not call lxc_container_free().
294 */
295
296 int lxc_container_get(struct lxc_container *c)
297 {
298 if (!c)
299 return 0;
300
301 /* If someone else has already started freeing the container, don't try
302 * to take the lock, which may be invalid.
303 */
304 if (c->numthreads < 1)
305 return 0;
306
307 if (container_mem_lock(c))
308 return 0;
309
310 /* Bail without trying to unlock, bc the privlock is now probably in
311 * freed memory.
312 */
313 if (c->numthreads < 1)
314 return 0;
315
316 c->numthreads++;
317 container_mem_unlock(c);
318 return 1;
319 }
320
321 int lxc_container_put(struct lxc_container *c)
322 {
323 if (!c)
324 return -1;
325 if (container_mem_lock(c))
326 return -1;
327 if (--c->numthreads < 1) {
328 container_mem_unlock(c);
329 lxc_container_free(c);
330 return 1;
331 }
332 container_mem_unlock(c);
333 return 0;
334 }
335
336 static bool do_lxcapi_is_defined(struct lxc_container *c)
337 {
338 struct stat statbuf;
339 bool ret = false;
340 int statret;
341
342 if (!c)
343 return false;
344
345 if (container_mem_lock(c))
346 return false;
347 if (!c->configfile)
348 goto out;
349 statret = stat(c->configfile, &statbuf);
350 if (statret != 0)
351 goto out;
352 ret = true;
353
354 out:
355 container_mem_unlock(c);
356 return ret;
357 }
358
359 #define WRAP_API(rettype, fnname) \
360 static rettype fnname(struct lxc_container *c) \
361 { \
362 rettype ret; \
363 bool reset_config = false; \
364 \
365 if (!current_config && c && c->lxc_conf) { \
366 current_config = c->lxc_conf; \
367 reset_config = true; \
368 } \
369 \
370 ret = do_##fnname(c); \
371 if (reset_config) \
372 current_config = NULL; \
373 \
374 return ret; \
375 }
376
377 #define WRAP_API_1(rettype, fnname, t1) \
378 static rettype fnname(struct lxc_container *c, t1 a1) \
379 { \
380 rettype ret; \
381 bool reset_config = false; \
382 \
383 if (!current_config && c && c->lxc_conf) { \
384 current_config = c->lxc_conf; \
385 reset_config = true; \
386 } \
387 \
388 ret = do_##fnname(c, a1); \
389 if (reset_config) \
390 current_config = NULL; \
391 \
392 return ret; \
393 }
394
395 #define WRAP_API_2(rettype, fnname, t1, t2) \
396 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
397 { \
398 rettype ret; \
399 bool reset_config = false; \
400 \
401 if (!current_config && c && c->lxc_conf) { \
402 current_config = c->lxc_conf; \
403 reset_config = true; \
404 } \
405 \
406 ret = do_##fnname(c, a1, a2); \
407 if (reset_config) \
408 current_config = NULL; \
409 \
410 return ret; \
411 }
412
413 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
414 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
415 { \
416 rettype ret; \
417 bool reset_config = false; \
418 \
419 if (!current_config && c && c->lxc_conf) { \
420 current_config = c->lxc_conf; \
421 reset_config = true; \
422 } \
423 \
424 ret = do_##fnname(c, a1, a2, a3); \
425 if (reset_config) \
426 current_config = NULL; \
427 \
428 return ret; \
429 }
430
431 WRAP_API(bool, lxcapi_is_defined)
432
433 static const char *do_lxcapi_state(struct lxc_container *c)
434 {
435 lxc_state_t s;
436
437 if (!c)
438 return NULL;
439 s = lxc_getstate(c->name, c->config_path);
440 return lxc_state2str(s);
441 }
442
443 WRAP_API(const char *, lxcapi_state)
444
445 static bool is_stopped(struct lxc_container *c)
446 {
447 lxc_state_t s;
448 s = lxc_getstate(c->name, c->config_path);
449 return (s == STOPPED);
450 }
451
452 static bool do_lxcapi_is_running(struct lxc_container *c)
453 {
454 const char *s;
455
456 if (!c)
457 return false;
458 s = do_lxcapi_state(c);
459 if (!s || strcmp(s, "STOPPED") == 0)
460 return false;
461 return true;
462 }
463
464 WRAP_API(bool, lxcapi_is_running)
465
466 static bool do_lxcapi_freeze(struct lxc_container *c)
467 {
468 int ret;
469 if (!c)
470 return false;
471
472 ret = lxc_freeze(c->name, c->config_path);
473 if (ret)
474 return false;
475 return true;
476 }
477
478 WRAP_API(bool, lxcapi_freeze)
479
480 static bool do_lxcapi_unfreeze(struct lxc_container *c)
481 {
482 int ret;
483 if (!c)
484 return false;
485
486 ret = lxc_unfreeze(c->name, c->config_path);
487 if (ret)
488 return false;
489 return true;
490 }
491
492 WRAP_API(bool, lxcapi_unfreeze)
493
494 static int do_lxcapi_console_getfd(struct lxc_container *c, int *ttynum, int *masterfd)
495 {
496 int ttyfd;
497 if (!c)
498 return -1;
499
500 ttyfd = lxc_console_getfd(c, ttynum, masterfd);
501 return ttyfd;
502 }
503
504 WRAP_API_2(int, lxcapi_console_getfd, int *, int *)
505
506 static int lxcapi_console(struct lxc_container *c, int ttynum, int stdinfd,
507 int stdoutfd, int stderrfd, int escape)
508 {
509 int ret;
510
511 if (!c)
512 return -1;
513
514 current_config = c->lxc_conf;
515 ret = lxc_console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape);
516 current_config = NULL;
517 return ret;
518 }
519
520 static int do_lxcapi_console_log(struct lxc_container *c, struct lxc_console_log *log)
521 {
522 int ret;
523
524 ret = lxc_cmd_console_log(c->name, do_lxcapi_get_config_path(c), log);
525 if (ret < 0) {
526 if (ret == -ENODATA)
527 NOTICE("The console log is empty");
528 else if (ret == -EFAULT)
529 NOTICE("The container does not keep a console log");
530 else if (ret == -ENOENT)
531 NOTICE("The container does not keep a console log file");
532 else if (ret == -EIO)
533 NOTICE("Failed to write console log to log file");
534 else
535 ERROR("Failed to retrieve console log");
536 }
537
538 return ret;
539 }
540
541 WRAP_API_1(int, lxcapi_console_log, struct lxc_console_log *)
542
543 static pid_t do_lxcapi_init_pid(struct lxc_container *c)
544 {
545 if (!c)
546 return -1;
547
548 return lxc_cmd_get_init_pid(c->name, c->config_path);
549 }
550
551 WRAP_API(pid_t, lxcapi_init_pid)
552
553 static bool load_config_locked(struct lxc_container *c, const char *fname)
554 {
555 if (!c->lxc_conf)
556 c->lxc_conf = lxc_conf_init();
557 if (!c->lxc_conf)
558 return false;
559 if (lxc_config_read(fname, c->lxc_conf, false) != 0)
560 return false;
561 return true;
562 }
563
564 static bool do_lxcapi_load_config(struct lxc_container *c, const char *alt_file)
565 {
566 bool ret = false, need_disklock = false;
567 int lret;
568 const char *fname;
569 if (!c)
570 return false;
571
572 fname = c->configfile;
573 if (alt_file)
574 fname = alt_file;
575 if (!fname)
576 return false;
577 /*
578 * If we're reading something other than the container's config,
579 * we only need to lock the in-memory container. If loading the
580 * container's config file, take the disk lock.
581 */
582 if (strcmp(fname, c->configfile) == 0)
583 need_disklock = true;
584
585 if (need_disklock)
586 lret = container_disk_lock(c);
587 else
588 lret = container_mem_lock(c);
589 if (lret)
590 return false;
591
592 ret = load_config_locked(c, fname);
593
594 if (need_disklock)
595 container_disk_unlock(c);
596 else
597 container_mem_unlock(c);
598 return ret;
599 }
600
601 WRAP_API_1(bool, lxcapi_load_config, const char *)
602
603 static bool do_lxcapi_want_daemonize(struct lxc_container *c, bool state)
604 {
605 if (!c || !c->lxc_conf)
606 return false;
607 if (container_mem_lock(c)) {
608 ERROR("Error getting mem lock");
609 return false;
610 }
611 c->daemonize = state;
612 container_mem_unlock(c);
613 return true;
614 }
615
616 WRAP_API_1(bool, lxcapi_want_daemonize, bool)
617
618 static bool do_lxcapi_want_close_all_fds(struct lxc_container *c, bool state)
619 {
620 if (!c || !c->lxc_conf)
621 return false;
622 if (container_mem_lock(c)) {
623 ERROR("Error getting mem lock");
624 return false;
625 }
626 c->lxc_conf->close_all_fds = state;
627 container_mem_unlock(c);
628 return true;
629 }
630
631 WRAP_API_1(bool, lxcapi_want_close_all_fds, bool)
632
633 static bool do_lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
634 {
635 int ret;
636
637 if (!c)
638 return false;
639
640 ret = lxc_wait(c->name, state, timeout, c->config_path);
641 return ret == 0;
642 }
643
644 WRAP_API_2(bool, lxcapi_wait, const char *, int)
645
646 static bool am_single_threaded(void)
647 {
648 struct dirent *direntp;
649 DIR *dir;
650 int count=0;
651
652 dir = opendir("/proc/self/task");
653 if (!dir) {
654 INFO("failed to open /proc/self/task");
655 return false;
656 }
657
658 while ((direntp = readdir(dir))) {
659 if (!strcmp(direntp->d_name, "."))
660 continue;
661
662 if (!strcmp(direntp->d_name, ".."))
663 continue;
664 if (++count > 1)
665 break;
666 }
667 closedir(dir);
668 return count == 1;
669 }
670
671 static void push_arg(char ***argp, char *arg, int *nargs)
672 {
673 char **argv;
674 char *copy;
675
676 do {
677 copy = strdup(arg);
678 } while (!copy);
679 do {
680 argv = realloc(*argp, (*nargs + 2) * sizeof(char *));
681 } while (!argv);
682 *argp = argv;
683 argv[*nargs] = copy;
684 (*nargs)++;
685 argv[*nargs] = NULL;
686 }
687
688 static char **split_init_cmd(const char *incmd)
689 {
690 size_t len;
691 int nargs = 0;
692 char *copy, *p, *saveptr = NULL;
693 char **argv;
694
695 if (!incmd)
696 return NULL;
697
698 len = strlen(incmd) + 1;
699 copy = alloca(len);
700 strncpy(copy, incmd, len);
701 copy[len-1] = '\0';
702
703 do {
704 argv = malloc(sizeof(char *));
705 } while (!argv);
706 argv[0] = NULL;
707 for (p = strtok_r(copy, " ", &saveptr); p != NULL;
708 p = strtok_r(NULL, " ", &saveptr))
709 push_arg(&argv, p, &nargs);
710
711 if (nargs == 0) {
712 free(argv);
713 return NULL;
714 }
715 return argv;
716 }
717
718 static void free_init_cmd(char **argv)
719 {
720 int i = 0;
721
722 if (!argv)
723 return;
724 while (argv[i])
725 free(argv[i++]);
726 free(argv);
727 }
728
729 static int lxc_rcv_status(int state_socket)
730 {
731 int ret;
732 int state = -1;
733
734 again:
735 /* Receive container state. */
736 ret = lxc_abstract_unix_rcv_credential(state_socket, &state,
737 sizeof(int));
738 if (ret <= 0) {
739 if (errno != EINTR)
740 return -1;
741 TRACE("Caught EINTR; retrying");
742 goto again;
743 }
744
745 return state;
746 }
747
748 static bool wait_on_daemonized_start(struct lxc_handler *handler, int pid)
749 {
750 int ret, state;
751
752 /* Close write end of the socket pair. */
753 close(handler->state_socket_pair[1]);
754 handler->state_socket_pair[1] = -1;
755
756 state = lxc_rcv_status(handler->state_socket_pair[0]);
757
758 /* Close read end of the socket pair. */
759 close(handler->state_socket_pair[0]);
760 handler->state_socket_pair[0] = -1;
761
762 /* The first child is going to fork() again and then exits. So we reap
763 * the first child here.
764 */
765 ret = wait_for_pid(pid);
766 if (ret < 0)
767 DEBUG("Failed waiting on first child %d", pid);
768 else
769 DEBUG("First child %d exited", pid);
770
771 if (state < 0) {
772 SYSERROR("Failed to receive the container state");
773 return false;
774 }
775
776 /* If we receive anything else then running we know that the container
777 * failed to start.
778 */
779 if (state != RUNNING) {
780 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
781 lxc_state2str(state));
782 return false;
783 }
784
785 TRACE("Container is in \"RUNNING\" state");
786 return true;
787 }
788
789 static bool do_lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
790 {
791 int ret;
792 struct lxc_handler *handler;
793 struct lxc_conf *conf;
794 bool daemonize = false;
795 FILE *pid_fp = NULL;
796 char *default_args[] = {
797 "/sbin/init",
798 NULL,
799 };
800 char **init_cmd = NULL;
801 int keepfds[3] = {-1, -1, -1};
802
803 /* container does exist */
804 if (!c)
805 return false;
806
807 /* If anything fails before we set error_num, we want an error in there.
808 */
809 c->error_num = 1;
810
811 /* Container has not been setup. */
812 if (!c->lxc_conf)
813 return false;
814
815 ret = ongoing_create(c);
816 if (ret < 0) {
817 ERROR("Failed checking for incomplete container creation");
818 return false;
819 } else if (ret == 1) {
820 ERROR("Ongoing container creation detected");
821 return false;
822 } else if (ret == 2) {
823 ERROR("Failed to create container");
824 do_lxcapi_destroy(c);
825 return false;
826 }
827
828 if (container_mem_lock(c))
829 return false;
830 conf = c->lxc_conf;
831 daemonize = c->daemonize;
832
833 /* initialize handler */
834 handler = lxc_init_handler(c->name, conf, c->config_path, daemonize);
835 container_mem_unlock(c);
836 if (!handler)
837 return false;
838
839 if (!argv) {
840 if (useinit && conf->execute_cmd)
841 argv = init_cmd = split_init_cmd(conf->execute_cmd);
842 else
843 argv = init_cmd = split_init_cmd(conf->init_cmd);
844 }
845
846 /* ... otherwise use default_args. */
847 if (!argv) {
848 if (useinit) {
849 ERROR("No valid init detected");
850 lxc_free_handler(handler);
851 return false;
852 }
853 argv = default_args;
854 }
855
856 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
857 * here to protect the on disk container? We don't want to exclude
858 * things like lxc_info while the container is running.
859 */
860 if (daemonize) {
861 bool started;
862 char title[2048];
863 pid_t pid;
864
865 pid = fork();
866 if (pid < 0) {
867 free_init_cmd(init_cmd);
868 lxc_free_handler(handler);
869 return false;
870 }
871
872 /* first parent */
873 if (pid != 0) {
874 /* Set to NULL because we don't want father unlink
875 * the PID file, child will do the free and unlink.
876 */
877 c->pidfile = NULL;
878
879 /* Wait for container to tell us whether it started
880 * successfully.
881 */
882 started = wait_on_daemonized_start(handler, pid);
883
884 free_init_cmd(init_cmd);
885 lxc_free_handler(handler);
886 return started;
887 }
888
889 /* first child */
890
891 /* We don't really care if this doesn't print all the
892 * characters. All that it means is that the proctitle will be
893 * ugly. Similarly, we also don't care if setproctitle() fails.
894 * */
895 snprintf(title, sizeof(title), "[lxc monitor] %s %s", c->config_path, c->name);
896 INFO("Attempting to set proc title to %s", title);
897 setproctitle(title);
898
899 /* We fork() a second time to be reparented to init. Like
900 * POSIX's daemon() function we change to "/" and redirect
901 * std{in,out,err} to /dev/null.
902 */
903 pid = fork();
904 if (pid < 0) {
905 SYSERROR("Failed to fork first child process");
906 _exit(EXIT_FAILURE);
907 }
908
909 /* second parent */
910 if (pid != 0) {
911 free_init_cmd(init_cmd);
912 lxc_free_handler(handler);
913 _exit(EXIT_SUCCESS);
914 }
915
916 /* second child */
917
918 /* change to / directory */
919 ret = chdir("/");
920 if (ret < 0) {
921 SYSERROR("Failed to change to \"/\" directory");
922 _exit(EXIT_FAILURE);
923 }
924
925 keepfds[0] = handler->conf->maincmd_fd;
926 keepfds[1] = handler->state_socket_pair[0];
927 keepfds[2] = handler->state_socket_pair[1];
928 ret = lxc_check_inherited(conf, true, keepfds,
929 sizeof(keepfds) / sizeof(keepfds[0]));
930 if (ret < 0)
931 _exit(EXIT_FAILURE);
932
933 /* redirect std{in,out,err} to /dev/null */
934 ret = null_stdfds();
935 if (ret < 0) {
936 ERROR("Failed to redirect std{in,out,err} to /dev/null");
937 _exit(EXIT_FAILURE);
938 }
939
940 /* become session leader */
941 ret = setsid();
942 if (ret < 0)
943 TRACE("Process %d is already process group leader", lxc_raw_getpid());
944 } else {
945 if (!am_single_threaded()) {
946 ERROR("Cannot start non-daemonized container when threaded");
947 free_init_cmd(init_cmd);
948 lxc_free_handler(handler);
949 return false;
950 }
951 }
952
953 /* We need to write PID file after daemonize, so we always
954 * write the right PID.
955 */
956 if (c->pidfile) {
957 pid_fp = fopen(c->pidfile, "w");
958 if (pid_fp == NULL) {
959 SYSERROR("Failed to create pidfile '%s' for '%s'",
960 c->pidfile, c->name);
961 free_init_cmd(init_cmd);
962 lxc_free_handler(handler);
963 if (daemonize)
964 _exit(EXIT_FAILURE);
965 return false;
966 }
967
968 if (fprintf(pid_fp, "%d\n", lxc_raw_getpid()) < 0) {
969 SYSERROR("Failed to write '%s'", c->pidfile);
970 fclose(pid_fp);
971 pid_fp = NULL;
972 free_init_cmd(init_cmd);
973 lxc_free_handler(handler);
974 if (daemonize)
975 _exit(EXIT_FAILURE);
976 return false;
977 }
978
979 fclose(pid_fp);
980 pid_fp = NULL;
981 }
982
983 conf->reboot = 0;
984
985 /* Unshare the mount namespace if requested */
986 if (conf->monitor_unshare) {
987 ret = unshare(CLONE_NEWNS);
988 if (ret < 0) {
989 SYSERROR("failed to unshare mount namespace");
990 lxc_free_handler(handler);
991 ret = 1;
992 goto on_error;
993 }
994
995 ret = mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL);
996 if (ret < 0) {
997 SYSERROR("Failed to make / rslave at startup");
998 lxc_free_handler(handler);
999 ret = 1;
1000 goto on_error;
1001 }
1002 }
1003
1004 reboot:
1005 if (conf->reboot == 2) {
1006 /* initialize handler */
1007 handler = lxc_init_handler(c->name, conf, c->config_path, daemonize);
1008 if (!handler) {
1009 ret = 1;
1010 goto on_error;
1011 }
1012 }
1013
1014 keepfds[0] = handler->conf->maincmd_fd;
1015 keepfds[1] = handler->state_socket_pair[0];
1016 keepfds[2] = handler->state_socket_pair[1];
1017 ret = lxc_check_inherited(conf, daemonize, keepfds,
1018 sizeof(keepfds) / sizeof(keepfds[0]));
1019 if (ret < 0) {
1020 lxc_free_handler(handler);
1021 ret = 1;
1022 goto on_error;
1023 }
1024
1025 if (useinit)
1026 ret = lxc_execute(c->name, argv, 1, handler, c->config_path, daemonize);
1027 else
1028 ret = lxc_start(c->name, argv, handler, c->config_path, daemonize);
1029 c->error_num = handler->exit_status;
1030
1031 if (conf->reboot == 1) {
1032 INFO("Container requested reboot");
1033 conf->reboot = 2;
1034 goto reboot;
1035 }
1036
1037 on_error:
1038 if (c->pidfile) {
1039 unlink(c->pidfile);
1040 free(c->pidfile);
1041 c->pidfile = NULL;
1042 }
1043 free_init_cmd(init_cmd);
1044
1045 if (daemonize && ret != 0)
1046 _exit(EXIT_FAILURE);
1047 else if (daemonize)
1048 _exit(EXIT_SUCCESS);
1049
1050 if (ret != 0)
1051 return false;
1052
1053 return true;
1054 }
1055
1056 static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
1057 {
1058 bool ret;
1059 current_config = c ? c->lxc_conf : NULL;
1060 ret = do_lxcapi_start(c, useinit, argv);
1061 current_config = NULL;
1062 return ret;
1063 }
1064
1065 /*
1066 * note there MUST be an ending NULL
1067 */
1068 static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
1069 {
1070 va_list ap;
1071 char **inargs = NULL;
1072 bool bret = false;
1073
1074 /* container exists */
1075 if (!c)
1076 return false;
1077
1078 current_config = c->lxc_conf;
1079
1080 va_start(ap, useinit);
1081 inargs = lxc_va_arg_list_to_argv(ap, 0, 1);
1082 va_end(ap);
1083
1084 if (!inargs) {
1085 ERROR("Memory allocation error.");
1086 goto out;
1087 }
1088
1089 /* pass NULL if no arguments were supplied */
1090 bret = do_lxcapi_start(c, useinit, *inargs ? inargs : NULL);
1091
1092 out:
1093 if (inargs) {
1094 char **arg;
1095 for (arg = inargs; *arg; arg++)
1096 free(*arg);
1097 free(inargs);
1098 }
1099
1100 current_config = NULL;
1101 return bret;
1102 }
1103
1104 static bool do_lxcapi_stop(struct lxc_container *c)
1105 {
1106 int ret;
1107
1108 if (!c)
1109 return false;
1110
1111 ret = lxc_cmd_stop(c->name, c->config_path);
1112
1113 return ret == 0;
1114 }
1115
1116 WRAP_API(bool, lxcapi_stop)
1117
1118 static int do_create_container_dir(const char *path, struct lxc_conf *conf)
1119 {
1120 int ret = -1, lasterr;
1121 char *p = alloca(strlen(path)+1);
1122 mode_t mask = umask(0002);
1123 ret = mkdir(path, 0770);
1124 lasterr = errno;
1125 umask(mask);
1126 errno = lasterr;
1127 if (ret) {
1128 if (errno == EEXIST)
1129 ret = 0;
1130 else {
1131 SYSERROR("failed to create container path %s", path);
1132 return -1;
1133 }
1134 }
1135 strcpy(p, path);
1136 if (!lxc_list_empty(&conf->id_map) && chown_mapped_root(p, conf) != 0) {
1137 ERROR("Failed to chown container dir");
1138 ret = -1;
1139 }
1140 return ret;
1141 }
1142
1143 /*
1144 * create the standard expected container dir
1145 */
1146 static bool create_container_dir(struct lxc_container *c)
1147 {
1148 char *s;
1149 int len, ret;
1150
1151 len = strlen(c->config_path) + strlen(c->name) + 2;
1152 s = malloc(len);
1153 if (!s)
1154 return false;
1155 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
1156 if (ret < 0 || ret >= len) {
1157 free(s);
1158 return false;
1159 }
1160 ret = do_create_container_dir(s, c->lxc_conf);
1161 free(s);
1162 return ret == 0;
1163 }
1164
1165 /* do_storage_create: thin wrapper around storage_create(). Like
1166 * storage_create(), it returns a mounted bdev on success, NULL on error.
1167 */
1168 static struct lxc_storage *do_storage_create(struct lxc_container *c,
1169 const char *type,
1170 struct bdev_specs *specs)
1171 {
1172 int ret;
1173 size_t len;
1174 char *dest;
1175 struct lxc_storage *bdev;
1176
1177 /* rootfs.path or lxcpath/lxcname/rootfs */
1178 if (c->lxc_conf->rootfs.path &&
1179 (access(c->lxc_conf->rootfs.path, F_OK) == 0)) {
1180 const char *rpath = c->lxc_conf->rootfs.path;
1181 len = strlen(rpath) + 1;
1182 dest = alloca(len);
1183 ret = snprintf(dest, len, "%s", rpath);
1184 } else {
1185 const char *lxcpath = do_lxcapi_get_config_path(c);
1186 len = strlen(c->name) + strlen(lxcpath) + 9;
1187 dest = alloca(len);
1188 ret = snprintf(dest, len, "%s/%s/rootfs", lxcpath, c->name);
1189 }
1190 if (ret < 0 || (size_t)ret >= len)
1191 return NULL;
1192
1193 bdev = storage_create(dest, type, c->name, specs);
1194 if (!bdev) {
1195 ERROR("Failed to create \"%s\" storage", type);
1196 return NULL;
1197 }
1198
1199 if (!c->set_config_item(c, "lxc.rootfs.path", bdev->src)) {
1200 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev->src);
1201 return NULL;
1202 }
1203
1204 /* If we are not root, chown the rootfs dir to root in the target user
1205 * namespace.
1206 */
1207 ret = geteuid();
1208 if (ret != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) {
1209 ret = chown_mapped_root(bdev->dest, c->lxc_conf);
1210 if (ret < 0) {
1211 ERROR("Error chowning \"%s\" to container root", bdev->dest);
1212 suggest_default_idmap();
1213 storage_put(bdev);
1214 return NULL;
1215 }
1216 }
1217
1218 return bdev;
1219 }
1220
1221 static char *lxcbasename(char *path)
1222 {
1223 char *p;
1224
1225 p = path + strlen(path) - 1;
1226 while (*p != '/' && p > path)
1227 p--;
1228
1229 return p;
1230 }
1231
1232 static bool create_run_template(struct lxc_container *c, char *tpath,
1233 bool need_null_stdfds, char *const argv[])
1234 {
1235 int ret;
1236 pid_t pid;
1237
1238 if (!tpath)
1239 return true;
1240
1241 pid = fork();
1242 if (pid < 0) {
1243 SYSERROR("Failed to fork task for container creation template");
1244 return false;
1245 }
1246
1247 if (pid == 0) { /* child */
1248 int i, len;
1249 char *namearg, *patharg, *rootfsarg;
1250 char **newargv;
1251 int nargs = 0;
1252 struct lxc_storage *bdev = NULL;
1253 struct lxc_conf *conf = c->lxc_conf;
1254 uid_t euid;
1255
1256 if (need_null_stdfds) {
1257 ret = null_stdfds();
1258 if (ret < 0)
1259 _exit(EXIT_FAILURE);
1260 }
1261
1262 bdev = storage_init(c->lxc_conf);
1263 if (!bdev) {
1264 ERROR("Failed to initialize storage");
1265 _exit(EXIT_FAILURE);
1266 }
1267
1268 euid = geteuid();
1269 if (euid == 0) {
1270 ret = unshare(CLONE_NEWNS);
1271 if (ret < 0) {
1272 ERROR("Failed to unshare CLONE_NEWNS");
1273 _exit(EXIT_FAILURE);
1274 }
1275
1276 ret = detect_shared_rootfs();
1277 if (ret == 1) {
1278 ret = mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL);
1279 if (ret < 0) {
1280 SYSERROR("Failed to make \"/\" rslave");
1281 ERROR("Continuing...");
1282 }
1283 }
1284 }
1285
1286 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "btrfs") != 0) {
1287 if (euid != 0) {
1288 ERROR("Unprivileged users can only create "
1289 "btrfs and directory-backed containers");
1290 _exit(EXIT_FAILURE);
1291 }
1292
1293 if (strcmp(bdev->type, "overlay") == 0 ||
1294 strcmp(bdev->type, "overlayfs") == 0) {
1295 /* If we create an overlay container we need to
1296 * rsync the contents into
1297 * <container-path>/<container-name>/rootfs.
1298 * However, the overlay mount function will
1299 * mount will mount
1300 * <container-path>/<container-name>/delta0
1301 * over
1302 * <container-path>/<container-name>/rootfs
1303 * which means we would rsync the rootfs into
1304 * the delta directory. That doesn't make sense
1305 * since the delta directory only exists to
1306 * record the differences to
1307 * <container-path>/<container-name>/rootfs. So
1308 * let's simply bind-mount here and then rsync
1309 * directly into
1310 * <container-path>/<container-name>/rootfs.
1311 */
1312 char *src;
1313
1314 src = ovl_get_rootfs(bdev->src, &(size_t){0});
1315 if (!src) {
1316 ERROR("Failed to get rootfs");
1317 _exit(EXIT_FAILURE);
1318 }
1319
1320 ret = mount(src, bdev->dest, "bind", MS_BIND | MS_REC, NULL);
1321 if (ret < 0) {
1322 ERROR("Failed to mount rootfs");
1323 return -1;
1324 }
1325 } else {
1326 ret = bdev->ops->mount(bdev);
1327 if (ret < 0) {
1328 ERROR("Failed to mount rootfs");
1329 _exit(EXIT_FAILURE);
1330 }
1331 }
1332 } else { /* TODO come up with a better way here! */
1333 const char *src;
1334 free(bdev->dest);
1335 src = lxc_storage_get_path(bdev->src, bdev->type);
1336 bdev->dest = strdup(src);
1337 }
1338
1339 /* Create our new array, pre-pend the template name and base
1340 * args.
1341 */
1342 if (argv)
1343 for (nargs = 0; argv[nargs]; nargs++) {
1344 ;
1345 }
1346 /* template, path, rootfs and name args */
1347 nargs += 4;
1348
1349 newargv = malloc(nargs * sizeof(*newargv));
1350 if (!newargv)
1351 _exit(EXIT_FAILURE);
1352 newargv[0] = lxcbasename(tpath);
1353
1354 /* --path */
1355 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
1356 patharg = malloc(len);
1357 if (!patharg)
1358 _exit(EXIT_FAILURE);
1359 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
1360 if (ret < 0 || ret >= len)
1361 _exit(EXIT_FAILURE);
1362 newargv[1] = patharg;
1363
1364 /* --name */
1365 len = strlen("--name=") + strlen(c->name) + 1;
1366 namearg = malloc(len);
1367 if (!namearg)
1368 _exit(EXIT_FAILURE);
1369 ret = snprintf(namearg, len, "--name=%s", c->name);
1370 if (ret < 0 || ret >= len)
1371 _exit(EXIT_FAILURE);
1372 newargv[2] = namearg;
1373
1374 /* --rootfs */
1375 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
1376 rootfsarg = malloc(len);
1377 if (!rootfsarg)
1378 _exit(EXIT_FAILURE);
1379 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
1380 if (ret < 0 || ret >= len)
1381 _exit(EXIT_FAILURE);
1382 newargv[3] = rootfsarg;
1383
1384 /* add passed-in args */
1385 if (argv)
1386 for (i = 4; i < nargs; i++)
1387 newargv[i] = argv[i - 4];
1388
1389 /* add trailing NULL */
1390 nargs++;
1391 newargv = realloc(newargv, nargs * sizeof(*newargv));
1392 if (!newargv)
1393 _exit(EXIT_FAILURE);
1394 newargv[nargs - 1] = NULL;
1395
1396 /* If we're running the template in a mapped userns, then we
1397 * prepend the template command with: lxc-usernsexec <-m map1>
1398 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1399 * the mapped uid for our geteuid()
1400 */
1401 if (!lxc_list_empty(&conf->id_map)) {
1402 int extraargs, hostuid_mapped, hostgid_mapped;
1403 char **n2;
1404 char txtuid[20], txtgid[20];
1405 struct lxc_list *it;
1406 struct id_map *map;
1407 int n2args = 1;
1408
1409 n2 = malloc(n2args * sizeof(*n2));
1410 if (!n2)
1411 _exit(EXIT_FAILURE);
1412
1413 newargv[0] = tpath;
1414 tpath = "lxc-usernsexec";
1415 n2[0] = "lxc-usernsexec";
1416 lxc_list_for_each(it, &conf->id_map) {
1417 map = it->elem;
1418 n2args += 2;
1419 n2 = realloc(n2, n2args * sizeof(char *));
1420 if (!n2)
1421 _exit(EXIT_FAILURE);
1422
1423 n2[n2args - 2] = "-m";
1424 n2[n2args - 1] = malloc(200);
1425 if (!n2[n2args - 1])
1426 _exit(EXIT_FAILURE);
1427
1428 ret = snprintf(n2[n2args - 1], 200, "%c:%lu:%lu:%lu",
1429 map->idtype == ID_TYPE_UID ? 'u' : 'g',
1430 map->nsid, map->hostid, map->range);
1431 if (ret < 0 || ret >= 200)
1432 _exit(EXIT_FAILURE);
1433 }
1434
1435 hostuid_mapped = mapped_hostid(geteuid(), conf, ID_TYPE_UID);
1436 extraargs = hostuid_mapped >= 0 ? 1 : 3;
1437 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1438 if (!n2)
1439 _exit(EXIT_FAILURE);
1440
1441 if (hostuid_mapped < 0) {
1442 hostuid_mapped = find_unmapped_nsid(conf, ID_TYPE_UID);
1443 n2[n2args++] = "-m";
1444 if (hostuid_mapped < 0) {
1445 ERROR("Failed to find free uid to map");
1446 _exit(EXIT_FAILURE);
1447 }
1448
1449 n2[n2args++] = malloc(200);
1450 if (!n2[n2args - 1]) {
1451 SYSERROR("out of memory");
1452 _exit(EXIT_FAILURE);
1453 }
1454 ret = snprintf(n2[n2args - 1], 200, "u:%d:%d:1",
1455 hostuid_mapped, geteuid());
1456 if (ret < 0 || ret >= 200)
1457 _exit(EXIT_FAILURE);
1458 }
1459
1460 hostgid_mapped = mapped_hostid(getegid(), conf, ID_TYPE_GID);
1461 extraargs = hostgid_mapped >= 0 ? 1 : 3;
1462 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(char *));
1463 if (!n2)
1464 _exit(EXIT_FAILURE);
1465
1466 if (hostgid_mapped < 0) {
1467 hostgid_mapped = find_unmapped_nsid(conf, ID_TYPE_GID);
1468 n2[n2args++] = "-m";
1469 if (hostgid_mapped < 0) {
1470 ERROR("Failed to find free gid to map");
1471 _exit(EXIT_FAILURE);
1472 }
1473
1474 n2[n2args++] = malloc(200);
1475 if (!n2[n2args - 1]) {
1476 SYSERROR("out of memory");
1477 _exit(EXIT_FAILURE);
1478 }
1479
1480 ret = snprintf(n2[n2args - 1], 200, "g:%d:%d:1",
1481 hostgid_mapped, getegid());
1482 if (ret < 0 || ret >= 200)
1483 _exit(EXIT_FAILURE);
1484 }
1485 n2[n2args++] = "--";
1486 for (i = 0; i < nargs; i++)
1487 n2[i + n2args] = newargv[i];
1488 n2args += nargs;
1489
1490 /* Finally add "--mapped-uid $uid" to tell template what
1491 * to chown cached images to.
1492 */
1493 n2args += 4;
1494 n2 = realloc(n2, n2args * sizeof(char *));
1495 if (!n2)
1496 _exit(EXIT_FAILURE);
1497
1498 /* note n2[n2args-1] is NULL */
1499 n2[n2args - 5] = "--mapped-uid";
1500 snprintf(txtuid, 20, "%d", hostuid_mapped);
1501 n2[n2args - 4] = txtuid;
1502 n2[n2args - 3] = "--mapped-gid";
1503 snprintf(txtgid, 20, "%d", hostgid_mapped);
1504 n2[n2args - 2] = txtgid;
1505 n2[n2args - 1] = NULL;
1506 free(newargv);
1507 newargv = n2;
1508 }
1509
1510 execvp(tpath, newargv);
1511 SYSERROR("Failed to execute template %s", tpath);
1512 _exit(EXIT_FAILURE);
1513 }
1514
1515 ret = wait_for_pid(pid);
1516 if (ret != 0) {
1517 ERROR("Failed to create container from template");
1518 return false;
1519 }
1520
1521 return true;
1522 }
1523
1524 static bool prepend_lxc_header(char *path, const char *t, char *const argv[])
1525 {
1526 long flen;
1527 char *contents;
1528 FILE *f;
1529 int ret = -1;
1530 #if HAVE_LIBGNUTLS
1531 int i;
1532 unsigned char md_value[SHA_DIGEST_LENGTH];
1533 char *tpath;
1534 #endif
1535
1536 f = fopen(path, "r");
1537 if (f == NULL)
1538 return false;
1539
1540 if (fseek(f, 0, SEEK_END) < 0)
1541 goto out_error;
1542 if ((flen = ftell(f)) < 0)
1543 goto out_error;
1544 if (fseek(f, 0, SEEK_SET) < 0)
1545 goto out_error;
1546 if ((contents = malloc(flen + 1)) == NULL)
1547 goto out_error;
1548 if (fread(contents, 1, flen, f) != flen)
1549 goto out_free_contents;
1550
1551 contents[flen] = '\0';
1552 ret = fclose(f);
1553 f = NULL;
1554 if (ret < 0)
1555 goto out_free_contents;
1556
1557 #if HAVE_LIBGNUTLS
1558 tpath = get_template_path(t);
1559 if (!tpath) {
1560 ERROR("bad template: %s", t);
1561 goto out_free_contents;
1562 }
1563
1564 ret = sha1sum_file(tpath, md_value);
1565 if (ret < 0) {
1566 ERROR("Error getting sha1sum of %s", tpath);
1567 free(tpath);
1568 goto out_free_contents;
1569 }
1570 free(tpath);
1571 #endif
1572
1573 f = fopen(path, "w");
1574 if (f == NULL) {
1575 SYSERROR("reopening config for writing");
1576 free(contents);
1577 return false;
1578 }
1579 fprintf(f, "# Template used to create this container: %s\n", t);
1580 if (argv) {
1581 fprintf(f, "# Parameters passed to the template:");
1582 while (*argv) {
1583 fprintf(f, " %s", *argv);
1584 argv++;
1585 }
1586 fprintf(f, "\n");
1587 }
1588 #if HAVE_LIBGNUTLS
1589 fprintf(f, "# Template script checksum (SHA-1): ");
1590 for (i=0; i<SHA_DIGEST_LENGTH; i++)
1591 fprintf(f, "%02x", md_value[i]);
1592 fprintf(f, "\n");
1593 #endif
1594 fprintf(f, "# For additional config options, please look at lxc.container.conf(5)\n");
1595 fprintf(f, "\n# Uncomment the following line to support nesting containers:\n");
1596 fprintf(f, "#lxc.include = " LXCTEMPLATECONFIG "/nesting.conf\n");
1597 fprintf(f, "# (Be aware this has security implications)\n\n");
1598 if (fwrite(contents, 1, flen, f) != flen) {
1599 SYSERROR("Writing original contents");
1600 free(contents);
1601 fclose(f);
1602 return false;
1603 }
1604 ret = 0;
1605 out_free_contents:
1606 free(contents);
1607 out_error:
1608 if (f) {
1609 int newret;
1610 newret = fclose(f);
1611 if (ret == 0)
1612 ret = newret;
1613 }
1614 if (ret < 0) {
1615 SYSERROR("Error prepending header");
1616 return false;
1617 }
1618 return true;
1619 }
1620
1621 static void lxcapi_clear_config(struct lxc_container *c)
1622 {
1623 if (c) {
1624 if (c->lxc_conf) {
1625 lxc_conf_free(c->lxc_conf);
1626 c->lxc_conf = NULL;
1627 }
1628 }
1629 }
1630
1631 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1632
1633 /*
1634 * lxcapi_create:
1635 * create a container with the given parameters.
1636 * @c: container to be created. It has the lxcpath, name, and a starting
1637 * configuration already set
1638 * @t: the template to execute to instantiate the root filesystem and
1639 * adjust the configuration.
1640 * @bdevtype: backing store type to use. If NULL, dir will be used.
1641 * @specs: additional parameters for the backing store, i.e. LVM vg to
1642 * use.
1643 *
1644 * @argv: the arguments to pass to the template, terminated by NULL. If no
1645 * arguments, you can just pass NULL.
1646 */
1647 static bool do_lxcapi_create(struct lxc_container *c, const char *t,
1648 const char *bdevtype, struct bdev_specs *specs,
1649 int flags, char *const argv[])
1650 {
1651 int partial_fd;
1652 pid_t pid;
1653 bool ret = false;
1654 char *tpath = NULL;
1655
1656 if (!c)
1657 return false;
1658
1659 if (t) {
1660 tpath = get_template_path(t);
1661 if (!tpath) {
1662 ERROR("Unknown template \"%s\"", t);
1663 goto out;
1664 }
1665 }
1666
1667 /* If a template is passed in, and the rootfs already is defined in the
1668 * container config and exists, then the caller is trying to create an
1669 * existing container. Return an error, but do NOT delete the container.
1670 */
1671 if (do_lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
1672 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
1673 ERROR("Container \"%s\" already exists in \"%s\"", c->name,
1674 c->config_path);
1675 goto free_tpath;
1676 }
1677
1678 if (!c->lxc_conf) {
1679 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
1680 ERROR("Error loading default configuration file %s",
1681 lxc_global_config_value("lxc.default_config"));
1682 goto free_tpath;
1683 }
1684 }
1685
1686 if (!create_container_dir(c))
1687 goto free_tpath;
1688
1689 /* If both template and rootfs.path are set, template is setup as
1690 * rootfs.path. The container is already created if we have a config and
1691 * rootfs.path is accessible
1692 */
1693 if (!c->lxc_conf->rootfs.path && !tpath) {
1694 /* No template passed in and rootfs does not exist. */
1695 if (!c->save_config(c, NULL)) {
1696 ERROR("Failed to save initial config for \"%s\"", c->name);
1697 goto out;
1698 }
1699 ret = true;
1700 goto out;
1701 }
1702
1703 /* Rootfs passed into configuration, but does not exist. */
1704 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
1705 goto out;
1706
1707 if (do_lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
1708 /* Rootfs already existed, user just wanted to save the loaded
1709 * configuration.
1710 */
1711 if (!c->save_config(c, NULL))
1712 ERROR("Failed to save initial config for \"%s\"", c->name);
1713 ret = true;
1714 goto out;
1715 }
1716
1717 /* Mark that this container is being created */
1718 partial_fd = create_partial(c);
1719 if (partial_fd < 0)
1720 goto out;
1721
1722 /* No need to get disk lock bc we have the partial lock. */
1723
1724 /* Create the storage.
1725 * Note we can't do this in the same task as we use to execute the
1726 * template because of the way zfs works.
1727 * After you 'zfs create', zfs mounts the fs only in the initial
1728 * namespace.
1729 */
1730 pid = fork();
1731 if (pid < 0) {
1732 SYSERROR("Failed to fork task for container creation template");
1733 goto out_unlock;
1734 }
1735
1736 if (pid == 0) { /* child */
1737 struct lxc_storage *bdev = NULL;
1738
1739 bdev = do_storage_create(c, bdevtype, specs);
1740 if (!bdev) {
1741 ERROR("Failed to create %s storage for %s",
1742 bdevtype ? bdevtype : "(none)", c->name);
1743 _exit(EXIT_FAILURE);
1744 }
1745
1746 /* Save config file again to store the new rootfs location. */
1747 if (!do_lxcapi_save_config(c, NULL)) {
1748 ERROR("Failed to save initial config for %s", c->name);
1749 /* Parent task won't see the storage driver in the
1750 * config so we delete it.
1751 */
1752 bdev->ops->umount(bdev);
1753 bdev->ops->destroy(bdev);
1754 _exit(EXIT_FAILURE);
1755 }
1756 _exit(EXIT_SUCCESS);
1757 }
1758 if (wait_for_pid(pid) != 0)
1759 goto out_unlock;
1760
1761 /* Reload config to get the rootfs. */
1762 lxc_conf_free(c->lxc_conf);
1763 c->lxc_conf = NULL;
1764 if (!load_config_locked(c, c->configfile))
1765 goto out_unlock;
1766
1767 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
1768 goto out_unlock;
1769
1770 /* Now clear out the lxc_conf we have, reload from the created
1771 * container.
1772 */
1773 do_lxcapi_clear_config(c);
1774
1775 if (t) {
1776 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
1777 ERROR("Failed to prepend header to config file");
1778 goto out_unlock;
1779 }
1780 }
1781 ret = load_config_locked(c, c->configfile);
1782
1783 out_unlock:
1784 if (partial_fd >= 0)
1785 remove_partial(c, partial_fd);
1786 out:
1787 if (!ret)
1788 container_destroy(c, NULL);
1789 free_tpath:
1790 free(tpath);
1791 return ret;
1792 }
1793
1794 static bool lxcapi_create(struct lxc_container *c, const char *t,
1795 const char *bdevtype, struct bdev_specs *specs,
1796 int flags, char *const argv[])
1797 {
1798 bool ret;
1799 current_config = c ? c->lxc_conf : NULL;
1800 ret = do_lxcapi_create(c, t, bdevtype, specs, flags, argv);
1801 current_config = NULL;
1802 return ret;
1803 }
1804
1805 static bool do_lxcapi_reboot(struct lxc_container *c)
1806 {
1807 pid_t pid;
1808 int rebootsignal = SIGINT;
1809
1810 if (!c)
1811 return false;
1812 if (!do_lxcapi_is_running(c))
1813 return false;
1814 pid = do_lxcapi_init_pid(c);
1815 if (pid <= 0)
1816 return false;
1817 if (c->lxc_conf && c->lxc_conf->rebootsignal)
1818 rebootsignal = c->lxc_conf->rebootsignal;
1819 if (kill(pid, rebootsignal) < 0) {
1820 WARN("Could not send signal %d to pid %d.", rebootsignal, pid);
1821 return false;
1822 }
1823 return true;
1824
1825 }
1826
1827 WRAP_API(bool, lxcapi_reboot)
1828
1829 static bool do_lxcapi_reboot2(struct lxc_container *c, int timeout)
1830 {
1831 int killret, ret;
1832 pid_t pid;
1833 int rebootsignal = SIGINT, state_client_fd = -1;
1834 lxc_state_t states[MAX_STATE] = {0};
1835
1836 if (!c)
1837 return false;
1838
1839 if (!do_lxcapi_is_running(c))
1840 return true;
1841
1842 pid = do_lxcapi_init_pid(c);
1843 if (pid <= 0)
1844 return true;
1845
1846 if (c->lxc_conf && c->lxc_conf->rebootsignal)
1847 rebootsignal = c->lxc_conf->rebootsignal;
1848
1849 /* Add a new state client before sending the shutdown signal so that we
1850 * don't miss a state.
1851 */
1852 if (timeout != 0) {
1853 states[RUNNING] = 2;
1854 ret = lxc_cmd_add_state_client(c->name, c->config_path, states,
1855 &state_client_fd);
1856 if (ret < 0)
1857 return false;
1858
1859 if (state_client_fd < 0)
1860 return false;
1861
1862 if (ret == RUNNING)
1863 return true;
1864
1865 if (ret < MAX_STATE)
1866 return false;
1867 }
1868
1869 /* Send reboot signal to container. */
1870 killret = kill(pid, rebootsignal);
1871 if (killret < 0) {
1872 WARN("Could not send signal %d to pid %d", rebootsignal, pid);
1873 if (state_client_fd >= 0)
1874 close(state_client_fd);
1875 return false;
1876 }
1877 TRACE("Sent signal %d to pid %d", rebootsignal, pid);
1878
1879 if (timeout == 0)
1880 return true;
1881
1882 ret = lxc_cmd_sock_rcv_state(state_client_fd, timeout);
1883 close(state_client_fd);
1884 if (ret < 0)
1885 return false;
1886
1887 TRACE("Received state \"%s\"", lxc_state2str(ret));
1888 if (ret != RUNNING)
1889 return false;
1890
1891 return true;
1892 }
1893
1894 WRAP_API_1(bool, lxcapi_reboot2, int)
1895
1896 static bool do_lxcapi_shutdown(struct lxc_container *c, int timeout)
1897 {
1898 int killret, ret;
1899 pid_t pid;
1900 int haltsignal = SIGPWR, state_client_fd = -1;
1901 lxc_state_t states[MAX_STATE] = {0};
1902
1903 if (!c)
1904 return false;
1905
1906 if (!do_lxcapi_is_running(c))
1907 return true;
1908
1909 pid = do_lxcapi_init_pid(c);
1910 if (pid <= 0)
1911 return true;
1912
1913 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
1914 if (task_blocking_signal(pid, (SIGRTMIN + 3)))
1915 haltsignal = (SIGRTMIN + 3);
1916
1917 if (c->lxc_conf && c->lxc_conf->haltsignal)
1918 haltsignal = c->lxc_conf->haltsignal;
1919
1920 /* Add a new state client before sending the shutdown signal so that we
1921 * don't miss a state.
1922 */
1923 if (timeout != 0) {
1924 states[STOPPED] = 1;
1925 ret = lxc_cmd_add_state_client(c->name, c->config_path, states,
1926 &state_client_fd);
1927 if (ret < 0)
1928 return false;
1929
1930 if (state_client_fd < 0)
1931 return false;
1932
1933 if (ret == STOPPED)
1934 return true;
1935
1936 if (ret < MAX_STATE)
1937 return false;
1938 }
1939
1940 /* Send shutdown signal to container. */
1941 killret = kill(pid, haltsignal);
1942 if (killret < 0) {
1943 WARN("Could not send signal %d to pid %d", haltsignal, pid);
1944 if (state_client_fd >= 0)
1945 close(state_client_fd);
1946 return false;
1947 }
1948 TRACE("Sent signal %d to pid %d", haltsignal, pid);
1949
1950 if (timeout == 0)
1951 return true;
1952
1953 ret = lxc_cmd_sock_rcv_state(state_client_fd, timeout);
1954 close(state_client_fd);
1955 if (ret < 0)
1956 return false;
1957
1958 TRACE("Received state \"%s\"", lxc_state2str(ret));
1959 if (ret != STOPPED)
1960 return false;
1961
1962 return true;
1963 }
1964
1965 WRAP_API_1(bool, lxcapi_shutdown, int)
1966
1967 static bool lxcapi_createl(struct lxc_container *c, const char *t,
1968 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
1969 {
1970 bool bret = false;
1971 char **args = NULL;
1972 va_list ap;
1973
1974 if (!c)
1975 return false;
1976
1977 current_config = c->lxc_conf;
1978
1979 /*
1980 * since we're going to wait for create to finish, I don't think we
1981 * need to get a copy of the arguments.
1982 */
1983 va_start(ap, flags);
1984 args = lxc_va_arg_list_to_argv(ap, 0, 0);
1985 va_end(ap);
1986 if (!args) {
1987 ERROR("Failed to allocate memory");
1988 goto out;
1989 }
1990
1991 bret = do_lxcapi_create(c, t, bdevtype, specs, flags, args);
1992
1993 out:
1994 free(args);
1995 current_config = NULL;
1996 return bret;
1997 }
1998
1999 static void do_clear_unexp_config_line(struct lxc_conf *conf, const char *key)
2000 {
2001 if (!strcmp(key, "lxc.cgroup"))
2002 return clear_unexp_config_line(conf, key, true);
2003
2004 if (!strcmp(key, "lxc.network"))
2005 return clear_unexp_config_line(conf, key, true);
2006
2007 if (!strcmp(key, "lxc.net"))
2008 return clear_unexp_config_line(conf, key, true);
2009
2010 /* Clear a network with a specific index. */
2011 if (!strncmp(key, "lxc.net.", 8)) {
2012 int ret;
2013 const char *idx;
2014
2015 idx = key + 8;
2016 ret = lxc_safe_uint(idx, &(unsigned int){0});
2017 if (!ret)
2018 return clear_unexp_config_line(conf, key, true);
2019 }
2020
2021 if (!strcmp(key, "lxc.hook"))
2022 return clear_unexp_config_line(conf, key, true);
2023
2024 return clear_unexp_config_line(conf, key, false);
2025 }
2026
2027 static bool do_lxcapi_clear_config_item(struct lxc_container *c,
2028 const char *key)
2029 {
2030 int ret = 1;
2031 struct lxc_config_t *config;
2032
2033 if (!c || !c->lxc_conf)
2034 return false;
2035
2036 if (container_mem_lock(c))
2037 return false;
2038
2039 config = lxc_get_config(key);
2040 /* Verify that the config key exists and that it has a callback
2041 * implemented.
2042 */
2043 if (config && config->clr)
2044 ret = config->clr(key, c->lxc_conf, NULL);
2045 if (!ret)
2046 do_clear_unexp_config_line(c->lxc_conf, key);
2047
2048 container_mem_unlock(c);
2049 return ret == 0;
2050 }
2051
2052 WRAP_API_1(bool, lxcapi_clear_config_item, const char *)
2053
2054 static inline bool enter_net_ns(struct lxc_container *c)
2055 {
2056 pid_t pid = do_lxcapi_init_pid(c);
2057
2058 if ((geteuid() != 0 || (c->lxc_conf && !lxc_list_empty(&c->lxc_conf->id_map))) && access("/proc/self/ns/user", F_OK) == 0) {
2059 if (!switch_to_ns(pid, "user"))
2060 return false;
2061 }
2062 return switch_to_ns(pid, "net");
2063 }
2064
2065 /* Used by qsort and bsearch functions for comparing names. */
2066 static inline int string_cmp(char **first, char **second)
2067 {
2068 return strcmp(*first, *second);
2069 }
2070
2071 /* Used by qsort and bsearch functions for comparing container names. */
2072 static inline int container_cmp(struct lxc_container **first,
2073 struct lxc_container **second)
2074 {
2075 return strcmp((*first)->name, (*second)->name);
2076 }
2077
2078 static bool add_to_array(char ***names, char *cname, int pos)
2079 {
2080 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
2081 if (!newnames) {
2082 ERROR("Out of memory");
2083 return false;
2084 }
2085
2086 *names = newnames;
2087 newnames[pos] = strdup(cname);
2088 if (!newnames[pos])
2089 return false;
2090
2091 /* Sort the arrray as we will use binary search on it. */
2092 qsort(newnames, pos + 1, sizeof(char *),
2093 (int (*)(const void *, const void *))string_cmp);
2094
2095 return true;
2096 }
2097
2098 static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c,
2099 int pos, bool sort)
2100 {
2101 struct lxc_container **newlist = realloc(*list, (pos + 1) * sizeof(struct lxc_container *));
2102 if (!newlist) {
2103 ERROR("Out of memory");
2104 return false;
2105 }
2106
2107 *list = newlist;
2108 newlist[pos] = c;
2109
2110 /* Sort the arrray as we will use binary search on it. */
2111 if (sort)
2112 qsort(newlist, pos + 1, sizeof(struct lxc_container *),
2113 (int (*)(const void *, const void *))container_cmp);
2114
2115 return true;
2116 }
2117
2118 static char** get_from_array(char ***names, char *cname, int size)
2119 {
2120 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
2121 }
2122
2123
2124 static bool array_contains(char ***names, char *cname, int size) {
2125 if(get_from_array(names, cname, size) != NULL)
2126 return true;
2127 return false;
2128 }
2129
2130 static bool remove_from_array(char ***names, char *cname, int size)
2131 {
2132 char **result = get_from_array(names, cname, size);
2133 if (result != NULL) {
2134 free(result);
2135 return true;
2136 }
2137 return false;
2138 }
2139
2140 static char ** do_lxcapi_get_interfaces(struct lxc_container *c)
2141 {
2142 pid_t pid;
2143 int i, count = 0, pipefd[2];
2144 char **interfaces = NULL;
2145 char interface[IFNAMSIZ];
2146
2147 if(pipe(pipefd) < 0) {
2148 SYSERROR("pipe failed");
2149 return NULL;
2150 }
2151
2152 pid = fork();
2153 if (pid < 0) {
2154 SYSERROR("failed to fork task to get interfaces information");
2155 close(pipefd[0]);
2156 close(pipefd[1]);
2157 return NULL;
2158 }
2159
2160 if (pid == 0) { /* child */
2161 int ret = 1, nbytes;
2162 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
2163
2164 /* close the read-end of the pipe */
2165 close(pipefd[0]);
2166
2167 if (!enter_net_ns(c)) {
2168 SYSERROR("failed to enter namespace");
2169 goto out;
2170 }
2171
2172 /* Grab the list of interfaces */
2173 if (getifaddrs(&interfaceArray)) {
2174 SYSERROR("failed to get interfaces list");
2175 goto out;
2176 }
2177
2178 /* Iterate through the interfaces */
2179 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
2180 nbytes = write(pipefd[1], tempIfAddr->ifa_name, IFNAMSIZ);
2181 if (nbytes < 0) {
2182 ERROR("write failed");
2183 goto out;
2184 }
2185 count++;
2186 }
2187 ret = 0;
2188
2189 out:
2190 if (interfaceArray)
2191 freeifaddrs(interfaceArray);
2192
2193 /* close the write-end of the pipe, thus sending EOF to the reader */
2194 close(pipefd[1]);
2195 exit(ret);
2196 }
2197
2198 /* close the write-end of the pipe */
2199 close(pipefd[1]);
2200
2201 while (read(pipefd[0], &interface, IFNAMSIZ) == IFNAMSIZ) {
2202 interface[IFNAMSIZ - 1] = '\0';
2203
2204 if (array_contains(&interfaces, interface, count))
2205 continue;
2206
2207 if(!add_to_array(&interfaces, interface, count))
2208 ERROR("Failed to add \"%s\" to array", interface);
2209
2210 count++;
2211 }
2212
2213 if (wait_for_pid(pid) != 0) {
2214 for(i=0;i<count;i++)
2215 free(interfaces[i]);
2216 free(interfaces);
2217 interfaces = NULL;
2218 }
2219
2220 /* close the read-end of the pipe */
2221 close(pipefd[0]);
2222
2223 /* Append NULL to the array */
2224 if(interfaces)
2225 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
2226
2227 return interfaces;
2228 }
2229
2230 WRAP_API(char **, lxcapi_get_interfaces)
2231
2232 static char** do_lxcapi_get_ips(struct lxc_container *c, const char* interface, const char* family, int scope)
2233 {
2234 pid_t pid;
2235 int i, count = 0, pipefd[2];
2236 char **addresses = NULL;
2237 char address[INET6_ADDRSTRLEN];
2238
2239 if(pipe(pipefd) < 0) {
2240 SYSERROR("pipe failed");
2241 return NULL;
2242 }
2243
2244 pid = fork();
2245 if (pid < 0) {
2246 SYSERROR("failed to fork task to get container ips");
2247 close(pipefd[0]);
2248 close(pipefd[1]);
2249 return NULL;
2250 }
2251
2252 if (pid == 0) { /* child */
2253 int ret = 1, nbytes;
2254 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
2255 char addressOutputBuffer[INET6_ADDRSTRLEN];
2256 void *tempAddrPtr = NULL;
2257 char *address = NULL;
2258
2259 /* close the read-end of the pipe */
2260 close(pipefd[0]);
2261
2262 if (!enter_net_ns(c)) {
2263 SYSERROR("failed to enter namespace");
2264 goto out;
2265 }
2266
2267 /* Grab the list of interfaces */
2268 if (getifaddrs(&interfaceArray)) {
2269 SYSERROR("failed to get interfaces list");
2270 goto out;
2271 }
2272
2273 /* Iterate through the interfaces */
2274 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
2275 if (tempIfAddr->ifa_addr == NULL)
2276 continue;
2277
2278 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
2279 if (family && strcmp(family, "inet"))
2280 continue;
2281 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
2282 }
2283 else {
2284 if (family && strcmp(family, "inet6"))
2285 continue;
2286
2287 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
2288 continue;
2289
2290 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
2291 }
2292
2293 if (interface && strcmp(interface, tempIfAddr->ifa_name))
2294 continue;
2295 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
2296 continue;
2297
2298 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
2299 tempAddrPtr,
2300 addressOutputBuffer,
2301 sizeof(addressOutputBuffer));
2302 if (!address)
2303 continue;
2304
2305 nbytes = write(pipefd[1], address, INET6_ADDRSTRLEN);
2306 if (nbytes < 0) {
2307 ERROR("write failed");
2308 goto out;
2309 }
2310 count++;
2311 }
2312 ret = 0;
2313
2314 out:
2315 if(interfaceArray)
2316 freeifaddrs(interfaceArray);
2317
2318 /* close the write-end of the pipe, thus sending EOF to the reader */
2319 close(pipefd[1]);
2320 exit(ret);
2321 }
2322
2323 /* close the write-end of the pipe */
2324 close(pipefd[1]);
2325
2326 while (read(pipefd[0], &address, INET6_ADDRSTRLEN) == INET6_ADDRSTRLEN) {
2327 if(!add_to_array(&addresses, address, count))
2328 ERROR("PARENT: add_to_array failed");
2329 count++;
2330 }
2331
2332 if (wait_for_pid(pid) != 0) {
2333 for(i=0;i<count;i++)
2334 free(addresses[i]);
2335 free(addresses);
2336 addresses = NULL;
2337 }
2338
2339 /* close the read-end of the pipe */
2340 close(pipefd[0]);
2341
2342 /* Append NULL to the array */
2343 if(addresses)
2344 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
2345
2346 return addresses;
2347 }
2348
2349 WRAP_API_3(char **, lxcapi_get_ips, const char *, const char *, int)
2350
2351 static int do_lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
2352 {
2353 int ret = -1;
2354 struct lxc_config_t *config;
2355
2356 if (!c || !c->lxc_conf)
2357 return -1;
2358
2359 if (container_mem_lock(c))
2360 return -1;
2361
2362 config = lxc_get_config(key);
2363 /* Verify that the config key exists and that it has a callback
2364 * implemented.
2365 */
2366 if (config && config->get)
2367 ret = config->get(key, retv, inlen, c->lxc_conf, NULL);
2368
2369 container_mem_unlock(c);
2370 return ret;
2371 }
2372
2373 WRAP_API_3(int, lxcapi_get_config_item, const char *, char *, int)
2374
2375 static char* do_lxcapi_get_running_config_item(struct lxc_container *c, const char *key)
2376 {
2377 char *ret;
2378
2379 if (!c || !c->lxc_conf)
2380 return NULL;
2381 if (container_mem_lock(c))
2382 return NULL;
2383 ret = lxc_cmd_get_config_item(c->name, key, do_lxcapi_get_config_path(c));
2384 container_mem_unlock(c);
2385 return ret;
2386 }
2387
2388 WRAP_API_1(char *, lxcapi_get_running_config_item, const char *)
2389
2390 static int do_lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
2391 {
2392 int ret = -1;
2393
2394 /* List all config items. */
2395 if (!key)
2396 return lxc_list_config_items(retv, inlen);
2397
2398 if (!c || !c->lxc_conf)
2399 return -1;
2400
2401 if (container_mem_lock(c))
2402 return -1;
2403
2404 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2405 * This is an intelligent result to show which keys are valid given the
2406 * type of nic it is.
2407 */
2408 if (strncmp(key, "lxc.net.", 8) == 0)
2409 ret = lxc_list_net(c->lxc_conf, key, retv, inlen);
2410 else
2411 ret = lxc_list_subkeys(c->lxc_conf, key, retv, inlen);
2412
2413 container_mem_unlock(c);
2414 return ret;
2415 }
2416
2417 WRAP_API_3(int, lxcapi_get_keys, const char *, char *, int)
2418
2419 static bool do_lxcapi_save_config(struct lxc_container *c, const char *alt_file)
2420 {
2421 FILE *fout;
2422 bool ret = false, need_disklock = false;
2423 int lret;
2424
2425 if (!alt_file)
2426 alt_file = c->configfile;
2427 if (!alt_file)
2428 return false;
2429
2430 /* If we haven't yet loaded a config, load the stock config. */
2431 if (!c->lxc_conf) {
2432 if (!do_lxcapi_load_config(c, lxc_global_config_value("lxc.default_config"))) {
2433 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c->name);
2434 return false;
2435 }
2436 }
2437
2438 if (!create_container_dir(c))
2439 return false;
2440
2441 /* If we're writing to the container's config file, take the disk lock.
2442 * Otherwise just take the memlock to protect the struct lxc_container
2443 * while we're traversing it.
2444 */
2445 if (strcmp(c->configfile, alt_file) == 0)
2446 need_disklock = true;
2447
2448 if (need_disklock)
2449 lret = container_disk_lock(c);
2450 else
2451 lret = container_mem_lock(c);
2452
2453 if (lret)
2454 return false;
2455
2456 fout = fopen(alt_file, "w");
2457 if (!fout)
2458 goto out;
2459 write_config(fout, c->lxc_conf);
2460 fclose(fout);
2461 ret = true;
2462
2463 out:
2464 if (need_disklock)
2465 container_disk_unlock(c);
2466 else
2467 container_mem_unlock(c);
2468 return ret;
2469 }
2470
2471 WRAP_API_1(bool, lxcapi_save_config, const char *)
2472
2473
2474 static bool mod_rdep(struct lxc_container *c0, struct lxc_container *c, bool inc)
2475 {
2476 FILE *f1;
2477 struct stat fbuf;
2478 void *buf = NULL;
2479 char *del = NULL;
2480 char path[MAXPATHLEN];
2481 char newpath[MAXPATHLEN];
2482 int fd, ret, n = 0, v = 0;
2483 bool bret = false;
2484 size_t len = 0, bytes = 0;
2485
2486 if (container_disk_lock(c0))
2487 return false;
2488
2489 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c0->config_path, c0->name);
2490 if (ret < 0 || ret > MAXPATHLEN)
2491 goto out;
2492 ret = snprintf(newpath, MAXPATHLEN, "%s\n%s\n", c->config_path, c->name);
2493 if (ret < 0 || ret > MAXPATHLEN)
2494 goto out;
2495
2496 /* If we find an lxc-snapshot file using the old format only listing the
2497 * number of snapshots we will keep using it. */
2498 f1 = fopen(path, "r");
2499 if (f1) {
2500 n = fscanf(f1, "%d", &v);
2501 fclose(f1);
2502 if (n == 1 && v == 0) {
2503 remove(path);
2504 n = 0;
2505 }
2506 }
2507 if (n == 1) {
2508 v += inc ? 1 : -1;
2509 f1 = fopen(path, "w");
2510 if (!f1)
2511 goto out;
2512 if (fprintf(f1, "%d\n", v) < 0) {
2513 ERROR("Error writing new snapshots value");
2514 fclose(f1);
2515 goto out;
2516 }
2517 ret = fclose(f1);
2518 if (ret != 0) {
2519 SYSERROR("Error writing to or closing snapshots file");
2520 goto out;
2521 }
2522 } else {
2523 /* Here we know that we have or can use an lxc-snapshot file
2524 * using the new format. */
2525 if (inc) {
2526 f1 = fopen(path, "a");
2527 if (!f1)
2528 goto out;
2529
2530 if (fprintf(f1, "%s", newpath) < 0) {
2531 ERROR("Error writing new snapshots entry");
2532 ret = fclose(f1);
2533 if (ret != 0)
2534 SYSERROR("Error writing to or closing snapshots file");
2535 goto out;
2536 }
2537
2538 ret = fclose(f1);
2539 if (ret != 0) {
2540 SYSERROR("Error writing to or closing snapshots file");
2541 goto out;
2542 }
2543 } else if (!inc) {
2544 if ((fd = open(path, O_RDWR | O_CLOEXEC)) < 0)
2545 goto out;
2546
2547 if (fstat(fd, &fbuf) < 0) {
2548 close(fd);
2549 goto out;
2550 }
2551
2552 if (fbuf.st_size != 0) {
2553
2554 buf = lxc_strmmap(NULL, fbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2555 if (buf == MAP_FAILED) {
2556 SYSERROR("Failed to create mapping %s", path);
2557 close(fd);
2558 goto out;
2559 }
2560
2561 len = strlen(newpath);
2562 while ((del = strstr((char *)buf, newpath))) {
2563 memmove(del, del + len, strlen(del) - len + 1);
2564 bytes += len;
2565 }
2566
2567 lxc_strmunmap(buf, fbuf.st_size);
2568 if (ftruncate(fd, fbuf.st_size - bytes) < 0) {
2569 SYSERROR("Failed to truncate file %s", path);
2570 close(fd);
2571 goto out;
2572 }
2573 }
2574 close(fd);
2575 }
2576
2577 /* If the lxc-snapshot file is empty, remove it. */
2578 if (stat(path, &fbuf) < 0)
2579 goto out;
2580 if (!fbuf.st_size) {
2581 remove(path);
2582 }
2583 }
2584
2585 bret = true;
2586
2587 out:
2588 container_disk_unlock(c0);
2589 return bret;
2590 }
2591
2592 static void strip_newline(char *p)
2593 {
2594 size_t len = strlen(p);
2595 if (len < 1)
2596 return;
2597 if (p[len-1] == '\n')
2598 p[len-1] = '\0';
2599 }
2600
2601 void mod_all_rdeps(struct lxc_container *c, bool inc)
2602 {
2603 struct lxc_container *p;
2604 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
2605 size_t pathlen = 0, namelen = 0;
2606 FILE *f;
2607 int ret;
2608
2609 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
2610 c->config_path, c->name);
2611 if (ret < 0 || ret >= MAXPATHLEN) {
2612 ERROR("Path name too long");
2613 return;
2614 }
2615 f = fopen(path, "r");
2616 if (f == NULL)
2617 return;
2618 while (getline(&lxcpath, &pathlen, f) != -1) {
2619 if (getline(&lxcname, &namelen, f) == -1) {
2620 ERROR("badly formatted file %s", path);
2621 goto out;
2622 }
2623 strip_newline(lxcpath);
2624 strip_newline(lxcname);
2625 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
2626 ERROR("Unable to find dependent container %s:%s",
2627 lxcpath, lxcname);
2628 continue;
2629 }
2630 if (!mod_rdep(p, c, inc))
2631 ERROR("Failed to update snapshots file for %s:%s",
2632 lxcpath, lxcname);
2633 lxc_container_put(p);
2634 }
2635 out:
2636 free(lxcpath);
2637 free(lxcname);
2638 fclose(f);
2639 }
2640
2641 static bool has_fs_snapshots(struct lxc_container *c)
2642 {
2643 FILE *f;
2644 char path[MAXPATHLEN];
2645 int ret, v;
2646 struct stat fbuf;
2647 bool bret = false;
2648
2649 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
2650 c->name);
2651 if (ret < 0 || ret > MAXPATHLEN)
2652 goto out;
2653 /* If the file doesn't exist there are no snapshots. */
2654 if (stat(path, &fbuf) < 0)
2655 goto out;
2656 v = fbuf.st_size;
2657 if (v != 0) {
2658 f = fopen(path, "r");
2659 if (!f)
2660 goto out;
2661 ret = fscanf(f, "%d", &v);
2662 fclose(f);
2663 /* TODO: Figure out what to do with the return value of fscanf. */
2664 if (ret != 1)
2665 INFO("Container uses new lxc-snapshots format %s", path);
2666 }
2667 bret = v != 0;
2668
2669 out:
2670 return bret;
2671 }
2672
2673 static bool has_snapshots(struct lxc_container *c)
2674 {
2675 char path[MAXPATHLEN];
2676 struct dirent *direntp;
2677 int count=0;
2678 DIR *dir;
2679
2680 if (!get_snappath_dir(c, path))
2681 return false;
2682 dir = opendir(path);
2683 if (!dir)
2684 return false;
2685 while ((direntp = readdir(dir))) {
2686 if (!direntp)
2687 break;
2688
2689 if (!strcmp(direntp->d_name, "."))
2690 continue;
2691
2692 if (!strcmp(direntp->d_name, ".."))
2693 continue;
2694 count++;
2695 break;
2696 }
2697 closedir(dir);
2698 return count > 0;
2699 }
2700
2701 static bool do_destroy_container(struct lxc_conf *conf) {
2702 int ret;
2703
2704 if (am_guest_unpriv()) {
2705 ret = userns_exec_full(conf, storage_destroy_wrapper, conf,
2706 "storage_destroy_wrapper");
2707 if (ret < 0)
2708 return false;
2709
2710 return true;
2711 }
2712
2713 return storage_destroy(conf);
2714 }
2715
2716 static int lxc_rmdir_onedev_wrapper(void *data)
2717 {
2718 char *arg = (char *) data;
2719 return lxc_rmdir_onedev(arg, "snaps");
2720 }
2721
2722 static int lxc_unlink_exec_wrapper(void *data)
2723 {
2724 char *arg = data;
2725 return unlink(arg);
2726 }
2727
2728 static bool container_destroy(struct lxc_container *c,
2729 struct lxc_storage *storage)
2730 {
2731 const char *p1;
2732 size_t len;
2733 struct lxc_conf *conf;
2734 char *path = NULL;
2735 bool bret = false;
2736 int ret = 0;
2737
2738 if (!c || !do_lxcapi_is_defined(c))
2739 return false;
2740
2741 conf = c->lxc_conf;
2742 if (container_disk_lock(c))
2743 return false;
2744
2745 if (!is_stopped(c)) {
2746 /* We should queue some sort of error - in c->error_string? */
2747 ERROR("container %s is not stopped", c->name);
2748 goto out;
2749 }
2750
2751 if (conf && !lxc_list_empty(&conf->hooks[LXCHOOK_DESTROY])) {
2752 /* Start of environment variable setup for hooks */
2753 if (setenv("LXC_NAME", c->name, 1))
2754 SYSERROR("Failed to set environment variable for container name");
2755
2756 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
2757 SYSERROR("Failed to set environment variable for config path");
2758
2759 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
2760 SYSERROR("Failed to set environment variable for rootfs mount");
2761
2762 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
2763 SYSERROR("Failed to set environment variable for rootfs mount");
2764
2765 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
2766 SYSERROR("Failed to set environment variable for console path");
2767
2768 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
2769 SYSERROR("Failed to set environment variable for console log");
2770 /* End of environment variable setup for hooks */
2771
2772 if (run_lxc_hooks(c->name, "destroy", conf, NULL)) {
2773 ERROR("Failed to execute clone hook for \"%s\"", c->name);
2774 goto out;
2775 }
2776 }
2777
2778 if (current_config && conf == current_config) {
2779 current_config = NULL;
2780 if (conf->logfd != -1) {
2781 close(conf->logfd);
2782 conf->logfd = -1;
2783 }
2784 }
2785
2786 if (conf && conf->rootfs.path && conf->rootfs.mount) {
2787 if (!do_destroy_container(conf)) {
2788 ERROR("Error destroying rootfs for %s", c->name);
2789 goto out;
2790 }
2791 INFO("Destroyed rootfs for %s", c->name);
2792 }
2793
2794 mod_all_rdeps(c, false);
2795
2796 p1 = do_lxcapi_get_config_path(c);
2797 /* strlen(p1)
2798 * +
2799 * /
2800 * +
2801 * strlen(c->name)
2802 * +
2803 * /
2804 * +
2805 * strlen("config") = 6
2806 * +
2807 * \0
2808 */
2809 len = strlen(p1) + 1 + strlen(c->name) + 1 + 6 + 1;
2810 path = malloc(len);
2811 if (!path) {
2812 ERROR("Failed to allocate memory");
2813 goto out;
2814 }
2815
2816 /* For an overlay container the rootfs is considered immutable and
2817 * cannot be removed when restoring from a snapshot.
2818 */
2819 if (storage && (!strcmp(storage->type, "overlay") ||
2820 !strcmp(storage->type, "overlayfs")) &&
2821 (storage->flags & LXC_STORAGE_INTERNAL_OVERLAY_RESTORE)) {
2822 ret = snprintf(path, len, "%s/%s/config", p1, c->name);
2823 if (ret < 0 || (size_t)ret >= len)
2824 goto out;
2825
2826 if (am_guest_unpriv())
2827 ret = userns_exec_1(conf, lxc_unlink_exec_wrapper, path,
2828 "lxc_unlink_exec_wrapper");
2829 else
2830 ret = unlink(path);
2831 if (ret < 0) {
2832 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
2833 path, c->name);
2834 goto out;
2835 }
2836 INFO("Destroyed config file \"%s\" for \"%s\"", path, c->name);
2837
2838 bret = true;
2839 goto out;
2840 }
2841
2842 ret = snprintf(path, len, "%s/%s", p1, c->name);
2843 if (ret < 0 || (size_t)ret >= len)
2844 goto out;
2845 if (am_guest_unpriv())
2846 ret = userns_exec_full(conf, lxc_rmdir_onedev_wrapper, path,
2847 "lxc_rmdir_onedev_wrapper");
2848 else
2849 ret = lxc_rmdir_onedev(path, "snaps");
2850 if (ret < 0) {
2851 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path,
2852 c->name);
2853 goto out;
2854 }
2855 INFO("Destroyed directory \"%s\" for \"%s\"", path, c->name);
2856
2857 bret = true;
2858
2859 out:
2860 if (path)
2861 free(path);
2862 container_disk_unlock(c);
2863 return bret;
2864 }
2865
2866 static bool do_lxcapi_destroy(struct lxc_container *c)
2867 {
2868 if (!c || !lxcapi_is_defined(c))
2869 return false;
2870 if (has_snapshots(c)) {
2871 ERROR("Container %s has snapshots; not removing", c->name);
2872 return false;
2873 }
2874
2875 if (has_fs_snapshots(c)) {
2876 ERROR("container %s has snapshots on its rootfs", c->name);
2877 return false;
2878 }
2879
2880 return container_destroy(c, NULL);
2881 }
2882
2883 WRAP_API(bool, lxcapi_destroy)
2884
2885 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container *c)
2886 {
2887 if (!c || !lxcapi_is_defined(c))
2888 return false;
2889 if (!lxcapi_snapshot_destroy_all(c)) {
2890 ERROR("Error deleting all snapshots");
2891 return false;
2892 }
2893 return lxcapi_destroy(c);
2894 }
2895
2896 WRAP_API(bool, lxcapi_destroy_with_snapshots)
2897
2898 int lxc_set_config_item_locked(struct lxc_conf *conf, const char *key,
2899 const char *v)
2900 {
2901 int ret;
2902 struct lxc_config_t *config;
2903 bool bret = true;
2904
2905 config = lxc_get_config(key);
2906 if (!config)
2907 return -EINVAL;
2908
2909 ret = config->set(key, v, conf, NULL);
2910 if (ret < 0)
2911 return -EINVAL;
2912
2913 if (lxc_config_value_empty(v))
2914 do_clear_unexp_config_line(conf, key);
2915 else
2916 bret = do_append_unexp_config_line(conf, key, v);
2917 if (!bret)
2918 return -ENOMEM;
2919
2920 return 0;
2921 }
2922
2923 static bool do_set_config_item_locked(struct lxc_container *c, const char *key,
2924 const char *v)
2925 {
2926 int ret;
2927
2928 if (!c->lxc_conf)
2929 c->lxc_conf = lxc_conf_init();
2930
2931 if (!c->lxc_conf)
2932 return false;
2933
2934 ret = lxc_set_config_item_locked(c->lxc_conf, key, v);
2935 if (ret < 0)
2936 return false;
2937
2938 return true;
2939 }
2940
2941 static bool do_lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
2942 {
2943 bool b = false;
2944
2945 if (!c)
2946 return false;
2947
2948 if (container_mem_lock(c))
2949 return false;
2950
2951 b = do_set_config_item_locked(c, key, v);
2952
2953 container_mem_unlock(c);
2954 return b;
2955 }
2956
2957 WRAP_API_2(bool, lxcapi_set_config_item, const char *, const char *)
2958
2959 static char *lxcapi_config_file_name(struct lxc_container *c)
2960 {
2961 if (!c || !c->configfile)
2962 return NULL;
2963 return strdup(c->configfile);
2964 }
2965
2966 static const char *lxcapi_get_config_path(struct lxc_container *c)
2967 {
2968 if (!c || !c->config_path)
2969 return NULL;
2970 return (const char *)(c->config_path);
2971 }
2972
2973 /*
2974 * not for export
2975 * Just recalculate the c->configfile based on the
2976 * c->config_path, which must be set.
2977 * The lxc_container must be locked or not yet public.
2978 */
2979 static bool set_config_filename(struct lxc_container *c)
2980 {
2981 char *newpath;
2982 int len, ret;
2983
2984 if (!c->config_path)
2985 return false;
2986
2987 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2988 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
2989 newpath = malloc(len);
2990 if (!newpath)
2991 return false;
2992
2993 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
2994 if (ret < 0 || ret >= len) {
2995 fprintf(stderr, "Error printing out config file name\n");
2996 free(newpath);
2997 return false;
2998 }
2999
3000 free(c->configfile);
3001 c->configfile = newpath;
3002
3003 return true;
3004 }
3005
3006 static bool do_lxcapi_set_config_path(struct lxc_container *c, const char *path)
3007 {
3008 char *p;
3009 bool b = false;
3010 char *oldpath = NULL;
3011
3012 if (!c)
3013 return b;
3014
3015 if (container_mem_lock(c))
3016 return b;
3017
3018 p = strdup(path);
3019 if (!p) {
3020 ERROR("Out of memory setting new lxc path");
3021 goto err;
3022 }
3023
3024 b = true;
3025 if (c->config_path)
3026 oldpath = c->config_path;
3027 c->config_path = p;
3028
3029 /* Since we've changed the config path, we have to change the
3030 * config file name too */
3031 if (!set_config_filename(c)) {
3032 ERROR("Out of memory setting new config filename");
3033 b = false;
3034 free(c->config_path);
3035 c->config_path = oldpath;
3036 oldpath = NULL;
3037 }
3038 err:
3039 free(oldpath);
3040 container_mem_unlock(c);
3041 return b;
3042 }
3043
3044 WRAP_API_1(bool, lxcapi_set_config_path, const char *)
3045
3046 static bool do_lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
3047 {
3048 int ret;
3049
3050 if (!c)
3051 return false;
3052
3053 if (is_stopped(c))
3054 return false;
3055
3056 if (container_disk_lock(c))
3057 return false;
3058
3059 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
3060
3061 container_disk_unlock(c);
3062 return ret == 0;
3063 }
3064
3065 WRAP_API_2(bool, lxcapi_set_cgroup_item, const char *, const char *)
3066
3067 static int do_lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
3068 {
3069 int ret;
3070
3071 if (!c)
3072 return -1;
3073
3074 if (is_stopped(c))
3075 return -1;
3076
3077 if (container_disk_lock(c))
3078 return -1;
3079
3080 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
3081
3082 container_disk_unlock(c);
3083 return ret;
3084 }
3085
3086 WRAP_API_3(int, lxcapi_get_cgroup_item, const char *, char *, int)
3087
3088 const char *lxc_get_global_config_item(const char *key)
3089 {
3090 return lxc_global_config_value(key);
3091 }
3092
3093 const char *lxc_get_version(void)
3094 {
3095 return LXC_VERSION;
3096 }
3097
3098 static int copy_file(const char *old, const char *new)
3099 {
3100 int in, out;
3101 ssize_t len, ret;
3102 char buf[8096];
3103 struct stat sbuf;
3104
3105 if (file_exists(new)) {
3106 ERROR("copy destination %s exists", new);
3107 return -1;
3108 }
3109 ret = stat(old, &sbuf);
3110 if (ret < 0) {
3111 INFO("Error stat'ing %s", old);
3112 return -1;
3113 }
3114
3115 in = open(old, O_RDONLY);
3116 if (in < 0) {
3117 SYSERROR("Error opening original file %s", old);
3118 return -1;
3119 }
3120 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
3121 if (out < 0) {
3122 SYSERROR("Error opening new file %s", new);
3123 close(in);
3124 return -1;
3125 }
3126
3127 while (1) {
3128 len = read(in, buf, 8096);
3129 if (len < 0) {
3130 SYSERROR("Error reading old file %s", old);
3131 goto err;
3132 }
3133 if (len == 0)
3134 break;
3135 ret = write(out, buf, len);
3136 if (ret < len) { /* should we retry? */
3137 SYSERROR("Error: write to new file %s was interrupted", new);
3138 goto err;
3139 }
3140 }
3141 close(in);
3142 close(out);
3143
3144 /* We set mode, but not owner/group. */
3145 ret = chmod(new, sbuf.st_mode);
3146 if (ret) {
3147 SYSERROR("Error setting mode on %s", new);
3148 return -1;
3149 }
3150
3151 return 0;
3152
3153 err:
3154 close(in);
3155 close(out);
3156 return -1;
3157 }
3158
3159 static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
3160 {
3161 int i, len, ret;
3162 struct lxc_list *it;
3163 char *cpath;
3164
3165 len = strlen(oldc->config_path) + strlen(oldc->name) + 3;
3166 cpath = alloca(len);
3167 ret = snprintf(cpath, len, "%s/%s/", oldc->config_path, oldc->name);
3168 if (ret < 0 || ret >= len)
3169 return -1;
3170
3171 for (i=0; i<NUM_LXC_HOOKS; i++) {
3172 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
3173 char *hookname = it->elem;
3174 char *fname = strrchr(hookname, '/');
3175 char tmppath[MAXPATHLEN];
3176 if (!fname) /* relative path - we don't support, but maybe we should */
3177 return 0;
3178 if (strncmp(hookname, cpath, len - 1) != 0) {
3179 /* this hook is public - ignore */
3180 continue;
3181 }
3182 /* copy the script, and change the entry in confile */
3183 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
3184 c->config_path, c->name, fname+1);
3185 if (ret < 0 || ret >= MAXPATHLEN)
3186 return -1;
3187 ret = copy_file(it->elem, tmppath);
3188 if (ret < 0)
3189 return -1;
3190 free(it->elem);
3191 it->elem = strdup(tmppath);
3192 if (!it->elem) {
3193 ERROR("out of memory copying hook path");
3194 return -1;
3195 }
3196 }
3197 }
3198
3199 if (!clone_update_unexp_hooks(c->lxc_conf, oldc->config_path,
3200 c->config_path, oldc->name, c->name)) {
3201 ERROR("Error saving new hooks in clone");
3202 return -1;
3203 }
3204 do_lxcapi_save_config(c, NULL);
3205 return 0;
3206 }
3207
3208
3209 static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
3210 {
3211 char newpath[MAXPATHLEN];
3212 char *oldpath = oldc->lxc_conf->fstab;
3213 int ret;
3214
3215 if (!oldpath)
3216 return 0;
3217
3218 clear_unexp_config_line(c->lxc_conf, "lxc.mount.fstab", false);
3219
3220 char *p = strrchr(oldpath, '/');
3221 if (!p)
3222 return -1;
3223 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
3224 c->config_path, c->name, p);
3225 if (ret < 0 || ret >= MAXPATHLEN) {
3226 ERROR("error printing new path for %s", oldpath);
3227 return -1;
3228 }
3229 if (file_exists(newpath)) {
3230 ERROR("error: fstab file %s exists", newpath);
3231 return -1;
3232 }
3233
3234 if (copy_file(oldpath, newpath) < 0) {
3235 ERROR("error: copying %s to %s", oldpath, newpath);
3236 return -1;
3237 }
3238 free(c->lxc_conf->fstab);
3239 c->lxc_conf->fstab = strdup(newpath);
3240 if (!c->lxc_conf->fstab) {
3241 ERROR("error: allocating pathname");
3242 return -1;
3243 }
3244 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.mount.fstab", newpath)) {
3245 ERROR("error saving new lxctab");
3246 return -1;
3247 }
3248
3249 return 0;
3250 }
3251
3252 static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
3253 {
3254 char path0[MAXPATHLEN], path1[MAXPATHLEN];
3255 int ret;
3256
3257 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
3258 c0->name);
3259 if (ret < 0 || ret >= MAXPATHLEN) {
3260 WARN("Error copying reverse dependencies");
3261 return;
3262 }
3263 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
3264 c->name);
3265 if (ret < 0 || ret >= MAXPATHLEN) {
3266 WARN("Error copying reverse dependencies");
3267 return;
3268 }
3269 if (copy_file(path0, path1) < 0) {
3270 INFO("Error copying reverse dependencies");
3271 return;
3272 }
3273 }
3274
3275 static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
3276 {
3277 int ret;
3278 char path[MAXPATHLEN];
3279 FILE *f;
3280 bool bret;
3281
3282 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
3283 c->name);
3284 if (ret < 0 || ret >= MAXPATHLEN)
3285 return false;
3286 f = fopen(path, "a");
3287 if (!f)
3288 return false;
3289 bret = true;
3290 /* If anything goes wrong, just return an error. */
3291 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
3292 bret = false;
3293 if (fclose(f) != 0)
3294 bret = false;
3295 return bret;
3296 }
3297
3298 /*
3299 * If the fs natively supports snapshot clones with no penalty,
3300 * then default to those even if not requested.
3301 * Currently we only do this for btrfs.
3302 */
3303 bool should_default_to_snapshot(struct lxc_container *c0,
3304 struct lxc_container *c1)
3305 {
3306 size_t l0 = strlen(c0->config_path) + strlen(c0->name) + 2;
3307 size_t l1 = strlen(c1->config_path) + strlen(c1->name) + 2;
3308 char *p0 = alloca(l0 + 1);
3309 char *p1 = alloca(l1 + 1);
3310 char *rootfs = c0->lxc_conf->rootfs.path;
3311
3312 snprintf(p0, l0, "%s/%s", c0->config_path, c0->name);
3313 snprintf(p1, l1, "%s/%s", c1->config_path, c1->name);
3314
3315 if (!is_btrfs_fs(p0) || !is_btrfs_fs(p1))
3316 return false;
3317
3318 if (is_btrfs_subvol(rootfs) <= 0)
3319 return false;
3320
3321 return btrfs_same_fs(p0, p1) == 0;
3322 }
3323
3324 static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
3325 const char *newtype, int flags, const char *bdevdata,
3326 uint64_t newsize)
3327 {
3328 struct lxc_storage *bdev;
3329 bool need_rdep;
3330
3331 if (should_default_to_snapshot(c0, c))
3332 flags |= LXC_CLONE_SNAPSHOT;
3333
3334 bdev = storage_copy(c0, c->name, c->config_path, newtype, flags,
3335 bdevdata, newsize, &need_rdep);
3336 if (!bdev) {
3337 ERROR("Error copying storage.");
3338 return -1;
3339 }
3340
3341 /* Set new rootfs. */
3342 free(c->lxc_conf->rootfs.path);
3343 c->lxc_conf->rootfs.path = strdup(bdev->src);
3344 storage_put(bdev);
3345
3346 if (!c->lxc_conf->rootfs.path) {
3347 ERROR("Out of memory while setting storage path.");
3348 return -1;
3349 }
3350
3351 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3352 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.path", false);
3353 if (!do_append_unexp_config_line(c->lxc_conf, "lxc.rootfs.path",
3354 c->lxc_conf->rootfs.path)) {
3355 ERROR("Error saving new rootfs to cloned config.");
3356 return -1;
3357 }
3358
3359 if (flags & LXC_CLONE_SNAPSHOT)
3360 copy_rdepends(c, c0);
3361 if (need_rdep) {
3362 if (!add_rdepends(c, c0))
3363 WARN("Error adding reverse dependency from %s to %s",
3364 c->name, c0->name);
3365 }
3366
3367 mod_all_rdeps(c, true);
3368
3369 return 0;
3370 }
3371
3372 struct clone_update_data {
3373 struct lxc_container *c0;
3374 struct lxc_container *c1;
3375 int flags;
3376 char **hookargs;
3377 };
3378
3379 static int clone_update_rootfs(struct clone_update_data *data)
3380 {
3381 struct lxc_container *c0 = data->c0;
3382 struct lxc_container *c = data->c1;
3383 int flags = data->flags;
3384 char **hookargs = data->hookargs;
3385 int ret = -1;
3386 char path[MAXPATHLEN];
3387 struct lxc_storage *bdev;
3388 FILE *fout;
3389 struct lxc_conf *conf = c->lxc_conf;
3390
3391 /* update hostname in rootfs */
3392 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3393
3394 if (setgid(0) < 0) {
3395 ERROR("Failed to setgid to 0");
3396 return -1;
3397 }
3398 if (setuid(0) < 0) {
3399 ERROR("Failed to setuid to 0");
3400 return -1;
3401 }
3402 if (setgroups(0, NULL) < 0)
3403 WARN("Failed to clear groups");
3404
3405 if (unshare(CLONE_NEWNS) < 0)
3406 return -1;
3407 bdev = storage_init(c->lxc_conf);
3408 if (!bdev)
3409 return -1;
3410 if (strcmp(bdev->type, "dir") != 0) {
3411 if (unshare(CLONE_NEWNS) < 0) {
3412 ERROR("error unsharing mounts");
3413 storage_put(bdev);
3414 return -1;
3415 }
3416 if (detect_shared_rootfs()) {
3417 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
3418 SYSERROR("Failed to make / rslave");
3419 ERROR("Continuing...");
3420 }
3421 }
3422 if (bdev->ops->mount(bdev) < 0) {
3423 storage_put(bdev);
3424 return -1;
3425 }
3426 } else { /* TODO come up with a better way */
3427 free(bdev->dest);
3428 bdev->dest = strdup(bdev->src);
3429 }
3430
3431 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
3432 /* Start of environment variable setup for hooks */
3433 if (c0->name && setenv("LXC_SRC_NAME", c0->name, 1)) {
3434 SYSERROR("failed to set environment variable for source container name");
3435 }
3436 if (setenv("LXC_NAME", c->name, 1)) {
3437 SYSERROR("failed to set environment variable for container name");
3438 }
3439 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
3440 SYSERROR("failed to set environment variable for config path");
3441 }
3442 if (bdev->dest && setenv("LXC_ROOTFS_MOUNT", bdev->dest, 1)) {
3443 SYSERROR("failed to set environment variable for rootfs mount");
3444 }
3445 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
3446 SYSERROR("failed to set environment variable for rootfs mount");
3447 }
3448
3449 if (run_lxc_hooks(c->name, "clone", conf, hookargs)) {
3450 ERROR("Error executing clone hook for %s", c->name);
3451 storage_put(bdev);
3452 return -1;
3453 }
3454 }
3455
3456 if (!(flags & LXC_CLONE_KEEPNAME)) {
3457 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
3458 storage_put(bdev);
3459
3460 if (ret < 0 || ret >= MAXPATHLEN)
3461 return -1;
3462 if (!file_exists(path))
3463 return 0;
3464 if (!(fout = fopen(path, "w"))) {
3465 SYSERROR("unable to open %s: ignoring", path);
3466 return 0;
3467 }
3468 if (fprintf(fout, "%s", c->name) < 0) {
3469 fclose(fout);
3470 return -1;
3471 }
3472 if (fclose(fout) < 0)
3473 return -1;
3474 } else {
3475 storage_put(bdev);
3476 }
3477
3478 return 0;
3479 }
3480
3481 static int clone_update_rootfs_wrapper(void *data)
3482 {
3483 struct clone_update_data *arg = (struct clone_update_data *) data;
3484 return clone_update_rootfs(arg);
3485 }
3486
3487 /*
3488 * We want to support:
3489 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3490 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3491
3492 -s [ implies overlay]
3493 -s -B overlay
3494 -s -B aufs
3495
3496 only rootfs gets converted (copied/snapshotted) on clone.
3497 */
3498
3499 static int create_file_dirname(char *path, struct lxc_conf *conf)
3500 {
3501 char *p = strrchr(path, '/');
3502 int ret = -1;
3503
3504 if (!p)
3505 return -1;
3506 *p = '\0';
3507 ret = do_create_container_dir(path, conf);
3508 *p = '/';
3509 return ret;
3510 }
3511
3512 static struct lxc_container *do_lxcapi_clone(struct lxc_container *c, const char *newname,
3513 const char *lxcpath, int flags,
3514 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3515 char **hookargs)
3516 {
3517 char newpath[MAXPATHLEN];
3518 int ret;
3519 struct clone_update_data data;
3520 size_t saved_unexp_len;
3521 FILE *fout;
3522 pid_t pid;
3523 int storage_copied = 0;
3524 char *origroot = NULL, *saved_unexp_conf = NULL;
3525 struct lxc_container *c2 = NULL;
3526
3527 if (!c || !do_lxcapi_is_defined(c))
3528 return NULL;
3529
3530 if (container_mem_lock(c))
3531 return NULL;
3532
3533 if (!is_stopped(c)) {
3534 ERROR("error: Original container (%s) is running", c->name);
3535 goto out;
3536 }
3537
3538 /* Make sure the container doesn't yet exist. */
3539 if (!newname)
3540 newname = c->name;
3541 if (!lxcpath)
3542 lxcpath = do_lxcapi_get_config_path(c);
3543 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", lxcpath, newname);
3544 if (ret < 0 || ret >= MAXPATHLEN) {
3545 SYSERROR("clone: failed making config pathname");
3546 goto out;
3547 }
3548
3549 if (file_exists(newpath)) {
3550 ERROR("error: clone: %s exists", newpath);
3551 goto out;
3552 }
3553
3554 ret = create_file_dirname(newpath, c->lxc_conf);
3555 if (ret < 0 && errno != EEXIST) {
3556 ERROR("Error creating container dir for %s", newpath);
3557 goto out;
3558 }
3559
3560 /* Copy the configuration. Tweak it as needed. */
3561 if (c->lxc_conf->rootfs.path) {
3562 origroot = c->lxc_conf->rootfs.path;
3563 c->lxc_conf->rootfs.path = NULL;
3564 }
3565 fout = fopen(newpath, "w");
3566 if (!fout) {
3567 SYSERROR("open %s", newpath);
3568 goto out;
3569 }
3570
3571 saved_unexp_conf = c->lxc_conf->unexpanded_config;
3572 saved_unexp_len = c->lxc_conf->unexpanded_len;
3573 c->lxc_conf->unexpanded_config = strdup(saved_unexp_conf);
3574 if (!c->lxc_conf->unexpanded_config) {
3575 ERROR("Out of memory");
3576 fclose(fout);
3577 goto out;
3578 }
3579
3580 clear_unexp_config_line(c->lxc_conf, "lxc.rootfs.path", false);
3581 write_config(fout, c->lxc_conf);
3582 fclose(fout);
3583 c->lxc_conf->rootfs.path = origroot;
3584 free(c->lxc_conf->unexpanded_config);
3585 c->lxc_conf->unexpanded_config = saved_unexp_conf;
3586 saved_unexp_conf = NULL;
3587 c->lxc_conf->unexpanded_len = saved_unexp_len;
3588
3589 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/rootfs", lxcpath, newname);
3590 if (ret < 0 || ret >= MAXPATHLEN) {
3591 SYSERROR("clone: failed making rootfs pathname");
3592 goto out;
3593 }
3594
3595 ret = mkdir(newpath, 0755);
3596 if (ret < 0) {
3597 /* For an overlay container the rootfs is considered immutable
3598 * and will not have been removed when restoring from a
3599 * snapshot.
3600 */
3601 if (errno != ENOENT &&
3602 !(flags & LXC_STORAGE_INTERNAL_OVERLAY_RESTORE)) {
3603 SYSERROR("Failed to create directory \"%s\"", newpath);
3604 goto out;
3605 }
3606 }
3607
3608 if (am_guest_unpriv()) {
3609 if (chown_mapped_root(newpath, c->lxc_conf) < 0) {
3610 ERROR("Error chowning %s to container root", newpath);
3611 goto out;
3612 }
3613 }
3614
3615 c2 = lxc_container_new(newname, lxcpath);
3616 if (!c2) {
3617 ERROR("clone: failed to create new container (%s %s)", newname,
3618 lxcpath);
3619 goto out;
3620 }
3621
3622 /* copy/snapshot rootfs's */
3623 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
3624 if (ret < 0)
3625 goto out;
3626
3627
3628 /* update utsname */
3629 if (!(flags & LXC_CLONE_KEEPNAME)) {
3630 clear_unexp_config_line(c2->lxc_conf, "lxc.utsname", false);
3631 clear_unexp_config_line(c2->lxc_conf, "lxc.uts.name", false);
3632
3633 if (!do_set_config_item_locked(c2, "lxc.uts.name", newname)) {
3634 ERROR("Error setting new hostname");
3635 goto out;
3636 }
3637 }
3638
3639 /* copy hooks */
3640 ret = copyhooks(c, c2);
3641 if (ret < 0) {
3642 ERROR("error copying hooks");
3643 goto out;
3644 }
3645
3646 if (copy_fstab(c, c2) < 0) {
3647 ERROR("error copying fstab");
3648 goto out;
3649 }
3650
3651 /* update macaddrs */
3652 if (!(flags & LXC_CLONE_KEEPMACADDR)) {
3653 if (!network_new_hwaddrs(c2->lxc_conf)) {
3654 ERROR("Error updating mac addresses");
3655 goto out;
3656 }
3657 }
3658
3659 /* Update absolute paths for overlay mount directories. */
3660 if (ovl_update_abs_paths(c2->lxc_conf, c->config_path, c->name, lxcpath, newname) < 0)
3661 goto out;
3662
3663 /* We've now successfully created c2's storage, so clear it out if we
3664 * fail after this.
3665 */
3666 storage_copied = 1;
3667
3668 if (!c2->save_config(c2, NULL))
3669 goto out;
3670
3671 if ((pid = fork()) < 0) {
3672 SYSERROR("fork");
3673 goto out;
3674 }
3675 if (pid > 0) {
3676 ret = wait_for_pid(pid);
3677 if (ret)
3678 goto out;
3679 container_mem_unlock(c);
3680 return c2;
3681 }
3682 data.c0 = c;
3683 data.c1 = c2;
3684 data.flags = flags;
3685 data.hookargs = hookargs;
3686 if (am_guest_unpriv())
3687 ret = userns_exec_full(c->lxc_conf, clone_update_rootfs_wrapper,
3688 &data, "clone_update_rootfs_wrapper");
3689 else
3690 ret = clone_update_rootfs(&data);
3691 if (ret < 0)
3692 exit(1);
3693
3694 container_mem_unlock(c);
3695 exit(0);
3696
3697 out:
3698 container_mem_unlock(c);
3699 if (c2) {
3700 if (!storage_copied)
3701 c2->lxc_conf->rootfs.path = NULL;
3702 c2->destroy(c2);
3703 lxc_container_put(c2);
3704 }
3705
3706 return NULL;
3707 }
3708
3709 static struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
3710 const char *lxcpath, int flags,
3711 const char *bdevtype, const char *bdevdata, uint64_t newsize,
3712 char **hookargs)
3713 {
3714 struct lxc_container * ret;
3715 current_config = c ? c->lxc_conf : NULL;
3716 ret = do_lxcapi_clone(c, newname, lxcpath, flags, bdevtype, bdevdata, newsize, hookargs);
3717 current_config = NULL;
3718 return ret;
3719 }
3720
3721 static bool do_lxcapi_rename(struct lxc_container *c, const char *newname)
3722 {
3723 struct lxc_storage *bdev;
3724 struct lxc_container *newc;
3725
3726 if (!c || !c->name || !c->config_path || !c->lxc_conf)
3727 return false;
3728
3729 if (has_fs_snapshots(c) || has_snapshots(c)) {
3730 ERROR("Renaming a container with snapshots is not supported");
3731 return false;
3732 }
3733 bdev = storage_init(c->lxc_conf);
3734 if (!bdev) {
3735 ERROR("Failed to find original backing store type");
3736 return false;
3737 }
3738
3739 newc = lxcapi_clone(c, newname, c->config_path, LXC_CLONE_KEEPMACADDR, NULL, bdev->type, 0, NULL);
3740 storage_put(bdev);
3741 if (!newc) {
3742 lxc_container_put(newc);
3743 return false;
3744 }
3745
3746 if (newc && lxcapi_is_defined(newc))
3747 lxc_container_put(newc);
3748
3749 if (!container_destroy(c, NULL)) {
3750 ERROR("Could not destroy existing container %s", c->name);
3751 return false;
3752 }
3753 return true;
3754 }
3755
3756 WRAP_API_1(bool, lxcapi_rename, const char *)
3757
3758 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)
3759 {
3760 int ret;
3761
3762 if (!c)
3763 return -1;
3764
3765 current_config = c->lxc_conf;
3766
3767 ret = lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
3768 current_config = NULL;
3769 return ret;
3770 }
3771
3772 static int do_lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
3773 {
3774 lxc_attach_command_t command;
3775 pid_t pid;
3776 int r;
3777
3778 if (!c)
3779 return -1;
3780
3781 command.program = (char*)program;
3782 command.argv = (char**)argv;
3783 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
3784 if (r < 0) {
3785 ERROR("ups");
3786 return r;
3787 }
3788 return lxc_wait_for_pid_status(pid);
3789 }
3790
3791 static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
3792 {
3793 int ret;
3794 current_config = c ? c->lxc_conf : NULL;
3795 ret = do_lxcapi_attach_run_wait(c, options, program, argv);
3796 current_config = NULL;
3797 return ret;
3798 }
3799
3800 static int get_next_index(const char *lxcpath, char *cname)
3801 {
3802 char *fname;
3803 struct stat sb;
3804 int i = 0, ret;
3805
3806 fname = alloca(strlen(lxcpath) + 20);
3807 while (1) {
3808 sprintf(fname, "%s/snap%d", lxcpath, i);
3809 ret = stat(fname, &sb);
3810 if (ret != 0)
3811 return i;
3812 i++;
3813 }
3814 }
3815
3816 static bool get_snappath_dir(struct lxc_container *c, char *snappath)
3817 {
3818 int ret;
3819 /*
3820 * If the old style snapshot path exists, use it
3821 * /var/lib/lxc -> /var/lib/lxcsnaps
3822 */
3823 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps", c->config_path);
3824 if (ret < 0 || ret >= MAXPATHLEN)
3825 return false;
3826 if (dir_exists(snappath)) {
3827 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
3828 if (ret < 0 || ret >= MAXPATHLEN)
3829 return false;
3830 return true;
3831 }
3832
3833 /*
3834 * Use the new style path
3835 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3836 */
3837 ret = snprintf(snappath, MAXPATHLEN, "%s/%s/snaps", c->config_path, c->name);
3838 if (ret < 0 || ret >= MAXPATHLEN)
3839 return false;
3840 return true;
3841 }
3842
3843 static int do_lxcapi_snapshot(struct lxc_container *c, const char *commentfile)
3844 {
3845 int i, flags, ret;
3846 struct lxc_container *c2;
3847 char snappath[MAXPATHLEN], newname[20];
3848
3849 if (!c || !lxcapi_is_defined(c))
3850 return -1;
3851
3852 if (!storage_can_backup(c->lxc_conf)) {
3853 ERROR("%s's backing store cannot be backed up.", c->name);
3854 ERROR("Your container must use another backing store type.");
3855 return -1;
3856 }
3857
3858 if (!get_snappath_dir(c, snappath))
3859 return -1;
3860
3861 i = get_next_index(snappath, c->name);
3862
3863 if (mkdir_p(snappath, 0755) < 0) {
3864 ERROR("Failed to create snapshot directory %s", snappath);
3865 return -1;
3866 }
3867
3868 ret = snprintf(newname, 20, "snap%d", i);
3869 if (ret < 0 || ret >= 20)
3870 return -1;
3871
3872 /*
3873 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3874 * created in the original container
3875 */
3876 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME |
3877 LXC_CLONE_KEEPBDEVTYPE | LXC_CLONE_MAYBE_SNAPSHOT;
3878 if (storage_is_dir(c->lxc_conf)) {
3879 ERROR("Snapshot of directory-backed container requested.");
3880 ERROR("Making a copy-clone. If you do want snapshots, then");
3881 ERROR("please create an aufs or overlay clone first, snapshot that");
3882 ERROR("and keep the original container pristine.");
3883 flags &= ~LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
3884 }
3885 c2 = do_lxcapi_clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
3886 if (!c2) {
3887 ERROR("clone of %s:%s failed", c->config_path, c->name);
3888 return -1;
3889 }
3890
3891 lxc_container_put(c2);
3892
3893 /* Now write down the creation time. */
3894 time_t timer;
3895 char buffer[25];
3896 struct tm* tm_info;
3897 FILE *f;
3898
3899 time(&timer);
3900 tm_info = localtime(&timer);
3901
3902 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
3903
3904 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
3905 sprintf(dfnam, "%s/%s/ts", snappath, newname);
3906 f = fopen(dfnam, "w");
3907 if (!f) {
3908 ERROR("Failed to open %s", dfnam);
3909 return -1;
3910 }
3911 if (fprintf(f, "%s", buffer) < 0) {
3912 SYSERROR("Writing timestamp");
3913 fclose(f);
3914 return -1;
3915 }
3916 ret = fclose(f);
3917 if (ret != 0) {
3918 SYSERROR("Writing timestamp");
3919 return -1;
3920 }
3921
3922 if (commentfile) {
3923 /* $p / $name / comment \0 */
3924 int len = strlen(snappath) + strlen(newname) + 10;
3925 char *path = alloca(len);
3926 sprintf(path, "%s/%s/comment", snappath, newname);
3927 return copy_file(commentfile, path) < 0 ? -1 : i;
3928 }
3929
3930 return i;
3931 }
3932
3933 WRAP_API_1(int, lxcapi_snapshot, const char *)
3934
3935 static void lxcsnap_free(struct lxc_snapshot *s)
3936 {
3937 free(s->name);
3938 free(s->comment_pathname);
3939 free(s->timestamp);
3940 free(s->lxcpath);
3941 }
3942
3943 static char *get_snapcomment_path(char* snappath, char *name)
3944 {
3945 /* $snappath/$name/comment */
3946 int ret, len = strlen(snappath) + strlen(name) + 10;
3947 char *s = malloc(len);
3948
3949 if (s) {
3950 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
3951 if (ret < 0 || ret >= len) {
3952 free(s);
3953 s = NULL;
3954 }
3955 }
3956 return s;
3957 }
3958
3959 static char *get_timestamp(char* snappath, char *name)
3960 {
3961 char path[MAXPATHLEN], *s = NULL;
3962 int ret, len;
3963 FILE *fin;
3964
3965 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
3966 if (ret < 0 || ret >= MAXPATHLEN)
3967 return NULL;
3968 fin = fopen(path, "r");
3969 if (!fin)
3970 return NULL;
3971 (void) fseek(fin, 0, SEEK_END);
3972 len = ftell(fin);
3973 (void) fseek(fin, 0, SEEK_SET);
3974 if (len > 0) {
3975 s = malloc(len+1);
3976 if (s) {
3977 s[len] = '\0';
3978 if (fread(s, 1, len, fin) != len) {
3979 SYSERROR("reading timestamp");
3980 free(s);
3981 s = NULL;
3982 }
3983 }
3984 }
3985 fclose(fin);
3986 return s;
3987 }
3988
3989 static int do_lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
3990 {
3991 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
3992 int count = 0, ret;
3993 struct dirent *direntp;
3994 struct lxc_snapshot *snaps =NULL, *nsnaps;
3995 DIR *dir;
3996
3997 if (!c || !lxcapi_is_defined(c))
3998 return -1;
3999
4000 if (!get_snappath_dir(c, snappath)) {
4001 ERROR("path name too long");
4002 return -1;
4003 }
4004 dir = opendir(snappath);
4005 if (!dir) {
4006 INFO("failed to open %s - assuming no snapshots", snappath);
4007 return 0;
4008 }
4009
4010 while ((direntp = readdir(dir))) {
4011 if (!direntp)
4012 break;
4013
4014 if (!strcmp(direntp->d_name, "."))
4015 continue;
4016
4017 if (!strcmp(direntp->d_name, ".."))
4018 continue;
4019
4020 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
4021 if (ret < 0 || ret >= MAXPATHLEN) {
4022 ERROR("pathname too long");
4023 goto out_free;
4024 }
4025 if (!file_exists(path2))
4026 continue;
4027 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
4028 if (!nsnaps) {
4029 SYSERROR("Out of memory");
4030 goto out_free;
4031 }
4032 snaps = nsnaps;
4033 snaps[count].free = lxcsnap_free;
4034 snaps[count].name = strdup(direntp->d_name);
4035 if (!snaps[count].name)
4036 goto out_free;
4037 snaps[count].lxcpath = strdup(snappath);
4038 if (!snaps[count].lxcpath) {
4039 free(snaps[count].name);
4040 goto out_free;
4041 }
4042 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
4043 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
4044 count++;
4045 }
4046
4047 if (closedir(dir))
4048 WARN("failed to close directory");
4049
4050 *ret_snaps = snaps;
4051 return count;
4052
4053 out_free:
4054 if (snaps) {
4055 int i;
4056 for (i=0; i<count; i++)
4057 lxcsnap_free(&snaps[i]);
4058 free(snaps);
4059 }
4060 if (closedir(dir))
4061 WARN("failed to close directory");
4062 return -1;
4063 }
4064
4065 WRAP_API_1(int, lxcapi_snapshot_list, struct lxc_snapshot **)
4066
4067 static bool do_lxcapi_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname)
4068 {
4069 char clonelxcpath[MAXPATHLEN];
4070 int flags = 0;
4071 struct lxc_container *snap, *rest;
4072 struct lxc_storage *bdev;
4073 bool b = false;
4074
4075 if (!c || !c->name || !c->config_path)
4076 return false;
4077
4078 if (has_fs_snapshots(c)) {
4079 ERROR("container rootfs has dependent snapshots");
4080 return false;
4081 }
4082
4083 bdev = storage_init(c->lxc_conf);
4084 if (!bdev) {
4085 ERROR("Failed to find original backing store type");
4086 return false;
4087 }
4088
4089 /* For an overlay container the rootfs is considered immutable
4090 * and cannot be removed when restoring from a snapshot. We pass this
4091 * internal flag along to communicate this to various parts of the
4092 * codebase.
4093 */
4094 if (!strcmp(bdev->type, "overlay") || !strcmp(bdev->type, "overlayfs"))
4095 bdev->flags |= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE;
4096
4097 if (!newname)
4098 newname = c->name;
4099
4100 if (!get_snappath_dir(c, clonelxcpath)) {
4101 storage_put(bdev);
4102 return false;
4103 }
4104 /* how should we lock this? */
4105
4106 snap = lxc_container_new(snapname, clonelxcpath);
4107 if (!snap || !lxcapi_is_defined(snap)) {
4108 ERROR("Could not open snapshot %s", snapname);
4109 if (snap)
4110 lxc_container_put(snap);
4111 storage_put(bdev);
4112 return false;
4113 }
4114
4115 if (!strcmp(c->name, newname)) {
4116 if (!container_destroy(c, bdev)) {
4117 ERROR("Could not destroy existing container %s", newname);
4118 lxc_container_put(snap);
4119 storage_put(bdev);
4120 return false;
4121 }
4122 }
4123
4124 if (strcmp(bdev->type, "dir") != 0 && strcmp(bdev->type, "loop") != 0)
4125 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_MAYBE_SNAPSHOT;
4126
4127 if (!strcmp(bdev->type, "overlay") || !strcmp(bdev->type, "overlayfs"))
4128 flags |= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE;
4129 rest = lxcapi_clone(snap, newname, c->config_path, flags, bdev->type,
4130 NULL, 0, NULL);
4131 storage_put(bdev);
4132 if (rest && lxcapi_is_defined(rest))
4133 b = true;
4134 if (rest)
4135 lxc_container_put(rest);
4136
4137 lxc_container_put(snap);
4138 return b;
4139 }
4140
4141 WRAP_API_2(bool, lxcapi_snapshot_restore, const char *, const char *)
4142
4143 static bool do_snapshot_destroy(const char *snapname, const char *clonelxcpath)
4144 {
4145 struct lxc_container *snap = NULL;
4146 bool bret = false;
4147
4148 snap = lxc_container_new(snapname, clonelxcpath);
4149 if (!snap) {
4150 ERROR("Could not find snapshot %s", snapname);
4151 goto err;
4152 }
4153
4154 if (!do_lxcapi_destroy(snap)) {
4155 ERROR("Could not destroy snapshot %s", snapname);
4156 goto err;
4157 }
4158 bret = true;
4159
4160 err:
4161 if (snap)
4162 lxc_container_put(snap);
4163 return bret;
4164 }
4165
4166 static bool remove_all_snapshots(const char *path)
4167 {
4168 DIR *dir;
4169 struct dirent *direntp;
4170 bool bret = true;
4171
4172 dir = opendir(path);
4173 if (!dir) {
4174 SYSERROR("opendir on snapshot path %s", path);
4175 return false;
4176 }
4177 while ((direntp = readdir(dir))) {
4178 if (!strcmp(direntp->d_name, "."))
4179 continue;
4180 if (!strcmp(direntp->d_name, ".."))
4181 continue;
4182 if (!do_snapshot_destroy(direntp->d_name, path)) {
4183 bret = false;
4184 continue;
4185 }
4186 }
4187
4188 closedir(dir);
4189
4190 if (rmdir(path))
4191 SYSERROR("Error removing directory %s", path);
4192
4193 return bret;
4194 }
4195
4196 static bool do_lxcapi_snapshot_destroy(struct lxc_container *c, const char *snapname)
4197 {
4198 char clonelxcpath[MAXPATHLEN];
4199
4200 if (!c || !c->name || !c->config_path || !snapname)
4201 return false;
4202
4203 if (!get_snappath_dir(c, clonelxcpath))
4204 return false;
4205
4206 return do_snapshot_destroy(snapname, clonelxcpath);
4207 }
4208
4209 WRAP_API_1(bool, lxcapi_snapshot_destroy, const char *)
4210
4211 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container *c)
4212 {
4213 char clonelxcpath[MAXPATHLEN];
4214
4215 if (!c || !c->name || !c->config_path)
4216 return false;
4217
4218 if (!get_snappath_dir(c, clonelxcpath))
4219 return false;
4220
4221 return remove_all_snapshots(clonelxcpath);
4222 }
4223
4224 WRAP_API(bool, lxcapi_snapshot_destroy_all)
4225
4226 static bool do_lxcapi_may_control(struct lxc_container *c)
4227 {
4228 return lxc_try_cmd(c->name, c->config_path) == 0;
4229 }
4230
4231 WRAP_API(bool, lxcapi_may_control)
4232
4233 static bool do_add_remove_node(pid_t init_pid, const char *path, bool add,
4234 struct stat *st)
4235 {
4236 int ret;
4237 char *tmp;
4238 pid_t pid;
4239 char chrootpath[MAXPATHLEN];
4240 char *directory_path = NULL;
4241
4242 pid = fork();
4243 if (pid < 0) {
4244 SYSERROR("Failed to fork()");
4245 return false;
4246 }
4247
4248 if (pid) {
4249 ret = wait_for_pid(pid);
4250 if (ret != 0) {
4251 ERROR("Failed to create device node");
4252 return false;
4253 }
4254
4255 return true;
4256 }
4257
4258 /* prepare the path */
4259 ret = snprintf(chrootpath, MAXPATHLEN, "/proc/%d/root", init_pid);
4260 if (ret < 0 || ret >= MAXPATHLEN)
4261 return false;
4262
4263 ret = chroot(chrootpath);
4264 if (ret < 0)
4265 exit(EXIT_FAILURE);
4266
4267 ret = chdir("/");
4268 if (ret < 0)
4269 exit(EXIT_FAILURE);
4270
4271 /* remove path if it exists */
4272 ret = faccessat(AT_FDCWD, path, F_OK, AT_SYMLINK_NOFOLLOW);
4273 if(ret == 0) {
4274 ret = unlink(path);
4275 if (ret < 0) {
4276 ERROR("%s - Failed to remove \"%s\"", strerror(errno), path);
4277 exit(EXIT_FAILURE);
4278 }
4279 }
4280
4281 if (!add)
4282 exit(EXIT_SUCCESS);
4283
4284 /* create any missing directories */
4285 tmp = strdup(path);
4286 if (!tmp)
4287 exit(EXIT_FAILURE);
4288
4289 directory_path = dirname(tmp);
4290 ret = mkdir_p(directory_path, 0755);
4291 if (ret < 0 && errno != EEXIST) {
4292 ERROR("%s - Failed to create path \"%s\"", strerror(errno), directory_path);
4293 free(tmp);
4294 exit(EXIT_FAILURE);
4295 }
4296
4297 /* create the device node */
4298 ret = mknod(path, st->st_mode, st->st_rdev);
4299 free(tmp);
4300 if (ret < 0) {
4301 ERROR("%s - Failed to create device node at \"%s\"", strerror(errno), path);
4302 exit(EXIT_FAILURE);
4303 }
4304
4305 exit(EXIT_SUCCESS);
4306 }
4307
4308 static bool add_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path, bool add)
4309 {
4310 int ret;
4311 struct stat st;
4312 char value[MAX_BUFFER];
4313 const char *p;
4314
4315 /* make sure container is running */
4316 if (!do_lxcapi_is_running(c)) {
4317 ERROR("container is not running");
4318 return false;
4319 }
4320
4321 /* use src_path if dest_path is NULL otherwise use dest_path */
4322 p = dest_path ? dest_path : src_path;
4323
4324 /* make sure we can access p */
4325 if(access(p, F_OK) < 0 || stat(p, &st) < 0)
4326 return false;
4327
4328 /* continue if path is character device or block device */
4329 if (S_ISCHR(st.st_mode))
4330 ret = snprintf(value, MAX_BUFFER, "c %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
4331 else if (S_ISBLK(st.st_mode))
4332 ret = snprintf(value, MAX_BUFFER, "b %d:%d rwm", major(st.st_rdev), minor(st.st_rdev));
4333 else
4334 return false;
4335
4336 /* check snprintf return code */
4337 if (ret < 0 || ret >= MAX_BUFFER)
4338 return false;
4339
4340 if (!do_add_remove_node(do_lxcapi_init_pid(c), p, add, &st))
4341 return false;
4342
4343 /* add or remove device to/from cgroup access list */
4344 if (add) {
4345 if (!do_lxcapi_set_cgroup_item(c, "devices.allow", value)) {
4346 ERROR("set_cgroup_item failed while adding the device node");
4347 return false;
4348 }
4349 } else {
4350 if (!do_lxcapi_set_cgroup_item(c, "devices.deny", value)) {
4351 ERROR("set_cgroup_item failed while removing the device node");
4352 return false;
4353 }
4354 }
4355
4356 return true;
4357 }
4358
4359 static bool do_lxcapi_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
4360 {
4361 // cannot mknod if we're not privileged wrt init_user_ns
4362 if (am_host_unpriv()) {
4363 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
4364 return false;
4365 }
4366 return add_remove_device_node(c, src_path, dest_path, true);
4367 }
4368
4369 WRAP_API_2(bool, lxcapi_add_device_node, const char *, const char *)
4370
4371 static bool do_lxcapi_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path)
4372 {
4373 if (am_guest_unpriv()) {
4374 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
4375 return false;
4376 }
4377 return add_remove_device_node(c, src_path, dest_path, false);
4378 }
4379
4380 WRAP_API_2(bool, lxcapi_remove_device_node, const char *, const char *)
4381
4382 static bool do_lxcapi_attach_interface(struct lxc_container *c,
4383 const char *ifname,
4384 const char *dst_ifname)
4385 {
4386 pid_t init_pid;
4387 int ret = 0;
4388
4389 if (am_guest_unpriv()) {
4390 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
4391 return false;
4392 }
4393
4394 if (!ifname) {
4395 ERROR("No source interface name given");
4396 return false;
4397 }
4398
4399 ret = lxc_netdev_isup(ifname);
4400 if (ret > 0) {
4401 /* netdev of ifname is up. */
4402 ret = lxc_netdev_down(ifname);
4403 if (ret)
4404 goto err;
4405 }
4406
4407 init_pid = do_lxcapi_init_pid(c);
4408 ret = lxc_netdev_move_by_name(ifname, init_pid, dst_ifname);
4409 if (ret)
4410 goto err;
4411
4412 INFO("Moved network device \"%s\" to network namespace of %d", ifname, init_pid);
4413 return true;
4414
4415 err:
4416 return false;
4417 }
4418
4419 WRAP_API_2(bool, lxcapi_attach_interface, const char *, const char *)
4420
4421 static bool do_lxcapi_detach_interface(struct lxc_container *c,
4422 const char *ifname,
4423 const char *dst_ifname)
4424 {
4425 int ret;
4426 pid_t pid, pid_outside;
4427
4428 /*
4429 * TODO - if this is a physical device, then we need am_host_unpriv.
4430 * But for other types guest privilege suffices.
4431 */
4432 if (am_guest_unpriv()) {
4433 ERROR(NOT_SUPPORTED_ERROR, __FUNCTION__);
4434 return false;
4435 }
4436
4437 if (!ifname) {
4438 ERROR("No source interface name given");
4439 return false;
4440 }
4441
4442 pid_outside = lxc_raw_getpid();
4443 pid = fork();
4444 if (pid < 0) {
4445 ERROR("Failed to fork");
4446 return false;
4447 }
4448
4449 if (pid == 0) { /* child */
4450 pid_t init_pid;
4451
4452 init_pid = do_lxcapi_init_pid(c);
4453 if (!switch_to_ns(init_pid, "net")) {
4454 ERROR("Failed to enter network namespace");
4455 exit(EXIT_FAILURE);
4456 }
4457
4458 ret = lxc_netdev_isup(ifname);
4459 if (ret < 0) {
4460 ERROR("Failed to determine whether network device \"%s\" is up", ifname);
4461 exit(EXIT_FAILURE);
4462 }
4463
4464 /* netdev of ifname is up. */
4465 if (ret) {
4466 ret = lxc_netdev_down(ifname);
4467 if (ret) {
4468 ERROR("Failed to set network device \"%s\" down", ifname);
4469 exit(EXIT_FAILURE);
4470 }
4471 }
4472
4473 ret = lxc_netdev_move_by_name(ifname, pid_outside, dst_ifname);
4474 /* -EINVAL means there is no netdev named as ifname. */
4475 if (ret < 0) {
4476 if (ret == -EINVAL)
4477 ERROR("Network device \"%s\" not found", ifname);
4478 else
4479 ERROR("Failed to remove network device \"%s\"", ifname);
4480 exit(EXIT_FAILURE);
4481 }
4482
4483 exit(EXIT_SUCCESS);
4484 }
4485
4486 ret = wait_for_pid(pid);
4487 if (ret != 0)
4488 return false;
4489
4490 INFO("Moved network device \"%s\" to network namespace of %d", ifname, pid_outside);
4491 return true;
4492 }
4493
4494 WRAP_API_2(bool, lxcapi_detach_interface, const char *, const char *)
4495
4496 static int do_lxcapi_migrate(struct lxc_container *c, unsigned int cmd,
4497 struct migrate_opts *opts, unsigned int size)
4498 {
4499 int ret = -1;
4500 struct migrate_opts *valid_opts = opts;
4501 uint64_t features_to_check = 0;
4502
4503 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4504 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4505 * to do anything special.
4506 */
4507 if (size > sizeof(*opts)) {
4508 unsigned char *addr;
4509 unsigned char *end;
4510
4511 addr = (void *)opts + sizeof(*opts);
4512 end = (void *)opts + size;
4513 for (; addr < end; addr++) {
4514 if (*addr) {
4515 return -E2BIG;
4516 }
4517 }
4518 }
4519
4520 /* If the caller has a smaller struct, let's zero out the end for them
4521 * so we don't accidentally use bits of it that they didn't know about
4522 * to initialize.
4523 */
4524 if (size < sizeof(*opts)) {
4525 valid_opts = malloc(sizeof(*opts));
4526 if (!valid_opts)
4527 return -ENOMEM;
4528
4529 memset(valid_opts, 0, sizeof(*opts));
4530 memcpy(valid_opts, opts, size);
4531 }
4532
4533 switch (cmd) {
4534 case MIGRATE_PRE_DUMP:
4535 if (!do_lxcapi_is_running(c)) {
4536 ERROR("container is not running");
4537 goto on_error;
4538 }
4539 ret = !__criu_pre_dump(c, valid_opts);
4540 break;
4541 case MIGRATE_DUMP:
4542 if (!do_lxcapi_is_running(c)) {
4543 ERROR("container is not running");
4544 goto on_error;
4545 }
4546 ret = !__criu_dump(c, valid_opts);
4547 break;
4548 case MIGRATE_RESTORE:
4549 if (do_lxcapi_is_running(c)) {
4550 ERROR("container is already running");
4551 goto on_error;
4552 }
4553 ret = !__criu_restore(c, valid_opts);
4554 break;
4555 case MIGRATE_FEATURE_CHECK:
4556 features_to_check = valid_opts->features_to_check;
4557 ret = !__criu_check_feature(&features_to_check);
4558 if (ret) {
4559 /* Something went wrong. Let's let the caller
4560 * know which feature checks failed. */
4561 valid_opts->features_to_check = features_to_check;
4562 }
4563 break;
4564 default:
4565 ERROR("invalid migrate command %u", cmd);
4566 ret = -EINVAL;
4567 }
4568
4569 on_error:
4570 if (size < sizeof(*opts))
4571 free(valid_opts);
4572
4573 return ret;
4574 }
4575
4576 WRAP_API_3(int, lxcapi_migrate, unsigned int, struct migrate_opts *, unsigned int)
4577
4578 static bool do_lxcapi_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose)
4579 {
4580 struct migrate_opts opts;
4581
4582 memset(&opts, 0, sizeof(opts));
4583
4584 opts.directory = directory;
4585 opts.stop = stop;
4586 opts.verbose = verbose;
4587
4588 return !do_lxcapi_migrate(c, MIGRATE_DUMP, &opts, sizeof(opts));
4589 }
4590
4591 WRAP_API_3(bool, lxcapi_checkpoint, char *, bool, bool)
4592
4593 static bool do_lxcapi_restore(struct lxc_container *c, char *directory, bool verbose)
4594 {
4595 struct migrate_opts opts;
4596
4597 memset(&opts, 0, sizeof(opts));
4598
4599 opts.directory = directory;
4600 opts.verbose = verbose;
4601
4602 return !do_lxcapi_migrate(c, MIGRATE_RESTORE, &opts, sizeof(opts));
4603 }
4604
4605 WRAP_API_2(bool, lxcapi_restore, char *, bool)
4606
4607 static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
4608 {
4609 va_list ap;
4610 const char **argv;
4611 int ret;
4612
4613 if (!c)
4614 return -1;
4615
4616 current_config = c->lxc_conf;
4617
4618 va_start(ap, arg);
4619 argv = lxc_va_arg_list_to_argv_const(ap, 1);
4620 va_end(ap);
4621
4622 if (!argv) {
4623 ERROR("Memory allocation error.");
4624 ret = -1;
4625 goto out;
4626 }
4627 argv[0] = arg;
4628
4629 ret = do_lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
4630 free((void*)argv);
4631 out:
4632 current_config = NULL;
4633 return ret;
4634 }
4635
4636 struct lxc_container *lxc_container_new(const char *name, const char *configpath)
4637 {
4638 struct lxc_container *c;
4639
4640 if (!name)
4641 return NULL;
4642
4643 c = malloc(sizeof(*c));
4644 if (!c) {
4645 fprintf(stderr, "Failed to allocate memory for %s\n", name);
4646 return NULL;
4647 }
4648 memset(c, 0, sizeof(*c));
4649
4650 if (configpath)
4651 c->config_path = strdup(configpath);
4652 else
4653 c->config_path = strdup(lxc_global_config_value("lxc.lxcpath"));
4654
4655 if (!c->config_path) {
4656 fprintf(stderr, "Failed to allocate memory for %s\n", name);
4657 goto err;
4658 }
4659
4660 remove_trailing_slashes(c->config_path);
4661 c->name = malloc(strlen(name)+1);
4662 if (!c->name) {
4663 fprintf(stderr, "Failed to allocate memory for %s\n", name);
4664 goto err;
4665 }
4666 strcpy(c->name, name);
4667
4668 c->numthreads = 1;
4669 c->slock = lxc_newlock(c->config_path, name);
4670 if (!c->slock) {
4671 fprintf(stderr, "Failed to create lock for %s\n", name);
4672 goto err;
4673 }
4674
4675 c->privlock = lxc_newlock(NULL, NULL);
4676 if (!c->privlock) {
4677 fprintf(stderr, "Failed to create private lock for %s\n", name);
4678 goto err;
4679 }
4680
4681 if (!set_config_filename(c)) {
4682 fprintf(stderr, "Failed to create config file name for %s\n", name);
4683 goto err;
4684 }
4685
4686 if (file_exists(c->configfile) && !lxcapi_load_config(c, NULL)) {
4687 fprintf(stderr, "Failed to load config for %s\n", name);
4688 goto err;
4689 }
4690
4691 if (ongoing_create(c) == 2) {
4692 ERROR("Failed to complete container creation for %s", c->name);
4693 container_destroy(c, NULL);
4694 lxcapi_clear_config(c);
4695 }
4696 c->daemonize = true;
4697 c->pidfile = NULL;
4698
4699 /* Assign the member functions. */
4700 c->is_defined = lxcapi_is_defined;
4701 c->state = lxcapi_state;
4702 c->is_running = lxcapi_is_running;
4703 c->freeze = lxcapi_freeze;
4704 c->unfreeze = lxcapi_unfreeze;
4705 c->console = lxcapi_console;
4706 c->console_getfd = lxcapi_console_getfd;
4707 c->init_pid = lxcapi_init_pid;
4708 c->load_config = lxcapi_load_config;
4709 c->want_daemonize = lxcapi_want_daemonize;
4710 c->want_close_all_fds = lxcapi_want_close_all_fds;
4711 c->start = lxcapi_start;
4712 c->startl = lxcapi_startl;
4713 c->stop = lxcapi_stop;
4714 c->config_file_name = lxcapi_config_file_name;
4715 c->wait = lxcapi_wait;
4716 c->set_config_item = lxcapi_set_config_item;
4717 c->destroy = lxcapi_destroy;
4718 c->destroy_with_snapshots = lxcapi_destroy_with_snapshots;
4719 c->rename = lxcapi_rename;
4720 c->save_config = lxcapi_save_config;
4721 c->get_keys = lxcapi_get_keys;
4722 c->create = lxcapi_create;
4723 c->createl = lxcapi_createl;
4724 c->shutdown = lxcapi_shutdown;
4725 c->reboot = lxcapi_reboot;
4726 c->reboot2 = lxcapi_reboot2;
4727 c->clear_config = lxcapi_clear_config;
4728 c->clear_config_item = lxcapi_clear_config_item;
4729 c->get_config_item = lxcapi_get_config_item;
4730 c->get_running_config_item = lxcapi_get_running_config_item;
4731 c->get_cgroup_item = lxcapi_get_cgroup_item;
4732 c->set_cgroup_item = lxcapi_set_cgroup_item;
4733 c->get_config_path = lxcapi_get_config_path;
4734 c->set_config_path = lxcapi_set_config_path;
4735 c->clone = lxcapi_clone;
4736 c->get_interfaces = lxcapi_get_interfaces;
4737 c->get_ips = lxcapi_get_ips;
4738 c->attach = lxcapi_attach;
4739 c->attach_run_wait = lxcapi_attach_run_wait;
4740 c->attach_run_waitl = lxcapi_attach_run_waitl;
4741 c->snapshot = lxcapi_snapshot;
4742 c->snapshot_list = lxcapi_snapshot_list;
4743 c->snapshot_restore = lxcapi_snapshot_restore;
4744 c->snapshot_destroy = lxcapi_snapshot_destroy;
4745 c->snapshot_destroy_all = lxcapi_snapshot_destroy_all;
4746 c->may_control = lxcapi_may_control;
4747 c->add_device_node = lxcapi_add_device_node;
4748 c->remove_device_node = lxcapi_remove_device_node;
4749 c->attach_interface = lxcapi_attach_interface;
4750 c->detach_interface = lxcapi_detach_interface;
4751 c->checkpoint = lxcapi_checkpoint;
4752 c->restore = lxcapi_restore;
4753 c->migrate = lxcapi_migrate;
4754 c->console_log = lxcapi_console_log;
4755
4756 return c;
4757
4758 err:
4759 lxc_container_free(c);
4760 return NULL;
4761 }
4762
4763 int lxc_get_wait_states(const char **states)
4764 {
4765 int i;
4766
4767 if (states)
4768 for (i=0; i<MAX_STATE; i++)
4769 states[i] = lxc_state2str(i);
4770 return MAX_STATE;
4771 }
4772
4773 /*
4774 * These next two could probably be done smarter with reusing a common function
4775 * with different iterators and tests...
4776 */
4777 int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
4778 {
4779 DIR *dir;
4780 int i, cfound = 0, nfound = 0;
4781 struct dirent *direntp;
4782 struct lxc_container *c;
4783
4784 if (!lxcpath)
4785 lxcpath = lxc_global_config_value("lxc.lxcpath");
4786
4787 dir = opendir(lxcpath);
4788 if (!dir) {
4789 SYSERROR("opendir on lxcpath");
4790 return -1;
4791 }
4792
4793 if (cret)
4794 *cret = NULL;
4795 if (names)
4796 *names = NULL;
4797
4798 while ((direntp = readdir(dir))) {
4799 if (!direntp)
4800 break;
4801
4802 /* Ignore '.', '..' and any hidden directory. */
4803 if (!strncmp(direntp->d_name, ".", 1))
4804 continue;
4805
4806 if (!config_file_exists(lxcpath, direntp->d_name))
4807 continue;
4808
4809 if (names) {
4810 if (!add_to_array(names, direntp->d_name, cfound))
4811 goto free_bad;
4812 }
4813 cfound++;
4814
4815 if (!cret) {
4816 nfound++;
4817 continue;
4818 }
4819
4820 c = lxc_container_new(direntp->d_name, lxcpath);
4821 if (!c) {
4822 INFO("Container %s:%s has a config but could not be loaded",
4823 lxcpath, direntp->d_name);
4824 if (names)
4825 if(!remove_from_array(names, direntp->d_name, cfound--))
4826 goto free_bad;
4827 continue;
4828 }
4829 if (!do_lxcapi_is_defined(c)) {
4830 INFO("Container %s:%s has a config but is not defined",
4831 lxcpath, direntp->d_name);
4832 if (names)
4833 if(!remove_from_array(names, direntp->d_name, cfound--))
4834 goto free_bad;
4835 lxc_container_put(c);
4836 continue;
4837 }
4838
4839 if (!add_to_clist(cret, c, nfound, true)) {
4840 lxc_container_put(c);
4841 goto free_bad;
4842 }
4843 nfound++;
4844 }
4845
4846 closedir(dir);
4847 return nfound;
4848
4849 free_bad:
4850 if (names && *names) {
4851 for (i=0; i<cfound; i++)
4852 free((*names)[i]);
4853 free(*names);
4854 }
4855 if (cret && *cret) {
4856 for (i=0; i<nfound; i++)
4857 lxc_container_put((*cret)[i]);
4858 free(*cret);
4859 }
4860 closedir(dir);
4861 return -1;
4862 }
4863
4864 int list_active_containers(const char *lxcpath, char ***nret,
4865 struct lxc_container ***cret)
4866 {
4867 int i, ret = -1, cret_cnt = 0, ct_name_cnt = 0;
4868 int lxcpath_len;
4869 char *line = NULL;
4870 char **ct_name = NULL;
4871 size_t len = 0;
4872 struct lxc_container *c = NULL;
4873 bool is_hashed;
4874
4875 if (!lxcpath)
4876 lxcpath = lxc_global_config_value("lxc.lxcpath");
4877 lxcpath_len = strlen(lxcpath);
4878
4879 if (cret)
4880 *cret = NULL;
4881 if (nret)
4882 *nret = NULL;
4883
4884 FILE *f = fopen("/proc/net/unix", "r");
4885 if (!f)
4886 return -1;
4887
4888 while (getline(&line, &len, f) != -1) {
4889
4890 char *p = strrchr(line, ' '), *p2;
4891 if (!p)
4892 continue;
4893 p++;
4894 if (*p != 0x40)
4895 continue;
4896 p++;
4897
4898 is_hashed = false;
4899 if (strncmp(p, lxcpath, lxcpath_len) == 0) {
4900 p += lxcpath_len;
4901 } else if (strncmp(p, "lxc/", 4) == 0) {
4902 p += 4;
4903 is_hashed = true;
4904 } else {
4905 continue;
4906 }
4907
4908 while (*p == '/')
4909 p++;
4910
4911 /* Now p is the start of lxc_name. */
4912 p2 = strchr(p, '/');
4913 if (!p2 || strncmp(p2, "/command", 8) != 0)
4914 continue;
4915 *p2 = '\0';
4916
4917 if (is_hashed) {
4918 char *recvpath = lxc_cmd_get_lxcpath(p);
4919 if (!recvpath)
4920 continue;
4921 if (strncmp(lxcpath, recvpath, lxcpath_len) != 0)
4922 continue;
4923 p = lxc_cmd_get_name(p);
4924 if (!p)
4925 continue;
4926 }
4927
4928 if (array_contains(&ct_name, p, ct_name_cnt))
4929 continue;
4930
4931 if (!add_to_array(&ct_name, p, ct_name_cnt))
4932 goto free_cret_list;
4933
4934 ct_name_cnt++;
4935
4936 if (!cret)
4937 continue;
4938
4939 c = lxc_container_new(p, lxcpath);
4940 if (!c) {
4941 INFO("Container %s:%s is running but could not be loaded",
4942 lxcpath, p);
4943 remove_from_array(&ct_name, p, ct_name_cnt--);
4944 continue;
4945 }
4946
4947 /*
4948 * If this is an anonymous container, then is_defined *can*
4949 * return false. So we don't do that check. Count on the
4950 * fact that the command socket exists.
4951 */
4952
4953 if (!add_to_clist(cret, c, cret_cnt, true)) {
4954 lxc_container_put(c);
4955 goto free_cret_list;
4956 }
4957 cret_cnt++;
4958 }
4959
4960 if (nret && cret && cret_cnt != ct_name_cnt) {
4961 if (c)
4962 lxc_container_put(c);
4963 goto free_cret_list;
4964 }
4965
4966 ret = ct_name_cnt;
4967 if (nret)
4968 *nret = ct_name;
4969 else
4970 goto free_ct_name;
4971 goto out;
4972
4973 free_cret_list:
4974 if (cret && *cret) {
4975 for (i = 0; i < cret_cnt; i++)
4976 lxc_container_put((*cret)[i]);
4977 free(*cret);
4978 }
4979
4980 free_ct_name:
4981 if (ct_name) {
4982 for (i = 0; i < ct_name_cnt; i++)
4983 free(ct_name[i]);
4984 free(ct_name);
4985 }
4986
4987 out:
4988 free(line);
4989
4990 fclose(f);
4991 return ret;
4992 }
4993
4994 int list_all_containers(const char *lxcpath, char ***nret,
4995 struct lxc_container ***cret)
4996 {
4997 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
4998 char **active_name;
4999 char **ct_name;
5000 struct lxc_container **ct_list = NULL;
5001
5002 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
5003 if (ct_cnt < 0)
5004 return ct_cnt;
5005
5006 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
5007 if (active_cnt < 0) {
5008 ret = active_cnt;
5009 goto free_ct_name;
5010 }
5011
5012 for (i = 0; i < active_cnt; i++) {
5013 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
5014 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
5015 ret = -1;
5016 goto free_active_name;
5017 }
5018 ct_cnt++;
5019 }
5020 free(active_name[i]);
5021 active_name[i] = NULL;
5022 }
5023 free(active_name);
5024 active_name = NULL;
5025 active_cnt = 0;
5026
5027 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
5028 struct lxc_container *c;
5029
5030 c = lxc_container_new(ct_name[i], lxcpath);
5031 if (!c) {
5032 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
5033 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
5034 continue;
5035 }
5036
5037 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
5038 lxc_container_put(c);
5039 ret = -1;
5040 goto free_ct_list;
5041 }
5042 ct_list_cnt++;
5043 }
5044
5045 if (cret)
5046 *cret = ct_list;
5047
5048 if (nret)
5049 *nret = ct_name;
5050 else {
5051 ret = ct_cnt;
5052 goto free_ct_name;
5053 }
5054 return ct_cnt;
5055
5056 free_ct_list:
5057 for (i = 0; i < ct_list_cnt; i++) {
5058 lxc_container_put(ct_list[i]);
5059 }
5060 free(ct_list);
5061
5062 free_active_name:
5063 for (i = 0; i < active_cnt; i++) {
5064 free(active_name[i]);
5065 }
5066 free(active_name);
5067
5068 free_ct_name:
5069 for (i = 0; i < ct_cnt; i++) {
5070 free(ct_name[i]);
5071 }
5072 free(ct_name);
5073 return ret;
5074 }
5075
5076 bool lxc_config_item_is_supported(const char *key)
5077 {
5078 return !!lxc_get_config(key);
5079 }