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