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