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