-
Notifications
You must be signed in to change notification settings - Fork 15
/
kfmon.c
3276 lines (3002 loc) · 115 KB
/
kfmon.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
/*
KFMon: Kobo inotify-based launcher
Copyright (C) 2016-2024 NiLuJe <ninuje@gmail.com>
SPDX-License-Identifier: GPL-3.0-or-later
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "kfmon.h"
// Because daemon() only appeared in glibc 2.21 (and doesn't double-fork anyway)
static int
daemonize(void)
{
switch (fork()) {
case -1:
PFLOG(LOG_CRIT, "initial fork: %m");
return -1;
case 0:
break;
default:
_exit(EXIT_SUCCESS);
}
if (setsid() == -1) {
PFLOG(LOG_CRIT, "setsid: %m");
return -1;
}
// Double fork, for... reasons!
// In practical terms, this ensures we get re-parented to init *now*.
// Ignore SIGHUP while we're there, since we don't want to be killed by it.
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART };
if (sigaction(SIGHUP, &sa, NULL) == -1) {
PFLOG(LOG_CRIT, "sigaction: %m");
return -1;
}
switch (fork()) {
case -1:
PFLOG(LOG_CRIT, "final fork: %m");
return -1;
case 0:
break;
default:
_exit(EXIT_SUCCESS);
}
if (chdir("/") == -1) {
PFLOG(LOG_CRIT, "chdir: %m");
return -1;
}
// Make sure we keep honoring rcS's umask
umask(022); // Flawfinder: ignore
// Store a copy of stdin, stdout & stderr so we can restore it to our children later on...
// NOTE: Hence the + 3 in the two (three w/ use_syslog) following fd tests.
origStdin = dup(fileno(stdin));
origStdout = dup(fileno(stdout));
origStderr = dup(fileno(stderr));
// Redirect stdin & stdout to /dev/null
int fd = open("/dev/null", O_RDWR);
if (fd != -1) {
dup2(fd, fileno(stdin));
dup2(fd, fileno(stdout));
if (fd > 2 + 3) {
close(fd);
}
} else {
PFLOG(LOG_CRIT, "Failed to redirect stdin & stdout to /dev/null (open: %m)");
return -1;
}
// Redirect stderr to our logfile
// NOTE: We do need O_APPEND (as opposed to simply calling lseek(fd, 0, SEEK_END) after open),
// because auxiliary scripts *may* also append to this log file ;).
int flags = O_WRONLY | O_CREAT | O_APPEND;
// Check if we need to truncate our log because it has grown too much...
struct stat st;
if ((stat(KFMON_LOGFILE, &st) == 0) && (S_ISREG(st.st_mode))) {
// Truncate if > 1MB
if (st.st_size > 1 * 1024 * 1024) {
flags |= O_TRUNC;
}
}
if ((fd = open(KFMON_LOGFILE, flags, S_IRUSR | S_IWUSR)) != -1) {
dup2(fd, fileno(stderr));
if (fd > 2 + 3) {
close(fd);
}
} else {
PFLOG(LOG_CRIT, "Failed to redirect stderr to logfile '%s' (open: %m)", KFMON_LOGFILE);
return -1;
}
return 0;
}
// Wrapper around localtime_r, making sure this part is thread-safe (used for logging)
static struct tm*
get_localtime(struct tm* restrict lt)
{
time_t t = time(NULL);
tzset();
return localtime_r(&t, lt);
}
// Wrapper around strftime, making sure this part is thread-safe (used for logging)
static char*
format_localtime(struct tm* restrict lt, char* restrict sz_time, size_t len)
{
// c.f., strftime(3) & https://stackoverflow.com/questions/7411301
strftime(sz_time, len, "%Y-%m-%d @ %H:%M:%S", lt);
return sz_time;
}
// Return the current time formatted as 2016-04-29 @ 20:44:13 (used for logging)
// NOTE: The use of static variables prevents this from being thread-safe,
// but in the main thread, we use static storage for simplicity's sake.
static char*
get_current_time(void)
{
static struct tm local_tm = { 0 };
struct tm* restrict lt = get_localtime(&local_tm);
static char sz_time[22];
return format_localtime(lt, sz_time, sizeof(sz_time));
}
// And now the same, but with user supplied storage, thus potentially thread-safe:
// e.g., we use the stack in reaper_thread().
static char*
get_current_time_r(struct tm* restrict local_tm, char* restrict sz_time, size_t len)
{
struct tm* restrict lt = get_localtime(local_tm);
return format_localtime(lt, sz_time, len);
}
static const char*
get_log_prefix(int prio)
{
// Reuse (part of) the syslog() priority constants
switch (prio) {
case LOG_CRIT:
return "CRIT";
case LOG_ERR:
return "ERR!";
case LOG_WARNING:
return "WARN";
case LOG_NOTICE:
return "NOTE";
case LOG_INFO:
return "INFO";
case LOG_DEBUG:
return "DBG!";
default:
return "OOPS";
}
}
// Check that our target mountpoint is indeed mounted...
static bool
is_target_mounted(void)
{
// c.f., http://program-nix.blogspot.com/2008/08/c-language-check-filesystem-is-mounted.html
FILE* restrict mtab = NULL;
struct mntent* restrict part = NULL;
bool is_mounted = false;
if ((mtab = setmntent("/proc/mounts", "r")) != NULL) {
while ((part = getmntent(mtab)) != NULL) {
DBGLOG("Checking fs %s mounted on %s", part->mnt_fsname, part->mnt_dir);
if ((part->mnt_dir != NULL) && (strcmp(part->mnt_dir, KFMON_TARGET_MOUNTPOINT)) == 0) {
is_mounted = true;
break;
}
}
endmntent(mtab);
}
return is_mounted;
}
// Monitor mountpoint activity...
static void
wait_for_target_mountpoint(void)
{
// c.f., https://stackoverflow.com/questions/5070801
int mfd = open("/proc/mounts", O_RDONLY | O_CLOEXEC);
struct pollfd pfd = { 0 };
pfd.fd = mfd;
pfd.events = POLLERR | POLLPRI;
pfd.revents = 0;
uint8_t changes = 0U;
uint8_t max_changes = 6U;
while (poll(&pfd, 1, -1) >= 0) {
if (pfd.revents & POLLERR) {
LOG(LOG_INFO, "Mountpoints changed (iteration nr. %d of %hhu)", ++changes, max_changes);
// Stop polling once we know our mountpoint is available...
if (is_target_mounted()) {
LOG(LOG_NOTICE, "Yay! Target mountpoint is available!");
break;
}
}
pfd.revents = 0;
// If we can't find our mountpoint after that many changes, assume we're screwed...
if (changes >= max_changes) {
LOG(LOG_ERR, "Too many mountpoint changes without finding our target (shutdown?), aborting!");
close(mfd);
// NOTE: We have to hide this behind a slightly crappy check, because this runs during load_config,
// at which point FBInk is not yet initialized...
if (fbinkConfig.row != 0) {
FB_PRINT("[KFMon] Internal storage unavailable, bye!");
}
exit(EXIT_FAILURE);
}
}
close(mfd);
}
// Sanitize user input for keys expecting an unsigned short integer
// NOTE: Inspired from git's strtoul_ui @ git-compat-util.h
static int
strtoul_hu(const char* str, unsigned short int* restrict result)
{
// NOTE: We want to *reject* negative values (which strtoul does not)!
if (strchr(str, '-')) {
LOG(LOG_WARNING, "Assigned a negative value (%s) to a key expecting an unsigned short int.", str);
return -EINVAL;
}
// Now that we know it's positive, we can go on with strtoul...
char* endptr;
errno = 0; // To distinguish success/failure after call
unsigned long int val = strtoul(str, &endptr, 10);
if (errno != 0) {
PFLOG(LOG_WARNING, "strtoul: %m");
return -EINVAL;
}
// NOTE: It fact, always clamp to SHRT_MAX, since some of these may end up cast to an int (e.g., db_timeout)
if (val > SHRT_MAX) {
LOG(LOG_WARNING,
"Encountered a value larger than SHRT_MAX assigned to a key, clamping it down to SHRT_MAX");
val = SHRT_MAX;
}
if (endptr == str) {
LOG(LOG_WARNING,
"No digits were found in value '%s' assigned to a key expecting an unsigned short int.",
str);
return -EINVAL;
}
// If we got here, strtoul() successfully parsed at least part of a number.
// But we do want to enforce the fact that the input really was *only* an integer value.
if (*endptr != '\0') {
LOG(LOG_WARNING,
"Found trailing characters (%s) behind value '%lu' assigned from string '%s' to a key expecting an unsigned short int.",
endptr,
val,
str);
return -EINVAL;
}
// Make sure there isn't a loss of precision on this arch when casting explicitly
if ((unsigned short int) val != val) {
LOG(LOG_WARNING, "Loss of precision when casting value '%lu' to an unsigned short int.", val);
return -EINVAL;
}
*result = (unsigned short int) val;
return EXIT_SUCCESS;
}
// Sanitize user input for keys expecting a boolean
// NOTE: Inspired from Linux's strtobool (tools/lib/string.c) as well as sudo's implementation of the same.
static int
strtobool(const char* restrict str, bool* restrict result)
{
if (!str) {
LOG(LOG_WARNING, "Passed an empty value to a key expecting a boolean.");
return -EINVAL;
}
switch (str[0]) {
case 't':
case 'T':
if (strcasecmp(str, "true") == 0) {
*result = true;
return EXIT_SUCCESS;
}
break;
case 'y':
case 'Y':
if (strcasecmp(str, "yes") == 0) {
*result = true;
return EXIT_SUCCESS;
}
break;
case '1':
if (str[1] == '\0') {
*result = true;
return EXIT_SUCCESS;
}
break;
case 'f':
case 'F':
if (strcasecmp(str, "false") == 0) {
*result = false;
return EXIT_SUCCESS;
}
break;
case 'n':
case 'N':
switch (str[1]) {
case 'o':
case 'O':
if (str[2] == '\0') {
*result = false;
return EXIT_SUCCESS;
}
break;
default:
break;
}
break;
case '0':
if (str[1] == '\0') {
*result = false;
return EXIT_SUCCESS;
}
break;
case 'o':
case 'O':
switch (str[1]) {
case 'n':
case 'N':
if (str[2] == '\0') {
*result = true;
return EXIT_SUCCESS;
}
break;
case 'f':
case 'F':
switch (str[2]) {
case 'f':
case 'F':
if (str[3] == '\0') {
*result = false;
return EXIT_SUCCESS;
}
break;
default:
break;
}
break;
default:
break;
}
break;
default:
// NOTE: *result is zero-initialized, no need to explicitly set it to false
break;
}
LOG(LOG_WARNING, "Assigned an invalid or malformed value (%s) to a key expecting a boolean.", str);
return -EINVAL;
}
// Handle parsing the main KFMon config
static int
daemon_handler(void* user, const char* restrict section, const char* restrict key, const char* restrict value)
{
DaemonConfig* restrict pconfig = (DaemonConfig*) user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(key, n) == 0
if (MATCH("daemon", "db_timeout")) {
if (strtoul_hu(value, &pconfig->db_timeout) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for db_timeout!");
return 0;
}
} else if (MATCH("daemon", "use_syslog")) {
if (strtobool(value, &pconfig->use_syslog) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for use_syslog!");
return 0;
}
} else if (MATCH("daemon", "with_notifications")) {
if (strtobool(value, &pconfig->with_notifications) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for with_notifications!");
return 0;
}
} else {
return 0; // unknown section/name, error
}
return 1;
}
// Handle parsing a watch config
static int
watch_handler(void* user, const char* restrict section, const char* restrict key, const char* restrict value)
{
WatchConfig* restrict pconfig = (WatchConfig*) user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(key, n) == 0
if (MATCH("watch", "filename")) {
if (str5cpy(pconfig->filename, CFG_SZ_MAX, value, CFG_SZ_MAX, NOTRUNC) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for filename (too long?)!");
return 0;
}
} else if (MATCH("watch", "action")) {
if (str5cpy(pconfig->action, CFG_SZ_MAX, value, CFG_SZ_MAX, NOTRUNC) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for action (too long?)!");
return 0;
}
} else if (MATCH("watch", "label")) {
if (str5cpy(pconfig->label, CFG_SZ_MAX, value, CFG_SZ_MAX, TRUNC) < 0) {
LOG(LOG_WARNING, "The value passed for label may have been truncated!");
}
} else if (MATCH("watch", "hidden")) {
if (strtobool(value, &pconfig->hidden) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for hidden!");
return 0;
}
} else if (MATCH("watch", "block_spawns")) {
if (strtobool(value, &pconfig->block_spawns) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for block_spawns!");
return 0;
}
} else if (MATCH("watch", "skip_db_checks")) {
if (strtobool(value, &pconfig->skip_db_checks) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for skip_db_checks!");
return 0;
}
} else if (MATCH("watch", "do_db_update")) {
if (strtobool(value, &pconfig->do_db_update) < 0) {
LOG(LOG_CRIT, "Passed an invalid value for do_db_update!");
return 0;
}
} else if (MATCH("watch", "db_title")) {
// NOTE: str5cpy returns OKTRUNC (1) if we allow truncation, which we do here
if (str5cpy(pconfig->db_title, DB_SZ_MAX, value, DB_SZ_MAX, TRUNC) != 0) {
LOG(LOG_WARNING, "The value passed for db_title may have been truncated!");
}
} else if (MATCH("watch", "db_author")) {
if (str5cpy(pconfig->db_author, DB_SZ_MAX, value, DB_SZ_MAX, TRUNC) != 0) {
LOG(LOG_WARNING, "The value passed for db_author may have been truncated!");
}
} else if (MATCH("watch", "db_comment")) {
if (str5cpy(pconfig->db_comment, DB_SZ_MAX, value, DB_SZ_MAX, TRUNC) != 0) {
LOG(LOG_WARNING, "The value passed for db_comment may have been truncated!");
}
} else if (MATCH("watch", "reboot_on_exit")) {
;
} else {
return 0; // unknown section/name, error
}
return 1;
}
// Validate a watch config
static bool
validate_watch_config(void* user)
{
WatchConfig* restrict pconfig = (WatchConfig*) user;
bool sane = true;
if (pconfig->filename[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'filename' is missing or blank!");
sane = false;
} else {
// Make sure we're not trying to set multiple watches on the same file...
// (because that would only actually register the first one parsed).
uint8_t matches = 0U;
uint8_t bmatches = 0U;
for (uint8_t watch_idx = 0U; watch_idx < WATCH_MAX; watch_idx++) {
// Only relevant for active watches
if (!watchConfig[watch_idx].is_active) {
continue;
}
if (strcmp(pconfig->filename, watchConfig[watch_idx].filename) == 0) {
matches++;
}
// Check the basename, too, for IPC...
if (strcmp(basename(pconfig->filename), basename(watchConfig[watch_idx].filename)) == 0) {
bmatches++;
}
}
// As we're not yet flagged active, we won't loop over ourselves ;).
if (matches >= 1U) {
LOG(LOG_WARNING, "Tried to setup multiple watches on file '%s'!", pconfig->filename);
sane = false;
}
if (bmatches >= 1U) {
LOG(LOG_WARNING,
"Tried to setup multiple watches on files with an identical basename: '%s'!",
basename(pconfig->filename));
sane = false;
}
}
if (pconfig->action[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'action' is missing or blank!");
sane = false;
}
// Don't warn about a missing/blank 'label', it's optional.
// If we asked for a database update, the next three keys become mandatory
if (pconfig->do_db_update) {
if (pconfig->db_title[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_title' is missing or blank!");
sane = false;
}
if (pconfig->db_author[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_author' is missing or blank!");
sane = false;
}
if (pconfig->db_comment[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_comment' is missing or blank!");
sane = false;
}
}
return sane;
}
// Validate a watch config, and merge it to its final location if it's sane and updated
static bool
validate_and_merge_watch_config(void* user, uint8_t target_idx, bool* was_updated)
{
WatchConfig* restrict pconfig = (WatchConfig*) user;
bool sane = true;
bool updated = false;
if (pconfig->filename[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'filename' is missing or blank!");
sane = false;
} else {
// Did it change?
if (strcmp(pconfig->filename, watchConfig[target_idx].filename) != 0) {
// Make sure we're not trying to set multiple watches on the same file...
// (because that would only actually register the first one parsed).
uint8_t matches = 0U;
uint8_t bmatches = 0U;
for (uint8_t watch_idx = 0U; watch_idx < WATCH_MAX; watch_idx++) {
// Only relevant for active watches
if (!watchConfig[watch_idx].is_active) {
continue;
}
// Skip the to-be-updated watch, since we'll overwrite it if this check pans out...
if (watch_idx == target_idx) {
continue;
}
if (strcmp(pconfig->filename, watchConfig[watch_idx].filename) == 0) {
matches++;
}
// Check basename, too, for IPC...
if (strcmp(basename(pconfig->filename), basename(watchConfig[watch_idx].filename)) == 0) {
bmatches++;
}
}
// We explicitly make sure not to loop over ourselves ;).
if (matches >= 1U) {
LOG(LOG_WARNING, "Tried to setup multiple watches on file '%s'!", pconfig->filename);
sane = false;
}
if (bmatches >= 1U) {
LOG(LOG_WARNING,
"Tried to setup multiple watches on files with an identical basename: '%s'!",
basename(pconfig->filename));
sane = false;
}
if (sane) {
// Filename changed, and it was updated to something sane, update our target watch!
// NOTE: Forgo error checking, as this has already gone through an input validation pass.
str5cpy(
watchConfig[target_idx].filename, CFG_SZ_MAX, pconfig->filename, CFG_SZ_MAX, NOTRUNC);
updated = true;
LOG(LOG_NOTICE,
"Updated filename to '%s' for watch config @ index %hhu",
watchConfig[target_idx].filename,
target_idx);
}
}
}
if (pconfig->action[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'action' is missing or blank!");
sane = false;
} else {
if (strcmp(pconfig->action, watchConfig[target_idx].action) != 0) {
str5cpy(watchConfig[target_idx].action, CFG_SZ_MAX, pconfig->action, CFG_SZ_MAX, NOTRUNC);
updated = true;
LOG(LOG_NOTICE,
"Updated action to '%s' for watch config @ index %hhu",
watchConfig[target_idx].action,
target_idx);
}
}
// Check if label was updated...
if (strcmp(pconfig->label, watchConfig[target_idx].label) != 0) {
str5cpy(watchConfig[target_idx].label, CFG_SZ_MAX, pconfig->label, CFG_SZ_MAX, TRUNC);
updated = true;
LOG(LOG_NOTICE,
"Updated label to '%s' for watch config @ index %hhu",
watchConfig[target_idx].label,
target_idx);
}
// Check if hidden was updated...
if (pconfig->hidden != watchConfig[target_idx].hidden) {
watchConfig[target_idx].hidden = pconfig->hidden;
updated = true;
LOG(LOG_NOTICE,
"Updated hidden to %s for watch config @ index %hhu",
BOOL2STR(watchConfig[target_idx].hidden),
target_idx);
}
// Check if block_spawns was updated...
if (pconfig->block_spawns != watchConfig[target_idx].block_spawns) {
watchConfig[target_idx].block_spawns = pconfig->block_spawns;
updated = true;
LOG(LOG_NOTICE,
"Updated block_spawns to %s for watch config @ index %hhu",
BOOL2STR(watchConfig[target_idx].block_spawns),
target_idx);
}
// Check if skip_db_checks was updated...
if (pconfig->skip_db_checks != watchConfig[target_idx].skip_db_checks) {
watchConfig[target_idx].skip_db_checks = pconfig->skip_db_checks;
updated = true;
LOG(LOG_NOTICE,
"Updated skip_db_checks to %s for watch config @ index %hhu",
BOOL2STR(watchConfig[target_idx].skip_db_checks),
target_idx);
}
// Check if do_db_update was updated...
if (pconfig->do_db_update != watchConfig[target_idx].do_db_update) {
watchConfig[target_idx].do_db_update = pconfig->do_db_update;
updated = true;
LOG(LOG_NOTICE,
"Updated do_db_update to %s for watch config @ index %hhu",
BOOL2STR(watchConfig[target_idx].do_db_update),
target_idx);
}
// If we asked for a database update, the next three keys become mandatory
if (pconfig->do_db_update) {
if (pconfig->db_title[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_title' is missing or blank!");
sane = false;
} else {
if (strcmp(pconfig->db_title, watchConfig[target_idx].db_title) != 0) {
str5cpy(watchConfig[target_idx].db_title, DB_SZ_MAX, pconfig->db_title, DB_SZ_MAX, TRUNC);
updated = true;
LOG(LOG_NOTICE,
"Updated db_title to '%s' for watch config @ index %hhu",
watchConfig[target_idx].db_title,
target_idx);
}
}
if (pconfig->db_author[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_author' is missing or blank!");
sane = false;
} else {
if (strcmp(pconfig->db_author, watchConfig[target_idx].db_author) != 0) {
str5cpy(
watchConfig[target_idx].db_author, DB_SZ_MAX, pconfig->db_author, DB_SZ_MAX, TRUNC);
updated = true;
LOG(LOG_NOTICE,
"Updated db_author to '%s' for watch config @ index %hhu",
watchConfig[target_idx].db_author,
target_idx);
}
}
if (pconfig->db_comment[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_comment' is missing or blank!");
sane = false;
} else {
if (strcmp(pconfig->db_comment, watchConfig[target_idx].db_comment) != 0) {
str5cpy(
watchConfig[target_idx].db_comment, DB_SZ_MAX, pconfig->db_comment, DB_SZ_MAX, TRUNC);
updated = true;
LOG(LOG_NOTICE,
"Updated db_comment to '%s' for watch config @ index %hhu",
watchConfig[target_idx].db_comment,
target_idx);
}
}
}
if (sane && updated) {
FB_PRINTF("[KFMon] Updated the watch on %s", basename(watchConfig[target_idx].filename));
// Notify the caller
*was_updated = true;
}
return sane;
}
// Returns the index of the first usable entry in the watch list
static int8_t
get_next_available_watch_entry(void)
{
for (uint8_t watch_idx = 0U; watch_idx < WATCH_MAX; watch_idx++) {
if (!watchConfig[watch_idx].is_active) {
return (int8_t) watch_idx;
}
}
return -1;
}
// Mimic scandir's alphasort
static int
fts_alphasort(const FTSENT** a, const FTSENT** b)
{
// NOTE: alphasort actually uses strcoll now, but this is Kobo, locales are broken anyway, so, strcmp is The Way.
// Or strverscmp is we wanted natural sorting, which we don't really need here ;).
return strcmp((*a)->fts_name, (*b)->fts_name);
}
// Load our config files...
static int
load_config(void)
{
// Our config files live in the target mountpoint...
if (!is_target_mounted()) {
LOG(LOG_NOTICE, "%s isn't mounted, waiting for it to be . . .", KFMON_TARGET_MOUNTPOINT);
// If it's not, wait for it to be...
wait_for_target_mountpoint();
}
// Walk the config directory to pickup our ini files... (c.f.,
// https://keramida.wordpress.com/2009/07/05/fts3-or-avoiding-to-reinvent-the-wheel/)
// We only need to walk a single directory...
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"
#pragma clang diagnostic ignored "-Wincompatible-pointer-types-discards-qualifiers"
char* const cfg_path[] = { KFMON_CONFIGPATH, NULL };
#pragma GCC diagnostic pop
// Don't chdir (because that mountpoint can go buh-bye).
// NOTE: We *could* use FTS_NOSTAT, because we *do* get basic info about regular files this way...
// ...because fts will actually stat those in FTS_LOGICAL mode (while you'd get a whole lot of FTS_NSOK w/ FTS_PHYSICAL).
// Which means this wouldn't save us much, so *do* stat all the things so we get accurate info regardless.
FTS* restrict ftsp;
if ((ftsp = fts_open(cfg_path, FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR | FTS_XDEV, &fts_alphasort)) == NULL) {
PFLOG(LOG_CRIT, "fts_open: %m");
return -1;
}
// Initialize ftsp with as many toplevel entries as possible.
FTSENT* restrict chp;
chp = fts_children(ftsp, 0);
if (chp == NULL) {
// No files to traverse!
LOG(LOG_CRIT, "Config directory '%s' appears to be empty, aborting!", KFMON_CONFIGPATH);
fts_close(ftsp);
return -1;
}
// Until something goes wrong...
int rval = EXIT_SUCCESS;
// Keep track of how many watches we've set up
uint8_t watch_count = 0U;
FTSENT* restrict p;
while ((p = fts_read(ftsp)) != NULL) {
switch (p->fts_info) {
case FTS_F:
// Check if it's a .ini and not either an unix hidden file or a Mac resource fork...
if (p->fts_namelen > 4 &&
strncasecmp(p->fts_name + (p->fts_namelen - 4), ".ini", 4) == 0 &&
strncasecmp(p->fts_name, ".", 1) != 0) {
LOG(LOG_INFO, "Trying to load config file '%s' . . .", p->fts_path);
// The main config has to be parsed slightly differently...
if (strcasecmp(p->fts_name, "kfmon.ini") == 0) {
// NOTE: Can technically return -1 on file open error,
// but that shouldn't really ever happen
// given the nature of the loop we're in ;).
int ret = ini_parse(p->fts_path, daemon_handler, &daemonConfig);
if (ret != 0) {
LOG(LOG_CRIT,
"Failed to parse main config file '%s' (first error on line %d), will abort!",
p->fts_name,
ret);
// Flag as a failure...
rval = -1;
} else {
LOG(LOG_NOTICE,
"Daemon config loaded from '%s': db_timeout=%hu, use_syslog=%s, with_notifications=%s",
p->fts_name,
daemonConfig.db_timeout,
BOOL2STR(daemonConfig.use_syslog),
BOOL2STR(daemonConfig.with_notifications));
}
} else if (strcasecmp(p->fts_name, "kfmon.user.ini") == 0) {
// NOTE: Skip the user config for now,
// as we cannot ensure the order in which files will be walked,
// and we need it to be parsed *after* the main daemon config.
continue;
} else {
// NOTE: Don't blow up when trying to store more watches than we have
// space for...
if (watch_count >= WATCH_MAX) {
LOG(LOG_WARNING,
"We've already setup the maximum amount of watches we can handle (%d), discarding '%s'!",
WATCH_MAX,
p->fts_name);
// Don't flag this as a hard failure, just warn and go on...
break;
}
// Assume a config is invalid until proven otherwise...
bool is_watch_valid = false;
int ret =
ini_parse(p->fts_path, watch_handler, &watchConfig[watch_count]);
if (ret != 0) {
LOG(LOG_WARNING,
"Failed to parse watch config file '%s' (first error on line %d), it will be discarded!",
p->fts_name,
ret);
} else {
if (validate_watch_config(&watchConfig[watch_count])) {
LOG(LOG_NOTICE,
"Watch config @ index %hhu loaded from '%s': filename=%s, action=%s, label=%s, hidden=%s, block_spawns=%s, do_db_update=%s, db_title=%s, db_author=%s, db_comment=%s",
watch_count,
p->fts_name,
watchConfig[watch_count].filename,
watchConfig[watch_count].action,
watchConfig[watch_count].label,
BOOL2STR(watchConfig[watch_count].hidden),
BOOL2STR(watchConfig[watch_count].block_spawns),
BOOL2STR(watchConfig[watch_count].do_db_update),
watchConfig[watch_count].db_title,
watchConfig[watch_count].db_author,
watchConfig[watch_count].db_comment);
is_watch_valid = true;
} else {
LOG(LOG_WARNING,
"Watch config file '%s' is not valid, it will be discarded!",
p->fts_name);
}
}
// If the watch config is valid, mark it as active, and increment the active count.
// Otherwise, clear the slot so it can be reused.
if (is_watch_valid) {
watchConfig[watch_count++].is_active = true;
} else {
watchConfig[watch_count] = (const WatchConfig){ 0 };
}
}
}
break;
default:
break;
}
}
fts_close(ftsp);
// Now we can see if we have an user daemon config to handle...
const char usercfg_path[] = KFMON_CONFIGPATH "/kfmon.user.ini";
if (access(usercfg_path, F_OK) == 0) {
int ret = ini_parse(usercfg_path, daemon_handler, &daemonConfig);
if (ret != 0) {
LOG(LOG_CRIT,
"Failed to parse user config file '%s' (first error on line %d), will abort!",
"kfmon.user.ini",
ret);
// Flag as a failure...
rval = -1;
} else {
LOG(LOG_NOTICE,
"Daemon config loaded from '%s': db_timeout=%hu, use_syslog=%s, with_notifications=%s",
"kfmon.user.ini",
daemonConfig.db_timeout,
BOOL2STR(daemonConfig.use_syslog),
BOOL2STR(daemonConfig.with_notifications));
}
}
#ifdef DEBUG
// Let's recap (including failures)...
DBGLOG("Daemon config recap: db_timeout=%hu, use_syslog=%s, with_notifications=%s",
daemonConfig.db_timeout,
BOOL2STR(daemonConfig.use_syslog),
BOOL2STR(daemonConfig.with_notifications));
for (uint8_t watch_idx = 0U; watch_idx < WATCH_MAX; watch_idx++) {
DBGLOG(
"Watch config @ index %hhu recap: active=%s, filename=%s, action=%s, label=%s, hidden=%s, block_spawns=%s, skip_db_checks=%s, do_db_update=%s, db_title=%s, db_author=%s, db_comment=%s",
watch_idx,
BOOL2STR(watchConfig[watch_idx].is_active),
watchConfig[watch_idx].filename,
watchConfig[watch_idx].action,
watchConfig[watch_idx].label,
BOOL2STR(watchConfig[watch_idx].hidden),
BOOL2STR(watchConfig[watch_idx].block_spawns),
BOOL2STR(watchConfig[watch_idx].skip_db_checks),
BOOL2STR(watchConfig[watch_idx].do_db_update),
watchConfig[watch_idx].db_title,
watchConfig[watch_idx].db_author,
watchConfig[watch_idx].db_comment);
}
#endif
return rval;
}
// Check if watch configs have been added/removed/updated...
static int
update_watch_configs(void)
{
// Walk the config directory to pickup our ini files... (c.f.,
// https://keramida.wordpress.com/2009/07/05/fts3-or-avoiding-to-reinvent-the-wheel/)
// We only need to walk a single directory...
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"
#pragma clang diagnostic ignored "-Wincompatible-pointer-types-discards-qualifiers"
char* const cfg_path[] = { KFMON_CONFIGPATH, NULL };
#pragma GCC diagnostic pop
// Don't chdir (because that mountpoint can go buh-bye), and don't stat (because we don't need to).
FTS* restrict ftsp;
if ((ftsp = fts_open(
cfg_path, FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR | FTS_NOSTAT | FTS_XDEV, &fts_alphasort)) == NULL) {
PFLOG(LOG_CRIT, "fts_open: %m");
return -1;
}
// Initialize ftsp with as many toplevel entries as possible.
FTSENT* restrict chp;
chp = fts_children(ftsp, 0);
if (chp == NULL) {
// No files to traverse!
LOG(LOG_CRIT, "Config directory '%s' appears to be empty, aborting!", KFMON_CONFIGPATH);
fts_close(ftsp);
return -1;
}
// Keep track of which watch indexes are up-to-date, so we can drop stale watches if some configs were deleted.
// NOTE: Init to -1 because 0 is a valid watch index ;).
int8_t new_watch_list[WATCH_MAX] = { [0 ... WATCH_MAX - 1] = -1 };
uint8_t new_watch_count = 0U;
// If there was a meaningful update, we'll update the IPC socket's mtime as a hint to clients that new data is available.
bool notify_update = false;
FTSENT* restrict p;
while ((p = fts_read(ftsp)) != NULL) {
switch (p->fts_info) {
case FTS_F:
// Check if it's a .ini and not either an unix hidden file or a Mac resource fork...
if (p->fts_namelen > 4 &&
strncasecmp(p->fts_name + (p->fts_namelen - 4), ".ini", 4) == 0 &&
strncasecmp(p->fts_name, ".", 1) != 0) {
// NOTE: We only care about *watch* configs,
// the main config is only loaded at startup
// This is mainly to keep our fd shenanigans sane,
// which would get a bit hairier
// if we needed to be able to toggle syslog usage...
if (strcasecmp(p->fts_name, "kfmon.ini") == 0) {
continue;
} else if (strcasecmp(p->fts_name, "kfmon.user.ini") == 0) {
continue;
} else {
LOG(LOG_INFO,
"Checking watch config file '%s' for changes . . .",
p->fts_path);