-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathkfmon.c
1248 lines (1100 loc) · 46.5 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-2018 NiLuJe <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "kfmon.h"
// Because daemon() only appeared in glibc 2.21
static int daemonize(void)
{
int fd;
switch (fork()) {
case -1:
return -1;
case 0:
break;
default:
_exit(0);
}
if (setsid() == -1) {
return -1;
}
// Double fork, for... reasons!
signal(SIGHUP, SIG_IGN);
switch (fork()) {
case -1:
return -1;
case 0:
break;
default:
_exit(0);
}
if (chdir("/") == -1) {
return -1;
}
umask(0);
// Store a copy of stdin, stdout & stderr so we can restore it to our children later on...
orig_stdin = dup(fileno(stdin));
orig_stdout = dup(fileno(stdout));
orig_stderr = dup(fileno(stderr));
// Redirect stdin & stdout to /dev/null
if ((fd = open("/dev/null", O_RDWR)) != -1) {
dup2(fd, fileno(stdin));
dup2(fd, fileno(stdout));
if (fd > 2 + 3) {
close(fd);
}
} else {
fprintf(stderr, "Failed to redirect stdin & stdout to /dev/null\n");
return -1;
}
// Redirect stderr to our logfile
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, 0600)) != -1) {
dup2(fd, fileno(stderr));
if (fd > 2 + 3) {
close(fd);
}
} else {
fprintf(stderr, "Failed to redirect stderr to logfile '%s'\n", KFMON_LOGFILE);
return -1;
}
return 0;
}
// Wrapper around localtime_r, making sure this part is thread-safe (used for logging)
struct tm *get_localtime(struct tm *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)
char *format_localtime(struct tm *lt, char *sz_time, size_t len)
{
// cf. 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.
char *get_current_time(void)
{
static struct tm local_tm = {0};
struct tm *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:
// f.g., we use the stack in reaper_thread().
char *get_current_time_r(struct tm *local_tm, char *sz_time, size_t len)
{
struct tm *lt = get_localtime(local_tm);
return format_localtime(lt, sz_time, len);
}
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)
{
// cf. http://program-nix.blogspot.fr/2008/08/c-language-check-filesystem-is-mounted.html
FILE *mtab = NULL;
struct mntent *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)
{
// cf. https://stackoverflow.com/questions/5070801
int mfd = open("/proc/mounts", O_RDONLY, 0);
struct pollfd pfd;
unsigned int changes = 0;
pfd.fd = mfd;
pfd.events = POLLERR | POLLPRI;
pfd.revents = 0;
while (poll(&pfd, 1, -1) >= 0) {
if (pfd.revents & POLLERR) {
LOG(LOG_INFO, "Mountpoints changed (iteration nr. %u)", 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 >= 5) {
LOG(LOG_ERR, "Too many mountpoint changes without finding our target (shutdown?), aborting!");
close(mfd);
exit(EXIT_FAILURE);
}
}
close(mfd);
}
// Sanitize user input for keys expecting an (unsigned) integer
static unsigned long int sane_strtoul(const char *str)
{
char *endptr;
unsigned long int val;
errno = 0; // To distinguish success/failure after call
val = strtoul(str, &endptr, 10);
// NOTE: To make things simpler for us, we return ULONG_MAX on error...
if ((errno == ERANGE && val == ULONG_MAX) || (errno != 0 && val == 0)) {
perror("[KFMon] [WARN] strtoul");
return ULONG_MAX;
// ... this means that if we were passed a legitimate ULONG_MAX (which, granted, should *never* happen in our context),
// we have to modify it to pass our sanity checks down the line.
} else if (val == ULONG_MAX) {
LOG(LOG_WARNING, "Encountered a legitimate ULONG_MAX assigned to a key, nerfing it down to UINT_MAX");
val = UINT_MAX;
}
if (endptr == str) {
LOG(LOG_WARNING, "No digits were found in value '%s' assigned to a key expecting an unsigned int", str);
return ULONG_MAX;
}
// If we got here, strtol() 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 '%ld' assigned from string '%s' to a key expecting an unsigned int", endptr, val, str);
return ULONG_MAX;
}
return val;
}
// Handle parsing the main KFMon config
static int daemon_handler(void *user, const char *section, const char *key, const char *value)
{
DaemonConfig *pconfig = (DaemonConfig *)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(key, n) == 0
if (MATCH("daemon", "db_timeout")) {
pconfig->db_timeout = sane_strtoul(value);
} else if (MATCH("daemon", "use_syslog")) {
pconfig->use_syslog = sane_strtoul(value);
} else {
return 0; // unknown section/name, error
}
return 1;
}
// Validate the main KFMon config
static bool validate_daemon_config(void *user)
{
DaemonConfig *pconfig = (DaemonConfig *)user;
bool sane = true;
if (pconfig->db_timeout == ULONG_MAX) {
LOG(LOG_CRIT, "Passed an invalid value for db_timeout!");
sane = false;
}
if (pconfig->use_syslog == ULONG_MAX) {
LOG(LOG_CRIT, "Passed an invalid value for use_syslog!");
sane = false;
}
return sane;
}
// Handle parsing a watch config
static int watch_handler(void *user, const char *section, const char *key, const char *value)
{
WatchConfig *pconfig = (WatchConfig *)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(key, n) == 0
// NOTE: Crappy strncpy() usage, but those char arrays are zeroed first (hence the MAX-1 len to ensure that we're NULL terminated)...
if (MATCH("watch", "filename")) {
strncpy(pconfig->filename, value, PATH_MAX-1);
} else if (MATCH("watch", "action")) {
strncpy(pconfig->action, value, PATH_MAX-1);
} else if (MATCH("watch", "do_db_update")) {
pconfig->do_db_update = sane_strtoul(value);
} else if (MATCH("watch", "skip_db_checks")) {
pconfig->skip_db_checks = sane_strtoul(value);
} else if (MATCH("watch", "db_title")) {
strncpy(pconfig->db_title, value, DB_SZ_MAX-1);
} else if (MATCH("watch", "db_author")) {
strncpy(pconfig->db_author, value, DB_SZ_MAX-1);
} else if (MATCH("watch", "db_comment")) {
strncpy(pconfig->db_comment, value, DB_SZ_MAX-1);
} else if (MATCH("watch", "block_spawns")) {
pconfig->block_spawns = sane_strtoul(value);
} 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 *pconfig = (WatchConfig *)user;
bool sane = true;
if (pconfig->filename[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'filename' is missing!");
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).
unsigned int watch_idx = 0;
unsigned int matches = 0;
for (watch_idx = 0; watch_idx < WATCH_MAX; watch_idx++) {
if (strcmp(pconfig->filename, watch_config[watch_idx].filename) == 0) {
matches++;
}
}
// Since we'll necessarily loop over ourselves, only warn if we matched two or more times.
if (matches >= 2) {
LOG(LOG_WARNING, "Tried to setup multiple watches on file '%s'!", pconfig->filename);
sane = false;
}
}
if (pconfig->action[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'action' is missing!");
sane = false;
}
// Handle the uint vars
if (pconfig->do_db_update == ULONG_MAX) {
LOG(LOG_WARNING, "Passed an invalid value for do_db_update!");
sane = false;
}
if (pconfig->skip_db_checks == ULONG_MAX) {
LOG(LOG_WARNING, "Passed an invalid value for skip_db_checks!");
sane = false;
}
// 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!");
sane = false;
}
if (pconfig->db_author[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_author' is missing!");
sane = false;
}
if (pconfig->db_comment[0] == '\0') {
LOG(LOG_CRIT, "Mandatory key 'db_comment' is missing!");
sane = false;
}
}
if (pconfig->block_spawns == ULONG_MAX) {
LOG(LOG_WARNING, "Passed an invalid value for block_spawns!");
sane = false;
}
return sane;
}
// 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/)
FTS *ftsp;
FTSENT *p, *chp;
// We only need to walk a single directory...
char *const cfg_path[] = {KFMON_CONFIGPATH, NULL};
int ret;
int rval = 0;
// Don't chdir (because that mountpoint can go buh-bye), and don't stat (because we don't need to).
if ((ftsp = fts_open(cfg_path, FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR | FTS_NOSTAT | FTS_XDEV, NULL)) == NULL) {
perror("[KFMon] [CRIT] fts_open");
return -1;
}
// Initialize ftsp with as many toplevel entries as possible.
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;
}
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 ;).
ret = ini_parse(p->fts_path, daemon_handler, &daemon_config);
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 {
if (validate_daemon_config(&daemon_config)) {
LOG(LOG_NOTICE, "Daemon config loaded from '%s': db_timeout=%lu, use_syslog=%lu", p->fts_name, daemon_config.db_timeout, daemon_config.use_syslog);
} else {
LOG(LOG_CRIT, "Main config file '%s' is not valid, will abort!", p->fts_name);
rval = -1;
}
}
} 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;
}
ret = ini_parse(p->fts_path, watch_handler, &watch_config[watch_count]);
if (ret != 0) {
LOG(LOG_CRIT, "Failed to parse watch config file '%s' (first error on line %d), will abort!", p->fts_name, ret);
// Flag as a failure...
rval = -1;
} else {
if (validate_watch_config(&watch_config[watch_count])) {
LOG(LOG_NOTICE, "Watch config @ index %zd loaded from '%s': filename=%s, action=%s, block_spawns=%lu, do_db_update=%lu, db_title=%s, db_author=%s, db_comment=%s",
watch_count,
p->fts_name,
watch_config[watch_count].filename,
watch_config[watch_count].action,
watch_config[watch_count].block_spawns,
watch_config[watch_count].do_db_update,
watch_config[watch_count].db_title,
watch_config[watch_count].db_author,
watch_config[watch_count].db_comment
);
} else {
LOG(LOG_CRIT, "Watch config file '%s' is not valid, will abort!", p->fts_name);
rval = -1;
}
}
// No matter what, switch to the next slot: we rely on zero-initialization (c.f., the comments around our strncpy() usage in watch_handler),
// so we can't reuse a slot, even in case of failure, or we risk mixing values from different config files together,
// which is why a broken watch config is flagged as a fatal failure.
watch_count++;
}
}
break;
default:
break;
}
}
fts_close(ftsp);
#ifdef DEBUG
// Let's recap (including failures)...
DBGLOG("Daemon config recap: db_timeout=%lu, use_syslog=%lu", daemon_config.db_timeout, daemon_config.use_syslog);
for (unsigned int watch_idx = 0; watch_idx < watch_count; watch_idx++) {
DBGLOG("Watch config @ index %d recap: filename=%s, action=%s, block_spawns=%lu, do_db_update=%lu, skip_db_checks=%lu, db_title=%s, db_author=%s, db_comment=%s",
watch_idx,
watch_config[watch_idx].filename,
watch_config[watch_idx].action,
watch_config[watch_count].block_spawns,
watch_config[watch_idx].do_db_update,
watch_config[watch_idx].skip_db_checks,
watch_config[watch_idx].db_title,
watch_config[watch_idx].db_author,
watch_config[watch_idx].db_comment
);
}
#endif
return rval;
}
// Implementation of Qt4's QtHash (cf. qhash @ https://github.com/kovidgoyal/calibre/blob/master/src/calibre/devices/kobo/driver.py#L37)
static unsigned int qhash(const unsigned char *bytes, size_t length)
{
unsigned int h = 0;
unsigned int i;
for(i = 0; i < length; i++) {
h = (h << 4) + bytes[i];
h ^= (h & 0xf0000000) >> 23;
h &= 0x0fffffff;
}
return h;
}
// Check if our target file has been processed by Nickel...
static bool is_target_processed(unsigned int watch_idx, bool wait_for_db)
{
sqlite3 *db;
sqlite3_stmt * stmt;
int rc;
int idx;
bool is_processed = false;
bool needs_update = false;
#ifdef DEBUG
// Bypass DB checks on demand for debugging purposes...
if(watch_config[watch_idx].skip_db_checks)
return true;
#endif
// Did the user want to try to update the DB for this icon?
bool update = watch_config[watch_idx].do_db_update;
if (update) {
CALL_SQLITE(open_v2(KOBO_DB_PATH , &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, NULL));
} else {
// Open the DB ro to be extra-safe...
CALL_SQLITE(open_v2(KOBO_DB_PATH , &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX, NULL));
}
// Wait at most for Nms on OPEN & N*2ms on CLOSE if we ever hit a locked database during any of our proceedings...
// NOTE: The defaults timings (steps of 500ms) appear to work reasonably well on my H2O with a 50MB Nickel DB... (i.e., it trips on OPEN when Nickel is moderately busy, but if everything's quiet, we're good).
// Time will tell if that's a good middle-ground or not ;). This is user configurable in kfmon.ini (db_timeout key).
sqlite3_busy_timeout(db, (int) daemon_config.db_timeout * (wait_for_db + 1));
DBGLOG("SQLite busy timeout set to %dms", (int) daemon_config.db_timeout * (wait_for_db + 1));
// NOTE: ContentType 6 should mean a book on pretty much anything since FW 1.9.17 (and why a book? Because Nickel currently identifies single PNGs as application/x-cbz, bless its cute little bytes).
CALL_SQLITE(prepare_v2(db, "SELECT EXISTS(SELECT 1 FROM content WHERE ContentID = @id AND ContentType = '6');", -1, &stmt, NULL));
// Append the proper URI scheme to our icon path...
char book_path[PATH_MAX+7];
snprintf(book_path, PATH_MAX+7, "file://%s", watch_config[watch_idx].filename);
idx = sqlite3_bind_parameter_index(stmt, "@id");
CALL_SQLITE(bind_text(stmt, idx, book_path, -1, SQLITE_STATIC));
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
DBGLOG("SELECT SQL query returned: %d", sqlite3_column_int(stmt, 0));
if (sqlite3_column_int(stmt, 0) == 1) {
is_processed = true;
}
}
sqlite3_finalize(stmt);
// Now that we know the book exists, we also want to check if the thumbnails do... to avoid getting triggered from the thumbnail creation.
// NOTE: Again, this assumes FW >= 2.9.0
if (is_processed) {
// Assume they haven't been processed until we can confirm it...
is_processed = false;
// We'll need the ImageID first...
CALL_SQLITE(prepare_v2(db, "SELECT ImageID FROM content WHERE ContentID = @id AND ContentType = '6';", -1, &stmt, NULL));
idx = sqlite3_bind_parameter_index(stmt, "@id");
CALL_SQLITE(bind_text(stmt, idx, book_path, -1, SQLITE_STATIC));
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
DBGLOG("SELECT SQL query returned: %s", sqlite3_column_text(stmt, 0));
const unsigned char *image_id = sqlite3_column_text(stmt, 0);
size_t len = (size_t)sqlite3_column_bytes(stmt, 0);
// Then we need the proper hashes Nickel devises...
// cf. images_path @ https://github.com/kovidgoyal/calibre/blob/master/src/calibre/devices/kobo/driver.py#L2489
unsigned int hash = qhash(image_id, len);
unsigned int dir1 = hash & (0xff * 1);
unsigned int dir2 = (hash & (0xff00 * 1)) >> 8;
char images_path[PATH_MAX];
snprintf(images_path, PATH_MAX, "%s/.kobo-images/%u/%u", KFMON_TARGET_MOUNTPOINT, dir1, dir2);
DBGLOG("Checking for thumbnails in '%s' . . .", images_path);
// Count the number of processed thumbnails we find...
unsigned int thumbnails_num = 0;
// Start with the full-size screensaver...
char ss_path[PATH_MAX];
snprintf(ss_path, PATH_MAX, "%s/%s - N3_FULL.parsed", images_path, image_id);
if (access(ss_path, F_OK) == 0) {
thumbnails_num++;
} else {
LOG(LOG_INFO, "Full-size screensaver hasn't been parsed yet!");
}
// Then the Homescreen tile...
// NOTE: This one might be a tad confusing...
// If the icon has never been processed, this will only happen the first time we *close* the PNG's "book"... (i.e., the moment it pops up as the 'last opened' tile).
// And *that* processing triggers a set of OPEN & CLOSE, meaning we can quite possibly run on book *exit* that first time (and only that first time), if database locking permits...
char tile_path[PATH_MAX];
snprintf(tile_path, PATH_MAX, "%s/%s - N3_LIBRARY_FULL.parsed", images_path, image_id);
if (access(tile_path, F_OK) == 0) {
thumbnails_num++;
} else {
LOG(LOG_INFO, "Homescreen tile hasn't been parsed yet!");
}
// And finally the Library thumbnail...
char thumb_path[PATH_MAX];
snprintf(thumb_path, PATH_MAX, "%s/%s - N3_LIBRARY_GRID.parsed", images_path, image_id);
if (access(thumb_path, F_OK) == 0) {
thumbnails_num++;
} else {
LOG(LOG_INFO, "Library thumbnail hasn't been parsed yet!");
}
// Only give a greenlight if we got all three!
if (thumbnails_num == 3) {
is_processed = true;
}
}
sqlite3_finalize(stmt);
}
// NOTE: Here be dragons! This works in theory, but risks confusing Nickel's handling of the DB if we do that when nickel is running (which we are).
// Because doing it with Nickel running is a potentially terrible idea, for various reasons (c.f., https://www.sqlite.org/howtocorrupt.html for the gory details, some of which probably even apply here! :p).
// As such, we leave enabling this option to the user's responsibility. KOReader ships with it disabled.
// The idea is to, optionally, update the Title, Author & Comment fields to make them more useful...
if (is_processed && update) {
// Check if the DB has already been updated by checking the title...
CALL_SQLITE(prepare_v2(db, "SELECT Title FROM content WHERE ContentID = @id AND ContentType = '6';", -1, &stmt, NULL));
idx = sqlite3_bind_parameter_index(stmt, "@id");
CALL_SQLITE(bind_text(stmt, idx, book_path, -1, SQLITE_STATIC));
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
DBGLOG("SELECT SQL query returned: %s", sqlite3_column_text(stmt, 0));
if (strcmp((const char *)sqlite3_column_text(stmt, 0), watch_config[watch_idx].db_title) != 0) {
needs_update = true;
}
}
sqlite3_finalize(stmt);
}
if (needs_update) {
CALL_SQLITE(prepare_v2(db, "UPDATE content SET Title = @title, Attribution = @author, Description = @comment WHERE ContentID = @id AND ContentType = '6';", -1, &stmt, NULL));
// NOTE: No sanity checks are done to confirm that those watch configs are sane, we only check that they are *present*... The example config ships with a strong warning not to forget them if wanted, but that's it.
idx = sqlite3_bind_parameter_index(stmt, "@title");
CALL_SQLITE(bind_text(stmt, idx, watch_config[watch_idx].db_title, -1, SQLITE_STATIC));
idx = sqlite3_bind_parameter_index(stmt, "@author");
CALL_SQLITE(bind_text(stmt, idx, watch_config[watch_idx].db_author, -1, SQLITE_STATIC));
idx = sqlite3_bind_parameter_index(stmt, "@comment");
CALL_SQLITE(bind_text(stmt, idx, watch_config[watch_idx].db_comment, -1, SQLITE_STATIC));
idx = sqlite3_bind_parameter_index(stmt, "@id");
CALL_SQLITE(bind_text(stmt, idx, book_path, -1, SQLITE_STATIC));
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
LOG(LOG_WARNING, "UPDATE SQL query failed: %s", sqlite3_errmsg(db));
} else {
LOG(LOG_NOTICE, "Successfully updated DB data for the target PNG");
}
sqlite3_finalize(stmt);
}
// A rather crappy check to wait for pending COMMITs...
if (is_processed && wait_for_db) {
// If there's a rollback journal for the DB, wait for it to go away...
// NOTE: This assumes the DB was opened with the default journal_mode, DELETE
// This doesn't appear to be the case anymore, on FW 4.7.x (and possibly earlier, I haven't looked at this stuff in quite a while), it's now using WAL (which makes sense).
unsigned int count = 0;
while (access(KOBO_DB_PATH"-journal", F_OK) == 0) {
LOG(LOG_INFO, "Found a SQLite rollback journal, waiting for it to go away (iteration nr. %u) . . .", count++);
usleep(250 * 1000);
// NOTE: Don't wait more than 10s
if (count > 40) {
LOG(LOG_WARNING, "Waited for the SQLite rollback journal to go away for far too long, going on anyway.");
break;
}
}
}
sqlite3_close(db);
return is_processed;
}
// Heavily inspired from https://stackoverflow.com/a/35235950
// Initializes the process table. -1 means the entry in the table is available.
static void init_process_table(void)
{
for (unsigned int i = 0; i < WATCH_MAX; i++) {
PT.spawn_pids[i] = -1;
PT.spawn_watchids[i] = -1;
}
}
// Returns the index of the next available entry in the process table.
static int get_next_available_pt_entry(void)
{
for (int i = 0; i < WATCH_MAX; i++) {
if (PT.spawn_watchids[i] == -1) {
return i;
}
}
return -1;
}
// Adds information about a new spawn to the process table.
static void add_process_to_table(int i, pid_t pid, unsigned int watch_idx)
{
PT.spawn_pids[i] = pid;
PT.spawn_watchids[i] = (int) watch_idx;
}
// Removes information about a spawn from the process table.
static void remove_process_from_table(int i)
{
PT.spawn_pids[i] = -1;
PT.spawn_watchids[i] = -1;
}
// Wait for a specific child process to die, and reap it (runs in a dedicated thread per spawn).
void *reaper_thread(void *ptr)
{
int i = *((int *) ptr);
pid_t tid;
tid = (pid_t) syscall(SYS_gettid);
pid_t cpid;
int watch_idx;
pthread_mutex_lock(&ptlock);
cpid = PT.spawn_pids[i];
watch_idx = PT.spawn_watchids[i];
pthread_mutex_unlock(&ptlock);
// Storage needed for get_current_time_r
struct tm local_tm;
char sz_time[22];
// Remember the current time for the execvp errno/exitcode heuristic...
time_t then = time(NULL);
MTLOG("[%s] [INFO] [TID: %ld] Waiting to reap process %ld (from watch idx %d) . . .", get_current_time_r(&local_tm, sz_time, sizeof(sz_time)), (long) tid, (long) cpid, watch_idx);
pid_t ret;
int wstatus;
// Wait for our child process to terminate, retrying on EINTR
do {
ret = waitpid(cpid, &wstatus, 0);
} while (ret == -1 && errno == EINTR);
// Recap what happened to it
if (ret != cpid) {
perror("[KFMon] [CRIT] waitpid");
free(ptr);
return (void*)NULL;
} else {
if (WIFEXITED(wstatus)) {
int exitcode = WEXITSTATUS(wstatus);
MTLOG("[%s] [NOTE] [TID: %ld] Reaped process %ld (from watch idx %d): It exited with status %d.", get_current_time_r(&local_tm, sz_time, sizeof(sz_time)), (long) tid, (long) cpid, watch_idx, exitcode);
// NOTE: Ugly hack to try to salvage execvp's potential error... If the process exited with a non-zero status code, within (roughly) a second of being launched, assume the exit code is actually inherited from execvp's errno...
time_t now = time(NULL);
if (exitcode != 0 && difftime(now, then) <= 1) {
char buf[256];
// NOTE: We *know* we'll be using the GNU, glibc >= 2.13 version of strerror_r
char *sz_error = strerror_r(exitcode, buf, sizeof(buf));
MTLOG("[%s] [CRIT] [TID: %ld] If nothing was visibly launched, and/or especially if status > 1, this *may* actually be an execvp() error: %s.", get_current_time_r(&local_tm, sz_time, sizeof(sz_time)), (long) tid, sz_error);
}
} else if (WIFSIGNALED(wstatus)) {
// NOTE: strsignal is not thread safe... Use psignal instead.
int sigcode = WTERMSIG(wstatus);
char buf[256];
snprintf(buf, sizeof(buf), "[KFMon] [%s] [WARN] [TID: %ld] Reaped process %ld (from watch idx %d): It was killed by signal %d", get_current_time_r(&local_tm, sz_time, sizeof(sz_time)), (long) tid, (long) cpid, watch_idx, sigcode);
if (daemon_config.use_syslog) {
// NOTE: No strsignal means no human-readable interpretation of the signal w/ syslog (the %m token only works for errno)...
syslog(LOG_NOTICE, "%s", buf);
} else {
psignal(sigcode, buf);
}
}
}
// And now we can safely remove it from the process table
pthread_mutex_lock(&ptlock);
remove_process_from_table(i);
pthread_mutex_unlock(&ptlock);
free(ptr);
return (void*)NULL;
}
/* Spawn a process and return its pid...
* Initially inspired from popen2() implementations from https://stackoverflow.com/questions/548063
* As well as the glibc's system() call,
* With a bit of added tracking to handle reaping without a SIGCHLD handler.
*/
static pid_t spawn(char *const *command, unsigned int watch_idx)
{
pid_t pid;
pid = fork();
if (pid < 0) {
// Fork failed?
perror("[KFMon] [ERR!] Aborting: fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Sweet child o' mine!
// NOTE: Since we're a child process, we essentially get a *copy* of the global variable watch_config *at the time of forking*!
// Our design *should* ensure its content to still be accurate at the time we'll be reading this copy, though.
LOG(LOG_NOTICE, "Spawned process %ld (%s -> %s @ watch idx %d) . . .", (long) getpid(), watch_config[watch_idx].filename, watch_config[watch_idx].action, watch_idx);
// Do the whole stdin/stdout/stderr dance again to ensure that child process doesn't inherit our tweaked fds...
dup2(orig_stdin, fileno(stdin));
dup2(orig_stdout, fileno(stdout));
dup2(orig_stderr, fileno(stderr));
close(orig_stdin);
close(orig_stdout);
close(orig_stderr);
// Restore signals
signal(SIGHUP, SIG_DFL);
// NOTE: We used to use execvpe when being launched from udev in order to sanitize all the crap we inherited from udev's env ;).
// Now, we actually rely on the specific env we inherit from rcS/on-animator!
execvp(*command, command);
// This will only ever be reached on error, hence the lack of actual return value check ;).
// NOTE: Since stderr is now the original stderr, this won't make it to the log...
perror("[KFMon] [CRIT] execvp");
// ...so resort to an ugly hack by exiting with execvp()'s errno, which we can then try to salvage in the reaper thread.
exit(errno);
} else {
// Parent
// Keep track of the process
int i;
pthread_mutex_lock(&ptlock);
i = get_next_available_pt_entry();
pthread_mutex_unlock(&ptlock);
if (i < 0) {
// NOTE: If we ever hit this error codepath, we don't have to worry about leaving that last spawn as a zombie:
// One of the benefits of the double-fork we do to daemonize is that, on our death, our children will get reparented to init,
// which, by design, will handle the reaping automatically.
LOG(LOG_ERR, "Failed to find an available entry in our process table for pid %ld, aborting!", (long) pid);
exit(EXIT_FAILURE);
} else {
pthread_mutex_lock(&ptlock);
add_process_to_table(i, pid, watch_idx);
pthread_mutex_unlock(&ptlock);
DBGLOG("Assigned pid %ld (from watch idx %d) to process table entry idx %d", (long) pid, watch_idx, i);
// NOTE: We achieve reaping in a non-blocking way by doing the reaping from a dedicated thread for every spawn...
// See #2 for an history of the previous failed attempts...
pthread_t rthread;
int *arg = malloc(sizeof(*arg));
if (arg == NULL) {
LOG(LOG_ERR, "Couldn't allocate memory for thread arg, aborting!");
exit(EXIT_FAILURE);
}
*arg = i;
// NOTE: We will *never* wait for one of these threads to die from the main thread, so, start them in detached state to make sure their resources will be released when they terminate.
pthread_attr_t attr;
if (pthread_attr_init(&attr) != 0) {
perror("[KFMon] [ERR!] Aborting: pthread_attr_init");
exit(EXIT_FAILURE);
}
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
perror("[KFMon] [ERR!] Aborting: pthread_attr_setdetachstate");
exit(EXIT_FAILURE);
}
// NOTE: Use a smaller stack (ulimit -s is 8MB on the Kobos). Base it on pointer size, aiming for 2MB on x64. Floor it at 1MB to be safe, though.
// In the grand scheme of things, this won't really change much ;).
if (pthread_attr_setstacksize(&attr, MIN(1 * 1024 * 1024, sizeof(void *) * 1024 * 1024 / 4)) != 0) {
perror("[KFMon] [ERR!] Aborting: pthread_attr_setstacksize");
exit(EXIT_FAILURE);
}
if (pthread_create(&rthread, &attr, reaper_thread, arg) != 0) {
perror("[KFMon] [ERR!] Aborting: pthread_create");
exit(EXIT_FAILURE);
}
if (pthread_attr_destroy(&attr) != 0) {
perror("[KFMon] [ERR!] Aborting: pthread_attr_destroy");
exit(EXIT_FAILURE);
}
}
}
return pid;
}
// Check if a given inotify watch already has a spawn running
static bool is_watch_already_spawned(unsigned int watch_idx)
{
// Walk our process table to see if the given watch currently has a registered running process
for (unsigned int i = 0; i < WATCH_MAX; i++) {
if (PT.spawn_watchids[i] == (int) watch_idx) {
return true;
// NOTE: Assume everything's peachy, and we'll never end up with the same watch_idx assigned to multiple indices in the process table.
// Good news: That assumption seems to hold true so far :).
}
}
return false;
}
// Check if a watch flagged as a spawn blocker (f.g., KOReader or Plato) is already running
// NOTE: This is mainly to prevent spurious spawns that might be unwittingly caused by their file manager (be it through metadata reading, thumbnails creation, or whatever).
// Another workaround is of course to kill KFMon as part of their startup process...
static bool is_blocker_running(void) {
// Walk our process table to identify watches with a currently running process
for (unsigned int i = 0; i < WATCH_MAX; i++) {
if (PT.spawn_watchids[i] != -1) {
// Walk the registered watch list to match that currently running watch to its block_spawns flag
for (unsigned int watch_idx = 0; watch_idx < watch_count; watch_idx++) {
if (PT.spawn_watchids[i] == (int) watch_idx) {
if (watch_config[watch_idx].block_spawns) {
return true;
}
}
}
}
}
// Nothing currently running is a spawn blocker, we're good to go!
return false;
}
// Return the pid of the spawn of a given inotify watch
static pid_t get_spawn_pid_for_watch(unsigned int watch_idx)
{
for (unsigned int i = 0; i < WATCH_MAX; i++) {
if (PT.spawn_watchids[i] == (int) watch_idx) {
return PT.spawn_pids[i];
}
}
return -1;
}
// Read all available inotify events from the file descriptor 'fd'.
static bool handle_events(int fd)
{
/* Some systems cannot read integer variables if they are not
properly aligned. On other systems, incorrect alignment may
decrease performance. Hence, the buffer used for reading from
the inotify file descriptor should have the same alignment as
struct inotify_event. */
char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
const struct inotify_event *event;
ssize_t len;
char *ptr;
bool destroyed_wd = false;
bool was_unmounted = false;
static bool pending_processing = false;
// Loop while events can be read from inotify file descriptor.
for (;;) {
// Read some events.
len = read(fd, buf, sizeof buf);
if (len == -1 && errno != EAGAIN) {
perror("[KFMon] [ERR!] Aborting: read");
exit(EXIT_FAILURE);
}
/* If the nonblocking read() found no events to read, then
it returns -1 with errno set to EAGAIN. In that case,
we exit the loop. */
if (len <= 0) {
break;
}
// Loop over all events in the buffer
for (ptr = buf; ptr < buf + len; ptr += sizeof(struct inotify_event) + event->len) {
// NOTE: This trips -Wcast-align on ARM, but should be safe nonetheless ;).
event = (const struct inotify_event *) ptr;
// NOTE: This *may* be a viable alternative, but don't hold me to that.
//memcpy(&event, &ptr, sizeof(struct inotify_event *));
// Identify which of our target file we've caught an event for...
unsigned int watch_idx = 0;
bool found_watch_idx = false;
for (watch_idx = 0; watch_idx < watch_count; watch_idx++) {
if (watch_config[watch_idx].inotify_wd == event->wd) {
found_watch_idx = true;
break;
}
}
if (!found_watch_idx) {
// NOTE: Err, that should (hopefully) never happen!
LOG(LOG_CRIT, "!! Failed to match the current inotify event to any of our watched file! !!");
}