-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon.c
More file actions
1917 lines (1667 loc) · 52.4 KB
/
daemon.c
File metadata and controls
1917 lines (1667 loc) · 52.4 KB
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
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <stdint.h>
#include <dirent.h>
#include <time.h>
#include <poll.h>
#include <syslog.h>
#include <stdatomic.h>
#include <limits.h>
/* ── Limits ── */
#define QUEUE_SIZE 1024
#define MAX_EVENTS 64
#define MAX_ID 256
#define MAX_DATA_HARD 65536
#define MAX_CMD_OVERHEAD (256 + MAX_ID + MAX_ID)
#define MAX_CMD (MAX_CMD_OVERHEAD + MAX_DATA_HARD)
#define MAX_RECV_BUF (MAX_CMD + 4096)
#define MAX_PATH_LEN 1024
#define MAX_WORKERS 256
#define MAX_KEYS_BUF (64 * 1024)
/* ── Default paths (overridable via environment) ── */
#define DEFAULT_SOCKET_PATH "/var/run/fsdb.sock"
#define DEFAULT_DB_FOLDER "/var/lib/fsdb"
#define DEFAULT_LOG_FOLDER "/var/log"
#define DEFAULT_PIDFILE_PATH "/var/run/fsdb.pid"
#define DEFAULT_AUTH_PATH "/etc/fsdb/token"
static const char *socket_path;
static const char *db_folder;
static const char *log_folder;
static const char *pidfile_path;
static const char *auth_token_path;
/* ── Global state: file descriptors ── */
static int server_fd = -1;
static int epoll_fd = -1;
static int audit_fd = -1;
static int pid_fd = -1;
/* ── Self-pipe for async-signal-safe signal delivery ── */
static int signal_pipe[2] = {-1, -1};
/* ── Worker thread pool and client queue ── */
static int client_queue[QUEUE_SIZE];
static int queue_head = 0, queue_tail = 0;
static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;
/* ── Worker thread handles ── */
static pthread_t worker_tids[MAX_WORKERS];
static int worker_count = 0;
/* ── Statistics counters ── */
static time_t start_time;
static atomic_uint_fast64_t stat_total_requests;
static atomic_uint_fast64_t stat_active_workers;
/* ── HTTP bearer-token authentication ── */
static char auth_token[256];
static int auth_enabled = 0;
/* ── Audit log serialization ── */
static pthread_mutex_t audit_lock = PTHREAD_MUTEX_INITIALIZER;
/* ── Configurable limits ── */
static size_t max_data_size = 1024;
static int rate_limit = 0;
static long default_ttl = 0;
static mode_t socket_mode = 0660;
/* ── Rate limiter state (main thread only) ── */
static int rate_count;
static time_t rate_window;
static _Atomic int running = 1;
static void handle_signal(int sig)
{
int saved = errno;
char c = (sig == SIGHUP) ? 'H' : 'T';
(void)write(signal_pipe[1], &c, 1);
errno = saved;
}
static int constant_time_eq(const void *a, const void *b, size_t len)
{
const volatile unsigned char *x = a;
const volatile unsigned char *y = b;
volatile unsigned char acc = 0;
for (size_t i = 0; i < len; i++)
acc |= x[i] ^ y[i];
return acc == 0;
}
static void log_sys(const char *msg)
{
syslog(LOG_ERR, "%s: %s", msg, strerror(errno));
}
static int url_decode_str(const char *src, char *dst, size_t dst_size);
static void extract_value(const char *body, const char *key, char *dest, size_t maxlen)
{
size_t keylen = strlen(key);
dest[0] = '\0';
while (*body)
{
const char *amp = strchr(body, '&');
const char *field_end = amp ? amp : body + strlen(body);
const char *eq = memchr(body, '=', (size_t)(field_end - body));
if (eq && (size_t)(eq - body) == keylen && memcmp(body, key, keylen) == 0)
{
size_t raw_len = (size_t)(field_end - eq - 1);
char *raw = malloc(raw_len + 1);
if (!raw)
{
dest[0] = '\0';
return;
}
memcpy(raw, eq + 1, raw_len);
raw[raw_len] = '\0';
if (url_decode_str(raw, dest, maxlen) == -1)
dest[0] = '\0';
free(raw);
return;
}
if (!amp)
break;
body = amp + 1;
}
}
static int url_decode_str(const char *src, char *dst, size_t dst_size)
{
size_t di = 0;
for (size_t si = 0; src[si] && di + 1 < dst_size; ++si)
{
if (src[si] == '%')
{
if (isxdigit((unsigned char)src[si + 1]) && isxdigit((unsigned char)src[si + 2]))
{
char hex[3] = {src[si + 1], src[si + 2], 0};
char *endptr;
long val = strtol(hex, &endptr, 16);
if (endptr != hex + 2 || val < 0 || val > 255)
return -1;
if (val == 0)
return -1;
dst[di++] = (char)val;
si += 2;
}
else
return -1;
}
else if (src[si] == '+')
dst[di++] = ' ';
else
dst[di++] = src[si];
}
dst[di] = '\0';
return 0;
}
static int http_to_legacy_command(char *buf, size_t buflen)
{
char action[32], db[256], id[256];
char *data = malloc(MAX_DATA_HARD);
if (!data)
return -1;
int rc = -1;
const char *p = strstr(buf, "\r\n\r\n");
if (!p)
goto out;
p += 4;
extract_value(p, "ACTION", action, sizeof(action));
extract_value(p, "db", db, sizeof(db));
extract_value(p, "id", id, sizeof(id));
extract_value(p, "data", data, (size_t)MAX_DATA_HARD);
if (db[0] && strlen(db) >= sizeof(db) - 1)
goto out;
if (id[0] && strlen(id) >= sizeof(id) - 1)
goto out;
if (strcmp(action, "INSERT") == 0 && db[0] && id[0] && data[0])
snprintf(buf, buflen, "INSERT %s %s %s", db, id, data);
else if (strcmp(action, "GET") == 0 && db[0] && id[0])
snprintf(buf, buflen, "GET %s %s", db, id);
else if (strcmp(action, "TOUCH") == 0 && db[0] && id[0])
snprintf(buf, buflen, "TOUCH %s %s", db, id);
else if (strcmp(action, "UPDATE") == 0 && db[0] && id[0] && data[0])
snprintf(buf, buflen, "UPDATE %s %s %s", db, id, data);
else if (strcmp(action, "EXISTS") == 0 && db[0] && id[0])
snprintf(buf, buflen, "EXISTS %s %s", db, id);
else if (strcmp(action, "CREATE") == 0 && db[0])
snprintf(buf, buflen, "CREATE %s", db);
else if (strcmp(action, "DELETE") == 0 && db[0] && id[0])
snprintf(buf, buflen, "DELETE %s %s", db, id);
else if (strcmp(action, "KEYS") == 0 && db[0])
snprintf(buf, buflen, "KEYS %s %s", db, id[0] ? id : "1000");
else if (strcmp(action, "COUNT") == 0 && db[0])
snprintf(buf, buflen, "COUNT %s", db);
else if (strcmp(action, "STATS") == 0)
snprintf(buf, buflen, "STATS");
else
goto out;
rc = 0;
out:
free(data);
return rc;
}
static int check_http_auth(const char *buf)
{
if (!auth_enabled)
return 1;
/* Only search headers, not the POST body, to prevent auth smuggling */
const char *hdr_end = strstr(buf, "\r\n\r\n");
const char *auth = strcasestr(buf, "\r\nAuthorization:");
if (!auth || (hdr_end && auth >= hdr_end))
return 0;
auth += 16;
while (*auth == ' ')
auth++;
if (strncmp(auth, "Bearer ", 7) != 0)
return 0;
auth += 7;
size_t tlen = strlen(auth_token);
const char *end = auth;
while (*end && *end != '\r' && *end != '\n')
end++;
size_t vlen = (size_t)(end - auth);
size_t cmplen = tlen < vlen ? tlen : vlen;
int cmp_ok = constant_time_eq(auth, auth_token, cmplen);
int len_ok = (vlen == tlen);
return len_ok & cmp_ok;
}
static void cleanup_socket(void)
{
if (socket_path)
unlink(socket_path);
if (server_fd >= 0)
close(server_fd);
if (epoll_fd >= 0)
close(epoll_fd);
if (audit_fd >= 0)
close(audit_fd);
if (pid_fd >= 0)
{
close(pid_fd);
if (pidfile_path)
unlink(pidfile_path);
}
if (signal_pipe[0] >= 0)
close(signal_pipe[0]);
if (signal_pipe[1] >= 0)
close(signal_pipe[1]);
}
static void reopen_audit_log(void)
{
pthread_mutex_lock(&audit_lock);
char path[512];
snprintf(path, sizeof(path), "%s/fsdb.log", log_folder);
int new_fd = open(path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600);
if (new_fd >= 0)
{
int old = audit_fd;
audit_fd = new_fd;
close(old);
syslog(LOG_INFO, "audit log reopened (SIGHUP)");
}
else
log_sys("reopen audit log");
pthread_mutex_unlock(&audit_lock);
}
static ssize_t send_all(int fd, const void *buf, size_t len, int flags)
{
const char *p = buf;
size_t remaining = len;
while (remaining > 0)
{
ssize_t n = send(fd, p, remaining, flags);
if (n < 0)
{
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
struct pollfd pfd = {.fd = fd, .events = POLLOUT};
if (poll(&pfd, 1, 1000) <= 0)
return -1;
continue;
}
return -1;
}
p += n;
remaining -= (size_t)n;
}
return (ssize_t)len;
}
static const char *http_status_line(int code)
{
switch (code)
{
case 200: return "200 OK";
case 400: return "400 Bad Request";
case 404: return "404 Not Found";
case 409: return "409 Conflict";
case 413: return "413 Payload Too Large";
case 429: return "429 Too Many Requests";
case 500: return "500 Internal Server Error";
case 503: return "503 Service Unavailable";
default: return "500 Internal Server Error";
}
}
/* Send response with explicit HTTP status code when post_request is true.
For native protocol (post_request == 0), status_code is ignored. */
static ssize_t sosend_status(int fd, const void *buf, size_t len,
int post_request, int status_code)
{
ssize_t sent;
if (post_request)
{
size_t resp_size = len + 512;
char *response = malloc(resp_size);
if (!response)
return -1;
int n = snprintf(response, resp_size,
"HTTP/1.1 %s\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %zu\r\n"
"Connection: close\r\n\r\n",
http_status_line(status_code), len);
if (n > 0 && (size_t)n < resp_size - len)
{
memcpy(response + n, buf, len);
sent = send_all(fd, response, (size_t)n + len, MSG_NOSIGNAL);
}
else
sent = -1;
free(response);
}
else
sent = send_all(fd, buf, len, MSG_NOSIGNAL);
if (sent < 0)
syslog(LOG_WARNING, "send failed: %s", strerror(errno));
return sent;
}
/* Convenience: send a 200 OK response */
static ssize_t sosend(int fd, const void *buf, size_t len, int post_request)
{
return sosend_status(fd, buf, len, post_request, 200);
}
static ssize_t recv_full(int fd, char *buf, size_t bufsize, int timeout_ms)
{
size_t total = 0;
int proto = -1;
int frame_complete = 0;
while (total < bufsize - 1)
{
int wait_ms;
if (total == 0)
wait_ms = timeout_ms;
else if (proto == 1)
wait_ms = 2000; /* HTTP: allow slow bodies up to 2s between chunks */
else
wait_ms = 1000; /* native: 1s for fragmented line to complete */
struct pollfd pfd = {.fd = fd, .events = POLLIN};
int pret = poll(&pfd, 1, wait_ms);
if (pret < 0)
{
if (errno == EINTR)
continue;
break;
}
if (pret == 0)
break; /* timeout — frame_complete stays 0 */
ssize_t n = recv(fd, buf + total, bufsize - 1 - total, 0);
if (n <= 0)
break;
total += (size_t)n;
buf[total] = '\0';
if (proto == -1)
{
if (total >= 5 && strncmp(buf, "POST ", 5) == 0)
proto = 1;
else if (total >= 14 && strncmp(buf, "GET /", 5) == 0 &&
strstr(buf, " HTTP/") != NULL)
proto = 1;
else if (total >= 4 && strncmp(buf, "GET ", 4) == 0)
proto = 0;
else
proto = 0;
}
if (proto == 1)
{
if (strncmp(buf, "POST ", 5) == 0)
{
char *hdr_end = strstr(buf, "\r\n\r\n");
if (hdr_end)
{
size_t hdr_len = (size_t)(hdr_end - buf) + 4;
const char *cl = strcasestr(buf, "\r\nContent-Length:");
if (cl && cl < hdr_end)
{
char *endp;
long clen = strtol(cl + 17, &endp, 10);
if (clen < 0 || clen > (long)(bufsize - hdr_len))
{
frame_complete = 1; /* reject: malformed/too large */
break;
}
if (endp == cl + 17)
{
frame_complete = 1;
break;
}
if (hdr_len + (size_t)clen <= total)
{
frame_complete = 1;
break; /* full body received */
}
}
else
{
frame_complete = 1; /* no Content-Length, treat headers-only as complete */
break;
}
}
}
else /* HTTP GET */
{
if (strstr(buf, "\r\n\r\n"))
{
frame_complete = 1;
break;
}
}
}
else /* native protocol */
{
if (memchr(buf, '\n', total))
{
frame_complete = 1;
break;
}
}
}
/* Reject incomplete frames: if we received data but never saw a complete
message boundary (newline for native, headers+body for HTTP), treat
the request as malformed rather than processing truncated input. */
if (total > 0 && !frame_complete)
return -1;
/* Strip trailing newline/CR for native protocol */
if (total > 0 && proto != 1 && buf[total - 1] == '\n')
buf[--total] = '\0';
if (total > 0 && proto != 1 && buf[total - 1] == '\r')
buf[--total] = '\0';
return (ssize_t)total;
}
static int build_data_path(char *path, size_t size, const char *db, const char *id)
{
int n;
if (id[1])
n = snprintf(path, size, "%s/%s/%c/%c/%s", db_folder, db, id[0], id[1], id);
else
n = snprintf(path, size, "%s/%s/_/%s", db_folder, db, id);
if (n < 0 || (size_t)n >= size)
return -1;
return 0;
}
static void ensure_parent_dir(const char *db, const char *id)
{
char dir[MAX_PATH_LEN];
snprintf(dir, sizeof(dir), "%s/%s", db_folder, db);
mkdir(dir, 0700);
if (id[1])
{
snprintf(dir, sizeof(dir), "%s/%s/%c", db_folder, db, id[0]);
mkdir(dir, 0700);
snprintf(dir, sizeof(dir), "%s/%s/%c/%c", db_folder, db, id[0], id[1]);
mkdir(dir, 0700);
}
else
{
snprintf(dir, sizeof(dir), "%s/%s/_", db_folder, db);
mkdir(dir, 0700);
}
}
/* fsync the parent directory to ensure metadata changes (link/rename/unlink)
are durable. Best-effort: returns -1 on failure but callers may ignore. */
static int fsync_parent_dir(const char *path)
{
char dir[MAX_PATH_LEN];
size_t len = strlen(path);
if (len >= sizeof(dir))
return -1;
memcpy(dir, path, len + 1);
/* Walk backwards to find last '/' */
char *slash = strrchr(dir, '/');
if (!slash)
return -1;
*slash = '\0';
int dfd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (dfd < 0)
return -1;
int rc = fsync(dfd);
close(dfd);
return rc;
}
static int is_expired(const char *path)
{
if (default_ttl <= 0)
return 0;
struct stat st;
if (stat(path, &st) != 0)
return 0;
return (time(NULL) - st.st_mtime) >= default_ttl;
}
static int write_file(const char *db, const char *id, const char *data, int update)
{
char path[MAX_PATH_LEN];
if (build_data_path(path, sizeof(path), db, id) != 0)
return -1;
ensure_parent_dir(db, id);
char tmp_path[MAX_PATH_LEN];
snprintf(tmp_path, sizeof(tmp_path), "%s.XXXXXX", path);
int fd = mkstemp(tmp_path);
if (fd < 0)
return -1;
fcntl(fd, F_SETFD, FD_CLOEXEC);
size_t len = strlen(data);
size_t total_written = 0;
while (total_written < len)
{
ssize_t w = write(fd, data + total_written, len - total_written);
if (w < 0)
{
if (errno == EINTR)
continue;
close(fd);
unlink(tmp_path);
return -1;
}
total_written += (size_t)w;
}
if (fdatasync(fd) != 0)
{
close(fd);
unlink(tmp_path);
return -1;
}
if (close(fd) != 0)
{
/* close failure after fdatasync means data may not be on disk */
unlink(tmp_path);
return -1;
}
/* TTL: treat expired keys as non-existent for UPDATE (returns error)
and as free slots for INSERT (allows reuse without explicit DELETE). */
if (is_expired(path))
unlink(path);
if (update)
{
/* Note: TOCTOU between lstat() and rename() — a concurrent DELETE
could remove the key after this check. The filesystem offers no
atomic "rename-only-if-target-exists". Acceptable for a file-backed
KV store; concurrent UPDATE+DELETE on the same key is inherently racy. */
struct stat st;
if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode))
{
int saved = errno;
unlink(tmp_path);
errno = saved ? saved : ENOENT;
return -1;
}
if (rename(tmp_path, path) != 0)
{
unlink(tmp_path);
return -1;
}
}
else
{
if (link(tmp_path, path) != 0)
{
int saved = errno;
unlink(tmp_path);
errno = saved;
return -1;
}
unlink(tmp_path);
}
fsync_parent_dir(path);
return 0;
}
static int read_file(const char *db, const char *id, char *out, size_t out_size)
{
char path[MAX_PATH_LEN];
if (build_data_path(path, sizeof(path), db, id) != 0)
return -1;
if (is_expired(path))
{
unlink(path);
errno = ENOENT;
return -1;
}
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
/* Verify file size fits in buffer before reading */
struct stat st;
if (fstat(fd, &st) != 0)
{
close(fd);
return -1;
}
if (!S_ISREG(st.st_mode))
{
close(fd);
errno = EINVAL;
return -1;
}
if (st.st_size >= (off_t)out_size)
{
close(fd);
errno = EOVERFLOW;
return -1;
}
/* Read loop: keep reading until EOF or buffer full */
size_t total = 0;
while (total < out_size - 1)
{
ssize_t n = read(fd, out + total, out_size - 1 - total);
if (n < 0)
{
if (errno == EINTR)
continue;
close(fd);
return -1;
}
if (n == 0)
break; /* EOF */
total += (size_t)n;
}
close(fd);
/* Verify we read the expected amount (detect concurrent truncation) */
if ((off_t)total != st.st_size)
{
errno = EIO;
return -1;
}
out[total] = '\0';
return 0;
}
static int delete_file(const char *db, const char *id)
{
char path[MAX_PATH_LEN];
if (build_data_path(path, sizeof(path), db, id) != 0)
return -1;
if (is_expired(path))
{
unlink(path);
errno = ENOENT;
return -1;
}
if (unlink(path) != 0)
return -1;
fsync_parent_dir(path);
return 0;
}
static int check_file(const char *db, const char *id)
{
char path[MAX_PATH_LEN];
if (build_data_path(path, sizeof(path), db, id) != 0)
return -1;
if (is_expired(path))
{
unlink(path);
return -1;
}
return access(path, F_OK);
}
static int touch_file(const char *db, const char *id)
{
char path[MAX_PATH_LEN];
if (build_data_path(path, sizeof(path), db, id) != 0)
return -1;
if (is_expired(path))
unlink(path);
ensure_parent_dir(db, id);
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
if (fd < 0)
return -1;
if (close(fd) != 0)
{
unlink(path);
return -1;
}
fsync_parent_dir(path);
return 0;
}
/* Reserve bytes at end of KEYS buffer for "+TRUNCATED\n" indicator */
#define KEYS_TRUNCATED_RESERVE 16
static void handle_keys(int fd, const char *db, int limit, int post_request)
{
char *out = malloc(MAX_KEYS_BUF);
if (!out)
{
sosend_status(fd, "ERR out of memory", 17, post_request, 500);
return;
}
size_t pos = 0;
int count = 0;
int truncated = 0;
char base[MAX_PATH_LEN];
snprintf(base, sizeof(base), "%s/%s", db_folder, db);
DIR *d1 = opendir(base);
if (!d1)
{
sosend_status(fd, "ERR database not found", 22, post_request, 404);
free(out);
return;
}
struct dirent *e1;
while ((e1 = readdir(d1)) != NULL && count < limit)
{
if (e1->d_name[0] == '.')
continue;
char l1[MAX_PATH_LEN];
snprintf(l1, sizeof(l1), "%s/%s", base, e1->d_name);
if (e1->d_name[0] == '_' && e1->d_name[1] == '\0')
{
DIR *ds = opendir(l1);
if (!ds)
continue;
struct dirent *es;
while ((es = readdir(ds)) != NULL && count < limit)
{
if (es->d_name[0] == '.')
continue;
if (strchr(es->d_name, '.'))
continue; /* temp-file artifact (e.g. a.XXXXXX from crash) */
char fp[MAX_PATH_LEN];
snprintf(fp, sizeof(fp), "%s/%s", l1, es->d_name);
struct stat est;
if (lstat(fp, &est) != 0 || !S_ISREG(est.st_mode))
continue; /* skip stray subdirs / non-files */
if (default_ttl > 0 && is_expired(fp))
{
unlink(fp);
continue;
}
int n = snprintf(out + pos, MAX_KEYS_BUF - pos, "%s\n", es->d_name);
if (n < 0 || pos + (size_t)n >= MAX_KEYS_BUF - KEYS_TRUNCATED_RESERVE)
{
truncated = 1;
closedir(ds);
goto keys_done;
}
pos += (size_t)n;
count++;
}
closedir(ds);
}
else
{
DIR *d2 = opendir(l1);
if (!d2)
continue;
struct dirent *e2;
while ((e2 = readdir(d2)) != NULL && count < limit)
{
if (e2->d_name[0] == '.')
continue;
char l2[MAX_PATH_LEN];
snprintf(l2, sizeof(l2), "%s/%s", l1, e2->d_name);
DIR *d3 = opendir(l2);
if (!d3)
continue;
struct dirent *e3;
while ((e3 = readdir(d3)) != NULL && count < limit)
{
if (e3->d_name[0] == '.')
continue;
if (strchr(e3->d_name, '.'))
continue;
char fp[MAX_PATH_LEN];
snprintf(fp, sizeof(fp), "%s/%s", l2, e3->d_name);
struct stat est;
if (lstat(fp, &est) != 0 || !S_ISREG(est.st_mode))
continue; /* skip stray subdirs / non-files */
if (default_ttl > 0 && is_expired(fp))
{
unlink(fp);
continue;
}
int n = snprintf(out + pos, MAX_KEYS_BUF - pos, "%s\n", e3->d_name);
if (n < 0 || pos + (size_t)n >= MAX_KEYS_BUF - KEYS_TRUNCATED_RESERVE)
{
truncated = 1;
closedir(d3);
closedir(d2);
goto keys_done;
}
pos += (size_t)n;
count++;
}
closedir(d3);
}
closedir(d2);
}
}
keys_done:
closedir(d1);
if (pos == 0)
{
sosend(fd, "EMPTY", 5, post_request);
}
else
{
if (truncated)
{
/* Append truncation indicator so clients know the list is incomplete */
int tn = snprintf(out + pos, MAX_KEYS_BUF - pos, "+TRUNCATED\n");
if (tn > 0 && pos + (size_t)tn < MAX_KEYS_BUF)
pos += (size_t)tn;
}
if (pos > 0 && out[pos - 1] == '\n')
pos--;
sosend(fd, out, pos, post_request);
}
free(out);
}
static void handle_count(int fd, const char *db, int post_request)
{
char base[MAX_PATH_LEN];
snprintf(base, sizeof(base), "%s/%s", db_folder, db);
DIR *d1 = opendir(base);
if (!d1)
{
sosend_status(fd, "ERR database not found", 22, post_request, 404);
return;
}
long count = 0;
struct dirent *e1;
while ((e1 = readdir(d1)) != NULL)
{
if (e1->d_name[0] == '.')
continue;
char l1[MAX_PATH_LEN];
snprintf(l1, sizeof(l1), "%s/%s", base, e1->d_name);
if (e1->d_name[0] == '_' && e1->d_name[1] == '\0')
{
DIR *ds = opendir(l1);
if (!ds)
continue;
struct dirent *es;
while ((es = readdir(ds)) != NULL)
{
if (es->d_name[0] == '.')
continue;
if (strchr(es->d_name, '.'))
continue; /* temp-file artifact */
char fp[MAX_PATH_LEN];
snprintf(fp, sizeof(fp), "%s/%s", l1, es->d_name);
struct stat est;
if (lstat(fp, &est) != 0 || !S_ISREG(est.st_mode))
continue; /* skip stray subdirs / non-files */
if (default_ttl > 0 && is_expired(fp))
{
unlink(fp);
continue;
}
count++;
}
closedir(ds);
}
else
{
DIR *d2 = opendir(l1);
if (!d2)
continue;
struct dirent *e2;
while ((e2 = readdir(d2)) != NULL)
{
if (e2->d_name[0] == '.')
continue;
char l2[MAX_PATH_LEN];
snprintf(l2, sizeof(l2), "%s/%s", l1, e2->d_name);
DIR *d3 = opendir(l2);