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
|
/* run-guix-system-container.c — daemon that starts Guix system
* containers on request, meant to be run as root from shepherd (Guix
* System) or systemd (Debian).
*
* Usage:
* run-guix-system-container [--listen IP] [--port N] [--fingerprint WORD]
*
* It listens on the given IP (default 127.0.0.1 — loopback only).
* Pass an explicit IP such as 0.0.0.0 to listen on all interfaces.
*
* The daemon has a FINGERPRINT: a short word or version (e.g. "v0.1")
* given with --fingerprint, or a random hash generated at startup when
* not specified. Clients can verify they are talking to the daemon
* they expect (FINGERPRINT command, or "START <hash> <fingerprint>").
* The fingerprint is also passed to started containers in the
* GUIX_CONTAINER_FINGERPRINT environment variable, so a container can
* show which daemon generation started it (e.g. in /etc/issue).
*
* When the daemon receives SIGINT or SIGTERM it terminates the
* containers it started: SIGTERM, then after a 10 s timeout SIGKILL.
*
* The daemon runs AT MOST ONE container at a time: START is refused
* while a previously started container is still alive.
*
* Protocol (one line per connection):
* START <hash|/gnu/store/HASH-run-container> [<fingerprint>]\n
* → OK <pid>\n container started
* → ERR <reason>\n validation failure (a non-matching optional
* fingerprint yields "ERR fingerprint mismatch")
* KILL <pid>\n
* → OK killed <pid>\n SIGKILL (kill -9) sent
* → ERR <reason>\n not a known container, etc.
* LIST\n
* → OK\n + one "<pid> <name>" line per running container
* LOG <hash|/gnu/store/HASH-run-container>\n
* → OK\n + the raw contents of the container's log file
* (LOG_DIR/HASH-run-container.log)
* → ERR <reason>\n no log file
* FINGERPRINT\n
* → OK <fingerprint>\n the daemon's fingerprint
*
* Container stdout/stderr is appended to LOG_DIR (default
* /var/log/guix-containers) so boot failures can be diagnosed.
*
* The daemon refuses to start unless it runs as root with CAP_SETUID
* and CAP_SYS_ADMIN: without them every START would fork a container
* that dies within milliseconds (EPERM writing /proc/PID/uid_map, or
* mounting its file systems) and leave no useful trace behind.
*
* Before exec'ing a container script it is verified that:
* - the resolved name is exactly HASH-run-container (32-char nix-base32)
* - the script contents reference linux-container
* - the file is a direct child of /gnu/store, executable and immutable
* (no write bits; Guix store items are 0555 root-owned)
*
* Build: gcc -O2 -Wall -o run-guix-system-container run-guix-system-container.c
*/
#include <arpa/inet.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdint.h>
#define PROGRAM "run-guix-system-container"
#define STORE "/gnu/store/"
#define DEFAULT_PORT 8989
#define DEFAULT_LISTEN "127.0.0.1"
#define MAX_LINE 256
/* Container stdout/stderr is appended to LOG_DIR/<name>.log. The
* default suits a system-wide install; --log-dir (or
* GUIX_CONTAINER_LOG_DIR) takes a directory the daemon can write, for
* hosts where /var/log is read-only or the daemon is not system-wide. */
#define DEFAULT_LOG_DIR "/var/log/guix-containers"
static const char *log_dir = DEFAULT_LOG_DIR;
/* The two capabilities container creation needs, from
* <linux/capability.h> (not included to keep the build dependency-free).
* CAP_SETUID: write the 65536-entry uid_map of the container's user
* namespace. CAP_SYS_ADMIN: mount its file systems, /proc and /dev. */
#define CAP_SETUID 7
#define CAP_SYS_ADMIN 21
/* Fingerprint of this daemon instance: a short word or version
* ("v0.1") given with --fingerprint, or a random hash when none is
* given. Used to make sure clients talk to the daemon they expect,
* and passed to containers via GUIX_CONTAINER_FINGERPRINT. */
static char daemon_fingerprint[33];
/* Set when SIGINT/SIGTERM asks us to shut down. */
static volatile sig_atomic_t stop_requested;
static void logmsg(const char *fmt, ...)
{
va_list ap;
flockfile(stderr);
fprintf(stderr, "[%d] ", (int)time(NULL));
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
funlockfile(stderr);
}
/* ------------------------------------------------------------------ */
/* Privileges */
/* ------------------------------------------------------------------ */
/* Parse the CapEff bitmask (hex) from /proc/self/status. Returns 0
* when it cannot be read, in which case the caller trusts the uid. */
static int read_cap_eff(unsigned long long *caps)
{
char line[MAX_LINE];
FILE *port = fopen("/proc/self/status", "r");
int found = 0;
if (!port)
return 0;
while (fgets(line, sizeof(line), port))
if (strncmp(line, "CapEff:", 7) == 0) {
char *end;
*caps = strtoull(line + 7, &end, 16);
found = end != line + 7;
break;
}
fclose(port);
return found;
}
/* Refuse to serve when we cannot create containers: as non-root every
* START would exec a launcher that dies before it can even write its
* log, and a client only sees "OK <pid>" followed by silence. */
static int have_container_privileges(void)
{
unsigned long long cap_eff = 0;
int ok = 1;
if (geteuid() != 0) {
logmsg("error: %s must run as root (uid %d): container "
"creation needs CAP_SETUID and CAP_SYS_ADMIN, without "
"them every START fails",
PROGRAM, (int)geteuid());
return 0;
}
if (!read_cap_eff(&cap_eff))
return 1; /* no CapEff: trust euid 0 */
if (!(cap_eff & (1ULL << CAP_SETUID))) {
logmsg("error: root but without CAP_SETUID: cannot write the "
"container's uid_map");
ok = 0;
}
if (!(cap_eff & (1ULL << CAP_SYS_ADMIN))) {
logmsg("error: root but without CAP_SYS_ADMIN: cannot mount "
"the container's file systems");
ok = 0;
}
return ok;
}
/* Container boot output goes to LOG_DIR. When it cannot be created or
* written (read-only /var, hardened unit) that output is lost and a
* boot failure cannot be diagnosed, so complain loudly -- but keep
* serving, the container itself still works. */
static void check_log_dir(void)
{
char path[MAX_LINE];
int fd;
snprintf(path, sizeof(path), "%s/.writable", log_dir);
if (mkdir(log_dir, 0755) < 0 && errno != EEXIST) {
logmsg("warning: cannot create %s: %s -- container boot "
"output will be lost", log_dir, strerror(errno));
return;
}
fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
logmsg("warning: cannot write to %s: %s -- container boot "
"output will be lost", log_dir, strerror(errno));
return;
}
close(fd);
unlink(path);
}
/* ------------------------------------------------------------------ */
/* Fingerprint */
/* ------------------------------------------------------------------ */
/* A fingerprint must be a short word or version like "v0.1": 1–32
* printable characters, no whitespace or control characters. */
static int valid_fingerprint(const char *s)
{
size_t i, len = strlen(s);
if (len == 0 || len > sizeof(daemon_fingerprint) - 1)
return 0;
for (i = 0; i < len; i++)
if (isspace((unsigned char)s[i]) ||
iscntrl((unsigned char)s[i]))
return 0;
return 1;
}
/* Generate a random 8-char hex fingerprint into daemon_fingerprint. */
static void random_fingerprint(void)
{
unsigned char rnd[4];
int fd = open("/dev/urandom", O_RDONLY);
size_t i;
if (fd < 0 || read(fd, rnd, sizeof(rnd)) != sizeof(rnd)) {
/* fallback: mix of time, pid and a stack address */
unsigned x = (unsigned)time(NULL) ^ ((unsigned)getpid() << 16) ^
(unsigned)(uintptr_t)&rnd;
for (i = 0; i < sizeof(rnd); i++) {
rnd[i] = (unsigned char)x;
x = x * 1103515245u + 12345u;
}
}
if (fd >= 0)
close(fd);
for (i = 0; i < sizeof(rnd); i++)
sprintf(daemon_fingerprint + i * 2, "%02x", rnd[i]);
}
/* ------------------------------------------------------------------ */
/* Validation */
/* ------------------------------------------------------------------ */
static int is_nix_base32_hash(const char *s, size_t n)
{
size_t i;
if (n != 32)
return 0;
for (i = 0; i < n; i++)
if (!isdigit((unsigned char)s[i]) &&
!(s[i] >= 'a' && s[i] <= 'z'))
return 0;
return 1;
}
/* Resolve a 32-char hash to /gnu/store/HASH-run-container.
* Returns a malloc'd path or NULL. */
static char *resolve_container(const char *hash)
{
DIR *dir = opendir(STORE);
struct dirent *de;
char *found = NULL;
size_t prefix_len = strlen(hash) + 1;
char prefix[prefix_len + 1];
if (!dir)
return NULL;
memcpy(prefix, hash, prefix_len - 1);
prefix[prefix_len - 1] = '-';
prefix[prefix_len] = '\0';
while ((de = readdir(dir))) {
if (strncmp(de->d_name, prefix, prefix_len) != 0)
continue;
if (strcmp(de->d_name + prefix_len, "run-container") != 0)
continue;
if (found) { /* ambiguous: more than one match */
free(found);
closedir(dir);
return NULL;
}
if (asprintf(&found, "%s%s", STORE, de->d_name) < 0)
found = NULL;
}
closedir(dir);
return found;
}
/* A generated Guix system container launcher is a guile script with a
* distinctive structure. We require all of the following, so that no
* regular store binary or unrelated script passes:
*
* 1. first line is a guile shebang:
* #!/gnu/store/...-guile-.../bin/guile ...
* (this also rules out ELF binaries, which start with \x7fELF)
* 2. it calls (call-with-container ...), the container entry point
* 3. it sets GUIX_NEW_SYSTEM, as generated system containers do
* 4. it mentions linux-container (the module it uses)
*/
static int is_container_script(const char *path, const char *base)
{
const char *dash = strchr(base, '-');
char buf[65536];
ssize_t n, i;
int fd, eol = 0;
/* The basename must be HASH-run-container: a 32-char nix-base32
* hash, then a dash, then exactly "run-container". */
if (!dash || dash - base != 32 || strcmp(dash + 1, "run-container") != 0)
return 0;
if (!is_nix_base32_hash(base, dash - base))
return 0;
fd = open(path, O_RDONLY);
if (fd < 0)
return 0;
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0)
return 0;
buf[n] = '\0';
/* 1. guile shebang as the first line. */
if (strncmp(buf, "#!/gnu/store/", 13) != 0)
return 0;
for (i = 13; i < n && buf[i] != '\n'; i++)
;
if (i >= n)
return 0;
eol = i;
{
char shebang[65536];
memcpy(shebang, buf, eol);
shebang[eol] = '\0';
if (!strstr(shebang, "-guile-") ||
!strstr(shebang, "/bin/guile"))
return 0;
}
/* 2-4. container entry point and generated-system markers. */
if (!strstr(buf, "call-with-container"))
return 0;
if (!strstr(buf, "GUIX_NEW_SYSTEM"))
return 0;
if (!strstr(buf, "linux-container"))
return 0;
return 1;
}
/* Full validation of a user-supplied argument (hash or store path).
* Returns a malloc'd container path, or NULL with *err pointing at a
* static error string. */
static char *validate(const char *arg, const char **err)
{
char *path, *base;
struct stat st;
size_t store_len = strlen(STORE);
*err = "invalid argument";
if (is_nix_base32_hash(arg, strlen(arg))) {
path = resolve_container(arg);
if (!path) {
*err = "no unique HASH-run-container found in the store";
return NULL;
}
} else {
if (strncmp(arg, STORE, store_len) != 0) {
*err = "path must be inside " STORE;
return NULL;
}
if (strchr(arg + store_len, '/')) {
*err = "path must be a direct child of " STORE;
return NULL;
}
path = strdup(arg);
}
base = path + store_len;
if (access(path, X_OK) != 0) {
*err = strerror(errno);
goto bad;
}
/* The file must be immutable: no write bits at all. Guix store
* items are created read-only (0555) by the daemon; if any write
* bit is set the file may have been tampered with or replaced,
* and we refuse to exec it. */
if (stat(path, &st) != 0) {
*err = strerror(errno);
goto bad;
}
if (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) {
*err = "container script is writable; refusing to run it";
goto bad;
}
if (!is_container_script(path, base)) {
*err = "not a Guix container launcher (HASH-run-container)";
goto bad;
}
return path;
bad:
free(path);
return NULL;
}
/* ------------------------------------------------------------------ */
/* Started-container tracking (for KILL) */
/* ------------------------------------------------------------------ */
static pid_t *started_pids;
static size_t started_count, started_cap;
static void track_pid(pid_t pid)
{
if (started_count == started_cap) {
size_t cap = started_cap ? started_cap * 2 : 16;
pid_t *p = realloc(started_pids, cap * sizeof(*p));
if (!p)
return; /* non-fatal: KILL falls back to /proc */
started_pids = p;
started_cap = cap;
}
started_pids[started_count++] = pid;
}
static void untrack_pid(pid_t pid)
{
size_t i;
for (i = 0; i < started_count; i++)
if (started_pids[i] == pid) {
memmove(&started_pids[i], &started_pids[i + 1],
(started_count - i - 1) * sizeof(*started_pids));
started_count--;
return;
}
}
static int pid_tracked(pid_t pid)
{
size_t i;
for (i = 0; i < started_count; i++)
if (started_pids[i] == pid)
return 1;
return 0;
}
/* Is a process still alive? (kill(0) with EPERM also means alive.) */
static int pid_alive(pid_t pid)
{
return kill(pid, 0) == 0 || errno != ESRCH;
}
/* Kill a container the daemon started: SIGKILL its whole process
* group (the launcher did setsid(), so the group covers the container's
* shepherd PID 1 and all its services); fall back to the single pid. */
static int kill_container_group(pid_t pid)
{
if (kill(-pid, SIGKILL) == 0)
return 0;
if (errno == EPERM || errno == ESRCH)
return kill(pid, SIGKILL);
return -1;
}
/* Fallback for PIDs started by a previous daemon instance: either a
* /gnu/store/HASH-run-container launcher script, or a stray shepherd
* (PID 1 of a container whose launcher was killed) running
* ".../bin/shepherd --config ...-shepherd.conf". */
static int pid_is_container(pid_t pid)
{
char path[MAX_LINE], buf[MAX_LINE];
int fd;
ssize_t n;
snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pid);
fd = open(path, O_RDONLY);
if (fd < 0)
return 0;
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0)
return 0;
buf[n] = '\0';
return strstr(buf, "-run-container") != NULL ||
(strstr(buf, "bin/shepherd") != NULL &&
strstr(buf, "-shepherd.conf") != NULL);
}
/* On shutdown, terminate the containers this daemon started: send
* SIGTERM to all of them, wait up to 10 s for them to exit, then
* SIGKILL the survivors. */
static void shutdown_containers(void)
{
size_t i;
int waited;
if (started_count == 0)
return;
logmsg("shutting down %zu container(s)", started_count);
for (i = 0; i < started_count; i++)
kill(-started_pids[i], SIGTERM); /* whole process group */
for (waited = 0; waited < 100; waited++) { /* 100 x 100 ms = 10 s */
int alive = 0;
for (i = 0; i < started_count; i++)
if (pid_alive(started_pids[i]))
alive++;
if (alive == 0) {
logmsg("all containers exited");
return;
}
usleep(100 * 1000);
}
for (i = 0; i < started_count; i++)
if (pid_alive(started_pids[i])) {
logmsg("container %d did not exit within 10 s; sending SIGKILL",
(int)started_pids[i]);
kill_container_group(started_pids[i]);
}
}
static void handle_stop(int sig)
{
(void)sig;
stop_requested = 1;
}
/* Drop pids that are no longer alive from the tracking table. */
static void sweep_dead_pids(void)
{
size_t i;
for (i = 0; i < started_count; ) {
if (pid_alive(started_pids[i])) {
i++;
continue;
}
untrack_pid(started_pids[i]);
}
}
/* Handle "LIST": report running containers, one "<pid> <name>" line
* after the OK line. Includes containers started by previous
* daemon instances (found by scanning /proc for *-run-container
* launchers), so they can be KILLed after a daemon restart. */
static void list_containers(int fd)
{
size_t i;
sweep_dead_pids();
dprintf(fd, "OK\n");
for (i = 0; i < started_count; i++) {
char path[MAX_LINE], buf[MAX_LINE], name[MAX_LINE];
char *slash;
int f, n;
snprintf(path, sizeof(path), "/proc/%d/cmdline",
(int)started_pids[i]);
f = open(path, O_RDONLY);
if (f < 0)
continue;
n = read(f, buf, sizeof(buf) - 1);
close(f);
if (n <= 0)
continue;
buf[n] = '\0'; /* first NUL-terminated arg = argv[0] */
slash = strrchr(buf, '/');
snprintf(name, sizeof(name), "%s", slash ? slash + 1 : buf);
dprintf(fd, "%d %s\n", (int)started_pids[i], name);
}
/* Containers started by a previous daemon instance. */
{
DIR *dir = opendir("/proc");
struct dirent *de;
int found = started_count;
while (dir && (de = readdir(dir))) {
char path[MAX_LINE], buf[MAX_LINE], name[MAX_LINE];
char *slash;
long pid;
char *end;
int f, n;
pid = strtol(de->d_name, &end, 10);
if (*end || pid <= 1)
continue;
if (pid_tracked((pid_t)pid))
continue; /* already reported */
snprintf(path, sizeof(path), "/proc/%ld/cmdline", pid);
f = open(path, O_RDONLY);
if (f < 0)
continue;
n = read(f, buf, sizeof(buf) - 1);
close(f);
if (n <= 0)
continue;
buf[n] = '\0';
if (!pid_is_container((pid_t)pid))
continue;
slash = strrchr(buf, '/');
snprintf(name, sizeof(name), "%s", slash ? slash + 1 : buf);
dprintf(fd, "%d %s (started by a previous daemon)\n",
(int)pid, name);
found++;
}
if (dir)
closedir(dir);
if (found == 0)
dprintf(fd, "(none)\n");
}
}
/* Handle "KILL <pid>": terminate a container the daemon started
* (or a previous instance started) with SIGKILL. */
static void kill_container(int fd, const char *arg, const char *client_ip)
{
char *end;
long pid = strtol(arg, &end, 10);
if (*end || pid <= 1) {
dprintf(fd, "ERR invalid pid\n");
return;
}
if (!pid_tracked(pid) && !pid_is_container(pid)) {
logmsg("refused to kill %ld from %s: not a container",
pid, client_ip);
dprintf(fd, "ERR not a container started by this daemon\n");
return;
}
if (kill_container_group((pid_t)pid) != 0) {
logmsg("failed to kill %ld: %s", pid, strerror(errno));
dprintf(fd, "ERR %s\n", strerror(errno));
return;
}
untrack_pid((pid_t)pid);
logmsg("sent SIGKILL to %ld (client %s)", pid, client_ip);
dprintf(fd, "OK killed %ld\n", pid);
}
/* Handle "LOG <hash|path>": dump the container's log file. */
static void send_log(int fd, const char *arg)
{
char base[MAX_LINE], logpath[MAX_LINE * 2];
char buf[4096];
int log, n;
const char *slash;
if (is_nix_base32_hash(arg, strlen(arg))) {
snprintf(base, sizeof(base), "%s-run-container", arg);
} else {
slash = strrchr(arg, '/');
snprintf(base, sizeof(base), "%s",
slash ? slash + 1 : arg);
if (!strstr(base, "-run-container")) {
dprintf(fd, "ERR expected HASH or HASH-run-container\n");
return;
}
}
snprintf(logpath, sizeof(logpath), "%s/%s.log", log_dir, base);
log = open(logpath, O_RDONLY);
if (log < 0) {
dprintf(fd, "ERR no log for %s (%s)\n", base,
strerror(errno));
return;
}
dprintf(fd, "OK\n");
while ((n = read(log, buf, sizeof(buf))) > 0)
write(fd, buf, n);
close(log);
}
/* ------------------------------------------------------------------ */
/* Starting */
/* ------------------------------------------------------------------ */
/* Start a validated container script detached; returns its pid, or
* -1 on failure. The container's stdout/stderr is appended to
* LOG_DIR/<basename>.log so boot failures can be diagnosed. */
static pid_t start_container(const char *path)
{
const char *base = strrchr(path, '/');
char logpath[MAX_LINE];
pid_t pid;
base = base ? base + 1 : path;
/* Prepared by the parent (running as root); ignore errors — we
* fall back to /dev/null below. */
mkdir(log_dir, 0755);
pid = fork();
if (pid < 0)
return -1;
if (pid == 0) {
int devnull = open("/dev/null", O_RDWR);
int log = -1;
/* Let the container know which daemon instance (and thus
* which fingerprint) started it, so it can show it. */
setenv("GUIX_CONTAINER_FINGERPRINT", daemon_fingerprint, 1);
snprintf(logpath, sizeof(logpath), "%s/%s.log", log_dir, base);
log = open(logpath, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (log >= 0) {
dup2(log, STDOUT_FILENO);
dup2(log, STDERR_FILENO);
if (log > 2)
close(log);
}
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
if (devnull > 2)
close(devnull);
}
setsid();
execl(path, path, (char *)NULL);
_exit(127);
}
track_pid(pid);
return pid;
}
/* ------------------------------------------------------------------ */
/* Server */
/* ------------------------------------------------------------------ */
/* Handle one connection: read "START <arg>\n", validate, start, reply. */
static void handle_connection(int fd, const char *client_ip)
{
char line[MAX_LINE], *p, *arg;
char *path;
const char *err;
pid_t pid;
ssize_t n;
char *fp_arg;
n = read(fd, line, sizeof(line) - 1);
if (n <= 0)
return;
line[n] = '\0';
p = strpbrk(line, "\r\n");
if (p)
*p = '\0';
if (strncmp(line, "FINGERPRINT", 11) == 0) {
dprintf(fd, "OK %s\n", daemon_fingerprint);
return;
}
if (strcmp(line, "LIST") == 0) {
list_containers(fd);
return;
}
if (strncmp(line, "LOG ", 4) == 0) {
send_log(fd, line + 4);
return;
}
if (strncmp(line, "KILL ", 5) == 0) {
kill_container(fd, line + 5, client_ip);
return;
}
if (strncmp(line, "START ", 6) != 0) {
dprintf(fd, "ERR expected 'START <hash|path> [fingerprint]', 'KILL <pid>', 'LIST', 'LOG <hash>' or 'FINGERPRINT'\n");
return;
}
arg = line + 6;
/* Optional second token: the fingerprint the client expects
* this daemon to have. */
fp_arg = strchr(arg, ' ');
if (fp_arg) {
*fp_arg++ = '\0';
if (strcmp(fp_arg, daemon_fingerprint) != 0) {
logmsg("fingerprint mismatch from %s (got '%s')",
client_ip, fp_arg);
dprintf(fd, "ERR fingerprint mismatch\n");
return;
}
}
/* One container at a time: refuse while a previously started
* container is still alive. */
sweep_dead_pids();
if (started_count > 0) {
logmsg("refused START from %s: container %d already running",
client_ip, (int)started_pids[0]);
dprintf(fd, "ERR already running container %d; KILL it first\n",
(int)started_pids[0]);
return;
}
path = validate(arg, &err);
if (!path) {
logmsg("rejected '%s' from %s: %s", arg, client_ip, err);
dprintf(fd, "ERR %s\n", err);
return;
}
pid = start_container(path);
if (pid < 0) {
logmsg("failed to start %s: %s", path, strerror(errno));
dprintf(fd, "ERR failed to start container\n");
} else {
logmsg("started %s as pid %d (client %s, fingerprint %s)", path,
pid, client_ip, daemon_fingerprint);
dprintf(fd, "OK %d\n", pid);
}
free(path);
}
static int serve(const char *listen_ip, int port)
{
struct sockaddr_in6 addr6;
struct sockaddr_in addr4;
struct sockaddr *sa;
socklen_t sa_len;
int family, srv, one = 1;
struct sigaction stop_action;
signal(SIGCHLD, SIG_IGN); /* reap children automatically */
/* Shut down on SIGINT/SIGTERM: kill the containers we started.
* No SA_RESTART, so accept() is interrupted and we notice. */
memset(&stop_action, 0, sizeof(stop_action));
stop_action.sa_handler = handle_stop;
sigemptyset(&stop_action.sa_mask);
sigaction(SIGINT, &stop_action, NULL);
sigaction(SIGTERM, &stop_action, NULL);
memset(&addr6, 0, sizeof(addr6));
memset(&addr4, 0, sizeof(addr4));
if (strchr(listen_ip, ':')) { /* IPv6 address */
family = AF_INET6;
addr6.sin6_family = AF_INET6;
addr6.sin6_port = htons(port);
if (inet_pton(AF_INET6, listen_ip, &addr6.sin6_addr) != 1) {
fprintf(stderr, "invalid IPv6 address: %s\n",
listen_ip);
return 1;
}
sa = (struct sockaddr *)&addr6;
sa_len = sizeof(addr6);
} else { /* IPv4 address */
family = AF_INET;
addr4.sin_family = AF_INET;
addr4.sin_port = htons(port);
if (inet_pton(AF_INET, listen_ip, &addr4.sin_addr) != 1) {
fprintf(stderr, "invalid IPv4 address: %s\n",
listen_ip);
return 1;
}
sa = (struct sockaddr *)&addr4;
sa_len = sizeof(addr4);
}
srv = socket(family, SOCK_STREAM, 0);
if (srv < 0) {
perror("socket");
return 1;
}
setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
if (family == AF_INET6)
setsockopt(srv, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
if (bind(srv, sa, sa_len) != 0) {
perror("bind");
return 1;
}
if (listen(srv, 16) != 0) {
perror("listen");
return 1;
}
logmsg(PROGRAM " listening on [%s]:%d (fingerprint %s)", listen_ip,
port, daemon_fingerprint);
for (;;) {
struct sockaddr_storage peer;
socklen_t peer_len = sizeof(peer);
char ip[INET6_ADDRSTRLEN];
int fd = accept(srv, (struct sockaddr *)&peer, &peer_len);
const void *src;
if (stop_requested)
break;
if (fd < 0) {
if (errno == EINTR)
continue;
logmsg("accept: %s", strerror(errno));
continue;
}
src = peer.ss_family == AF_INET6
? (void *)&((struct sockaddr_in6 *)&peer)->sin6_addr
: (void *)&((struct sockaddr_in *)&peer)->sin_addr;
inet_ntop(peer.ss_family, src, ip, sizeof(ip));
handle_connection(fd, ip);
close(fd);
}
shutdown_containers();
logmsg(PROGRAM " exiting");
return 0;
}
/* ------------------------------------------------------------------ */
int main(int argc, char **argv)
{
const char *listen_ip = DEFAULT_LISTEN;
const char *fp_opt = NULL;
int port = DEFAULT_PORT;
int i;
const char *env_log_dir = getenv("GUIX_CONTAINER_LOG_DIR");
if (env_log_dir && *env_log_dir)
log_dir = env_log_dir;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--listen") == 0 && i + 1 < argc) {
listen_ip = argv[++i];
} else if (strcmp(argv[i], "--port") == 0 && i + 1 < argc) {
char *end;
long p = strtol(argv[++i], &end, 10);
if (*end || p <= 0 || p > 65535) {
fprintf(stderr, "invalid port: %s\n", argv[i]);
return 1;
}
port = p;
} else if (strcmp(argv[i], "--log-dir") == 0 && i + 1 < argc) {
log_dir = argv[++i];
} else if (strcmp(argv[i], "--fingerprint") == 0 && i + 1 < argc) {
fp_opt = argv[++i];
} else {
fprintf(stderr,
"usage: %s [--listen IP] [--port N] [--log-dir DIR] "
"[--fingerprint WORD]\n"
" --listen IP address to listen on (default "
DEFAULT_LISTEN ")\n"
" --port N port (default %d)\n"
" --log-dir DIR where container boot output goes\n"
" (default " DEFAULT_LOG_DIR ", or\n"
" $GUIX_CONTAINER_LOG_DIR)\n"
" --fingerprint WORD short word or version (e.g. v0.1)\n"
" identifying this daemon; containers\n"
" started here get it in the\n"
" GUIX_CONTAINER_FINGERPRINT variable.\n"
" Default: a random hash.\n",
PROGRAM, DEFAULT_PORT);
return 1;
}
}
if (fp_opt) {
if (!valid_fingerprint(fp_opt)) {
fprintf(stderr, "invalid fingerprint: '%s' (1-32 printable chars, no whitespace)\n",
fp_opt);
return 1;
}
strncpy(daemon_fingerprint, fp_opt, sizeof(daemon_fingerprint) - 1);
daemon_fingerprint[sizeof(daemon_fingerprint) - 1] = '\0';
} else {
random_fingerprint();
}
/* Say where boot output will go before anything can fail: it is the
* first thing an operator needs when a container does not come up, and
* it makes --log-dir observable without root. */
logmsg("container logs: %s", log_dir);
if (!have_container_privileges())
return 1;
check_log_dir();
return serve(listen_ip, port);
}
|