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