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