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