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