]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
add list_all_containers(), returns defined and active containers
[mirror_lxc.git] / src / lxc / lxccontainer.c
CommitLineData
72d0e1cb
SG
1/* liblxcapi
2 *
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
5 *
d75462e4
SH
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
72d0e1cb
SG
19 */
20
9be53773 21#define _GNU_SOURCE
a0e93eeb 22#include <stdarg.h>
71454076 23#include <pthread.h>
9be53773
SH
24#include <unistd.h>
25#include <sys/types.h>
26#include <sys/wait.h>
4de2791f 27#include <sys/mount.h>
9be53773 28#include <errno.h>
93dc5327 29#include <fcntl.h>
9be53773 30#include <sched.h>
f5dd1d53 31#include <dirent.h>
9be53773 32#include "config.h"
72d0e1cb
SG
33#include "lxc.h"
34#include "state.h"
948955a2 35#include <lxc/lxccontainer.h>
72d0e1cb 36#include "conf.h"
72d0e1cb 37#include "confile.h"
b5159817 38#include "console.h"
72d0e1cb
SG
39#include "cgroup.h"
40#include "commands.h"
b6b918a1 41#include "version.h"
72d0e1cb 42#include "log.h"
9be53773 43#include "bdev.h"
6a44839f 44#include "utils.h"
a0e93eeb 45#include "attach.h"
2a59a681 46#include <lxc/utils.h>
e51d4895 47#include <lxc/monitor.h>
e768f9c0 48#include <lxc/namespace.h>
9c83a661 49#include <sched.h>
9c83a661 50#include <arpa/inet.h>
4ba0d9af
SG
51
52#if HAVE_IFADDRS_H
9c83a661 53#include <ifaddrs.h>
4ba0d9af
SG
54#else
55#include <../include/ifaddrs.h>
56#endif
72d0e1cb 57
dfb31b25
SH
58#ifndef HAVE_GETLINE
59#ifdef HAVE_FGETLN
60#include <../include/getline.h>
61#endif
62#endif
63
72d0e1cb
SG
64lxc_log_define(lxc_container, lxc);
65
3e625e2d
SH
66static bool file_exists(char *f)
67{
68 struct stat statbuf;
69
70 return stat(f, &statbuf) == 0;
71}
72
a41f104b
SH
73static bool config_file_exists(const char *lxcpath, const char *cname)
74{
75 /* $lxcpath + '/' + $cname + '/config' + \0 */
76 int ret, len = strlen(lxcpath) + strlen(cname) + 9;
77 char *fname = alloca(len);
78
79 ret = snprintf(fname, len, "%s/%s/config", lxcpath, cname);
80 if (ret < 0 || ret >= len)
81 return false;
82
83 return file_exists(fname);
84}
85
3e625e2d
SH
86/*
87 * A few functions to help detect when a container creation failed.
88 * If a container creation was killed partway through, then trying
89 * to actually start that container could harm the host. We detect
90 * this by creating a 'partial' file under the container directory,
91 * and keeping an advisory lock. When container creation completes,
92 * we remove that file. When we load or try to start a container, if
93 * we find that file, without a flock, we remove the container.
94 */
95int ongoing_create(struct lxc_container *c)
96{
97 int len = strlen(c->config_path) + strlen(c->name) + 10;
98 char *path = alloca(len);
99 int fd, ret;
93dc5327
SH
100 struct flock lk;
101
3e625e2d
SH
102 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
103 if (ret < 0 || ret >= len) {
104 ERROR("Error writing partial pathname");
105 return -1;
106 }
107
108 if (!file_exists(path))
109 return 0;
025ed0f3
SH
110 process_lock();
111 fd = open(path, O_RDWR);
112 process_unlock();
113 if (fd < 0) {
3e625e2d
SH
114 // give benefit of the doubt
115 SYSERROR("Error opening partial file");
3e625e2d
SH
116 return 0;
117 }
93dc5327
SH
118 lk.l_type = F_WRLCK;
119 lk.l_whence = SEEK_SET;
120 lk.l_start = 0;
121 lk.l_len = 0;
122 lk.l_pid = -1;
123 if (fcntl(fd, F_GETLK, &lk) == 0 && lk.l_pid != -1) {
3e625e2d 124 // create is still ongoing
025ed0f3 125 process_lock();
3e625e2d
SH
126 close(fd);
127 process_unlock();
128 return 1;
129 }
130 // create completed but partial is still there.
025ed0f3 131 process_lock();
3e625e2d
SH
132 close(fd);
133 process_unlock();
134 return 2;
135}
136
137int create_partial(struct lxc_container *c)
138{
139 // $lxcpath + '/' + $name + '/partial' + \0
140 int len = strlen(c->config_path) + strlen(c->name) + 10;
141 char *path = alloca(len);
142 int fd, ret;
93dc5327
SH
143 struct flock lk;
144
3e625e2d
SH
145 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
146 if (ret < 0 || ret >= len) {
147 ERROR("Error writing partial pathname");
148 return -1;
149 }
025ed0f3 150 process_lock();
93dc5327 151 if ((fd=open(path, O_RDWR | O_CREAT | O_EXCL, 0755)) < 0) {
3e625e2d
SH
152 SYSERROR("Erorr creating partial file");
153 process_unlock();
154 return -1;
155 }
93dc5327
SH
156 lk.l_type = F_WRLCK;
157 lk.l_whence = SEEK_SET;
158 lk.l_start = 0;
159 lk.l_len = 0;
160 if (fcntl(fd, F_SETLKW, &lk) < 0) {
3e625e2d
SH
161 SYSERROR("Error locking partial file %s", path);
162 close(fd);
163 process_unlock();
164 return -1;
165 }
166 process_unlock();
167
168 return fd;
169}
170
171void remove_partial(struct lxc_container *c, int fd)
172{
173 // $lxcpath + '/' + $name + '/partial' + \0
174 int len = strlen(c->config_path) + strlen(c->name) + 10;
175 char *path = alloca(len);
176 int ret;
177
025ed0f3 178 process_lock();
3e625e2d 179 close(fd);
025ed0f3 180 process_unlock();
3e625e2d
SH
181 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
182 if (ret < 0 || ret >= len) {
183 ERROR("Error writing partial pathname");
184 return;
185 }
3e625e2d
SH
186 if (unlink(path) < 0)
187 SYSERROR("Error unlink partial file %s", path);
3e625e2d
SH
188}
189
72d0e1cb 190/* LOCKING
3bc449ed
SH
191 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
192 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
193 * container configuration file.
194 * The container_disk_lock also takes the container_mem_lock.
195 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
72d0e1cb
SG
196 * NOTHING mutexes two independent programs with their own struct
197 * lxc_container for the same c->name, between API calls. For instance,
198 * c->config_read(); c->start(); Between those calls, data on disk
199 * could change (which shouldn't bother the caller unless for instance
200 * the rootfs get moved). c->config_read(); update; c->config_write();
201 * Two such updaters could race. The callers should therefore check their
202 * results. Trying to prevent that would necessarily expose us to deadlocks
203 * due to hung callers. So I prefer to keep the locks only within our own
204 * functions, not across functions.
205 *
3bc449ed 206 * If you're going to clone while holding a lxccontainer, increment
72d0e1cb
SG
207 * c->numthreads (under privlock) before forking. When deleting,
208 * decrement numthreads under privlock, then if it hits 0 you can delete.
209 * Do not ever use a lxccontainer whose numthreads you did not bump.
210 */
211
212static void lxc_container_free(struct lxc_container *c)
213{
214 if (!c)
215 return;
216
217 if (c->configfile) {
218 free(c->configfile);
219 c->configfile = NULL;
220 }
221 if (c->error_string) {
222 free(c->error_string);
223 c->error_string = NULL;
224 }
d95db067 225 if (c->slock) {
df271a59 226 lxc_putlock(c->slock);
d95db067
DE
227 c->slock = NULL;
228 }
72d0e1cb 229 if (c->privlock) {
df271a59 230 lxc_putlock(c->privlock);
72d0e1cb
SG
231 c->privlock = NULL;
232 }
233 if (c->name) {
234 free(c->name);
235 c->name = NULL;
236 }
d95db067
DE
237 if (c->lxc_conf) {
238 lxc_conf_free(c->lxc_conf);
239 c->lxc_conf = NULL;
240 }
2a59a681
SH
241 if (c->config_path) {
242 free(c->config_path);
243 c->config_path = NULL;
244 }
72d0e1cb
SG
245 free(c);
246}
247
43d1aa34
SH
248/*
249 * Consider the following case:
250freer | racing get()er
251==================================================================
252lxc_container_put() | lxc_container_get()
253\ lxclock(c->privlock) | c->numthreads < 1? (no)
254\ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
255\ lxcunlock() | \
256\ lxc_container_free() | \ lxclock() returns
257 | \ c->numthreads < 1 -> return 0
258\ \ (free stuff) |
259\ \ sem_destroy(privlock) |
260
261 * When the get()er checks numthreads the first time, one of the following
262 * is true:
263 * 1. freer has set numthreads = 0. get() returns 0
264 * 2. freer is between lxclock and setting numthreads to 0. get()er will
265 * sem_wait on privlock, get lxclock after freer() drops it, then see
266 * numthreads is 0 and exit without touching lxclock again..
267 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
268 * will see --numthreads = 1 and not call lxc_container_free().
269*/
270
72d0e1cb
SG
271int lxc_container_get(struct lxc_container *c)
272{
273 if (!c)
274 return 0;
275
43d1aa34
SH
276 // if someone else has already started freeing the container, don't
277 // try to take the lock, which may be invalid
278 if (c->numthreads < 1)
279 return 0;
280
5cee8c50 281 if (container_mem_lock(c))
72d0e1cb
SG
282 return 0;
283 if (c->numthreads < 1) {
284 // bail without trying to unlock, bc the privlock is now probably
285 // in freed memory
286 return 0;
287 }
288 c->numthreads++;
5cee8c50 289 container_mem_unlock(c);
72d0e1cb
SG
290 return 1;
291}
292
293int lxc_container_put(struct lxc_container *c)
294{
295 if (!c)
296 return -1;
5cee8c50 297 if (container_mem_lock(c))
72d0e1cb
SG
298 return -1;
299 if (--c->numthreads < 1) {
5cee8c50 300 container_mem_unlock(c);
72d0e1cb
SG
301 lxc_container_free(c);
302 return 1;
303 }
5cee8c50 304 container_mem_unlock(c);
72d0e1cb
SG
305 return 0;
306}
307
72d0e1cb
SG
308static bool lxcapi_is_defined(struct lxc_container *c)
309{
310 struct stat statbuf;
311 bool ret = false;
312 int statret;
313
314 if (!c)
315 return false;
316
5cee8c50 317 if (container_mem_lock(c))
72d0e1cb
SG
318 return false;
319 if (!c->configfile)
320 goto out;
321 statret = stat(c->configfile, &statbuf);
322 if (statret != 0)
323 goto out;
324 ret = true;
325
326out:
5cee8c50 327 container_mem_unlock(c);
72d0e1cb
SG
328 return ret;
329}
330
331static const char *lxcapi_state(struct lxc_container *c)
332{
72d0e1cb
SG
333 lxc_state_t s;
334
335 if (!c)
336 return NULL;
13f5be62 337 s = lxc_getstate(c->name, c->config_path);
39dc698c 338 return lxc_state2str(s);
72d0e1cb
SG
339}
340
39dc698c 341static bool is_stopped(struct lxc_container *c)
794dd120
SH
342{
343 lxc_state_t s;
13f5be62 344 s = lxc_getstate(c->name, c->config_path);
794dd120
SH
345 return (s == STOPPED);
346}
347
72d0e1cb
SG
348static bool lxcapi_is_running(struct lxc_container *c)
349{
350 const char *s;
351
352 if (!c)
353 return false;
354 s = lxcapi_state(c);
355 if (!s || strcmp(s, "STOPPED") == 0)
356 return false;
357 return true;
358}
359
360static bool lxcapi_freeze(struct lxc_container *c)
361{
362 int ret;
363 if (!c)
364 return false;
365
9123e471 366 ret = lxc_freeze(c->name, c->config_path);
72d0e1cb
SG
367 if (ret)
368 return false;
369 return true;
370}
371
372static bool lxcapi_unfreeze(struct lxc_container *c)
373{
374 int ret;
375 if (!c)
376 return false;
377
9123e471 378 ret = lxc_unfreeze(c->name, c->config_path);
72d0e1cb
SG
379 if (ret)
380 return false;
381 return true;
382}
383
b5159817 384static int lxcapi_console_getfd(struct lxc_container *c, int *ttynum, int *masterfd)
0115f8fd
DE
385{
386 int ttyfd;
387 if (!c)
388 return -1;
389
b5159817 390 ttyfd = lxc_console_getfd(c, ttynum, masterfd);
0115f8fd
DE
391 return ttyfd;
392}
393
b5159817
DE
394static int lxcapi_console(struct lxc_container *c, int ttynum, int stdinfd,
395 int stdoutfd, int stderrfd, int escape)
396{
397 return lxc_console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape);
398}
399
72d0e1cb
SG
400static pid_t lxcapi_init_pid(struct lxc_container *c)
401{
72d0e1cb
SG
402 if (!c)
403 return -1;
404
5cee8c50 405 return lxc_cmd_get_init_pid(c->name, c->config_path);
72d0e1cb
SG
406}
407
12a50cc6 408static bool load_config_locked(struct lxc_container *c, const char *fname)
8eb5694b
SH
409{
410 if (!c->lxc_conf)
411 c->lxc_conf = lxc_conf_init();
412 if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
413 return true;
414 return false;
415}
416
12a50cc6 417static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 418{
39dc698c
SH
419 bool ret = false, need_disklock = false;
420 int lret;
12a50cc6 421 const char *fname;
72d0e1cb
SG
422 if (!c)
423 return false;
424
425 fname = c->configfile;
426 if (alt_file)
427 fname = alt_file;
428 if (!fname)
429 return false;
39dc698c
SH
430 /*
431 * If we're reading something other than the container's config,
432 * we only need to lock the in-memory container. If loading the
433 * container's config file, take the disk lock.
434 */
435 if (strcmp(fname, c->configfile) == 0)
436 need_disklock = true;
437
438 if (need_disklock)
439 lret = container_disk_lock(c);
440 else
441 lret = container_mem_lock(c);
442 if (lret)
72d0e1cb 443 return false;
39dc698c 444
8eb5694b 445 ret = load_config_locked(c, fname);
39dc698c
SH
446
447 if (need_disklock)
448 container_disk_unlock(c);
449 else
450 container_mem_unlock(c);
72d0e1cb
SG
451 return ret;
452}
453
454static void lxcapi_want_daemonize(struct lxc_container *c)
455{
497a2995 456 if (!c || !c->lxc_conf)
72d0e1cb 457 return;
f02abefe 458 if (container_mem_lock(c)) {
3bc449ed
SH
459 ERROR("Error getting mem lock");
460 return;
461 }
72d0e1cb 462 c->daemonize = 1;
83758ed0
ÇO
463 /* daemonize implies close_all_fds so set it */
464 c->lxc_conf->close_all_fds = 1;
3bc449ed 465 container_mem_unlock(c);
72d0e1cb
SG
466}
467
49badbbe 468static bool lxcapi_want_close_all_fds(struct lxc_container *c)
130a1888
ÇO
469{
470 if (!c || !c->lxc_conf)
49badbbe 471 return false;
130a1888
ÇO
472 if (container_mem_lock(c)) {
473 ERROR("Error getting mem lock");
49badbbe 474 return false;
130a1888
ÇO
475 }
476 c->lxc_conf->close_all_fds = 1;
477 container_mem_unlock(c);
49badbbe 478 return true;
130a1888
ÇO
479}
480
12a50cc6 481static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
7a44c8b4
SG
482{
483 int ret;
484
485 if (!c)
486 return false;
487
67e571de 488 ret = lxc_wait(c->name, state, timeout, c->config_path);
7a44c8b4
SG
489 return ret == 0;
490}
491
492
493static bool wait_on_daemonized_start(struct lxc_container *c)
494{
495 /* we'll probably want to make this timeout configurable? */
697fa639 496 int timeout = 5, ret, status;
7a44c8b4 497
697fa639
SH
498 /*
499 * our child is going to fork again, then exit. reap the
500 * child
501 */
502 ret = wait(&status);
503 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
504 DEBUG("failed waiting for first dual-fork child");
7a44c8b4
SG
505 return lxcapi_wait(c, "RUNNING", timeout);
506}
507
72d0e1cb
SG
508/*
509 * I can't decide if it'd be more convenient for callers if we accept '...',
510 * or a null-terminated array (i.e. execl vs execv)
511 */
12a50cc6 512static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
72d0e1cb
SG
513{
514 int ret;
515 struct lxc_conf *conf;
516 int daemonize = 0;
517 char *default_args[] = {
518 "/sbin/init",
519 '\0',
520 };
521
522 /* container exists */
523 if (!c)
524 return false;
525 /* container has been setup */
526 if (!c->lxc_conf)
527 return false;
528
3e625e2d
SH
529 if ((ret = ongoing_create(c)) < 0) {
530 ERROR("Error checking for incomplete creation");
531 return false;
532 }
533 if (ret == 2) {
534 ERROR("Error: %s creation was not completed", c->name);
535 c->destroy(c);
536 return false;
537 } else if (ret == 1) {
538 ERROR("Error: creation of %s is ongoing", c->name);
539 return false;
540 }
541
72d0e1cb
SG
542 /* is this app meant to be run through lxcinit, as in lxc-execute? */
543 if (useinit && !argv)
544 return false;
545
5cee8c50 546 if (container_mem_lock(c))
72d0e1cb
SG
547 return false;
548 conf = c->lxc_conf;
549 daemonize = c->daemonize;
5cee8c50 550 container_mem_unlock(c);
72d0e1cb
SG
551
552 if (useinit) {
13f5be62 553 ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
72d0e1cb
SG
554 return ret == 0 ? true : false;
555 }
556
557 if (!argv)
558 argv = default_args;
559
560 /*
561 * say, I'm not sure - what locks do we want here? Any?
562 * Is liblxc's locking enough here to protect the on disk
563 * container? We don't want to exclude things like lxc_info
564 * while container is running...
565 */
566 if (daemonize) {
567 if (!lxc_container_get(c))
568 return false;
e51d4895 569 lxc_monitord_spawn(c->config_path);
71454076 570
72d0e1cb
SG
571 pid_t pid = fork();
572 if (pid < 0) {
573 lxc_container_put(c);
574 return false;
575 }
025ed0f3
SH
576 if (pid != 0)
577 return wait_on_daemonized_start(c);
578
579 process_unlock(); // we're no longer sharing
697fa639
SH
580 /* second fork to be reparented by init */
581 pid = fork();
582 if (pid < 0) {
583 SYSERROR("Error doing dual-fork");
584 return false;
585 }
586 if (pid != 0)
587 exit(0);
72d0e1cb 588 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
c278cef2
SH
589 if (chdir("/")) {
590 SYSERROR("Error chdir()ing to /.");
591 return false;
592 }
72d0e1cb
SG
593 close(0);
594 close(1);
595 close(2);
eddaaafd 596 open("/dev/zero", O_RDONLY);
72d0e1cb
SG
597 open("/dev/null", O_RDWR);
598 open("/dev/null", O_RDWR);
599 setsid();
600 }
601
72d0e1cb
SG
602reboot:
603 conf->reboot = 0;
13f5be62 604 ret = lxc_start(c->name, argv, conf, c->config_path);
72d0e1cb
SG
605
606 if (conf->reboot) {
607 INFO("container requested reboot");
608 conf->reboot = 0;
72d0e1cb
SG
609 goto reboot;
610 }
611
612 if (daemonize) {
613 lxc_container_put(c);
614 exit (ret == 0 ? true : false);
615 } else {
616 return (ret == 0 ? true : false);
617 }
618}
619
620/*
621 * note there MUST be an ending NULL
622 */
623static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
624{
625 va_list ap;
a0e93eeb 626 char **inargs = NULL;
72d0e1cb
SG
627 bool bret = false;
628
629 /* container exists */
630 if (!c)
631 return false;
632
72d0e1cb 633 va_start(ap, useinit);
a0e93eeb 634 inargs = lxc_va_arg_list_to_argv(ap, 0, 1);
72d0e1cb
SG
635 va_end(ap);
636
a0e93eeb
CS
637 if (!inargs) {
638 ERROR("Memory allocation error.");
639 goto out;
72d0e1cb
SG
640 }
641
a0e93eeb
CS
642 /* pass NULL if no arguments were supplied */
643 bret = lxcapi_start(c, useinit, *inargs ? inargs : NULL);
72d0e1cb
SG
644
645out:
646 if (inargs) {
4e03ae57
DE
647 char **arg;
648 for (arg = inargs; *arg; arg++)
649 free(*arg);
72d0e1cb
SG
650 free(inargs);
651 }
652
653 return bret;
654}
655
656static bool lxcapi_stop(struct lxc_container *c)
657{
658 int ret;
659
660 if (!c)
661 return false;
662
ef6e34ee 663 ret = lxc_cmd_stop(c->name, c->config_path);
72d0e1cb
SG
664
665 return ret == 0;
72d0e1cb
SG
666}
667
72d0e1cb
SG
668/*
669 * create the standard expected container dir
670 */
671static bool create_container_dir(struct lxc_container *c)
672{
673 char *s;
674 int len, ret;
675
2a59a681 676 len = strlen(c->config_path) + strlen(c->name) + 2;
72d0e1cb
SG
677 s = malloc(len);
678 if (!s)
679 return false;
2a59a681 680 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
72d0e1cb
SG
681 if (ret < 0 || ret >= len) {
682 free(s);
683 return false;
684 }
685 ret = mkdir(s, 0755);
686 if (ret) {
687 if (errno == EEXIST)
688 ret = 0;
689 else
690 SYSERROR("failed to create container path for %s\n", c->name);
691 }
692 free(s);
693 return ret == 0;
694}
695
1897e3bc
SH
696static const char *lxcapi_get_config_path(struct lxc_container *c);
697static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v);
698
72d0e1cb 699/*
1897e3bc
SH
700 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
701 * it returns a mounted bdev on success, NULL on error.
72d0e1cb 702 */
1897e3bc
SH
703static struct bdev *do_bdev_create(struct lxc_container *c, const char *type,
704 struct bdev_specs *specs)
705{
706 char *dest;
1897e3bc
SH
707 size_t len;
708 struct bdev *bdev;
709 int ret;
710
cd219ae6
SY
711 /* rootfs.path or lxcpath/lxcname/rootfs */
712 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0) {
cf465fe4
SH
713 const char *rpath = c->lxc_conf->rootfs.path;
714 len = strlen(rpath) + 1;
cd219ae6 715 dest = alloca(len);
cf465fe4 716 ret = snprintf(dest, len, "%s", rpath);
cd219ae6 717 } else {
cf465fe4 718 const char *lxcpath = lxcapi_get_config_path(c);
cd219ae6
SY
719 len = strlen(c->name) + strlen(lxcpath) + 9;
720 dest = alloca(len);
721 ret = snprintf(dest, len, "%s/%s/rootfs", lxcpath, c->name);
722 }
1897e3bc
SH
723 if (ret < 0 || ret >= len)
724 return NULL;
725
726 bdev = bdev_create(dest, type, c->name, specs);
d44e88c2
SH
727 if (!bdev) {
728 ERROR("Failed to create backing store type %s\n", type);
1897e3bc 729 return NULL;
d44e88c2
SH
730 }
731
1897e3bc 732 lxcapi_set_config_item(c, "lxc.rootfs", bdev->src);
cf3ef16d
SH
733
734 /* if we are not root, chown the rootfs dir to root in the
735 * target uidmap */
736
737 if (geteuid() != 0) {
c4d10a05
SH
738 if (chown_mapped_root(bdev->dest, c->lxc_conf) < 0) {
739 ERROR("Error chowning %s to container root\n", bdev->dest);
cf3ef16d
SH
740 bdev_put(bdev);
741 return NULL;
742 }
743 }
744
1897e3bc
SH
745 return bdev;
746}
747
cbee8106
SH
748/*
749 * Given the '-t' template option to lxc-create, figure out what to
750 * do. If the template is a full executable path, use that. If it
85db5535
DE
751 * is something like 'sshd', then return $templatepath/lxc-sshd.
752 * On success return the template, on error return NULL.
cbee8106 753 */
85db5535 754static char *get_template_path(const char *t)
cbee8106
SH
755{
756 int ret, len;
757 char *tpath;
758
cbee8106
SH
759 if (t[0] == '/' && access(t, X_OK) == 0) {
760 tpath = strdup(t);
cbee8106
SH
761 return tpath;
762 }
763
764 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
765 tpath = malloc(len);
766 if (!tpath)
85db5535 767 return NULL;
cbee8106
SH
768 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
769 if (ret < 0 || ret >= len) {
770 free(tpath);
85db5535 771 return NULL;
cbee8106
SH
772 }
773 if (access(tpath, X_OK) < 0) {
774 SYSERROR("bad template: %s\n", t);
775 free(tpath);
85db5535 776 return NULL;
cbee8106
SH
777 }
778
779 return tpath;
780}
781
96b3cb40 782static char *lxcbasename(char *path)
72d0e1cb 783{
96b3cb40
SH
784 char *p = path + strlen(path) - 1;
785 while (*p != '/' && p > path)
786 p--;
787 return p;
788}
72d0e1cb 789
dc23c1c8 790static bool create_run_template(struct lxc_container *c, char *tpath, bool quiet,
96b3cb40
SH
791 char *const argv[])
792{
793 pid_t pid;
72d0e1cb 794
72d0e1cb 795 if (!tpath)
96b3cb40 796 return true;
72d0e1cb
SG
797
798 pid = fork();
799 if (pid < 0) {
800 SYSERROR("failed to fork task for container creation template\n");
96b3cb40 801 return false;
72d0e1cb
SG
802 }
803
804 if (pid == 0) { // child
1897e3bc
SH
805 char *patharg, *namearg, *rootfsarg, *src;
806 struct bdev *bdev = NULL;
72d0e1cb 807 int i;
96b3cb40
SH
808 int ret, len, nargs = 0;
809 char **newargv;
cf3ef16d 810 struct lxc_conf *conf = c->lxc_conf;
72d0e1cb 811
025ed0f3 812 process_unlock(); // we're no longer sharing
dc23c1c8
SH
813 if (quiet) {
814 close(0);
815 close(1);
816 close(2);
817 open("/dev/zero", O_RDONLY);
818 open("/dev/null", O_RDWR);
819 open("/dev/null", O_RDWR);
820 }
1897e3bc
SH
821
822 src = c->lxc_conf->rootfs.path;
823 /*
824 * for an overlayfs create, what the user wants is the template to fill
825 * in what will become the readonly lower layer. So don't mount for
826 * the template
827 */
828 if (strncmp(src, "overlayfs:", 10) == 0) {
829 src = overlayfs_getlower(src+10);
830 }
831 bdev = bdev_init(src, c->lxc_conf->rootfs.mount, NULL);
832 if (!bdev) {
833 ERROR("Error opening rootfs");
834 exit(1);
835 }
836
4de2791f 837 if (geteuid() == 0) {
cf3ef16d
SH
838 if (unshare(CLONE_NEWNS) < 0) {
839 ERROR("error unsharing mounts");
840 exit(1);
841 }
4de2791f
SH
842 if (detect_shared_rootfs()) {
843 if (mount("", "", NULL, MS_SLAVE|MS_REC, 0)) {
844 SYSERROR("Failed to make / rslave to run template");
845 ERROR("Continuing...");
846 }
847 }
848 }
849 if (strcmp(bdev->type, "dir") != 0) {
850 if (geteuid() != 0) {
851 ERROR("non-root users can only create directory-backed containers");
852 exit(1);
853 }
cf3ef16d
SH
854 if (bdev->ops->mount(bdev) < 0) {
855 ERROR("Error mounting rootfs");
856 exit(1);
857 }
858 } else { // TODO come up with a better way here!
859 if (bdev->dest)
860 free(bdev->dest);
861 bdev->dest = strdup(bdev->src);
1897e3bc
SH
862 }
863
72d0e1cb
SG
864 /*
865 * create our new array, pre-pend the template name and
866 * base args
867 */
868 if (argv)
1897e3bc
SH
869 for (nargs = 0; argv[nargs]; nargs++) ;
870 nargs += 4; // template, path, rootfs and name args
cf3ef16d 871
72d0e1cb
SG
872 newargv = malloc(nargs * sizeof(*newargv));
873 if (!newargv)
874 exit(1);
96b3cb40 875 newargv[0] = lxcbasename(tpath);
72d0e1cb 876
2a59a681 877 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
72d0e1cb
SG
878 patharg = malloc(len);
879 if (!patharg)
880 exit(1);
2a59a681 881 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
72d0e1cb
SG
882 if (ret < 0 || ret >= len)
883 exit(1);
884 newargv[1] = patharg;
885 len = strlen("--name=") + strlen(c->name) + 1;
886 namearg = malloc(len);
887 if (!namearg)
888 exit(1);
889 ret = snprintf(namearg, len, "--name=%s", c->name);
890 if (ret < 0 || ret >= len)
891 exit(1);
892 newargv[2] = namearg;
893
1897e3bc
SH
894 len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
895 rootfsarg = malloc(len);
896 if (!rootfsarg)
897 exit(1);
898 ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
899 if (ret < 0 || ret >= len)
900 exit(1);
901 newargv[3] = rootfsarg;
902
72d0e1cb
SG
903 /* add passed-in args */
904 if (argv)
1897e3bc
SH
905 for (i = 4; i < nargs; i++)
906 newargv[i] = argv[i-4];
72d0e1cb
SG
907
908 /* add trailing NULL */
909 nargs++;
910 newargv = realloc(newargv, nargs * sizeof(*newargv));
911 if (!newargv)
912 exit(1);
913 newargv[nargs - 1] = NULL;
914
cf3ef16d
SH
915 /*
916 * If we're running the template in a mapped userns, then
917 * we prepend the template command with:
918 * lxc-usernsexec <-m map1> ... <-m mapn> --
919 */
920 if (geteuid() != 0 && !lxc_list_empty(&conf->id_map)) {
921 int n2args = 1;
922 char **n2 = malloc(n2args * sizeof(*n2));
923 struct lxc_list *it;
924 struct id_map *map;
925
926 newargv[0] = tpath;
927 tpath = "lxc-usernsexec";
928 n2[0] = "lxc-usernsexec";
929 lxc_list_for_each(it, &conf->id_map) {
930 map = it->elem;
931 n2args += 2;
932 n2 = realloc(n2, n2args * sizeof(*n2));
933 if (!n2)
934 exit(1);
935 n2[n2args-2] = "-m";
936 n2[n2args-1] = malloc(200);
937 if (!n2[n2args-1])
938 exit(1);
939 ret = snprintf(n2[n2args-1], 200, "%c:%lu:%lu:%lu",
940 map->idtype == ID_TYPE_UID ? 'u' : 'g',
941 map->nsid, map->hostid, map->range);
942 if (ret < 0 || ret >= 200)
943 exit(1);
944 }
945 bool hostid_mapped = hostid_is_mapped(geteuid(), conf);
946 int extraargs = hostid_mapped ? 1 : 3;
947 n2 = realloc(n2, (nargs + n2args + extraargs) * sizeof(*n2));
948 if (!n2)
949 exit(1);
950 if (!hostid_mapped) {
951 int free_id = find_unmapped_nsuid(conf);
952 n2[n2args++] = "-m";
953 if (free_id < 0) {
954 ERROR("Could not find free uid to map");
955 exit(1);
956 }
957 n2[n2args++] = malloc(200);
958 if (!n2[n2args-1]) {
959 SYSERROR("out of memory");
960 exit(1);
961 }
962 ret = snprintf(n2[n2args-1], 200, "u:%d:%d:1",
963 free_id, geteuid());
964 if (ret < 0 || ret >= 200) {
965 ERROR("string too long");
966 exit(1);
967 }
968 }
969 n2[n2args++] = "--";
970 for (i = 0; i < nargs; i++)
971 n2[i + n2args] = newargv[i];
972 free(newargv);
973 newargv = n2;
974 }
72d0e1cb 975 /* execute */
cf3ef16d 976 execvp(tpath, newargv);
72d0e1cb
SG
977 SYSERROR("failed to execute template %s", tpath);
978 exit(1);
979 }
980
9be53773
SH
981 if (wait_for_pid(pid) != 0) {
982 ERROR("container creation template for %s failed\n", c->name);
96b3cb40
SH
983 return false;
984 }
985
986 return true;
987}
988
3ce74686
SH
989bool prepend_lxc_header(char *path, const char *t, char *const argv[])
990{
1fd9bd50 991 long flen;
b4569e93 992 char *contents;
3ce74686 993 FILE *f;
025ed0f3 994 int ret = -1;
52026772 995#if HAVE_LIBGNUTLS
025ed0f3 996 int i;
3ce74686 997 unsigned char md_value[SHA_DIGEST_LENGTH];
b4569e93 998 char *tpath;
52026772 999#endif
3ce74686 1000
025ed0f3
SH
1001 process_lock();
1002 f = fopen(path, "r");
1003 process_unlock();
1004 if (f == NULL)
3ce74686 1005 return false;
025ed0f3
SH
1006
1007 if (fseek(f, 0, SEEK_END) < 0)
1008 goto out_error;
1009 if ((flen = ftell(f)) < 0)
1010 goto out_error;
1011 if (fseek(f, 0, SEEK_SET) < 0)
1012 goto out_error;
1013 if ((contents = malloc(flen + 1)) == NULL)
1014 goto out_error;
1015 if (fread(contents, 1, flen, f) != flen)
1016 goto out_free_contents;
1017
3ce74686 1018 contents[flen] = '\0';
025ed0f3
SH
1019 process_lock();
1020 ret = fclose(f);
1021 process_unlock();
1022 f = NULL;
1023 if (ret < 0)
1024 goto out_free_contents;
3ce74686 1025
b4569e93 1026#if HAVE_LIBGNUTLS
01efd4d3 1027 tpath = get_template_path(t);
85db5535 1028 if (!tpath) {
3ce74686 1029 ERROR("bad template: %s\n", t);
025ed0f3 1030 goto out_free_contents;
3ce74686
SH
1031 }
1032
85db5535
DE
1033 ret = sha1sum_file(tpath, md_value);
1034 if (ret < 0) {
1035 ERROR("Error getting sha1sum of %s", tpath);
3ce74686 1036 free(tpath);
85db5535 1037 goto out_free_contents;
3ce74686 1038 }
85db5535 1039 free(tpath);
3ce74686
SH
1040#endif
1041
025ed0f3
SH
1042 process_lock();
1043 f = fopen(path, "w");
1044 process_unlock();
1045 if (f == NULL) {
3ce74686
SH
1046 SYSERROR("reopening config for writing");
1047 free(contents);
1048 return false;
1049 }
1050 fprintf(f, "# Template used to create this container: %s\n", t);
1051 if (argv) {
1052 fprintf(f, "# Parameters passed to the template:");
1053 while (*argv) {
1054 fprintf(f, " %s", *argv);
1055 argv++;
1056 }
1057 fprintf(f, "\n");
1058 }
1059#if HAVE_LIBGNUTLS
56698177
SH
1060 fprintf(f, "# Template script checksum (SHA-1): ");
1061 for (i=0; i<SHA_DIGEST_LENGTH; i++)
1062 fprintf(f, "%02x", md_value[i]);
1063 fprintf(f, "\n");
3ce74686
SH
1064#endif
1065 if (fwrite(contents, 1, flen, f) != flen) {
1066 SYSERROR("Writing original contents");
1067 free(contents);
025ed0f3 1068 process_lock();
3ce74686 1069 fclose(f);
025ed0f3 1070 process_unlock();
3ce74686
SH
1071 return false;
1072 }
025ed0f3
SH
1073 ret = 0;
1074out_free_contents:
3ce74686 1075 free(contents);
025ed0f3
SH
1076out_error:
1077 if (f) {
1078 int newret;
1079 process_lock();
1080 newret = fclose(f);
1081 process_unlock();
1082 if (ret == 0)
1083 ret = newret;
1084 }
1085 if (ret < 0) {
1086 SYSERROR("Error prepending header");
3ce74686
SH
1087 return false;
1088 }
1089 return true;
1090}
1091
96b3cb40
SH
1092static bool lxcapi_destroy(struct lxc_container *c);
1093/*
1094 * lxcapi_create:
1095 * create a container with the given parameters.
1096 * @c: container to be created. It has the lxcpath, name, and a starting
1097 * configuration already set
1098 * @t: the template to execute to instantiate the root filesystem and
1099 * adjust the configuration.
1100 * @bdevtype: backing store type to use. If NULL, dir will be used.
1101 * @specs: additional parameters for the backing store, i.e. LVM vg to
1102 * use.
1103 *
1104 * @argv: the arguments to pass to the template, terminated by NULL. If no
1105 * arguments, you can just pass NULL.
1106 */
1107static bool lxcapi_create(struct lxc_container *c, const char *t,
dc23c1c8 1108 const char *bdevtype, struct bdev_specs *specs, int flags,
96b3cb40
SH
1109 char *const argv[])
1110{
a69aad27 1111 bool ret = false;
96b3cb40 1112 pid_t pid;
85db5535 1113 char *tpath = NULL;
cbee8106 1114 int partial_fd;
96b3cb40
SH
1115
1116 if (!c)
1117 return false;
1118
85db5535
DE
1119 if (t) {
1120 tpath = get_template_path(t);
1121 if (!tpath) {
1122 ERROR("bad template: %s\n", t);
1123 goto out;
1124 }
96b3cb40
SH
1125 }
1126
cf465fe4
SH
1127 /*
1128 * If a template is passed in, and the rootfs already is defined in
1129 * the container config and exists, then * caller is trying to create
1130 * an existing container. Return an error, but do NOT delete the
1131 * container.
1132 */
1133 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path &&
1134 access(c->lxc_conf->rootfs.path, F_OK) == 0 && tpath) {
1135 ERROR("Container %s:%s already exists", c->config_path, c->name);
1136 free(tpath);
1137 return false;
1138 }
1139
1140 /* Save the loaded configuration to disk */
96b3cb40
SH
1141 if (!c->save_config(c, NULL)) {
1142 ERROR("failed to save starting configuration for %s\n", c->name);
1143 goto out;
1144 }
1145
0590e82c
SH
1146 /*
1147 * either template or rootfs.path should be set.
1148 * if both template and rootfs.path are set, template is setup as rootfs.path.
1149 * container is already created if we have a config and rootfs.path is accessible
1150 */
1151 if (!c->lxc_conf->rootfs.path && !tpath)
1152 /* no template passed in and rootfs does not exist: error */
1153 goto out;
1154 if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) != 0)
1155 /* rootfs passed into configuration, but does not exist: error */
1156 goto out;
1157 if (lxcapi_is_defined(c) && c->lxc_conf->rootfs.path && !tpath) {
1158 /* Rootfs already existed, user just wanted to save the
1159 * loaded configuration */
1160 ret = true;
1161 goto out;
a69aad27 1162 }
96b3cb40
SH
1163
1164 /* Mark that this container is being created */
1165 if ((partial_fd = create_partial(c)) < 0)
1166 goto out;
1167
1168 /* no need to get disk lock bc we have the partial locked */
1169
1170 /*
1171 * Create the backing store
1172 * Note we can't do this in the same task as we use to execute the
1173 * template because of the way zfs works.
1174 * After you 'zfs create', zfs mounts the fs only in the initial
1175 * namespace.
1176 */
1177 pid = fork();
1178 if (pid < 0) {
1179 SYSERROR("failed to fork task for container creation template\n");
8eb5694b
SH
1180 goto out_unlock;
1181 }
1182
96b3cb40
SH
1183 if (pid == 0) { // child
1184 struct bdev *bdev = NULL;
1185
025ed0f3 1186 process_unlock(); // we're no longer sharing
96b3cb40
SH
1187 if (!(bdev = do_bdev_create(c, bdevtype, specs))) {
1188 ERROR("Error creating backing store type %s for %s",
1189 bdevtype ? bdevtype : "(none)", c->name);
1190 exit(1);
1191 }
1192
1193 /* save config file again to store the new rootfs location */
1194 if (!c->save_config(c, NULL)) {
1195 ERROR("failed to save starting configuration for %s\n", c->name);
1196 // parent task won't see bdev in config so we delete it
1197 bdev->ops->umount(bdev);
1198 bdev->ops->destroy(bdev);
1199 exit(1);
1200 }
1201 exit(0);
1202 }
1203 if (wait_for_pid(pid) != 0)
a09295f8 1204 goto out_unlock;
96b3cb40
SH
1205
1206 /* reload config to get the rootfs */
1207 if (c->lxc_conf)
1208 lxc_conf_free(c->lxc_conf);
1209 c->lxc_conf = NULL;
1210 if (!load_config_locked(c, c->configfile))
a09295f8 1211 goto out_unlock;
96b3cb40 1212
dc23c1c8 1213 if (!create_run_template(c, tpath, !!(flags & LXC_CREATE_QUIET), argv))
96b3cb40
SH
1214 goto out_unlock;
1215
8eb5694b
SH
1216 // now clear out the lxc_conf we have, reload from the created
1217 // container
1218 if (c->lxc_conf)
1219 lxc_conf_free(c->lxc_conf);
1220 c->lxc_conf = NULL;
3ce74686 1221
9d65a487
KY
1222 if (t) {
1223 if (!prepend_lxc_header(c->configfile, tpath, argv)) {
1224 ERROR("Error prepending header to configuration file");
1225 goto out_unlock;
1226 }
3ce74686 1227 }
a69aad27 1228 ret = load_config_locked(c, c->configfile);
72d0e1cb
SG
1229
1230out_unlock:
3e625e2d
SH
1231 if (partial_fd >= 0)
1232 remove_partial(c, partial_fd);
72d0e1cb
SG
1233out:
1234 if (tpath)
1235 free(tpath);
a69aad27 1236 if (!ret && c)
1897e3bc 1237 lxcapi_destroy(c);
a69aad27 1238 return ret;
72d0e1cb
SG
1239}
1240
3e625e2d
SH
1241static bool lxcapi_reboot(struct lxc_container *c)
1242{
1243 pid_t pid;
1244
1245 if (!c)
1246 return false;
1247 if (!c->is_running(c))
1248 return false;
1249 pid = c->init_pid(c);
1250 if (pid <= 0)
1251 return false;
1252 if (kill(pid, SIGINT) < 0)
1253 return false;
1254 return true;
1255
1256}
1257
72d0e1cb
SG
1258static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
1259{
1260 bool retv;
1261 pid_t pid;
1262
1263 if (!c)
1264 return false;
1265
1266 if (!timeout)
1267 timeout = -1;
1268 if (!c->is_running(c))
1269 return true;
1270 pid = c->init_pid(c);
1271 if (pid <= 0)
1272 return true;
1273 kill(pid, SIGPWR);
1274 retv = c->wait(c, "STOPPED", timeout);
f6144ed4 1275 if (!retv && timeout > 0) {
72d0e1cb
SG
1276 c->stop(c);
1277 retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
1278 }
1279 return retv;
1280}
1281
1897e3bc 1282static bool lxcapi_createl(struct lxc_container *c, const char *t,
dc23c1c8 1283 const char *bdevtype, struct bdev_specs *specs, int flags, ...)
72d0e1cb
SG
1284{
1285 bool bret = false;
a0e93eeb 1286 char **args = NULL;
72d0e1cb 1287 va_list ap;
72d0e1cb
SG
1288
1289 if (!c)
1290 return false;
1291
1292 /*
1293 * since we're going to wait for create to finish, I don't think we
1294 * need to get a copy of the arguments.
1295 */
dc23c1c8 1296 va_start(ap, flags);
a0e93eeb 1297 args = lxc_va_arg_list_to_argv(ap, 0, 0);
72d0e1cb 1298 va_end(ap);
a0e93eeb
CS
1299 if (!args) {
1300 ERROR("Memory allocation error.");
1301 goto out;
1302 }
72d0e1cb 1303
dc23c1c8 1304 bret = c->create(c, t, bdevtype, specs, flags, args);
72d0e1cb
SG
1305
1306out:
a0e93eeb 1307 free(args);
72d0e1cb
SG
1308 return bret;
1309}
1310
12a50cc6 1311static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
72d0e1cb
SG
1312{
1313 int ret;
1314
1315 if (!c || !c->lxc_conf)
1316 return false;
5cee8c50 1317 if (container_mem_lock(c))
72d0e1cb 1318 return false;
72d0e1cb 1319 ret = lxc_clear_config_item(c->lxc_conf, key);
5cee8c50 1320 container_mem_unlock(c);
72d0e1cb
SG
1321 return ret == 0;
1322}
1323
799f29ab
ÇO
1324static inline void exit_from_ns(struct lxc_container *c, int *old_netns, int *new_netns) {
1325 /* Switch back to original netns */
1326 if (*old_netns >= 0 && setns(*old_netns, CLONE_NEWNET))
1327 SYSERROR("failed to setns");
1328 process_lock();
1329 if (*new_netns >= 0)
1330 close(*new_netns);
1331 if (*old_netns >= 0)
1332 close(*old_netns);
1333 process_unlock();
1334}
1335
1336static inline bool enter_to_ns(struct lxc_container *c, int *old_netns, int *new_netns) {
1337 int ret = 0;
9c83a661 1338 char new_netns_path[MAXPATHLEN];
9c83a661
SG
1339
1340 if (!c->is_running(c))
1341 goto out;
1342
1343 /* Save reference to old netns */
025ed0f3 1344 process_lock();
799f29ab 1345 *old_netns = open("/proc/self/ns/net", O_RDONLY);
025ed0f3 1346 process_unlock();
799f29ab 1347 if (*old_netns < 0) {
9c83a661
SG
1348 SYSERROR("failed to open /proc/self/ns/net");
1349 goto out;
1350 }
1351
1352 /* Switch to new netns */
1353 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", c->init_pid(c));
1354 if (ret < 0 || ret >= MAXPATHLEN)
1355 goto out;
1356
025ed0f3 1357 process_lock();
799f29ab 1358 *new_netns = open(new_netns_path, O_RDONLY);
025ed0f3 1359 process_unlock();
799f29ab 1360 if (*new_netns < 0) {
9c83a661
SG
1361 SYSERROR("failed to open %s", new_netns_path);
1362 goto out;
1363 }
1364
799f29ab 1365 if (setns(*new_netns, CLONE_NEWNET)) {
9c83a661
SG
1366 SYSERROR("failed to setns");
1367 goto out;
1368 }
799f29ab
ÇO
1369 return true;
1370out:
1371 exit_from_ns(c, old_netns, new_netns);
1372 return false;
1373}
1374
9c88ff1f
ÇO
1375// used by qsort and bsearch functions for comparing names
1376static inline int string_cmp(char **first, char **second)
1377{
1378 return strcmp(*first, *second);
1379}
1380
1381// used by qsort and bsearch functions for comparing container names
1382static inline int container_cmp(struct lxc_container **first, struct lxc_container **second)
1383{
1384 return strcmp((*first)->name, (*second)->name);
1385}
1386
1387static bool add_to_array(char ***names, char *cname, int pos)
1388{
1389 char **newnames = realloc(*names, (pos+1) * sizeof(char *));
1390 if (!newnames) {
1391 ERROR("Out of memory");
1392 return false;
1393 }
1394
1395 *names = newnames;
1396 newnames[pos] = strdup(cname);
1397 if (!newnames[pos])
1398 return false;
1399
1400 // sort the arrray as we will use binary search on it
1401 qsort(newnames, pos + 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp);
1402
1403 return true;
1404}
1405
2871830a 1406static bool add_to_clist(struct lxc_container ***list, struct lxc_container *c, int pos, bool sort)
9c88ff1f
ÇO
1407{
1408 struct lxc_container **newlist = realloc(*list, (pos+1) * sizeof(struct lxc_container *));
1409 if (!newlist) {
1410 ERROR("Out of memory");
1411 return false;
1412 }
1413
1414 *list = newlist;
1415 newlist[pos] = c;
1416
1417 // sort the arrray as we will use binary search on it
2871830a
DE
1418 if (sort)
1419 qsort(newlist, pos + 1, sizeof(struct lxc_container *), (int (*)(const void *,const void *))container_cmp);
9c88ff1f
ÇO
1420
1421 return true;
1422}
1423
1424static char** get_from_array(char ***names, char *cname, int size)
1425{
1426 return (char **)bsearch(&cname, *names, size, sizeof(char *), (int (*)(const void *, const void *))string_cmp);
1427}
1428
1429
1430static bool array_contains(char ***names, char *cname, int size) {
1431 if(get_from_array(names, cname, size) != NULL)
1432 return true;
1433 return false;
1434}
1435
1436static bool remove_from_array(char ***names, char *cname, int size)
1437{
1438 char **result = get_from_array(names, cname, size);
1439 if (result != NULL) {
1440 free(result);
1441 return true;
1442 }
1443 return false;
1444}
1445
799f29ab
ÇO
1446static char** lxcapi_get_interfaces(struct lxc_container *c)
1447{
9c88ff1f 1448 int i, count = 0;
799f29ab 1449 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
9c88ff1f 1450 char **interfaces = NULL;
799f29ab
ÇO
1451 int old_netns = -1, new_netns = -1;
1452
1453 if (!enter_to_ns(c, &old_netns, &new_netns))
1454 goto out;
1455
1456 /* Grab the list of interfaces */
1457 if (getifaddrs(&interfaceArray)) {
1458 SYSERROR("failed to get interfaces list");
1459 goto out;
1460 }
1461
1462 /* Iterate through the interfaces */
1463 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
9c88ff1f
ÇO
1464 if (array_contains(&interfaces, tempIfAddr->ifa_name, count))
1465 continue;
799f29ab 1466
9c88ff1f
ÇO
1467 if(!add_to_array(&interfaces, tempIfAddr->ifa_name, count))
1468 goto err;
1469 count++;
1470 }
799f29ab
ÇO
1471
1472out:
9c88ff1f
ÇO
1473 if (interfaceArray)
1474 freeifaddrs(interfaceArray);
1475
1476 exit_from_ns(c, &old_netns, &new_netns);
799f29ab 1477
9c88ff1f
ÇO
1478 /* Append NULL to the array */
1479 if(interfaces)
1480 interfaces = (char **)lxc_append_null_to_array((void **)interfaces, count);
799f29ab 1481
9c88ff1f 1482 return interfaces;
799f29ab 1483
9c88ff1f
ÇO
1484err:
1485 for(i=0;i<count;i++)
1486 free(interfaces[i]);
1487 free(interfaces);
1488 interfaces = NULL;
1489 goto out;
799f29ab
ÇO
1490}
1491
1492static char** lxcapi_get_ips(struct lxc_container *c, char* interface, char* family, int scope)
1493{
9c88ff1f 1494 int i, count = 0;
799f29ab
ÇO
1495 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
1496 char addressOutputBuffer[INET6_ADDRSTRLEN];
1497 void *tempAddrPtr = NULL;
9c88ff1f 1498 char **addresses = NULL;
799f29ab
ÇO
1499 char *address = NULL;
1500 int old_netns = -1, new_netns = -1;
1501
1502 if (!enter_to_ns(c, &old_netns, &new_netns))
1503 goto out;
9c83a661
SG
1504
1505 /* Grab the list of interfaces */
1506 if (getifaddrs(&interfaceArray)) {
1507 SYSERROR("failed to get interfaces list");
1508 goto out;
1509 }
1510
1511 /* Iterate through the interfaces */
1512 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
fe218ca3
SG
1513 if (tempIfAddr->ifa_addr == NULL)
1514 continue;
1515
9c83a661
SG
1516 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
1517 if (family && strcmp(family, "inet"))
1518 continue;
1519 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
1520 }
1521 else {
1522 if (family && strcmp(family, "inet6"))
1523 continue;
1524
1525 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
1526 continue;
1527
1528 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
1529 }
1530
1531 if (interface && strcmp(interface, tempIfAddr->ifa_name))
1532 continue;
1533 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
1534 continue;
1535
1536 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
1537 tempAddrPtr,
1538 addressOutputBuffer,
1539 sizeof(addressOutputBuffer));
1540 if (!address)
1541 continue;
1542
9c88ff1f
ÇO
1543 if(!add_to_array(&addresses, address, count))
1544 goto err;
1545 count++;
9c83a661
SG
1546 }
1547
1548out:
1549 if(interfaceArray)
1550 freeifaddrs(interfaceArray);
1551
799f29ab 1552 exit_from_ns(c, &old_netns, &new_netns);
9c83a661
SG
1553
1554 /* Append NULL to the array */
9c88ff1f
ÇO
1555 if(addresses)
1556 addresses = (char **)lxc_append_null_to_array((void **)addresses, count);
9c83a661
SG
1557
1558 return addresses;
9c88ff1f
ÇO
1559
1560err:
1561 for(i=0;i<count;i++)
1562 free(addresses[i]);
1563 free(addresses);
1564 addresses = NULL;
1565
1566 goto out;
9c83a661
SG
1567}
1568
12a50cc6 1569static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1570{
1571 int ret;
1572
1573 if (!c || !c->lxc_conf)
1574 return -1;
5cee8c50 1575 if (container_mem_lock(c))
72d0e1cb 1576 return -1;
72d0e1cb 1577 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
5cee8c50 1578 container_mem_unlock(c);
72d0e1cb
SG
1579 return ret;
1580}
1581
12a50cc6 1582static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
1583{
1584 if (!key)
1585 return lxc_listconfigs(retv, inlen);
1586 /*
1587 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1588 * This is an intelligent result to show which keys are valid given
1589 * the type of nic it is
1590 */
1591 if (!c || !c->lxc_conf)
1592 return -1;
5cee8c50 1593 if (container_mem_lock(c))
72d0e1cb
SG
1594 return -1;
1595 int ret = -1;
1596 if (strncmp(key, "lxc.network.", 12) == 0)
1597 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
5cee8c50 1598 container_mem_unlock(c);
72d0e1cb
SG
1599 return ret;
1600}
1601
12a50cc6 1602static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb 1603{
39dc698c
SH
1604 FILE *fout;
1605 bool ret = false, need_disklock = false;
1606 int lret;
1607
72d0e1cb
SG
1608 if (!alt_file)
1609 alt_file = c->configfile;
1610 if (!alt_file)
1611 return false; // should we write to stdout if no file is specified?
39dc698c
SH
1612
1613 // If we haven't yet loaded a config, load the stock config
1614 if (!c->lxc_conf) {
72d0e1cb
SG
1615 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
1616 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
1617 return false;
1618 }
39dc698c 1619 }
72d0e1cb 1620
5a3d2e1e
SG
1621 if (!create_container_dir(c))
1622 return false;
1623
39dc698c
SH
1624 /*
1625 * If we're writing to the container's config file, take the
1626 * disk lock. Otherwise just take the memlock to protect the
1627 * struct lxc_container while we're traversing it.
1628 */
1629 if (strcmp(c->configfile, alt_file) == 0)
1630 need_disklock = true;
1631
1632 if (need_disklock)
1633 lret = container_disk_lock(c);
1634 else
1635 lret = container_mem_lock(c);
1636
1637 if (lret)
72d0e1cb 1638 return false;
39dc698c
SH
1639
1640 fout = fopen(alt_file, "w");
1641 if (!fout)
1642 goto out;
72d0e1cb
SG
1643 write_config(fout, c->lxc_conf);
1644 fclose(fout);
39dc698c
SH
1645 ret = true;
1646
1647out:
1648 if (need_disklock)
1649 container_disk_unlock(c);
1650 else
1651 container_mem_unlock(c);
1652 return ret;
72d0e1cb
SG
1653}
1654
dfb31b25
SH
1655static bool mod_rdep(struct lxc_container *c, bool inc)
1656{
1657 char path[MAXPATHLEN];
1658 int ret, v = 0;
1659 FILE *f;
1660 bool bret = false;
1661
1662 if (container_disk_lock(c))
1663 return false;
1664 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1665 c->name);
1666 if (ret < 0 || ret > MAXPATHLEN)
1667 goto out;
025ed0f3 1668 process_lock();
dfb31b25 1669 f = fopen(path, "r");
025ed0f3 1670 process_unlock();
dfb31b25
SH
1671 if (f) {
1672 ret = fscanf(f, "%d", &v);
025ed0f3 1673 process_lock();
dfb31b25 1674 fclose(f);
025ed0f3 1675 process_unlock();
dfb31b25
SH
1676 if (ret != 1) {
1677 ERROR("Corrupted file %s", path);
1678 goto out;
1679 }
1680 }
1681 v += inc ? 1 : -1;
025ed0f3 1682 process_lock();
dfb31b25 1683 f = fopen(path, "w");
025ed0f3 1684 process_unlock();
dfb31b25
SH
1685 if (!f)
1686 goto out;
1687 if (fprintf(f, "%d\n", v) < 0) {
1688 ERROR("Error writing new snapshots value");
025ed0f3 1689 process_lock();
dfb31b25 1690 fclose(f);
025ed0f3 1691 process_unlock();
dfb31b25
SH
1692 goto out;
1693 }
025ed0f3
SH
1694 process_lock();
1695 ret = fclose(f);
1696 process_unlock();
1697 if (ret != 0) {
dfb31b25
SH
1698 SYSERROR("Error writing to or closing snapshots file");
1699 goto out;
1700 }
1701
1702 bret = true;
1703
1704out:
1705 container_disk_unlock(c);
1706 return bret;
1707}
1708
1709static void strip_newline(char *p)
1710{
1711 size_t len = strlen(p);
1712 if (len < 1)
1713 return;
1714 if (p[len-1] == '\n')
1715 p[len-1] = '\0';
1716}
1717
1718static void mod_all_rdeps(struct lxc_container *c, bool inc)
1719{
1720 struct lxc_container *p;
1721 char *lxcpath = NULL, *lxcname = NULL, path[MAXPATHLEN];
1722 size_t pathlen = 0, namelen = 0;
1723 FILE *f;
1724 int ret;
1725
1726 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends",
1727 c->config_path, c->name);
1728 if (ret < 0 || ret >= MAXPATHLEN) {
1729 ERROR("Path name too long");
1730 return;
1731 }
025ed0f3
SH
1732 process_lock();
1733 f = fopen(path, "r");
1734 process_unlock();
1735 if (f == NULL)
dfb31b25
SH
1736 return;
1737 while (getline(&lxcpath, &pathlen, f) != -1) {
1738 if (getline(&lxcname, &namelen, f) == -1) {
1739 ERROR("badly formatted file %s\n", path);
1740 goto out;
1741 }
1742 strip_newline(lxcpath);
1743 strip_newline(lxcname);
1744 if ((p = lxc_container_new(lxcname, lxcpath)) == NULL) {
1745 ERROR("Unable to find dependent container %s:%s",
1746 lxcpath, lxcname);
1747 continue;
1748 }
1749 if (!mod_rdep(p, inc))
1750 ERROR("Failed to increase numsnapshots for %s:%s",
1751 lxcpath, lxcname);
1752 lxc_container_put(p);
1753 }
1754out:
1755 if (lxcpath) free(lxcpath);
1756 if (lxcname) free(lxcname);
025ed0f3 1757 process_lock();
dfb31b25 1758 fclose(f);
025ed0f3 1759 process_unlock();
dfb31b25
SH
1760}
1761
1762static bool has_snapshots(struct lxc_container *c)
1763{
1764 char path[MAXPATHLEN];
1765 int ret, v;
1766 FILE *f;
1767 bool bret = false;
1768
1769 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_snapshots", c->config_path,
1770 c->name);
1771 if (ret < 0 || ret > MAXPATHLEN)
1772 goto out;
025ed0f3 1773 process_lock();
dfb31b25 1774 f = fopen(path, "r");
025ed0f3 1775 process_unlock();
dfb31b25
SH
1776 if (!f)
1777 goto out;
1778 ret = fscanf(f, "%d", &v);
025ed0f3 1779 process_lock();
dfb31b25 1780 fclose(f);
025ed0f3 1781 process_unlock();
dfb31b25
SH
1782 if (ret != 1)
1783 goto out;
1784 bret = v != 0;
1785
1786out:
1787 return bret;
1788}
1789
60bf62d4 1790// do we want the api to support --force, or leave that to the caller?
72d0e1cb
SG
1791static bool lxcapi_destroy(struct lxc_container *c)
1792{
1897e3bc 1793 struct bdev *r = NULL;
60bf62d4 1794 bool ret = false;
72d0e1cb 1795
1897e3bc 1796 if (!c || !lxcapi_is_defined(c))
5a3d2e1e
SG
1797 return false;
1798
3bc449ed 1799 if (container_disk_lock(c))
72d0e1cb 1800 return false;
72d0e1cb 1801
39dc698c 1802 if (!is_stopped(c)) {
60bf62d4
SH
1803 // we should queue some sort of error - in c->error_string?
1804 ERROR("container %s is not stopped", c->name);
1805 goto out;
72d0e1cb
SG
1806 }
1807
dfb31b25 1808 if (c->lxc_conf && has_snapshots(c)) {
2a2d36a4 1809 ERROR("container %s has dependent snapshots", c->name);
dfb31b25
SH
1810 goto out;
1811 }
1812
3bc449ed 1813 if (c->lxc_conf && c->lxc_conf->rootfs.path && c->lxc_conf->rootfs.mount)
1897e3bc 1814 r = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
60bf62d4
SH
1815 if (r) {
1816 if (r->ops->destroy(r) < 0) {
59d66af2 1817 bdev_put(r);
60bf62d4
SH
1818 ERROR("Error destroying rootfs for %s", c->name);
1819 goto out;
1820 }
59d66af2 1821 bdev_put(r);
60bf62d4
SH
1822 }
1823
dfb31b25
SH
1824 mod_all_rdeps(c, false);
1825
60bf62d4
SH
1826 const char *p1 = lxcapi_get_config_path(c);
1827 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
1828 sprintf(path, "%s/%s", p1, c->name);
1829 if (lxc_rmdir_onedev(path) < 0) {
1830 ERROR("Error destroying container directory for %s", c->name);
1831 goto out;
1832 }
1833 ret = true;
1834
1835out:
3bc449ed 1836 container_disk_unlock(c);
60bf62d4 1837 return ret;
72d0e1cb
SG
1838}
1839
96532523
SH
1840static bool set_config_item_locked(struct lxc_container *c, const char *key, const char *v)
1841{
1842 struct lxc_config_t *config;
1843
1844 if (!c->lxc_conf)
1845 c->lxc_conf = lxc_conf_init();
1846 if (!c->lxc_conf)
1847 return false;
1848 config = lxc_getconfig(key);
1849 if (!config)
1850 return false;
1851 return (0 == config->cb(key, v, c->lxc_conf));
1852}
1853
12a50cc6 1854static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb 1855{
72d0e1cb 1856 bool b = false;
72d0e1cb
SG
1857
1858 if (!c)
1859 return false;
1860
5cee8c50 1861 if (container_mem_lock(c))
72d0e1cb
SG
1862 return false;
1863
96532523 1864 b = set_config_item_locked(c, key, v);
72d0e1cb 1865
5cee8c50 1866 container_mem_unlock(c);
72d0e1cb
SG
1867 return b;
1868}
1869
1870static char *lxcapi_config_file_name(struct lxc_container *c)
1871{
1872 if (!c || !c->configfile)
1873 return NULL;
1874 return strdup(c->configfile);
1875}
1876
2a59a681
SH
1877static const char *lxcapi_get_config_path(struct lxc_container *c)
1878{
1879 if (!c || !c->config_path)
1880 return NULL;
1881 return (const char *)(c->config_path);
1882}
1883
afeecbba
SH
1884/*
1885 * not for export
1886 * Just recalculate the c->configfile based on the
1887 * c->config_path, which must be set.
1888 * The lxc_container must be locked or not yet public.
1889 */
1890static bool set_config_filename(struct lxc_container *c)
1891{
1892 char *newpath;
1893 int len, ret;
1894
1895 if (!c->config_path)
1896 return false;
1897
1898 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1899 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
1900 newpath = malloc(len);
1901 if (!newpath)
1902 return false;
1903
1904 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
1905 if (ret < 0 || ret >= len) {
1906 fprintf(stderr, "Error printing out config file name\n");
1907 free(newpath);
1908 return false;
1909 }
1910
1911 if (c->configfile)
1912 free(c->configfile);
1913 c->configfile = newpath;
1914
1915 return true;
1916}
1917
2a59a681
SH
1918static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
1919{
1920 char *p;
1921 bool b = false;
afeecbba 1922 char *oldpath = NULL;
2a59a681
SH
1923
1924 if (!c)
1925 return b;
1926
5cee8c50 1927 if (container_mem_lock(c))
2a59a681
SH
1928 return b;
1929
1930 p = strdup(path);
afeecbba
SH
1931 if (!p) {
1932 ERROR("Out of memory setting new lxc path");
2a59a681 1933 goto err;
afeecbba
SH
1934 }
1935
2a59a681
SH
1936 b = true;
1937 if (c->config_path)
afeecbba 1938 oldpath = c->config_path;
2a59a681 1939 c->config_path = p;
afeecbba
SH
1940
1941 /* Since we've changed the config path, we have to change the
1942 * config file name too */
1943 if (!set_config_filename(c)) {
1944 ERROR("Out of memory setting new config filename");
1945 b = false;
1946 free(c->config_path);
1947 c->config_path = oldpath;
1948 oldpath = NULL;
1949 }
2a59a681 1950err:
afeecbba
SH
1951 if (oldpath)
1952 free(oldpath);
5cee8c50 1953 container_mem_unlock(c);
2a59a681
SH
1954 return b;
1955}
1956
1957
794dd120
SH
1958static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
1959{
1960 int ret;
794dd120
SH
1961
1962 if (!c)
1963 return false;
1964
3bc449ed 1965 if (is_stopped(c))
794dd120
SH
1966 return false;
1967
3bc449ed
SH
1968 if (container_disk_lock(c))
1969 return false;
794dd120 1970
33ad9f1a 1971 ret = lxc_cgroup_set(subsys, value, c->name, c->config_path);
3bc449ed
SH
1972
1973 container_disk_unlock(c);
1974 return ret == 0;
794dd120
SH
1975}
1976
1977static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
1978{
3bc449ed 1979 int ret;
794dd120 1980
6502006a 1981 if (!c)
794dd120
SH
1982 return -1;
1983
3bc449ed 1984 if (is_stopped(c))
794dd120
SH
1985 return -1;
1986
3bc449ed
SH
1987 if (container_disk_lock(c))
1988 return -1;
794dd120 1989
33ad9f1a 1990 ret = lxc_cgroup_get(subsys, retv, inlen, c->name, c->config_path);
794dd120 1991
3bc449ed 1992 container_disk_unlock(c);
794dd120
SH
1993 return ret;
1994}
1995
67e571de 1996const char *lxc_get_default_config_path(void)
83c98d82
DE
1997{
1998 return default_lxc_path();
1999}
794dd120 2000
a8428dfa
SH
2001const char *lxc_get_default_lvm_vg(void)
2002{
2003 return default_lvm_vg();
2004}
2005
f99c386b
SS
2006const char *lxc_get_default_lvm_thin_pool(void)
2007{
2008 return default_lvm_thin_pool();
2009}
2010
a8428dfa
SH
2011const char *lxc_get_default_zfs_root(void)
2012{
2013 return default_zfs_root();
2014}
2015
b6b918a1
SG
2016const char *lxc_get_version(void)
2017{
2018 return lxc_version();
2019}
2020
9be53773
SH
2021static int copy_file(char *old, char *new)
2022{
2023 int in, out;
2024 ssize_t len, ret;
2025 char buf[8096];
2026 struct stat sbuf;
2027
2028 if (file_exists(new)) {
2029 ERROR("copy destination %s exists", new);
2030 return -1;
2031 }
2032 ret = stat(old, &sbuf);
2033 if (ret < 0) {
dfb31b25 2034 INFO("Error stat'ing %s", old);
9be53773
SH
2035 return -1;
2036 }
2037
025ed0f3 2038 process_lock();
9be53773 2039 in = open(old, O_RDONLY);
025ed0f3 2040 process_unlock();
9be53773 2041 if (in < 0) {
dfb31b25 2042 SYSERROR("Error opening original file %s", old);
9be53773
SH
2043 return -1;
2044 }
025ed0f3 2045 process_lock();
9be53773 2046 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
025ed0f3 2047 process_unlock();
9be53773 2048 if (out < 0) {
dfb31b25 2049 SYSERROR("Error opening new file %s", new);
025ed0f3 2050 process_lock();
9be53773 2051 close(in);
025ed0f3 2052 process_unlock();
9be53773
SH
2053 return -1;
2054 }
2055
2056 while (1) {
2057 len = read(in, buf, 8096);
2058 if (len < 0) {
dfb31b25 2059 SYSERROR("Error reading old file %s", old);
9be53773
SH
2060 goto err;
2061 }
2062 if (len == 0)
2063 break;
2064 ret = write(out, buf, len);
2065 if (ret < len) { // should we retry?
dfb31b25 2066 SYSERROR("Error: write to new file %s was interrupted", new);
9be53773
SH
2067 goto err;
2068 }
2069 }
025ed0f3 2070 process_lock();
9be53773
SH
2071 close(in);
2072 close(out);
025ed0f3 2073 process_unlock();
9be53773
SH
2074
2075 // we set mode, but not owner/group
2076 ret = chmod(new, sbuf.st_mode);
2077 if (ret) {
dfb31b25 2078 SYSERROR("Error setting mode on %s", new);
9be53773
SH
2079 return -1;
2080 }
2081
2082 return 0;
2083
2084err:
025ed0f3 2085 process_lock();
9be53773
SH
2086 close(in);
2087 close(out);
025ed0f3 2088 process_unlock();
9be53773
SH
2089 return -1;
2090}
2091
9be53773
SH
2092static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
2093{
2094 int i;
2095 int ret;
2096 struct lxc_list *it;
2097
2098 for (i=0; i<NUM_LXC_HOOKS; i++) {
2099 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
2100 char *hookname = it->elem;
c32981c3 2101 char *fname = strrchr(hookname, '/');
9be53773
SH
2102 char tmppath[MAXPATHLEN];
2103 if (!fname) // relative path - we don't support, but maybe we should
2104 return 0;
2105 // copy the script, and change the entry in confile
2106 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
2107 c->config_path, c->name, fname+1);
2108 if (ret < 0 || ret >= MAXPATHLEN)
2109 return -1;
2110 ret = copy_file(it->elem, tmppath);
2111 if (ret < 0)
2112 return -1;
2113 free(it->elem);
2114 it->elem = strdup(tmppath);
2115 if (!it->elem) {
2116 ERROR("out of memory copying hook path");
2117 return -1;
2118 }
9be53773
SH
2119 }
2120 }
2121
2122 c->save_config(c, NULL);
2123 return 0;
2124}
2125
2126static void new_hwaddr(char *hwaddr)
2127{
025ed0f3
SH
2128 FILE *f;
2129 process_lock();
2130 f = fopen("/dev/urandom", "r");
2131 process_unlock();
9be53773
SH
2132 if (f) {
2133 unsigned int seed;
2134 int ret = fread(&seed, sizeof(seed), 1, f);
2135 if (ret != 1)
2136 seed = time(NULL);
025ed0f3 2137 process_lock();
9be53773 2138 fclose(f);
025ed0f3 2139 process_unlock();
9be53773
SH
2140 srand(seed);
2141 } else
2142 srand(time(NULL));
2143 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
2144 rand() % 255, rand() % 255, rand() % 255);
2145}
2146
2147static void network_new_hwaddrs(struct lxc_container *c)
2148{
2149 struct lxc_list *it;
2150
2151 lxc_list_for_each(it, &c->lxc_conf->network) {
2152 struct lxc_netdev *n = it->elem;
2153 if (n->hwaddr)
2154 new_hwaddr(n->hwaddr);
2155 }
2156}
2157
2158static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
2159{
2160 char newpath[MAXPATHLEN];
2161 char *oldpath = oldc->lxc_conf->fstab;
2162 int ret;
2163
2164 if (!oldpath)
2165 return 0;
2166
c32981c3 2167 char *p = strrchr(oldpath, '/');
9be53773
SH
2168 if (!p)
2169 return -1;
2170 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
2171 c->config_path, c->name, p);
2172 if (ret < 0 || ret >= MAXPATHLEN) {
2173 ERROR("error printing new path for %s", oldpath);
2174 return -1;
2175 }
2176 if (file_exists(newpath)) {
2177 ERROR("error: fstab file %s exists", newpath);
2178 return -1;
2179 }
2180
2181 if (copy_file(oldpath, newpath) < 0) {
2182 ERROR("error: copying %s to %s", oldpath, newpath);
2183 return -1;
2184 }
2185 free(c->lxc_conf->fstab);
2186 c->lxc_conf->fstab = strdup(newpath);
2187 if (!c->lxc_conf->fstab) {
2188 ERROR("error: allocating pathname");
2189 return -1;
2190 }
2191
2192 return 0;
2193}
2194
dfb31b25
SH
2195static void copy_rdepends(struct lxc_container *c, struct lxc_container *c0)
2196{
2197 char path0[MAXPATHLEN], path1[MAXPATHLEN];
2198 int ret;
2199
2200 ret = snprintf(path0, MAXPATHLEN, "%s/%s/lxc_rdepends", c0->config_path,
2201 c0->name);
2202 if (ret < 0 || ret >= MAXPATHLEN) {
2203 WARN("Error copying reverse dependencies");
2204 return;
2205 }
2206 ret = snprintf(path1, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2207 c->name);
2208 if (ret < 0 || ret >= MAXPATHLEN) {
2209 WARN("Error copying reverse dependencies");
2210 return;
2211 }
2212 if (copy_file(path0, path1) < 0) {
2213 INFO("Error copying reverse dependencies");
2214 return;
2215 }
2216}
2217
2218static bool add_rdepends(struct lxc_container *c, struct lxc_container *c0)
2219{
2220 int ret;
2221 char path[MAXPATHLEN];
2222 FILE *f;
2223 bool bret;
2224
2225 ret = snprintf(path, MAXPATHLEN, "%s/%s/lxc_rdepends", c->config_path,
2226 c->name);
2227 if (ret < 0 || ret >= MAXPATHLEN)
2228 return false;
025ed0f3 2229 process_lock();
dfb31b25 2230 f = fopen(path, "a");
025ed0f3 2231 process_unlock();
dfb31b25
SH
2232 if (!f)
2233 return false;
2234 bret = true;
2235 // if anything goes wrong, just return an error
2236 if (fprintf(f, "%s\n%s\n", c0->config_path, c0->name) < 0)
2237 bret = false;
025ed0f3 2238 process_lock();
dfb31b25
SH
2239 if (fclose(f) != 0)
2240 bret = false;
025ed0f3 2241 process_unlock();
dfb31b25
SH
2242 return bret;
2243}
2244
9be53773
SH
2245static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
2246 const char *newtype, int flags, const char *bdevdata, unsigned long newsize)
2247{
2248 struct bdev *bdev;
dfb31b25 2249 int need_rdep;
9be53773
SH
2250
2251 bdev = bdev_copy(c0->lxc_conf->rootfs.path, c0->name, c->name,
2252 c0->config_path, c->config_path, newtype, !!(flags & LXC_CLONE_SNAPSHOT),
dfb31b25 2253 bdevdata, newsize, &need_rdep);
9be53773 2254 if (!bdev) {
dfb31b25 2255 ERROR("Error copying storage");
9be53773
SH
2256 return -1;
2257 }
2258 free(c->lxc_conf->rootfs.path);
2259 c->lxc_conf->rootfs.path = strdup(bdev->src);
2260 bdev_put(bdev);
dfb31b25
SH
2261 if (!c->lxc_conf->rootfs.path) {
2262 ERROR("Out of memory while setting storage path");
9be53773 2263 return -1;
dfb31b25 2264 }
eee59f94
SH
2265 if (flags & LXC_CLONE_SNAPSHOT)
2266 copy_rdepends(c, c0);
dfb31b25
SH
2267 if (need_rdep) {
2268 if (!add_rdepends(c, c0))
2269 WARN("Error adding reverse dependency from %s to %s",
2270 c->name, c0->name);
2271 }
2272
2273 mod_all_rdeps(c, true);
2274
9be53773
SH
2275 return 0;
2276}
2277
1143ed39
DE
2278static int clone_update_rootfs(struct lxc_container *c0,
2279 struct lxc_container *c, int flags,
2280 char **hookargs)
9be53773
SH
2281{
2282 int ret = -1;
2283 char path[MAXPATHLEN];
2284 struct bdev *bdev;
2285 FILE *fout;
2286 pid_t pid;
148e91f5 2287 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
2288
2289 /* update hostname in rootfs */
2290 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2291
2292 pid = fork();
2293 if (pid < 0)
2294 return -1;
2295 if (pid > 0)
2296 return wait_for_pid(pid);
2297
025ed0f3 2298 process_unlock(); // we're no longer sharing
9be53773
SH
2299 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2300 if (!bdev)
2301 exit(1);
cf3ef16d
SH
2302 if (strcmp(bdev->type, "dir") != 0) {
2303 if (unshare(CLONE_NEWNS) < 0) {
2304 ERROR("error unsharing mounts");
2305 exit(1);
2306 }
2307 if (bdev->ops->mount(bdev) < 0)
2308 exit(1);
2309 } else { // TODO come up with a better way
2310 if (bdev->dest)
2311 free(bdev->dest);
2312 bdev->dest = strdup(bdev->src);
2313 }
148e91f5
SH
2314
2315 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
2316 /* Start of environment variable setup for hooks */
1143ed39
DE
2317 if (setenv("LXC_SRC_NAME", c0->name, 1)) {
2318 SYSERROR("failed to set environment variable for source container name");
2319 }
148e91f5
SH
2320 if (setenv("LXC_NAME", c->name, 1)) {
2321 SYSERROR("failed to set environment variable for container name");
2322 }
2323 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
2324 SYSERROR("failed to set environment variable for config path");
2325 }
2326 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
2327 SYSERROR("failed to set environment variable for rootfs mount");
2328 }
2329 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
2330 SYSERROR("failed to set environment variable for rootfs mount");
2331 }
2332
283678ed 2333 if (run_lxc_hooks(c->name, "clone", conf, c->get_config_path(c), hookargs)) {
148e91f5
SH
2334 ERROR("Error executing clone hook for %s", c->name);
2335 exit(1);
2336 }
2337 }
2338
2339 if (!(flags & LXC_CLONE_KEEPNAME)) {
2340 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
2341 if (ret < 0 || ret >= MAXPATHLEN)
2342 exit(1);
8058be39
DE
2343 if (!file_exists(path))
2344 exit(0);
148e91f5
SH
2345 if (!(fout = fopen(path, "w"))) {
2346 SYSERROR("unable to open %s: ignoring\n", path);
2347 exit(0);
2348 }
2349 if (fprintf(fout, "%s", c->name) < 0)
2350 exit(1);
2351 if (fclose(fout) < 0)
2352 exit(1);
9be53773 2353 }
9be53773
SH
2354 exit(0);
2355}
2356
2357/*
2358 * We want to support:
2359sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2360 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2361
2362-s [ implies overlayfs]
2363-s -B overlayfs
2364-s -B aufs
2365
2366only rootfs gets converted (copied/snapshotted) on clone.
2367*/
2368
2369static int create_file_dirname(char *path)
2370{
c32981c3 2371 char *p = strrchr(path, '/');
9be53773
SH
2372 int ret;
2373
2374 if (!p)
2375 return -1;
2376 *p = '\0';
2377 ret = mkdir(path, 0755);
2378 if (ret && errno != EEXIST)
2379 SYSERROR("creating container path %s\n", path);
2380 *p = '/';
2381 return ret;
2382}
2383
2384struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
2385 const char *lxcpath, int flags,
148e91f5
SH
2386 const char *bdevtype, const char *bdevdata, unsigned long newsize,
2387 char **hookargs)
9be53773
SH
2388{
2389 struct lxc_container *c2 = NULL;
2390 char newpath[MAXPATHLEN];
176d9acb 2391 int ret, storage_copied = 0;
9be53773
SH
2392 const char *n, *l;
2393 FILE *fout;
2394
2395 if (!c || !c->is_defined(c))
2396 return NULL;
2397
5cee8c50 2398 if (container_mem_lock(c))
9be53773
SH
2399 return NULL;
2400
39dc698c 2401 if (!is_stopped(c)) {
9be53773
SH
2402 ERROR("error: Original container (%s) is running", c->name);
2403 goto out;
2404 }
2405
2406 // Make sure the container doesn't yet exist.
2407 n = newname ? newname : c->name;
2408 l = lxcpath ? lxcpath : c->get_config_path(c);
2409 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
2410 if (ret < 0 || ret >= MAXPATHLEN) {
2411 SYSERROR("clone: failed making config pathname");
2412 goto out;
2413 }
2414 if (file_exists(newpath)) {
2415 ERROR("error: clone: %s exists", newpath);
2416 goto out;
2417 }
2418
96532523
SH
2419 ret = create_file_dirname(newpath);
2420 if (ret < 0 && errno != EEXIST) {
9be53773
SH
2421 ERROR("Error creating container dir for %s", newpath);
2422 goto out;
2423 }
2424
2425 // copy the configuration, tweak it as needed,
025ed0f3 2426 process_lock();
9be53773 2427 fout = fopen(newpath, "w");
025ed0f3 2428 process_unlock();
9be53773
SH
2429 if (!fout) {
2430 SYSERROR("open %s", newpath);
2431 goto out;
2432 }
2433 write_config(fout, c->lxc_conf);
025ed0f3 2434 process_lock();
9be53773 2435 fclose(fout);
025ed0f3 2436 process_unlock();
9be53773 2437
9be53773
SH
2438 sprintf(newpath, "%s/%s/rootfs", l, n);
2439 if (mkdir(newpath, 0755) < 0) {
2440 SYSERROR("error creating %s", newpath);
2441 goto out;
2442 }
2443
2444 c2 = lxc_container_new(n, l);
375c2258 2445 if (!c2) {
9be53773
SH
2446 ERROR("clone: failed to create new container (%s %s)", n, l);
2447 goto out;
2448 }
2449
96532523
SH
2450 // update utsname
2451 if (!set_config_item_locked(c2, "lxc.utsname", newname)) {
2452 ERROR("Error setting new hostname");
2453 goto out;
2454 }
2455
2456
9be53773
SH
2457 // copy hooks if requested
2458 if (flags & LXC_CLONE_COPYHOOKS) {
2459 ret = copyhooks(c, c2);
2460 if (ret < 0) {
2461 ERROR("error copying hooks");
9be53773
SH
2462 goto out;
2463 }
2464 }
2465
2466 if (copy_fstab(c, c2) < 0) {
2467 ERROR("error copying fstab");
9be53773
SH
2468 goto out;
2469 }
2470
2471 // update macaddrs
2472 if (!(flags & LXC_CLONE_KEEPMACADDR))
2473 network_new_hwaddrs(c2);
2474
2475 // copy/snapshot rootfs's
2476 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
375c2258 2477 if (ret < 0)
9be53773 2478 goto out;
9be53773 2479
176d9acb
SH
2480 // We've now successfully created c2's storage, so clear it out if we
2481 // fail after this
2482 storage_copied = 1;
2483
375c2258 2484 if (!c2->save_config(c2, NULL))
9be53773 2485 goto out;
9be53773 2486
1143ed39 2487 if (clone_update_rootfs(c, c2, flags, hookargs) < 0)
9be53773 2488 goto out;
9be53773
SH
2489
2490 // TODO: update c's lxc.snapshot = count
5cee8c50 2491 container_mem_unlock(c);
9be53773
SH
2492 return c2;
2493
2494out:
5cee8c50 2495 container_mem_unlock(c);
375c2258 2496 if (c2) {
176d9acb
SH
2497 if (!storage_copied)
2498 c2->lxc_conf->rootfs.path = NULL;
375c2258 2499 c2->destroy(c2);
9be53773 2500 lxc_container_put(c2);
375c2258 2501 }
9be53773
SH
2502
2503 return NULL;
2504}
2505
a0e93eeb
CS
2506static 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)
2507{
2508 if (!c)
2509 return -1;
2510
2511 return lxc_attach(c->name, c->config_path, exec_function, exec_payload, options, attached_process);
2512}
2513
2514static int lxcapi_attach_run_wait(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char * const argv[])
2515{
2516 lxc_attach_command_t command;
2517 pid_t pid;
2518 int r;
2519
2520 if (!c)
2521 return -1;
2522
2523 command.program = (char*)program;
2524 command.argv = (char**)argv;
2525 r = lxc_attach(c->name, c->config_path, lxc_attach_run_command, &command, options, &pid);
2526 if (r < 0) {
2527 ERROR("ups");
2528 return r;
2529 }
2530 return lxc_wait_for_pid_status(pid);
2531}
2532
f5dd1d53
SH
2533int get_next_index(const char *lxcpath, char *cname)
2534{
2535 char *fname;
2536 struct stat sb;
2537 int i = 0, ret;
2538
2539 fname = alloca(strlen(lxcpath) + 20);
2540 while (1) {
2541 sprintf(fname, "%s/snap%d", lxcpath, i);
2542 ret = stat(fname, &sb);
2543 if (ret != 0)
2544 return i;
2545 i++;
2546 }
2547}
2548
2549static int lxcapi_snapshot(struct lxc_container *c, char *commentfile)
2550{
2551 int i, flags, ret;
2552 struct lxc_container *c2;
2553 char snappath[MAXPATHLEN], newname[20];
2554
2555 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2556 ret = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2557 if (ret < 0 || ret >= MAXPATHLEN)
2558 return -1;
2559 i = get_next_index(snappath, c->name);
2560
2561 if (mkdir_p(snappath, 0755) < 0) {
2562 ERROR("Failed to create snapshot directory %s", snappath);
2563 return -1;
2564 }
2565
2566 ret = snprintf(newname, 20, "snap%d", i);
2567 if (ret < 0 || ret >= 20)
2568 return -1;
2569
2570 flags = LXC_CLONE_SNAPSHOT | LXC_CLONE_KEEPMACADDR | LXC_CLONE_KEEPNAME;
2571 c2 = c->clone(c, newname, snappath, flags, NULL, NULL, 0, NULL);
2572 if (!c2) {
2573 ERROR("clone of %s:%s failed\n", c->config_path, c->name);
2574 return -1;
2575 }
2576
2577 lxc_container_put(c2);
2578
2579 // Now write down the creation time
2580 time_t timer;
2581 char buffer[25];
2582 struct tm* tm_info;
025ed0f3 2583 FILE *f;
f5dd1d53
SH
2584
2585 time(&timer);
2586 tm_info = localtime(&timer);
2587
2588 strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info);
2589
2590 char *dfnam = alloca(strlen(snappath) + strlen(newname) + 5);
2591 sprintf(dfnam, "%s/%s/ts", snappath, newname);
025ed0f3
SH
2592 process_lock();
2593 f = fopen(dfnam, "w");
2594 process_unlock();
f5dd1d53
SH
2595 if (!f) {
2596 ERROR("Failed to open %s\n", dfnam);
2597 return -1;
2598 }
2599 if (fprintf(f, "%s", buffer) < 0) {
2600 SYSERROR("Writing timestamp");
2601 fclose(f);
2602 return -1;
2603 }
025ed0f3
SH
2604 process_lock();
2605 ret = fclose(f);
2606 process_unlock();
2607 if (ret != 0) {
f5dd1d53
SH
2608 SYSERROR("Writing timestamp");
2609 return -1;
2610 }
2611
2612 if (commentfile) {
2613 // $p / $name / comment \0
2614 int len = strlen(snappath) + strlen(newname) + 10;
2615 char *path = alloca(len);
2616 sprintf(path, "%s/%s/comment", snappath, newname);
2617 return copy_file(commentfile, path) < 0 ? -1 : i;
2618 }
2619
2620 return i;
2621}
2622
2623static void lxcsnap_free(struct lxc_snapshot *s)
2624{
2625 if (s->name)
2626 free(s->name);
2627 if (s->comment_pathname)
2628 free(s->comment_pathname);
2629 if (s->timestamp)
2630 free(s->timestamp);
2631 if (s->lxcpath)
2632 free(s->lxcpath);
2633}
2634
2635static char *get_snapcomment_path(char* snappath, char *name)
2636{
2637 // $snappath/$name/comment
2638 int ret, len = strlen(snappath) + strlen(name) + 10;
2639 char *s = malloc(len);
2640
2641 if (s) {
2642 ret = snprintf(s, len, "%s/%s/comment", snappath, name);
2643 if (ret < 0 || ret >= len) {
2644 free(s);
2645 s = NULL;
2646 }
2647 }
2648 return s;
2649}
2650
2651static char *get_timestamp(char* snappath, char *name)
2652{
2653 char path[MAXPATHLEN], *s = NULL;
2654 int ret, len;
2655 FILE *fin;
2656
2657 ret = snprintf(path, MAXPATHLEN, "%s/%s/ts", snappath, name);
2658 if (ret < 0 || ret >= MAXPATHLEN)
2659 return NULL;
025ed0f3
SH
2660 process_lock();
2661 fin = fopen(path, "r");
2662 process_unlock();
2663 if (!fin)
f5dd1d53
SH
2664 return NULL;
2665 (void) fseek(fin, 0, SEEK_END);
2666 len = ftell(fin);
2667 (void) fseek(fin, 0, SEEK_SET);
2668 if (len > 0) {
2669 s = malloc(len+1);
2670 if (s) {
2671 s[len] = '\0';
2672 if (fread(s, 1, len, fin) != len) {
2673 SYSERROR("reading timestamp");
2674 free(s);
2675 s = NULL;
2676 }
2677 }
2678 }
025ed0f3 2679 process_lock();
f5dd1d53 2680 fclose(fin);
025ed0f3 2681 process_unlock();
f5dd1d53
SH
2682 return s;
2683}
2684
2685static int lxcapi_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret_snaps)
2686{
2687 char snappath[MAXPATHLEN], path2[MAXPATHLEN];
2688 int dirlen, count = 0, ret;
2689 struct dirent dirent, *direntp;
2690 struct lxc_snapshot *snaps =NULL, *nsnaps;
2691 DIR *dir;
2692
2693 if (!c || !lxcapi_is_defined(c))
2694 return -1;
2695 // snappath is ${lxcpath}snaps/${lxcname}/
2696 dirlen = snprintf(snappath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2697 if (dirlen < 0 || dirlen >= MAXPATHLEN) {
2698 ERROR("path name too long");
2699 return -1;
2700 }
025ed0f3
SH
2701 process_lock();
2702 dir = opendir(snappath);
2703 process_unlock();
2704 if (!dir) {
f5dd1d53
SH
2705 INFO("failed to open %s - assuming no snapshots", snappath);
2706 return 0;
2707 }
2708
2709 while (!readdir_r(dir, &dirent, &direntp)) {
2710 if (!direntp)
2711 break;
2712
2713 if (!strcmp(direntp->d_name, "."))
2714 continue;
2715
2716 if (!strcmp(direntp->d_name, ".."))
2717 continue;
2718
2719 ret = snprintf(path2, MAXPATHLEN, "%s/%s/config", snappath, direntp->d_name);
2720 if (ret < 0 || ret >= MAXPATHLEN) {
2721 ERROR("pathname too long");
2722 goto out_free;
2723 }
2724 if (!file_exists(path2))
2725 continue;
2726 nsnaps = realloc(snaps, (count + 1)*sizeof(*snaps));
2727 if (!nsnaps) {
2728 SYSERROR("Out of memory");
2729 goto out_free;
2730 }
2731 snaps = nsnaps;
2732 snaps[count].free = lxcsnap_free;
2733 snaps[count].name = strdup(direntp->d_name);
2734 if (!snaps[count].name)
2735 goto out_free;
2736 snaps[count].lxcpath = strdup(snappath);
2737 if (!snaps[count].lxcpath) {
2738 free(snaps[count].name);
2739 goto out_free;
2740 }
2741 snaps[count].comment_pathname = get_snapcomment_path(snappath, direntp->d_name);
2742 snaps[count].timestamp = get_timestamp(snappath, direntp->d_name);
2743 count++;
2744 }
2745
025ed0f3 2746 process_lock();
f5dd1d53
SH
2747 if (closedir(dir))
2748 WARN("failed to close directory");
025ed0f3 2749 process_unlock();
f5dd1d53
SH
2750
2751 *ret_snaps = snaps;
2752 return count;
2753
2754out_free:
2755 if (snaps) {
2756 int i;
2757 for (i=0; i<count; i++)
2758 lxcsnap_free(&snaps[i]);
2759 free(snaps);
2760 }
9baa57bd
SH
2761 process_lock();
2762 if (closedir(dir))
2763 WARN("failed to close directory");
2764 process_unlock();
f5dd1d53
SH
2765 return -1;
2766}
2767
2768static bool lxcapi_snapshot_restore(struct lxc_container *c, char *snapname, char *newname)
2769{
2770 char clonelxcpath[MAXPATHLEN];
2771 int ret;
2772 struct lxc_container *snap, *rest;
2773 struct bdev *bdev;
2774 bool b = false;
2775
2776 if (!c || !c->name || !c->config_path)
2777 return false;
2778
2779 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
2780 if (!bdev) {
2781 ERROR("Failed to find original backing store type");
2782 return false;
2783 }
2784
2785 if (!newname)
2786 newname = c->name;
2787 if (strcmp(c->name, newname) == 0) {
2788 if (!lxcapi_destroy(c)) {
2789 ERROR("Could not destroy existing container %s", newname);
2790 bdev_put(bdev);
2791 return false;
2792 }
2793 }
2794 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2795 if (ret < 0 || ret >= MAXPATHLEN) {
2796 bdev_put(bdev);
2797 return false;
2798 }
2799 // how should we lock this?
2800
2801 snap = lxc_container_new(snapname, clonelxcpath);
2802 if (!snap || !lxcapi_is_defined(snap)) {
2803 ERROR("Could not open snapshot %s", snapname);
2804 if (snap) lxc_container_put(snap);
2805 bdev_put(bdev);
2806 return false;
2807 }
2808
2809 rest = lxcapi_clone(snap, newname, c->config_path, 0, bdev->type, NULL, 0, NULL);
2810 bdev_put(bdev);
2811 if (rest && lxcapi_is_defined(rest))
2812 b = true;
2813 if (rest)
2814 lxc_container_put(rest);
2815 lxc_container_put(snap);
2816 return b;
2817}
2818
771d96b3
ÇO
2819static bool lxcapi_snapshot_destroy(struct lxc_container *c, char *snapname)
2820{
2821 int ret;
2822 char clonelxcpath[MAXPATHLEN];
2823 struct lxc_container *snap = NULL;
2824
2825 if (!c || !c->name || !c->config_path)
2826 return false;
2827
2828 ret = snprintf(clonelxcpath, MAXPATHLEN, "%ssnaps/%s", c->config_path, c->name);
2829 if (ret < 0 || ret >= MAXPATHLEN)
2830 goto err;
2831
2832 snap = lxc_container_new(snapname, clonelxcpath);
2833 if (!snap || !lxcapi_is_defined(snap)) {
2834 ERROR("Could not find snapshot %s", snapname);
2835 goto err;
2836 }
2837
2838 if (!lxcapi_destroy(snap)) {
2839 ERROR("Could not destroy snapshot %s", snapname);
2840 goto err;
2841 }
2842 lxc_container_put(snap);
2843
2844 return true;
2845err:
2846 if (snap)
2847 lxc_container_put(snap);
2848 return false;
2849}
2850
b494d2dd
SH
2851static bool lxcapi_may_control(struct lxc_container *c)
2852{
2853 return lxc_try_cmd(c->name, c->config_path) == 0;
2854}
2855
a0e93eeb
CS
2856static int lxcapi_attach_run_waitl(struct lxc_container *c, lxc_attach_options_t *options, const char *program, const char *arg, ...)
2857{
2858 va_list ap;
2859 const char **argv;
2860 int ret;
2861
2862 if (!c)
2863 return -1;
2864
2865 va_start(ap, arg);
2866 argv = lxc_va_arg_list_to_argv_const(ap, 1);
2867 va_end(ap);
2868
2869 if (!argv) {
2870 ERROR("Memory allocation error.");
2871 return -1;
2872 }
2873 argv[0] = arg;
2874
2875 ret = lxcapi_attach_run_wait(c, options, program, (const char * const *)argv);
2876 free((void*)argv);
2877 return ret;
2878}
2879
afeecbba 2880struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
2881{
2882 struct lxc_container *c;
72d0e1cb
SG
2883
2884 c = malloc(sizeof(*c));
2885 if (!c) {
2886 fprintf(stderr, "failed to malloc lxc_container\n");
2887 return NULL;
2888 }
2889 memset(c, 0, sizeof(*c));
2890
afeecbba
SH
2891 if (configpath)
2892 c->config_path = strdup(configpath);
2893 else
67e571de 2894 c->config_path = strdup(default_lxc_path());
afeecbba 2895
2a59a681
SH
2896 if (!c->config_path) {
2897 fprintf(stderr, "Out of memory");
2898 goto err;
2899 }
2900
f5dd1d53 2901 remove_trailing_slashes(c->config_path);
72d0e1cb
SG
2902 c->name = malloc(strlen(name)+1);
2903 if (!c->name) {
2904 fprintf(stderr, "Error allocating lxc_container name\n");
2905 goto err;
2906 }
2907 strcpy(c->name, name);
2908
2909 c->numthreads = 1;
df271a59 2910 if (!(c->slock = lxc_newlock(c->config_path, name))) {
72d0e1cb
SG
2911 fprintf(stderr, "failed to create lock\n");
2912 goto err;
2913 }
2914
df271a59 2915 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
72d0e1cb
SG
2916 fprintf(stderr, "failed to alloc privlock\n");
2917 goto err;
2918 }
2919
afeecbba 2920 if (!set_config_filename(c)) {
72d0e1cb
SG
2921 fprintf(stderr, "Error allocating config file pathname\n");
2922 goto err;
2923 }
72d0e1cb
SG
2924
2925 if (file_exists(c->configfile))
2926 lxcapi_load_config(c, NULL);
2927
3e625e2d
SH
2928 if (ongoing_create(c) == 2) {
2929 ERROR("Error: %s creation was not completed", c->name);
1897e3bc
SH
2930 lxcapi_destroy(c);
2931 lxc_conf_free(c->lxc_conf);
2932 c->lxc_conf = NULL;
3e625e2d
SH
2933 }
2934
72d0e1cb
SG
2935 // assign the member functions
2936 c->is_defined = lxcapi_is_defined;
2937 c->state = lxcapi_state;
2938 c->is_running = lxcapi_is_running;
2939 c->freeze = lxcapi_freeze;
2940 c->unfreeze = lxcapi_unfreeze;
0115f8fd 2941 c->console = lxcapi_console;
b5159817 2942 c->console_getfd = lxcapi_console_getfd;
72d0e1cb
SG
2943 c->init_pid = lxcapi_init_pid;
2944 c->load_config = lxcapi_load_config;
2945 c->want_daemonize = lxcapi_want_daemonize;
130a1888 2946 c->want_close_all_fds = lxcapi_want_close_all_fds;
72d0e1cb
SG
2947 c->start = lxcapi_start;
2948 c->startl = lxcapi_startl;
2949 c->stop = lxcapi_stop;
2950 c->config_file_name = lxcapi_config_file_name;
2951 c->wait = lxcapi_wait;
2952 c->set_config_item = lxcapi_set_config_item;
2953 c->destroy = lxcapi_destroy;
2954 c->save_config = lxcapi_save_config;
2955 c->get_keys = lxcapi_get_keys;
2956 c->create = lxcapi_create;
2957 c->createl = lxcapi_createl;
2958 c->shutdown = lxcapi_shutdown;
3e625e2d 2959 c->reboot = lxcapi_reboot;
72d0e1cb
SG
2960 c->clear_config_item = lxcapi_clear_config_item;
2961 c->get_config_item = lxcapi_get_config_item;
794dd120
SH
2962 c->get_cgroup_item = lxcapi_get_cgroup_item;
2963 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
2964 c->get_config_path = lxcapi_get_config_path;
2965 c->set_config_path = lxcapi_set_config_path;
9be53773 2966 c->clone = lxcapi_clone;
799f29ab 2967 c->get_interfaces = lxcapi_get_interfaces;
9c83a661 2968 c->get_ips = lxcapi_get_ips;
a0e93eeb
CS
2969 c->attach = lxcapi_attach;
2970 c->attach_run_wait = lxcapi_attach_run_wait;
2971 c->attach_run_waitl = lxcapi_attach_run_waitl;
f5dd1d53
SH
2972 c->snapshot = lxcapi_snapshot;
2973 c->snapshot_list = lxcapi_snapshot_list;
2974 c->snapshot_restore = lxcapi_snapshot_restore;
771d96b3 2975 c->snapshot_destroy = lxcapi_snapshot_destroy;
b494d2dd 2976 c->may_control = lxcapi_may_control;
72d0e1cb
SG
2977
2978 /* we'll allow the caller to update these later */
ab1bf971 2979 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
72d0e1cb
SG
2980 fprintf(stderr, "failed to open log\n");
2981 goto err;
2982 }
2983
72d0e1cb
SG
2984 return c;
2985
2986err:
2987 lxc_container_free(c);
2988 return NULL;
2989}
2990
4a7c7daa 2991int lxc_get_wait_states(const char **states)
72d0e1cb
SG
2992{
2993 int i;
2994
2995 if (states)
2996 for (i=0; i<MAX_STATE; i++)
2997 states[i] = lxc_state2str(i);
2998 return MAX_STATE;
2999}
a41f104b 3000
a41f104b
SH
3001/*
3002 * These next two could probably be done smarter with reusing a common function
3003 * with different iterators and tests...
3004 */
3005int list_defined_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
3006{
3007 DIR *dir;
3008 int i, cfound = 0, nfound = 0;
3009 struct dirent dirent, *direntp;
3010 struct lxc_container *c;
3011
3012 if (!lxcpath)
3013 lxcpath = default_lxc_path();
3014
3015 process_lock();
3016 dir = opendir(lxcpath);
3017 process_unlock();
3018
3019 if (!dir) {
3020 SYSERROR("opendir on lxcpath");
3021 return -1;
3022 }
3023
3024 if (cret)
3025 *cret = NULL;
3026 if (names)
3027 *names = NULL;
3028
3029 while (!readdir_r(dir, &dirent, &direntp)) {
3030 if (!direntp)
3031 break;
3032 if (!strcmp(direntp->d_name, "."))
3033 continue;
3034 if (!strcmp(direntp->d_name, ".."))
3035 continue;
3036
3037 if (!config_file_exists(lxcpath, direntp->d_name))
3038 continue;
3039
3040 if (names) {
9c88ff1f 3041 if (!add_to_array(names, direntp->d_name, cfound))
a41f104b
SH
3042 goto free_bad;
3043 }
3044 cfound++;
3045
3046 if (!cret) {
3047 nfound++;
3048 continue;
3049 }
3050
3051 c = lxc_container_new(direntp->d_name, lxcpath);
3052 if (!c) {
3053 INFO("Container %s:%s has a config but could not be loaded",
3054 lxcpath, direntp->d_name);
3055 if (names)
9c88ff1f
ÇO
3056 if(!remove_from_array(names, direntp->d_name, cfound--))
3057 goto free_bad;
a41f104b
SH
3058 continue;
3059 }
3060 if (!lxcapi_is_defined(c)) {
3061 INFO("Container %s:%s has a config but is not defined",
3062 lxcpath, direntp->d_name);
3063 if (names)
9c88ff1f
ÇO
3064 if(!remove_from_array(names, direntp->d_name, cfound--))
3065 goto free_bad;
a41f104b
SH
3066 lxc_container_put(c);
3067 continue;
3068 }
3069
2871830a 3070 if (!add_to_clist(cret, c, nfound, true)) {
a41f104b
SH
3071 lxc_container_put(c);
3072 goto free_bad;
3073 }
3074 nfound++;
3075 }
3076
3077 process_lock();
3078 closedir(dir);
3079 process_unlock();
3080 return nfound;
3081
3082free_bad:
3083 if (names && *names) {
3084 for (i=0; i<cfound; i++)
3085 free((*names)[i]);
3086 free(*names);
3087 }
3088 if (cret && *cret) {
3089 for (i=0; i<nfound; i++)
3090 lxc_container_put((*cret)[i]);
3091 free(*cret);
3092 }
3093 process_lock();
3094 closedir(dir);
3095 process_unlock();
3096 return -1;
3097}
3098
3099int list_active_containers(const char *lxcpath, char ***names, struct lxc_container ***cret)
3100{
3101 int i, cfound = 0, nfound = 0;
3102 int lxcpath_len;
3103 char *line = NULL;
9c88ff1f 3104 char **unique_names = NULL;
a41f104b
SH
3105 size_t len = 0;
3106 struct lxc_container *c;
3107
3108 if (!lxcpath)
3109 lxcpath = default_lxc_path();
3110 lxcpath_len = strlen(lxcpath);
3111
3112 if (cret)
3113 *cret = NULL;
3114 if (names)
3115 *names = NULL;
3116
3117 process_lock();
3118 FILE *f = fopen("/proc/net/unix", "r");
3119 process_unlock();
3120 if (!f)
3121 return -1;
3122
3123 while (getline(&line, &len, f) != -1) {
0f8f9c8a 3124 char *p = strrchr(line, ' '), *p2;
a41f104b
SH
3125 if (!p)
3126 continue;
3127 p++;
3128 if (*p != 0x40)
3129 continue;
3130 p++;
3131 if (strncmp(p, lxcpath, lxcpath_len) != 0)
3132 continue;
3133 p += lxcpath_len;
3134 while (*p == '/')
3135 p++;
3136
3137 // Now p is the start of lxc_name
3138 p2 = index(p, '/');
3139 if (!p2 || strncmp(p2, "/command", 8) != 0)
3140 continue;
3141 *p2 = '\0';
3142
9c88ff1f
ÇO
3143 if (array_contains(&unique_names, p, nfound))
3144 continue;
3145
3146 if (!add_to_array(&unique_names, p, nfound))
3147 goto free_bad;
3148
a41f104b
SH
3149 cfound++;
3150
3151 if (!cret) {
3152 nfound++;
3153 continue;
3154 }
3155
3156 c = lxc_container_new(p, lxcpath);
3157 if (!c) {
3158 INFO("Container %s:%s is running but could not be loaded",
3159 lxcpath, p);
9c88ff1f
ÇO
3160 if (names) {
3161 if(!remove_from_array(&unique_names, p, cfound--))
3162 goto free_bad;
3163 }
a41f104b
SH
3164 continue;
3165 }
3166
3167 /*
3168 * If this is an anonymous container, then is_defined *can*
3169 * return false. So we don't do that check. Count on the
3170 * fact that the command socket exists.
3171 */
3172
2871830a 3173 if (!add_to_clist(cret, c, nfound, true)) {
a41f104b
SH
3174 lxc_container_put(c);
3175 goto free_bad;
3176 }
3177 nfound++;
3178 }
3179
9c88ff1f
ÇO
3180 if (names)
3181 *names = unique_names;
3182
e853a32d
ÇO
3183 if (line)
3184 free(line);
3185
a41f104b
SH
3186 process_lock();
3187 fclose(f);
3188 process_unlock();
3189 return nfound;
3190
3191free_bad:
3192 if (names && *names) {
3193 for (i=0; i<cfound; i++)
3194 free((*names)[i]);
3195 free(*names);
3196 }
3197 if (cret && *cret) {
3198 for (i=0; i<nfound; i++)
3199 lxc_container_put((*cret)[i]);
3200 free(*cret);
3201 }
e853a32d
ÇO
3202 if (line)
3203 free(line);
3204
a41f104b
SH
3205 process_lock();
3206 fclose(f);
3207 process_unlock();
3208 return -1;
3209}
2871830a
DE
3210
3211int list_all_containers(const char *lxcpath, char ***nret,
3212 struct lxc_container ***cret)
3213{
3214 int i, ret, active_cnt, ct_cnt, ct_list_cnt;
3215 char **active_name;
3216 char **ct_name;
3217 struct lxc_container **ct_list = NULL;
3218
3219 ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);
3220 if (ct_cnt < 0)
3221 return ct_cnt;
3222
3223 active_cnt = list_active_containers(lxcpath, &active_name, NULL);
3224 if (active_cnt < 0) {
3225 ret = active_cnt;
3226 goto free_ct_name;
3227 }
3228
3229 for (i = 0; i < active_cnt; i++) {
3230 if (!array_contains(&ct_name, active_name[i], ct_cnt)) {
3231 if (!add_to_array(&ct_name, active_name[i], ct_cnt)) {
3232 ret = -1;
3233 goto free_active_name;
3234 }
3235 ct_cnt++;
3236 }
3237 free(active_name[i]);
3238 active_name[i] = NULL;
3239 }
3240 free(active_name);
3241 active_name = NULL;
3242 active_cnt = 0;
3243
3244 for (i = 0, ct_list_cnt = 0; i < ct_cnt && cret; i++) {
3245 struct lxc_container *c;
3246
3247 c = lxc_container_new(ct_name[i], lxcpath);
3248 if (!c) {
3249 WARN("Container %s:%s could not be loaded", lxcpath, ct_name[i]);
3250 remove_from_array(&ct_name, ct_name[i], ct_cnt--);
3251 continue;
3252 }
3253
3254 if (!add_to_clist(&ct_list, c, ct_list_cnt, false)) {
3255 lxc_container_put(c);
3256 ret = -1;
3257 goto free_ct_list;
3258 }
3259 ct_list_cnt++;
3260 }
3261
3262 if (cret)
3263 *cret = ct_list;
3264
3265 if (nret)
3266 *nret = ct_name;
3267 else {
3268 ret = ct_cnt;
3269 goto free_ct_name;
3270 }
3271 return ct_cnt;
3272
3273free_ct_list:
3274 for (i = 0; i < ct_list_cnt; i++) {
3275 lxc_container_put(ct_list[i]);
3276 }
3277 if (ct_list)
3278 free(ct_list);
3279
3280free_active_name:
3281 for (i = 0; i < active_cnt; i++) {
3282 if (active_name[i])
3283 free(active_name[i]);
3284 }
3285 if (active_name)
3286 free(active_name);
3287
3288free_ct_name:
3289 for (i = 0; i < ct_cnt; i++) {
3290 free(ct_name[i]);
3291 }
3292 free(ct_name);
3293 return ret;
3294}