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