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