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