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