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