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