/
lxccontainer.c
3582 lines (3092 loc) · 79.9 KB
/
lxccontainer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* liblxcapi
*
* Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
* Copyright © 2012 Canonical Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define _GNU_SOURCE
#include <assert.h>
#include <stdarg.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <dirent.h>
#include <sched.h>
#include <arpa/inet.h>
#include <libgen.h>
#include <stdint.h>
#include <lxc/lxccontainer.h>
#include <lxc/version.h>
#include "config.h"
#include "lxc.h"
#include "state.h"
#include "conf.h"
#include "confile.h"
#include "console.h"
#include "cgroup.h"
#include "commands.h"
#include "log.h"
#include "bdev.h"
#include "utils.h"
#include "attach.h"
#include "monitor.h"
#include "namespace.h"
#include "lxclock.h"
#if HAVE_IFADDRS_H
#include <ifaddrs.h>
#else
#include <../include/ifaddrs.h>
#endif
#define MAX_BUFFER 4096
#define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
lxc_log_define(lxc_container, lxc);
static bool file_exists(const char *f)
{
struct stat statbuf;
return stat(f, &statbuf) == 0;
}
static bool config_file_exists(const char *lxcpath, const char *cname)
{
/* $lxcpath + '/' + $cname + '/config' + \0 */
int ret, len = strlen(lxcpath) + strlen(cname) + 9;
char *fname = alloca(len);
ret = snprintf(fname, len, "%s/%s/config", lxcpath, cname);
if (ret < 0 || ret >= len)
return false;
return file_exists(fname);
}
/*
* A few functions to help detect when a container creation failed.
* If a container creation was killed partway through, then trying
* to actually start that container could harm the host. We detect
* this by creating a 'partial' file under the container directory,
* and keeping an advisory lock. When container creation completes,
* we remove that file. When we load or try to start a container, if
* we find that file, without a flock, we remove the container.
*/
static int ongoing_create(struct lxc_container *c)
{
int len = strlen(c->config_path) + strlen(c->name) + 10;
char *path = alloca(len);
int fd, ret;
struct flock lk;
ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
if (ret < 0 || ret >= len) {
ERROR("Error writing partial pathname");
return -1;
}
if (!file_exists(path))
return 0;
fd = open(path, O_RDWR);
if (fd < 0) {
// give benefit of the doubt
SYSERROR("Error opening partial file");
return 0;
}
lk.l_type = F_WRLCK;
lk.l_whence = SEEK_SET;
lk.l_start = 0;
lk.l_len = 0;
lk.l_pid = -1;
if (fcntl(fd, F_GETLK, &lk) == 0 && lk.l_pid != -1) {
// create is still ongoing
close(fd);
return 1;
}
// create completed but partial is still there.
close(fd);
return 2;
}
static int create_partial(struct lxc_container *c)
{
// $lxcpath + '/' + $name + '/partial' + \0
int len = strlen(c->config_path) + strlen(c->name) + 10;
char *path = alloca(len);
int fd, ret;
struct flock lk;
ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
if (ret < 0 || ret >= len) {
ERROR("Error writing partial pathname");
return -1;
}
if ((fd=open(path, O_RDWR | O_CREAT | O_EXCL, 0755)) < 0) {
SYSERROR("Erorr creating partial file");
return -1;
}
lk.l_type = F_WRLCK;
lk.l_whence = SEEK_SET;
lk.l_start = 0;
lk.l_len = 0;
if (fcntl(fd, F_SETLKW, &lk) < 0) {
SYSERROR("Error locking partial file %s", path);
close(fd);
return -1;
}
return fd;
}
static void remove_partial(struct lxc_container *c, int fd)
{
// $lxcpath + '/' + $name + '/partial' + \0
int len = strlen(c->config_path) + strlen(c->name) + 10;
char *path = alloca(len);
int ret;
close(fd);
ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
if (ret < 0 || ret >= len) {
ERROR("Error writing partial pathname");
return;
}
if (unlink(path) < 0)
SYSERROR("Error unlink partial file %s", path);
}
/* LOCKING
* 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
* 2. container_disk_lock(c) protects the on-disk container data - in particular the
* container configuration file.
* The container_disk_lock also takes the container_mem_lock.
* 3. thread_mutex protects process data (ex: fd table) from multiple threads.
* NOTHING mutexes two independent programs with their own struct
* lxc_container for the same c->name, between API calls. For instance,
* c->config_read(); c->start(); Between those calls, data on disk
* could change (which shouldn't bother the caller unless for instance
* the rootfs get moved). c->config_read(); update; c->config_write();
* Two such updaters could race. The callers should therefore check their
* results. Trying to prevent that would necessarily expose us to deadlocks
* due to hung callers. So I prefer to keep the locks only within our own
* functions, not across functions.
*
* If you're going to clone while holding a lxccontainer, increment
* c->numthreads (under privlock) before forking. When deleting,
* decrement numthreads under privlock, then if it hits 0 you can delete.
* Do not ever use a lxccontainer whose numthreads you did not bump.
*/
static void lxc_container_free(struct lxc_container *c)
{
if (!c)
return;
if (c->configfile) {
free(c->configfile);
c->configfile = NULL;
}
if (c->error_string) {
free(c->error_string);
c->error_string = NULL;
}
if (c->slock) {
lxc_putlock(c->slock);
c->slock = NULL;
}
if (c->privlock) {
lxc_putlock(c->privlock);
c->privlock = NULL;
}
if (c->name) {
free(c->name);
c->name = NULL;
}
if (c->lxc_conf) {
lxc_conf_free(c->lxc_conf);
c->lxc_conf = NULL;
}
if (c->config_path) {
free(c->config_path);
c->config_path = NULL;
}
free(c);
}
/*
* Consider the following case:
freer | racing get()er
==================================================================
lxc_container_put() | lxc_container_get()
\ lxclock(c->privlock) | c->numthreads < 1? (no)
\ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
\ lxcunlock() | \
\ lxc_container_free() | \ lxclock() returns
| \ c->numthreads < 1 -> return 0
\ \ (free stuff) |
\ \ sem_destroy(privlock) |
* When the get()er checks numthreads the first time, one of the following
* is true:
* 1. freer has set numthreads = 0. get() returns 0
* 2. freer is between lxclock and setting numthreads to 0. get()er will
* sem_wait on privlock, get lxclock after freer() drops it, then see
* numthreads is 0 and exit without touching lxclock again..
* 3. freer has not yet locked privlock. If get()er runs first, then put()er
* will see --numthreads = 1 and not call lxc_container_free().
*/
int lxc_container_get(struct lxc_container *c)
{
if (!c)
return 0;
// if someone else has already started freeing the container, don't
// try to take the lock, which may be invalid
if (c->numthreads < 1)
return 0;
if (container_mem_lock(c))
return 0;
if (c->numthreads < 1) {
// bail without trying to unlock, bc the privlock is now probably
// in freed memory
return 0;
}
c->numthreads++;
container_mem_unlock(c);
return 1;
}
int lxc_container_put(struct lxc_container *c)
{
if (!c)
return -1;
if (container_mem_lock(c))
return -1;
if (--c->numthreads < 1) {
container_mem_unlock(c);
lxc_container_free(c);
return 1;
}
container_mem_unlock(c);
return 0;
}
static bool lxcapi_is_defined(struct lxc_container *c)
{
struct stat statbuf;
bool ret = false;
int statret;
if (!c)
return false;
if (container_mem_lock(c))
return false;
if (!c->configfile)
goto out;
statret = stat(c->configfile, &statbuf);
if (statret != 0)
goto out;
ret = true;
out:
container_mem_unlock(c);
return ret;
}
static const char *lxcapi_state(struct lxc_container *c)
{
lxc_state_t s;
if (!c)
return NULL;
s = lxc_getstate(c->name, c->config_path);
return lxc_state2str(s);
}
static bool is_stopped(struct lxc_container *c)
{
lxc_state_t s;
s = lxc_getstate(c->name, c->config_path);
return (s == STOPPED);
}
static bool lxcapi_is_running(struct lxc_container *c)
{
const char *s;
if (!c)
return false;
s = lxcapi_state(c);
if (!s || strcmp(s, "STOPPED") == 0)
return false;
return true;
}
static bool lxcapi_freeze(struct lxc_container *c)
{
int ret;
if (!c)
return false;
ret = lxc_freeze(c->name, c->config_path);
if (ret)
return false;
return true;
}
static bool lxcapi_unfreeze(struct lxc_container *c)
{
int ret;
if (!c)
return false;
ret = lxc_unfreeze(c->name, c->config_path);
if (ret)
return false;
return true;
}
static int lxcapi_console_getfd(struct lxc_container *c, int *ttynum, int *masterfd)
{
int ttyfd;
if (!c)
return -1;
ttyfd = lxc_console_getfd(c, ttynum, masterfd);
return ttyfd;
}
static int lxcapi_console(struct lxc_container *c, int ttynum, int stdinfd,
int stdoutfd, int stderrfd, int escape)
{
return lxc_console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape);
}
static pid_t lxcapi_init_pid(struct lxc_container *c)
{
if (!c)
return -1;
return lxc_cmd_get_init_pid(c->name, c->config_path);
}
static bool load_config_locked(struct lxc_container *c, const char *fname)
{
if (!c->lxc_conf)
c->lxc_conf = lxc_conf_init();
if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
return true;
return false;
}
static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
{
bool ret = false, need_disklock = false;
int lret;
const char *fname;
if (!c)
return false;
fname = c->configfile;
if (alt_file)
fname = alt_file;
if (!fname)
return false;
/*
* If we're reading something other than the container's config,
* we only need to lock the in-memory container. If loading the
* container's config file, take the disk lock.
*/
if (strcmp(fname, c->configfile) == 0)
need_disklock = true;
if (need_disklock)
lret = container_disk_lock(c);
else
lret = container_mem_lock(c);
if (lret)
return false;
ret = load_config_locked(c, fname);
if (need_disklock)
container_disk_unlock(c);
else
container_mem_unlock(c);
return ret;
}
static bool lxcapi_want_daemonize(struct lxc_container *c, bool state)
{
if (!c || !c->lxc_conf)
return false;
if (container_mem_lock(c)) {
ERROR("Error getting mem lock");
return false;
}
c->daemonize = state;
/* daemonize implies close_all_fds so set it */
if (state == 1)
c->lxc_conf->close_all_fds = 1;
container_mem_unlock(c);
return true;
}
static bool lxcapi_want_close_all_fds(struct lxc_container *c, bool state)
{
if (!c || !c->lxc_conf)
return false;
if (container_mem_lock(c)) {
ERROR("Error getting mem lock");
return false;
}
c->lxc_conf->close_all_fds = state;
container_mem_unlock(c);
return true;
}
static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
{
int ret;
if (!c)
return false;
ret = lxc_wait(c->name, state, timeout, c->config_path);
return ret == 0;
}
static bool wait_on_daemonized_start(struct lxc_container *c, int pid)
{
/* we'll probably want to make this timeout configurable? */
int timeout = 5, ret, status;
/*
* our child is going to fork again, then exit. reap the
* child
*/
ret = waitpid(pid, &status, 0);
if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
DEBUG("failed waiting for first dual-fork child");
return lxcapi_wait(c, "RUNNING", timeout);
}
static bool am_single_threaded(void)
{
struct dirent dirent, *direntp;
DIR *dir;
int count=0;
dir = opendir("/proc/self/task");
if (!dir) {
INFO("failed to open /proc/self/task");
return false;
}
while (!readdir_r(dir, &dirent, &direntp)) {
if (!direntp)
break;
if (!strcmp(direntp->d_name, "."))
continue;
if (!strcmp(direntp->d_name, ".."))
continue;
if (++count > 1)
break;
}
closedir(dir);
return count == 1;
}
/*
* I can't decide if it'd be more convenient for callers if we accept '...',
* or a null-terminated array (i.e. execl vs execv)
*/
static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
{
int ret;
struct lxc_conf *conf;
bool daemonize = false;
FILE *pid_fp = NULL;
char *default_args[] = {
"/sbin/init",
'\0',
};
/* container exists */
if (!c)
return false;
/* container has been setup */
if (!c->lxc_conf)
return false;
if ((ret = ongoing_create(c)) < 0) {
ERROR("Error checking for incomplete creation");
return false;
}
if (ret == 2) {
ERROR("Error: %s creation was not completed", c->name);
c->destroy(c);
return false;
} else if (ret == 1) {
ERROR("Error: creation of %s is ongoing", c->name);
return false;
}
/* is this app meant to be run through lxcinit, as in lxc-execute? */
if (useinit && !argv)
return false;
if (container_mem_lock(c))
return false;
conf = c->lxc_conf;
daemonize = c->daemonize;
container_mem_unlock(c);
if (useinit) {
ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
return ret == 0 ? true : false;
}
if (!argv)
argv = default_args;
/*
* say, I'm not sure - what locks do we want here? Any?
* Is liblxc's locking enough here to protect the on disk
* container? We don't want to exclude things like lxc_info
* while container is running...
*/
if (daemonize) {
lxc_monitord_spawn(c->config_path);
pid_t pid = fork();
if (pid < 0)
return false;
if (pid != 0) {
/* Set to NULL because we don't want father unlink
* the PID file, child will do the free and unlink.
*/
c->pidfile = NULL;
return wait_on_daemonized_start(c, pid);
}
/* second fork to be reparented by init */
pid = fork();
if (pid < 0) {
SYSERROR("Error doing dual-fork");
return false;
}
if (pid != 0)
exit(0);
/* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
if (chdir("/")) {
SYSERROR("Error chdir()ing to /.");
return false;
}
close(0);
close(1);
close(2);
open("/dev/zero", O_RDONLY);
open("/dev/null", O_RDWR);
open("/dev/null", O_RDWR);
setsid();
} else {
if (!am_single_threaded()) {
ERROR("Cannot start non-daemonized container when threaded");
return false;
}
}
/* We need to write PID file after daeminize, so we always
* write the right PID.
*/
if (c->pidfile) {
pid_fp = fopen(c->pidfile, "w");
if (pid_fp == NULL) {
SYSERROR("Failed to create pidfile '%s' for '%s'",
c->pidfile, c->name);
return false;
}
if (fprintf(pid_fp, "%d\n", getpid()) < 0) {
SYSERROR("Failed to write '%s'", c->pidfile);
fclose(pid_fp);
pid_fp = NULL;
return false;
}
fclose(pid_fp);
pid_fp = NULL;
}
reboot:
conf->reboot = 0;
ret = lxc_start(c->name, argv, conf, c->config_path);
if (conf->reboot) {
INFO("container requested reboot");
conf->reboot = 0;
goto reboot;
}
if (c->pidfile) {
unlink(c->pidfile);
free(c->pidfile);
c->pidfile = NULL;
}
if (daemonize)
exit (ret == 0 ? true : false);
else
return (ret == 0 ? true : false);
}
/*
* note there MUST be an ending NULL
*/
static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
{
va_list ap;
char **inargs = NULL;
bool bret = false;
/* container exists */
if (!c)
return false;
va_start(ap, useinit);
inargs = lxc_va_arg_list_to_argv(ap, 0, 1);
va_end(ap);
if (!inargs) {
ERROR("Memory allocation error.");
goto out;
}
/* pass NULL if no arguments were supplied */
bret = lxcapi_start(c, useinit, *inargs ? inargs : NULL);
out:
if (inargs) {
char **arg;
for (arg = inargs; *arg; arg++)
free(*arg);
free(inargs);
}
return bret;
}
static bool lxcapi_stop(struct lxc_container *c)
{
int ret;
if (!c)
return false;
ret = lxc_cmd_stop(c->name, c->config_path);
return ret == 0;
}
/*
* create the standard expected container dir
*/
static bool create_container_dir(struct lxc_container *c)
{
char *s;
int len, ret;
len = strlen(c->config_path) + strlen(c->name) + 2;
s = malloc(len);
if (!s)
return false;
ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
if (ret < 0 || ret >= len) {
free(s);
return false;
}
ret = mkdir(s, 0755);
if (ret) {
if (errno == EEXIST)
ret = 0;
else
SYSERROR("failed to create container path for %s\n", c->name);
}
free(s);
return ret == 0;
}
static const char *lxcapi_get_config_path(struct lxc_container *c);
static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v);
/*
* do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
* it returns a mounted bdev on success, NULL on error.
*/
static struct bdev *do_bdev_create(struct lxc_container *c, const char *type,
struct bdev_specs *specs)
{
char *dest;
size_t len;
struct bdev *bdev;
int ret;
/* rootfs.path or lxcpath/lxcname/rootfs */
if (c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0) {
const char *rpath = c->lxc_conf->rootfs.path;
len = strlen(rpath) + 1;
dest = alloca(len);
ret = snprintf(dest, len, "%s", rpath);
} else {
const char *lxcpath = lxcapi_get_config_path(c);
len = strlen(c->name) + strlen(lxcpath) + 9;
dest = alloca(len);
ret = snprintf(dest, len, "%s/%s/rootfs", lxcpath, c->name);
}
if (ret < 0 || ret >= len)
return NULL;
bdev = bdev_create(dest, type, c->name, specs);
if (!bdev) {
ERROR("Failed to create backing store type %s\n", type);
return NULL;
}
lxcapi_set_config_item(c, "lxc.rootfs", bdev->src);
/* if we are not root, chown the rootfs dir to root in the
* target uidmap */
if (geteuid() != 0) {
if (chown_mapped_root(bdev->dest, c->lxc_conf) < 0) {
ERROR("Error chowning %s to container root\n", bdev->dest);
bdev_put(bdev);
return NULL;
}
}
return bdev;
}
/*
* Given the '-t' template option to lxc-create, figure out what to
* do. If the template is a full executable path, use that. If it
* is something like 'sshd', then return $templatepath/lxc-sshd.
* On success return the template, on error return NULL.
*/
static char *get_template_path(const char *t)
{
int ret, len;
char *tpath;
if (t[0] == '/' && access(t, X_OK) == 0) {
tpath = strdup(t);
return tpath;
}
len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
tpath = malloc(len);
if (!tpath)
return NULL;
ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
if (ret < 0 || ret >= len) {
free(tpath);
return NULL;
}
if (access(tpath, X_OK) < 0) {
SYSERROR("bad template: %s\n", t);
free(tpath);
return NULL;
}
return tpath;
}
static char *lxcbasename(char *path)
{
char *p = path + strlen(path) - 1;
while (*p != '/' && p > path)
p--;
return p;
}
static bool create_run_template(struct lxc_container *c, char *tpath, bool quiet,
char *const argv[])
{
pid_t pid;
if (!tpath)
return true;
pid = fork();
if (pid < 0) {
SYSERROR("failed to fork task for container creation template\n");
return false;
}
if (pid == 0) { // child
char *patharg, *namearg, *rootfsarg, *src;
struct bdev *bdev = NULL;
int i;
int ret, len, nargs = 0;
char **newargv;
struct lxc_conf *conf = c->lxc_conf;
if (quiet) {
close(0);
close(1);
close(2);
open("/dev/zero", O_RDONLY);
open("/dev/null", O_RDWR);
open("/dev/null", O_RDWR);
}
src = c->lxc_conf->rootfs.path;
/*
* for an overlayfs create, what the user wants is the template to fill
* in what will become the readonly lower layer. So don't mount for
* the template
*/
if (strncmp(src, "overlayfs:", 10) == 0) {
src = overlayfs_getlower(src+10);
}
bdev = bdev_init(src, c->lxc_conf->rootfs.mount, NULL);
if (!bdev) {
ERROR("Error opening rootfs");
exit(1);
}
if (geteuid() == 0) {
if (unshare(CLONE_NEWNS) < 0) {
ERROR("error unsharing mounts");
exit(1);
}
if (detect_shared_rootfs()) {
if (mount("", "", NULL, MS_SLAVE|MS_REC, 0)) {
SYSERROR("Failed to make / rslave to run template");
ERROR("Continuing...");
}
}
}
if (strcmp(bdev->type, "dir") != 0) {
if (geteuid() != 0) {
ERROR("non-root users can only create directory-backed containers");
exit(1);
}
if (bdev->ops->mount(bdev) < 0) {
ERROR("Error mounting rootfs");
exit(1);
}
} else { // TODO come up with a better way here!
if (bdev->dest)
free(bdev->dest);
bdev->dest = strdup(bdev->src);
}
/*
* create our new array, pre-pend the template name and
* base args
*/
if (argv)
for (nargs = 0; argv[nargs]; nargs++) ;
nargs += 4; // template, path, rootfs and name args
newargv = malloc(nargs * sizeof(*newargv));
if (!newargv)
exit(1);
newargv[0] = lxcbasename(tpath);
len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
patharg = malloc(len);
if (!patharg)
exit(1);
ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
if (ret < 0 || ret >= len)
exit(1);
newargv[1] = patharg;
len = strlen("--name=") + strlen(c->name) + 1;
namearg = malloc(len);
if (!namearg)
exit(1);
ret = snprintf(namearg, len, "--name=%s", c->name);
if (ret < 0 || ret >= len)
exit(1);
newargv[2] = namearg;
len = strlen("--rootfs=") + 1 + strlen(bdev->dest);
rootfsarg = malloc(len);
if (!rootfsarg)
exit(1);
ret = snprintf(rootfsarg, len, "--rootfs=%s", bdev->dest);
if (ret < 0 || ret >= len)
exit(1);
newargv[3] = rootfsarg;
/* add passed-in args */
if (argv)
for (i = 4; i < nargs; i++)
newargv[i] = argv[i-4];
/* add trailing NULL */
nargs++;
newargv = realloc(newargv, nargs * sizeof(*newargv));
if (!newargv)
exit(1);
newargv[nargs - 1] = NULL;
/*
* If we're running the template in a mapped userns, then
* we prepend the template command with:
* lxc-usernsexec <-m map1> ... <-m mapn> --
* and we append "--mapped-uid x", where x is the mapped uid
* for our geteuid()
*/
if (geteuid() != 0 && !lxc_list_empty(&conf->id_map)) {
int n2args = 1;
char txtuid[20];
char **n2 = malloc(n2args * sizeof(*n2));
struct lxc_list *it;
struct id_map *map;
if (!n2) {
SYSERROR("out of memory");
exit(1);
}
newargv[0] = tpath;
tpath = "lxc-usernsexec";
n2[0] = "lxc-usernsexec";
lxc_list_for_each(it, &conf->id_map) {
map = it->elem;
n2args += 2;
n2 = realloc(n2, n2args * sizeof(char *));
if (!n2)
exit(1);
n2[n2args-2] = "-m";
n2[n2args-1] = malloc(200);
if (!n2[n2args-1])
exit(1);
ret = snprintf(n2[n2args-1], 200, "%c:%lu:%lu:%lu",