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