This repository has been archived by the owner on Oct 15, 2022. It is now read-only.
forked from alec-liu/frugalify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
frugalify.c
1239 lines (979 loc) · 28.4 KB
/
frugalify.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
#include <unistd.h>
#include <linux/loop.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <sys/mount.h>
#include <signal.h>
#include <pwd.h>
#include <sys/wait.h>
#include <sys/reboot.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/statvfs.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <time.h>
#include <limits.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/klog.h>
#include <syslog.h>
#include <sys/sysmacros.h>
#ifdef HAVE_FSCRYPT
# include <linux/fscrypt.h>
# include <mbedtls/sha512.h>
#endif
#ifndef LOOP_CTL_GET_FREE
# define LOOP_CTL_GET_FREE 0x4C82
#endif
#ifndef LOOP_CTL_REMOVE
# define LOOP_CTL_REMOVE 0x4C81
#endif
#ifndef FITRIM
# define FITRIM _IOWR('X', 121, struct fstrim_range)
struct fstrim_range {
uint64_t start;
uint64_t len;
uint64_t minlen;
};
#endif
#define MAXSFS 32
#ifdef HAVE_AUFS
# define FS "aufs"
# define FSOPTS_HEAD "br=/upper/save"
#else
# define FS "overlay"
# define FSOPTS_HEAD "upperdir=/upper/save,workdir=/upper/.work,lowerdir="
#endif
#define CLEAR_TTY "\033[2J\033[H"
#define HIDE_KEY "\033[32m\033[102m"
#define RESET_TTY "\033[39m\033[49m"
#define FSTRIM_FREQ (60 * 60 * 24 * 7)
#define RESPAWN_DELAY 1
enum {
BOOTCODE_NOCOPY = 1,
BOOTCODE_RAM = 1 << 1,
};
static const struct sockaddr_un devlog = {.sun_family = AF_UNIX, .sun_path = "/dev/log"};
static inline void do_autoclose(void *fdp)
{
if (*(int *)fdp != -1)
close(*(int *)fdp);
}
#define autoclose __attribute__((cleanup(do_autoclose)))
static void fakelogin(void)
{
struct passwd *user;
user = getpwuid(geteuid());
if (!user ||
(setenv("USER", user->pw_name, 1) < 0) ||
(setenv("HOME", user->pw_dir, 1) < 0) ||
(setenv("SHELL", user->pw_shell, 1) < 0) ||
(chdir(user->pw_dir) < 0))
return;
execlp(user->pw_shell, user->pw_shell, "-l", (char *)NULL);
}
static void do_cttyhack(void)
{
autoclose int fd = -1;
if (setsid() < 0)
return;
fd = open("/dev/console", O_RDWR);
if ((fd < 0) ||
(ioctl(fd, TIOCSCTTY, NULL) < 0) ||
(dup2(fd, STDIN_FILENO) < 0) ||
(dup2(fd, STDOUT_FILENO) < 0) ||
(dup2(fd, STDERR_FILENO) < 0))
return;
close(fd);
fd = -1;
fakelogin();
}
static void delay(const time_t sec)
{
struct timespec req = {.tv_sec = sec}, rem;
while (1) {
if (nanosleep(&req, &rem) == 0)
break;
if (errno != EINTR)
break;
memcpy(&req, &rem, sizeof(struct timespec));
}
}
static pid_t cttyhack(const time_t sec)
{
pid_t pid;
sigset_t mask;
pid = fork();
if (pid == 0) {
if ((sigfillset(&mask) < 0) ||
(sigprocmask(SIG_UNBLOCK, &mask, NULL) < 0))
exit(EXIT_FAILURE);
if (sec > 0)
delay(sec);
do_cttyhack();
exit(EXIT_FAILURE);
}
return pid;
}
static int initscript(void)
{
pid_t pid;
sigset_t mask;
int status;
pid = fork();
if (pid == 0) {
if ((sigfillset(&mask) < 0) ||
(sigprocmask(SIG_UNBLOCK, &mask, NULL) < 0))
exit(EXIT_FAILURE);
execl("/etc/rc.d/rc.sysinit", "/etc/rc.d/rc.sysinit", (char *)NULL);
exit(EXIT_FAILURE);
}
else if ((pid < 0) ||
(waitpid(pid, &status, 0) != pid) ||
!WIFEXITED(status))
return -1;
return 0;
}
static int init(void)
{
sigset_t mask;
pid_t pid, reaped;
siginfo_t sig = {.si_signo = SIGUSR2};
int status, ret;
openlog("init", 0, LOG_DAEMON);
/* block SIGCHLD, SIGTERM (poweroff) and SIGUSR2 (reboot) */
if ((sigemptyset(&mask) < 0) ||
(sigaddset(&mask, SIGCHLD) < 0) ||
(sigaddset(&mask, SIGTERM) < 0) ||
(sigaddset(&mask, SIGUSR2) < 0) ||
(sigprocmask(SIG_SETMASK, &mask, NULL) < 0))
goto shutdown;
syslog(LOG_INFO, "running init script");
if (initscript() < 0)
goto shutdown;
write(STDOUT_FILENO, CLEAR_TTY, sizeof(CLEAR_TTY) - 1);
syslog(LOG_INFO, "starting login shell");
pid = cttyhack(0);
if (pid < 0)
goto shutdown;
do {
if ((sigwaitinfo(&mask, &sig) < 0) || (sig.si_signo != SIGCHLD))
break;
reaped = waitpid(sig.si_pid, &status, WNOHANG);
if (reaped < 0) {
if (errno != ECHILD)
break;
continue;
}
else if (reaped == 0)
continue;
if (!WIFEXITED(status) && !WIFSIGNALED(status))
continue;
if (sig.si_pid == pid) {
syslog(LOG_INFO, "restarting login shell");
pid = cttyhack(RESPAWN_DELAY);
if (pid < 0)
goto shutdown;
}
} while (1);
shutdown:
closelog();
ret = kill(-1, SIGTERM);
delay(2);
if (ret == 0)
kill(-1, SIGKILL);
sync();
if (vfork() == 0) {
if (sig.si_signo == SIGUSR2)
reboot(RB_POWER_OFF);
else
reboot(RB_AUTOBOOT);
}
return EXIT_FAILURE;
}
// use of sprintf() can double the executable size
static char *itoa(char *s, int i)
{
if (i >= 10)
s = itoa(s, i / 10);
*s = '0' + i % 10;
++s;
*s = '\0';
return s;
}
static int get_free_lo(void)
{
autoclose int ctl = -1;
ctl = open("/upper/save/dev/loop-control", O_RDONLY);
if (ctl < 0)
return -1;
return ioctl(ctl, LOOP_CTL_GET_FREE);
}
static void remove_lo(int id)
{
autoclose int ctl = -1;
ctl = open("/dev/loop-control", O_RDONLY);
if (ctl > 0)
ioctl(ctl, LOOP_CTL_REMOVE, id);
}
static char *get_lo_path(int i)
{
static char loop[sizeof("/upper/save/dev/loop99")] = "/upper/save/dev/loop";
itoa(loop + sizeof("/upper/save/dev/loop") - 1, i);
return loop;
}
static const char *losetup(const char *sfs, const int i)
{
struct stat stbuf;
struct loop_info64 info = {.lo_flags = LO_FLAGS_READ_ONLY};
const char *loop;
autoclose int loopfd = -1, sfsfd = -1;
sfsfd = open(sfs, O_RDONLY);
if (sfsfd < 0)
return NULL;
if (fstat(sfsfd, &stbuf) < 0)
return NULL;
loop = get_lo_path(i);
loopfd = open(loop, O_RDONLY);
if (loopfd < 0)
return NULL;
if (ioctl(loopfd, LOOP_SET_FD, sfsfd) < 0)
return NULL;
#ifdef HAVE_STRLCPY
strlcpy(info.lo_file_name, sfs, sizeof(info.lo_file_name));
#else
strncpy((char *)info.lo_file_name, sfs, sizeof(info.lo_file_name));
info.lo_file_name[sizeof(info.lo_file_name) - 1] = '\0';
#endif
info.lo_sizelimit = (uint64_t)stbuf.st_size;
info.lo_flags = LO_FLAGS_READ_ONLY;
if (ioctl(loopfd, LOOP_SET_STATUS64, &info) < 0)
return NULL;
return loop;
}
static void losetup_d(const int i)
{
int loopfd;
autoclose int ctl = -1;
loopfd = open(get_lo_path(i), O_RDWR);
if (loopfd < 0)
return;
ioctl(loopfd, LOOP_CLR_FD);
close(loopfd);
ctl = open("/upper/save/dev/loop-control", O_RDONLY);
if (ctl >= 0)
ioctl(ctl, LOOP_CTL_REMOVE, i);
}
static int sfscmp(const void *a, const void *b)
{
const char *as = *(const char **)a, *bs = *(const char **)b, *abase, *bbase;
int m, n;
abase = strrchr(as, '/');
if (abase)
abase = &abase[1];
else
abase = as;
bbase = strrchr(bs, '/');
if (bbase)
bbase = &bbase[1];
else
bbase = bs;
m = strncmp(abase, "puppy_", sizeof("puppy_") - 1);
n = strncmp(bbase, "puppy_", sizeof("puppy_") - 1);
if ((m == 0) && (n != 0))
return 1;
if ((m != 0) && (n == 0))
return -1;
return -strverscmp(abase, bbase);
}
#ifdef HAVE_FSCRYPT
static unsigned int read_key(unsigned char key[FSCRYPT_MAX_KEY_SIZE])
{
unsigned char buf[32];
unsigned int len;
for (len = 0; len < sizeof(buf); ++len) {
if (read(STDIN_FILENO, &buf[len], sizeof(buf[len]) ) != sizeof(buf[len]))
return 0;
if (buf[len] == '\n')
break;
}
mbedtls_sha512_ret(buf, len, key, 0);
return len;
}
static void fscrypt(const char *path)
{
static unsigned char buf[sizeof(struct fscrypt_add_key_arg) + FSCRYPT_MAX_KEY_SIZE];
struct fscrypt_add_key_arg *arg = (struct fscrypt_add_key_arg *)buf;
struct fscrypt_remove_key_arg remove = {
.key_spec = {
.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER,
},
};
struct fscrypt_policy_v2 policy = {
.version = FSCRYPT_POLICY_V2,
.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS,
.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS,
.flags = FSCRYPT_POLICY_FLAGS_PAD_32,
};
unsigned int len;
int fd;
if (write(STDOUT_FILENO, "Key: ", sizeof("Key: ") - 1) != sizeof("Key: ") - 1)
return;
write(STDOUT_FILENO, HIDE_KEY, sizeof(HIDE_KEY) - 1);
len = read_key(&buf[sizeof(*arg)]);
write(STDOUT_FILENO, RESET_TTY, sizeof(RESET_TTY) - 1);
if (len == 0)
return;
fd = open(path, O_RDONLY);
if (fd < 0)
return;
*arg = (struct fscrypt_add_key_arg){
.key_spec = {
.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER,
},
.raw_size = sizeof(buf) - sizeof(*arg),
};
if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, buf) < 0) {
close(fd);
return;
}
memcpy(policy.master_key_identifier,
arg->key_spec.u.identifier,
sizeof(policy.master_key_identifier));
if (ioctl(fd, FS_IOC_SET_ENCRYPTION_POLICY, &policy) < 0) {
memcpy(remove.key_spec.u.identifier,
arg->key_spec.u.identifier,
sizeof(remove.key_spec.u.identifier));
ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &remove);
}
close(fd);
}
#endif
static int oom_score_adj(void)
{
autoclose int adj = -1;
adj = open("/proc/self/oom_score_adj", O_WRONLY);
if (adj < 0)
return -1;
if (write(adj, "1000", sizeof("1000") - 1) != sizeof("1000") - 1)
return -1;
return 0;
}
static int get_ver(char *buf, size_t len)
{
static char *const argv[] = {
"/bin/sh",
"-c",
". /etc/DISTRO_SPECS && echo -n \"$DISTRO_VERSION\"",
NULL
};
int pipefd[2];
ssize_t out;
autoclose int infd = -1, outfd = -1;
pid_t pid;
int status;
if (pipe(pipefd) < 0)
return -1;
infd = pipefd[0];
outfd = pipefd[1];
pid = fork();
switch (pid) {
case 0:
if (dup2(outfd, STDOUT_FILENO) == STDOUT_FILENO)
execv(argv[0], argv);
exit(EXIT_FAILURE);
case -1:
return -1;
}
if (waitpid(pid, &status, 0) != pid)
return -1;
out = read(infd, buf, len - 1);
if ((out <= 0) || (out == (len - 1)))
return -1;
if ((buf[0] < '0') || (buf[0] > '9'))
return -1;
buf[out] = '\0';
return 0;
}
static void do_pfixram(char **sfs, const int nsfs)
{
static char ver[sizeof("999.999.999")];
struct stat stbuf;
sigset_t mask;
const char *base;
void *p;
long minsize;
int fd, sig, i, locked = 0;
if (prctl(PR_SET_NAME, "pfixram") < 0)
return;
if ((sigemptyset(&mask) < 0) ||
(sigaddset(&mask, SIGTERM) < 0) ||
(sigprocmask(SIG_SETMASK, &mask, NULL) < 0))
return;
minsize = sysconf(_SC_PAGESIZE);
if (minsize <= 0)
return;
if (get_ver(ver, sizeof(ver)) < 0)
ver[0] = '\0';
for (i = nsfs -1; i >= 0; --i) {
base = strrchr(sfs[i], '/');
if (base)
++base;
else
base = sfs[i];
if ((strncmp(base, "zdrv_", sizeof("zdrv_") - 1) == 0) ||
(strncmp(base, "fdrv_", sizeof("fdrv_") - 1) == 0) ||
(strncmp(base, "devx_", sizeof("devx_") - 1) == 0) ||
(strncmp(base, "docx_", sizeof("docx_") - 1) == 0) ||
(strncmp(base, "nlsx_", sizeof("nlsx_") - 1) == 0))
continue;
if (ver[0] && !strstr(base, ver))
continue;
fd = open(sfs[i], O_RDONLY);
if (fd < 0)
continue;
if ((fstat(fd, &stbuf) < 0) || (stbuf.st_size < minsize)) {
close(fd);
continue;
}
p = mmap(NULL,
(size_t)stbuf.st_size,
PROT_READ,
MAP_PRIVATE | MAP_POPULATE,
fd,
0);
if (p == MAP_FAILED) {
if (errno == ENOMEM)
return;
close(fd);
continue;
}
if (mlock2(p, (size_t)stbuf.st_size, MLOCK_ONFAULT) < 0) {
if (errno == ENOMEM)
return;
munmap(p, (size_t)stbuf.st_size);
close(fd);
continue;
}
syslog(LOG_INFO, "locked %s to RAM", sfs[i]);
++locked;
}
if (locked > 0) {
while (1) {
if ((sigwait(&mask, &sig) < 0) || (sig == SIGTERM))
break;
}
}
}
static void pfixram(char **sfs, const int nsfs)
{
if (fork() == 0) {
if (chdir("/initrd") < 0)
exit(EXIT_FAILURE);
// lower our priority so we don't starve I/O intensive applications
if (setpriority(PRIO_PROCESS, 0, 10) < 0)
exit(EXIT_FAILURE);
// pfixram should be the first process to kill when out of memory
if (oom_score_adj() < 0)
exit(EXIT_FAILURE);
openlog("pfixram", 0, LOG_DAEMON);
do_pfixram(sfs, nsfs);
closelog();
exit(EXIT_FAILURE);
}
}
static int memexec(const int self, char *argv[])
{
struct stat stbuf;
char buf[16];
off_t total = 0;
ssize_t out;
const char *comm;
void *p;
autoclose int memfd = -1;
comm = getenv("COMM");
if (comm) {
close(self);
if (unsetenv("COMM") < 0)
return -1;
return prctl(PR_SET_NAME, comm);
}
if (prctl(PR_GET_NAME, buf) < 0)
return -1;
if (setenv("COMM", buf, 1) < 0)
return -1;
memfd = memfd_create(argv[0], 0);
if (memfd < 0)
return -1;
if (fcntl(memfd, F_SETFD, FD_CLOEXEC) < 0)
return -1;
if ((fstat(self, &stbuf) < 0) || (stbuf.st_size == 0))
return -1;
p = mmap(NULL,
(size_t)stbuf.st_size,
PROT_READ,
MAP_PRIVATE,
self,
0);
if (p == MAP_FAILED)
return -1;
do {
out = write(memfd, (unsigned char *)p + total, stbuf.st_size - total);
if (out <= 0)
return -1;
total += (off_t)out;
} while (total < stbuf.st_size);
munmap(p, (size_t)stbuf.st_size);
close(self);
return fexecve(memfd, argv, environ);
}
static int getcodes(unsigned int *bootcodes)
{
static char buf[256];
ssize_t len;
char *tok, *save;
autoclose int cmdline = -1;
cmdline = open("/upper/cmdline", O_RDONLY);
if (cmdline < 0)
return -1;
len = read(cmdline, buf, sizeof(buf));
if (len < 0)
return -1;
else if (len == 0)
return 0;
buf[len - 1] = '\0';
tok = strtok_r(buf, " ", &save);
do {
if (strcmp(tok, "pfix=nocopy") == 0)
*bootcodes |= BOOTCODE_NOCOPY;
else if (strcmp(tok, "pfix=ram") == 0)
*bootcodes |= BOOTCODE_RAM;
tok = strtok_r(NULL, " ", &save);
} while (tok);
return 0;
}
static char *getroot(void)
{
static char dst[512];
static char path[sizeof("/upper/dev/block/4294967295:4294967295")] = "/upper/dev/block/";
struct stat stbuf;
ssize_t out;
char *p;
if (stat("/", &stbuf) < 0)
return NULL;
p = itoa(path + sizeof("/upper/dev/block/") - 1, major(stbuf.st_dev));
*p = ':';
itoa(p + 1, minor(stbuf.st_dev));
out = readlink(path, dst, sizeof(dst));
if ((out <= 0) || (out >= sizeof(dst)))
return NULL;
dst[out] = '\0';
return basename(dst);
}
static int binmount(const char *dev, const char *target, const char *opts)
{
pid_t pid, reaped;
int status;
pid = fork();
if (pid == 0) {
execl("/bin/mount", "/bin/mount", "-o", opts, dev, target, (char *)NULL);
exit(EXIT_FAILURE);
}
else if (pid < 0)
return -1;
reaped = waitpid(pid, &status, 0);
if (((reaped < 0) && (errno != ECHILD)) ||
(!WIFEXITED(status) || (WEXITSTATUS(status) != EXIT_SUCCESS)))
return -1;
return 0;
}
static int mountroot(const char *rootname, const int ro)
{
static char rootdev[32] = "/dev/", rootmnt[32] = "/mnt/", dst[32];
ssize_t out;
strlcpy(rootmnt + sizeof("/mnt/") - 1, rootname, sizeof(rootmnt) - (sizeof("/mnt/") - 1));
if ((mkdir(rootmnt, 0755) < 0) && (errno != EEXIST))
return -1;
strlcpy(rootdev + sizeof("/dev/") - 1, rootname, sizeof(rootdev) - (sizeof("/dev/") - 1));
// mount the boot partition at /mnt/%s
if ((!ro && (binmount(rootdev, rootmnt, "noatime") < 0)) ||
(ro && (binmount(rootdev, rootmnt, "ro") < 0)))
return -1;
out = readlink("/mnt/home", dst, sizeof(dst));
if ((out > 0) && (out < sizeof(dst))) {
dst[out] = '\0';
// update the /mnt/home -> /mnt/%s symlink; some old scripts
// expect it to be a symlink, and expect an absolute path
if ((strcmp(dst, rootmnt) != 0) &&
((unlink("/mnt/home") < 0) || (symlink(rootmnt, "/mnt/home") < 0)))
return -1;
}
else if (out < 0) {
switch (errno) {
case EINVAL:
// if /mnt/home is not a link, we want to delete it first
if (((rmdir("/mnt/home") == 0) || (unlink("/mnt/home") == 0)) &&
(symlink(rootmnt, "/mnt/home") < 0))
return -1;
break;
case ENOENT:
// if this is the first boot, /mnt/home is missing
if (symlink(rootmnt, "/mnt/home") < 0)
return -1;
break;
default:
return -1;
}
}
else
return -1;
return 0;
}
static void fstrim(const int fd)
{
struct timespec now, prev;
struct stat stbuf;
struct fstrim_range range = {.len = ULLONG_MAX};
if (clock_gettime(CLOCK_REALTIME, &now) < 0)
return;
if (now.tv_sec < FSTRIM_FREQ)
return;
prev.tv_sec = now.tv_sec - FSTRIM_FREQ;
prev.tv_nsec = now.tv_nsec;
if (fstat(fd, &stbuf) < 0)
return;
if ((stbuf.st_mtim.tv_sec > prev.tv_sec) ||
((stbuf.st_mtim.tv_sec == prev.tv_sec) &&
(stbuf.st_mtim.tv_nsec >= prev.tv_nsec)))
return;
if (ioctl(fd, FITRIM, &range) == 0)
syslog(LOG_INFO, "successfully discarded unused blocks");
else
syslog(LOG_WARNING, "failed to discard unused blocks: %d", errno);
futimens(fd, NULL);
}
static void do_fstrimd(const int fd)
{
siginfo_t sig;
struct timespec ts = {.tv_sec = FSTRIM_FREQ + 120};
sigset_t mask;
fstrim(fd);
if (prctl(PR_SET_NAME, "fstrimd") < 0)
return;
if ((sigemptyset(&mask) < 0) ||
(sigaddset(&mask, SIGTERM) < 0) ||
(sigprocmask(SIG_SETMASK, &mask, NULL) < 0))
return;
while (1) {
if (sigtimedwait(&mask, &sig, &ts) < 0) {
if (errno == EAGAIN)
fstrim(fd);
else if (errno != EINTR)
break;
} else if (sig.si_signo == SIGTERM)
break;
}
}
static void fstrimd(void)
{
autoclose int fd = -1;
fd = open("/initrd/upper", O_DIRECTORY);
if (fd < 0)
return;
if (fork() == 0) {
openlog("fstrimd", 0, LOG_DAEMON);
do_fstrimd(fd);
closelog();
exit(EXIT_FAILURE);
}
}
static void do_syslogd(const int sockfd, const int logfd)
{
static char buf[1024];
sigset_t mask;
ssize_t len, out, total;
if (prctl(PR_SET_NAME, "syslogd") < 0)
return;
if ((sigfillset(&mask) < 0) ||
(sigprocmask(SIG_UNBLOCK, &mask, NULL) < 0))
return;
while (1) {
len = recv(sockfd, buf, sizeof(buf) - 2, 0);
if (len <= 0)
break;
if (buf[len - 1] != '\n') {
buf[len] = '\n';
++len;
buf[len] = '\0';
}
for (total = 0; total < len; total += out) {
out = write(logfd, buf + total, (size_t)len - total);
if (out <= 0)
return;
}
}
}
static int syslogd(void)
{
autoclose int sockfd = -1, logfd = -1;
pid_t pid;
sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sockfd < 0)
return -1;
unlink(devlog.sun_path);
if (bind(sockfd, (struct sockaddr *)&devlog, sizeof(devlog)) < 0)
return -1;
if ((mkdir("/var/log", 0755) < 0) && (errno != EEXIST))
return -1;
logfd = open("/var/log/messages", O_CREAT | O_TRUNC | O_WRONLY, 0600);
if (logfd < 0)
return -1;
pid = fork();
if (pid == 0) {
do_syslogd(sockfd, logfd);
exit(EXIT_FAILURE);
}
else if (pid < 0)
return -1;
return 0;
}
static void do_klogd(const int kmsg)
{
static char buf[1024];
sigset_t mask;
ssize_t len;
int sockfd;
if (prctl(PR_SET_NAME, "klogd") < 0)
return;
if ((sigfillset(&mask) < 0) ||
(sigprocmask(SIG_UNBLOCK, &mask, NULL) < 0))
return;
sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sockfd < 0)
return;
if (connect(sockfd, (const struct sockaddr *)&devlog, sizeof(devlog)) < 0)
return;
if (klogctl(6, NULL, 0) < 0)
return;
while (1) {
len = read(kmsg, buf, sizeof(buf));
if (len <= 0)
break;
send(sockfd, buf, (size_t)len, 0);
}
}
static void klogd(void)
{
autoclose int kmsg = -1;
kmsg = open("/proc/kmsg", O_RDONLY);
if (kmsg < 0)
return;
if (fork() == 0) {
do_klogd(kmsg);
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{