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