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