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