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