-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebdav.cpp
More file actions
2530 lines (2443 loc) · 153 KB
/
webdav.cpp
File metadata and controls
2530 lines (2443 loc) · 153 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
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "compat.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifdef _WIN32
#include <stdint.h>
#include <direct.h>
#include <getopt.h>
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#define mkdir(path, mode) _mkdir(path)
#define lstat stat
#else
#include <unistd.h>
#endif
#include <sys/types.h>
#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include <sys/stat.h>
#include <dirent.h>
#include <limits.h>
#include <time.h>
#include <ctype.h>
#include <stdarg.h>
#ifndef _WIN32
#include <strings.h>
#include <pwd.h>
#include <grp.h>
#endif
#include <assert.h>
#ifndef _WIN32
#include <sys/wait.h>
#include <sys/resource.h>
#include <poll.h> // Para poll()
#endif
/* ==================== CONFIGURAÇÕES ==================== */
#define BACKLOG 128
#define RECV_BUF 8192
#define SEND_BUF 8192
#define SMALL_BUF 512
#ifdef _WIN32
#undef MAX_PATH
#endif
#define MAX_PATH 4096
#define MAX_ENCODED_PATH (MAX_PATH * 3)
#define MAX_BODY 1099511627776LL
#define MAX_MULTIPART_BODY (100LL * 1024 * 1024) // 100 MB hard limit for multipart POST
#define MAX_CONNECTIONS 100
#define DEFAULT_TIMEOUT 30
#define LOCK_TIMEOUT_DEFAULT 600
#define RATE_LIMIT_WINDOW 60
#define RATE_LIMIT_MAX_REQ 1000
/* ==================== TIPOS E ESTRUTURAS ==================== */
typedef enum {
HTTP_200_OK = 200, HTTP_201_CREATED = 201, HTTP_204_NO_CONTENT = 204,
HTTP_206_PARTIAL_CONTENT = 206, HTTP_207_MULTI_STATUS = 207,
HTTP_303_SEE_OTHER = 303, HTTP_304_NOT_MODIFIED = 304,
HTTP_400_BAD_REQUEST = 400, HTTP_401_UNAUTHORIZED = 401,
HTTP_403_FORBIDDEN = 403, HTTP_404_NOT_FOUND = 404,
HTTP_405_METHOD_NOT_ALLOWED = 405, HTTP_409_CONFLICT = 409,
HTTP_412_PRECONDITION_FAILED = 412, HTTP_413_PAYLOAD_TOO_LARGE = 413,
HTTP_416_RANGE_NOT_SATISFIABLE = 416, HTTP_423_LOCKED = 423,
HTTP_429_TOO_MANY_REQUESTS = 429, HTTP_500_INTERNAL_SERVER_ERROR = 500,
HTTP_501_NOT_IMPLEMENTED = 501, HTTP_503_SERVICE_UNAVAILABLE = 503,
HTTP_507_INSUFFICIENT_STORAGE = 507
} http_status_t;
typedef enum { LOCK_EXCLUSIVE, LOCK_SHARED } lock_type_t;
typedef enum { DEPTH_ZERO = 0, DEPTH_ONE = 1, DEPTH_INFINITY = -1 } depth_t;
typedef struct {
char token[64]; lock_type_t type; char owner[256]; char path[MAX_PATH];
time_t created; time_t expires; int depth;
} lock_entry_t;
typedef struct {
char keys[128][SMALL_BUF]; char vals[128][SMALL_BUF]; int count;
} headers_t;
typedef struct {
char *data; size_t length; size_t capacity;
} buffer_t;
typedef struct {
char ip[INET_ADDRSTRLEN + 1]; time_t window_start; int request_count;
pthread_mutex_t mutex;
} rate_limit_entry_t;
/* ==================== VARIÁVEIS GLOBAIS ==================== */
static char *ROOT_DIR = NULL;
static char *AUTH_USER = NULL;
static char *AUTH_PASS = NULL;
static int VERBOSE = 0;
static int PORT = 8080;
static int TIMEOUT = DEFAULT_TIMEOUT;
static int MAX_REQ = RATE_LIMIT_MAX_REQ;
static volatile sig_atomic_t RUNNING = 1;
#ifdef _WIN32
static pthread_mutex_t lock_mutex;
#else
static pthread_mutex_t lock_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static lock_entry_t locks[100]; static int lock_count = 0;
#ifdef _WIN32
static pthread_mutex_t rate_mutex;
#else
static pthread_mutex_t rate_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static rate_limit_entry_t rate_table[1000]; static int rate_count = 0;
#ifdef __APPLE__
typedef struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
} conn_sem_t;
static int conn_sem_init(conn_sem_t *s, unsigned int value) {
if (pthread_mutex_init(&s->mutex, NULL) != 0) return -1;
if (pthread_cond_init(&s->cond, NULL) != 0) {
pthread_mutex_destroy(&s->mutex);
return -1;
}
s->count = (int)value;
return 0;
}
static int conn_sem_wait(conn_sem_t *s) {
pthread_mutex_lock(&s->mutex);
while (s->count == 0) pthread_cond_wait(&s->cond, &s->mutex);
s->count--;
pthread_mutex_unlock(&s->mutex);
return 0;
}
static int conn_sem_trywait(conn_sem_t *s) {
int rc = -1;
pthread_mutex_lock(&s->mutex);
if (s->count > 0) {
s->count--;
rc = 0;
} else {
errno = EAGAIN;
}
pthread_mutex_unlock(&s->mutex);
return rc;
}
static int conn_sem_post(conn_sem_t *s) {
pthread_mutex_lock(&s->mutex);
s->count++;
pthread_cond_signal(&s->cond);
pthread_mutex_unlock(&s->mutex);
return 0;
}
static int conn_sem_destroy(conn_sem_t *s) {
pthread_cond_destroy(&s->cond);
pthread_mutex_destroy(&s->mutex);
return 0;
}
#else
typedef sem_t conn_sem_t;
static int conn_sem_init(conn_sem_t *s, unsigned int value) { return sem_init(s, 0, value); }
static int conn_sem_wait(conn_sem_t *s) { return sem_wait(s); }
static int conn_sem_trywait(conn_sem_t *s) { return sem_trywait(s); }
static int conn_sem_post(conn_sem_t *s) { return sem_post(s); }
static int conn_sem_destroy(conn_sem_t *s) { return sem_destroy(s); }
#endif
static conn_sem_t connection_sem;
static int self_pipe[2] = {-1, -1}; // Self-pipe trick para shutdown gracioso
/* ==================== DESIGN BY CONTRACT ==================== */
#define REQUIRE(condition, msg) do { if (!(condition)) { log_error("PRE-CONDITION FAILED: %s at %s:%d", msg, __FILE__, __LINE__); return; } } while(0)
#define REQUIRE_RET(condition, msg, ret) do { if (!(condition)) { log_error("PRE-CONDITION FAILED: %s at %s:%d", msg, __FILE__, __LINE__); return ret; } } while(0)
#define ENSURE(condition, msg) do { if (!(condition)) { log_error("POST-CONDITION FAILED: %s at %s:%d", msg, __FILE__, __LINE__); } } while(0)
/* ==================== LOGGING ==================== */
static void log_msg(const char *level, const char *fmt, ...) {
if (!VERBOSE && strcmp(level, "ERROR") != 0) return;
time_t now = time(NULL); struct tm *tm_info = localtime(&now); char timebuf[32];
strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", tm_info);
fprintf(stderr, "[%s] [%s] ", timebuf, level);
va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
fprintf(stderr, "\n"); fflush(stderr);
}
#define log_debug(fmt, ...) log_msg("DEBUG", fmt, ##__VA_ARGS__)
#define log_info(fmt, ...) log_msg("INFO", fmt, ##__VA_ARGS__)
#define log_warn(fmt, ...) log_msg("WARN", fmt, ##__VA_ARGS__)
#define log_error(fmt, ...) log_msg("ERROR", fmt, ##__VA_ARGS__)
/* ==================== SELF-PIPE TRICK ==================== */
static void setup_self_pipe(void) {
#if defined(_WIN32) || defined(__COSMOPOLITAN__)
self_pipe[0] = -1; self_pipe[1] = -1;
return;
#else
if (pipe(self_pipe) != 0) {
perror("pipe (self-pipe)");
exit(1);
}
// Tornar ambos os fds não-bloqueantes
fcntl(self_pipe[0], F_SETFL, O_NONBLOCK);
fcntl(self_pipe[1], F_SETFL, O_NONBLOCK);
#endif
}
static void trigger_shutdown(void) {
#if !defined(_WIN32) && !defined(__COSMOPOLITAN__)
if (self_pipe[1] != -1) {
char byte = 'Q';
if (write(self_pipe[1], &byte, 1) < 0) {} // Acorda o poll()
}
#endif
}
static void sigint_handler(int sig) {
(void)sig;
RUNNING = 0;
trigger_shutdown(); // Acorda o poll() bloqueado
}
static void sigterm_handler(int sig) {
(void)sig;
RUNNING = 0;
trigger_shutdown();
}
#ifndef _WIN32
static void sigpipe_handler(int sig) { (void)sig; }
#endif
static void close_socket_fd(int fd) {
#ifdef _WIN32
closesocket((SOCKET)fd);
#else
close(fd);
#endif
}
#ifdef _WIN32
static int windows_socket_init(void) {
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) {
log_error("WSAStartup failed");
return -1;
}
return 0;
}
#endif
/* ==================== UTILITÁRIOS ==================== */
static int parse_http_date_gmt(const char *s, time_t *out) {
REQUIRE_RET(s != NULL, "date string cannot be NULL", 0);
REQUIRE_RET(out != NULL, "out cannot be NULL", 0);
#ifdef _WIN32
int day = 0, year = 0, hh = 0, mm = 0, ss = 0;
char mon[4] = {0};
if (sscanf(s, "%*3s, %d %3s %d %d:%d:%d GMT", &day, mon, &year, &hh, &mm, &ss) != 6) return 0;
const char *months = "JanFebMarAprMayJunJulAugSepOctNovDec";
const char *m = strstr(months, mon);
if (!m) return 0;
int month = (int)((m - months) / 3);
struct tm tm_if;
memset(&tm_if, 0, sizeof(tm_if));
tm_if.tm_mday = day;
tm_if.tm_mon = month;
tm_if.tm_year = year - 1900;
tm_if.tm_hour = hh;
tm_if.tm_min = mm;
tm_if.tm_sec = ss;
*out = _mkgmtime(&tm_if);
return (*out != (time_t)-1);
#else
struct tm tm_if;
memset(&tm_if, 0, sizeof(tm_if));
if (!strptime(s, "%a, %d %b %Y %H:%M:%S GMT", &tm_if)) return 0;
*out = timegm(&tm_if);
return 1;
#endif
}
static void trim_inplace(char *s) {
if (!s || !*s) return;
char *start = s; while (*start && isspace((unsigned char)*start)) start++;
if (start != s) memmove(s, start, strlen(start) + 1);
size_t len = strlen(s); while (len > 0 && isspace((unsigned char)s[len - 1])) s[--len] = '\0';
}
static void url_decode(char *dst, const char *src) {
REQUIRE(dst != NULL, "dst cannot be NULL"); REQUIRE(src != NULL, "src cannot be NULL");
char *d = dst; const char *s = src; char a, b;
while (*s) {
if ((*s == '%') && ((a = s[1]) && (b = s[2])) && (isxdigit((unsigned char)a) && isxdigit((unsigned char)b))) {
char hex[3] = {a, b, '\0'}; *d++ = (char)strtol(hex, NULL, 16); s += 3;
} else if (*s == '+') { *d++ = ' '; s++; }
else { *d++ = *s++; }
}
*d = '\0'; ENSURE(dst != NULL, "url_decode produced valid output");
}
static void url_encode(char *dst, size_t dstlen, const char *src) {
REQUIRE(dst != NULL, "dst cannot be NULL"); REQUIRE(src != NULL, "src cannot be NULL"); REQUIRE(dstlen > 0, "dstlen must be > 0");
size_t i = 0;
for (; *src && i < dstlen - 1; src++) {
if (isalnum((unsigned char)*src) || strchr("-_.~/", (unsigned char)*src)) dst[i++] = *src;
else {
if (i + 3 >= dstlen) break;
snprintf(dst + i, dstlen - i, "%%%02X", (unsigned char)*src); i += 3;
}
}
dst[i] = '\0'; ENSURE(i < dstlen, "url_encode did not overflow");
}
static void xml_escape(char *dst, size_t dstlen, const char *src) {
REQUIRE(dst != NULL, "dst cannot be NULL"); REQUIRE(src != NULL, "src cannot be NULL"); REQUIRE(dstlen > 0, "dstlen must be > 0");
size_t i = 0;
for (; *src && i < dstlen - 1; src++) {
switch (*src) {
case '&': if (i + 5 >= dstlen) break; memcpy(dst + i, "&", 5); i += 5; break;
case '<': if (i + 4 >= dstlen) break; memcpy(dst + i, "<", 4); i += 4; break;
case '>': if (i + 4 >= dstlen) break; memcpy(dst + i, ">", 4); i += 4; break;
case '"': if (i + 6 >= dstlen) break; memcpy(dst + i, """, 6); i += 6; break;
case '\'': if (i + 6 >= dstlen) break; memcpy(dst + i, "'", 6); i += 6; break;
default: dst[i++] = *src; break;
}
}
dst[i] = '\0'; ENSURE(i < dstlen, "xml_escape did not overflow");
}
static char* http_time(time_t t) {
static __thread char buf[64]; struct tm tm_info; gmtime_r(&t, &tm_info);
strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_info); return buf;
}
static char* iso8601_time(time_t t) {
static __thread char buf[64]; struct tm tm_info; gmtime_r(&t, &tm_info);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm_info); return buf;
}
/* ==================== BASE64 ==================== */
static int base64_decode(const char *src, char *dst, size_t dstlen) {
REQUIRE_RET(src != NULL, "src cannot be NULL", -1); REQUIRE_RET(dst != NULL, "dst cannot be NULL", -1);
static const char *tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int map[256]; for (int i = 0; i < 256; i++) map[i] = -1;
for (int i = 0; i < 64; i++) map[(unsigned char)tbl[i]] = i;
map['='] = 0;
unsigned char quartet[4]; int qidx = 0; size_t outidx = 0;
for (const unsigned char *p = (const unsigned char *)src; *p && outidx < dstlen - 1; ++p) {
unsigned char c = *p;
if (c == ' ' || c == '\r' || c == '\n' || c == '\t') continue;
if (map[c] == -1) return -1;
quartet[qidx++] = c;
if (qidx == 4) {
int vals[4]; for (int i = 0; i < 4; i++) vals[i] = (quartet[i] == '=') ? -1 : map[quartet[i]];
unsigned char b0 = (unsigned char)((vals[0] << 2) | ((vals[1] & 0x30) >> 4));
unsigned char b1 = 0, b2 = 0;
if (vals[1] != -1) b1 = (unsigned char)(((vals[1] & 0x0F) << 4) | ((vals[2] & 0x3C) >> 2));
if (vals[2] != -1) b2 = (unsigned char)(((vals[2] & 0x03) << 6) | (vals[3] & 0x3F));
dst[outidx++] = b0;
if (quartet[2] != '=' && outidx < dstlen - 1) dst[outidx++] = b1;
if (quartet[3] != '=' && outidx < dstlen - 1) dst[outidx++] = b2;
qidx = 0;
}
}
if (qidx != 0) {
if (qidx == 1) return -1;
unsigned char pad[4] = {'=', '=', '=', '='};
for (int i = 0; i < qidx; i++) pad[i] = quartet[i];
int vals[4]; for (int i = 0; i < 4; i++) vals[i] = (pad[i] == '=') ? -1 : map[pad[i]];
unsigned char b0 = (unsigned char)((vals[0] << 2) | ((vals[1] & 0x30) >> 4));
dst[outidx++] = b0;
}
dst[outidx] = '\0'; return 0;
}
/* ==================== AUTENTICAÇÃO ==================== */
static int check_auth(const char *auth_header) {
if (!AUTH_USER && !AUTH_PASS) return 1; // auth desabilitada
if (!AUTH_USER || !AUTH_PASS) { log_warn("Authentication misconfigured: user/password missing"); return 0; }
if (!auth_header) { log_debug("No Authorization header"); return 0; }
log_debug("Received Authorization: %.50s", auth_header);
if (strncasecmp(auth_header, "Basic ", 6) != 0) { log_debug("Not Basic auth"); return 0; }
const char *encoded = auth_header + 6; char decoded[1024];
if (base64_decode(encoded, decoded, sizeof(decoded)) != 0) { log_debug("Base64 decode failed"); return 0; }
char *colon = strchr(decoded, ':'); if (!colon) { log_debug("No colon in decoded"); return 0; }
*colon = '\0'; char *user = decoded; char *pass = colon + 1;
log_debug("Auth attempt - User: %s", user);
if (strcmp(user, AUTH_USER) == 0 && strcmp(pass, AUTH_PASS) == 0) { log_debug("Auth success"); return 1; }
else { log_debug("Auth fail"); return 0; }
}
/* ==================== PATH VALIDATION ==================== */
static int validate_path(const char *path) {
REQUIRE_RET(path != NULL, "path cannot be NULL", -1);
if (strstr(path, "..") != NULL) { log_warn("Path validation failed: contains '..'"); return -1; }
if (strstr(path, "//") != NULL) { log_warn("Path validation failed: contains '//'"); return -1; }
if (strstr(path, "/./") != NULL) { log_warn("Path validation failed: contains '/./'"); return -1; }
return 0;
}
static int build_fs_path(const char *root, const char *reqpath, char *out, size_t outlen) {
REQUIRE_RET(root != NULL, "root cannot be NULL", -1);
REQUIRE_RET(reqpath != NULL, "reqpath cannot be NULL", -1);
REQUIRE_RET(out != NULL, "out cannot be NULL", -1);
REQUIRE_RET(outlen > 0, "outlen must be > 0", -1);
char decoded[MAX_PATH]; url_decode(decoded, reqpath); char *q = strchr(decoded, '?');
if (q) *q = '\0';
char tmp[MAX_PATH + 1];
if (decoded[0] != '/') {
if (strlen(decoded) >= sizeof(tmp) - 2) { log_warn("Path too long: %s", decoded); return -1; }
snprintf(tmp, sizeof(tmp), "/%s", decoded);
} else {
if (strlen(decoded) >= sizeof(tmp)) { log_warn("Path too long: %s", decoded); return -1; }
strncpy(tmp, decoded, sizeof(tmp) - 1); tmp[sizeof(tmp) - 1] = '\0';
}
if (validate_path(tmp) != 0) { log_warn("Path forbidden: %s", tmp); return -1; }
char full[MAX_PATH + 1];
if (snprintf(full, sizeof(full), "%s%s", root, tmp) >= (int)sizeof(full)) {
log_warn("Path too long: %s%s", root, tmp); return -1;
}
char real[MAX_PATH + 1];
if (realpath(full, real) == NULL) {
if (errno != ENOENT) { log_error("realpath failed: %s (%s)", full, strerror(errno)); return -1; }
char parent[MAX_PATH + 1]; strncpy(parent, full, sizeof(parent) - 1); parent[sizeof(parent) - 1] = '\0';
char *p = parent + strlen(parent); while (p > parent && *p != '/') p--;
if (p == parent) return -1;
*p = '\0';
char realparent[MAX_PATH + 1];
if (realpath(parent, realparent) == NULL) return -1;
if (snprintf(real, sizeof(real), "%s%s", realparent, full + strlen(parent)) >= (int)sizeof(real)) {
log_warn("Path too long after realpath"); return -1;
}
}
char realroot[MAX_PATH + 1]; if (!realpath(root, realroot)) return -1;
size_t rlen = strlen(realroot);
if (strncmp(real, realroot, rlen) != 0 || (real[rlen] != '\0' && real[rlen] != '/')) {
log_warn("Path outside root: %s", real); return -1;
}
if (strlen(real) >= outlen) { log_warn("Output buffer too small for path"); return -1; }
strcpy(out, real); return 0;
}
/* ==================== LOCKS ==================== */
static int generate_lock_token(char *token, size_t len) {
REQUIRE_RET(token != NULL, "token cannot be NULL", -1);
struct timeval tv; gettimeofday(&tv, NULL);
unsigned long long timestamp = (unsigned long long)tv.tv_sec * 1000000 + tv.tv_usec;
unsigned long pid = (unsigned long)getpid();
snprintf(token, len, "opaquelocktoken:%llx-%lx-%x", timestamp, pid, (unsigned int)rand());
return 0;
}
static lock_entry_t* find_lock(const char *path, int exact) {
pthread_mutex_lock(&lock_mutex); time_t now = time(NULL);
for (int i = 0; i < lock_count; ) {
if (locks[i].expires < now) {
memmove(&locks[i], &locks[i + 1], sizeof(lock_entry_t) * (lock_count - i - 1));
lock_count--; continue;
}
if (exact) {
if (strcmp(locks[i].path, path) == 0) {
lock_entry_t *result = &locks[i]; pthread_mutex_unlock(&lock_mutex); return result;
}
} else {
if (strncmp(path, locks[i].path, strlen(locks[i].path)) == 0) {
lock_entry_t *result = &locks[i]; pthread_mutex_unlock(&lock_mutex); return result;
}
}
i++;
}
pthread_mutex_unlock(&lock_mutex); return NULL;
}
static int add_lock(const char *path, lock_type_t type, const char *owner, int depth, int timeout, const char *token) {
REQUIRE_RET(path != NULL, "path cannot be NULL", -1);
pthread_mutex_lock(&lock_mutex);
if (lock_count >= 100) { pthread_mutex_unlock(&lock_mutex); return -1; }
lock_entry_t *entry = &locks[lock_count];
if (token && *token) {
if (strlen(token) >= sizeof(entry->token)) { pthread_mutex_unlock(&lock_mutex); return -1; }
strcpy(entry->token, token);
} else {
generate_lock_token(entry->token, sizeof(entry->token));
}
entry->type = type;
if (owner && strlen(owner) < sizeof(entry->owner)) strcpy(entry->owner, owner);
else entry->owner[0] = '\0';
if (strlen(path) < sizeof(entry->path)) strcpy(entry->path, path);
else { pthread_mutex_unlock(&lock_mutex); return -1; }
entry->created = time(NULL);
entry->expires = entry->created + (timeout > 0 ? timeout : LOCK_TIMEOUT_DEFAULT);
entry->depth = depth; lock_count++;
pthread_mutex_unlock(&lock_mutex); log_debug("Lock added: %s on %s", entry->token, path); return 0;
}
static int remove_lock(const char *token) {
REQUIRE_RET(token != NULL, "token cannot be NULL", -1);
pthread_mutex_lock(&lock_mutex);
for (int i = 0; i < lock_count; i++) {
if (strcmp(locks[i].token, token) == 0) {
memmove(&locks[i], &locks[i + 1], sizeof(lock_entry_t) * (lock_count - i - 1));
lock_count--; pthread_mutex_unlock(&lock_mutex);
log_debug("Lock removed: %s", token); return 0;
}
}
pthread_mutex_unlock(&lock_mutex); return -1;
}
/* ==================== RATE LIMITING ==================== */
static int check_rate_limit(const char *ip) {
REQUIRE_RET(ip != NULL, "ip cannot be NULL", 0);
pthread_mutex_lock(&rate_mutex); time_t now = time(NULL); rate_limit_entry_t *entry = NULL;
for (int i = 0; i < rate_count; i++) {
if (strcmp(rate_table[i].ip, ip) == 0) { entry = &rate_table[i]; break; }
}
if (!entry) {
if (rate_count >= 1000) { pthread_mutex_unlock(&rate_mutex); return 1; }
entry = &rate_table[rate_count++];
if (strlen(ip) < sizeof(entry->ip)) strcpy(entry->ip, ip);
else { pthread_mutex_unlock(&rate_mutex); return 1; }
entry->window_start = now; entry->request_count = 0;
pthread_mutex_init(&entry->mutex, NULL);
}
pthread_mutex_lock(&entry->mutex);
if (now - entry->window_start > RATE_LIMIT_WINDOW) {
entry->window_start = now; entry->request_count = 0;
}
entry->request_count++; int exceeded = (entry->request_count > MAX_REQ);
pthread_mutex_unlock(&entry->mutex); pthread_mutex_unlock(&rate_mutex);
if (exceeded) log_warn("Rate limit exceeded for %s: %d requests", ip, entry->request_count);
return exceeded;
}
/* ==================== HEADERS ==================== */
static void headers_init(headers_t *h) { REQUIRE(h != NULL, "headers cannot be NULL"); h->count = 0; }
static void headers_set(headers_t *h, const char *k, const char *v) {
REQUIRE(h != NULL, "headers cannot be NULL"); REQUIRE(k != NULL, "key cannot be NULL"); REQUIRE(v != NULL, "value cannot be NULL");
if (h->count >= 128) return;
strncpy(h->keys[h->count], k, SMALL_BUF - 1); h->keys[h->count][SMALL_BUF - 1] = '\0';
strncpy(h->vals[h->count], v, SMALL_BUF - 1); h->vals[h->count][SMALL_BUF - 1] = '\0';
trim_inplace(h->vals[h->count]); h->count++;
}
static const char *headers_get(headers_t *h, const char *k) {
REQUIRE_RET(h != NULL, "headers cannot be NULL", NULL); REQUIRE_RET(k != NULL, "key cannot be NULL", NULL);
for (int i = 0; i < h->count; i++) {
if (strcasecmp(h->keys[i], k) == 0) return h->vals[i];
}
return NULL;
}
/* ==================== BUFFER ==================== */
static int buffer_init(buffer_t *buf, size_t initial_capacity) {
REQUIRE_RET(buf != NULL, "buffer cannot be NULL", -1);
buf->data = (char *)malloc(initial_capacity); if (!buf->data) return -1;
buf->length = 0; buf->capacity = initial_capacity; return 0;
}
static void buffer_free(buffer_t *buf) {
if (!buf) return;
free(buf->data); buf->data = NULL; buf->length = 0; buf->capacity = 0;
}
static int buffer_append(buffer_t *buf, const void *data, size_t len) {
REQUIRE_RET(buf != NULL, "buffer cannot be NULL", -1); REQUIRE_RET(data != NULL || len == 0, "data cannot be NULL", -1);
if (buf->length + len > buf->capacity) {
size_t new_capacity = buf->capacity * 2;
while (new_capacity < buf->length + len) new_capacity *= 2;
char *new_data = (char *)realloc(buf->data, new_capacity); if (!new_data) return -1;
buf->data = new_data; buf->capacity = new_capacity;
}
if (len > 0) { memcpy(buf->data + buf->length, data, len); buf->length += len; }
return 0;
}
static int buffer_append_str(buffer_t *buf, const char *str) {
REQUIRE_RET(buf != NULL, "buffer cannot be NULL", -1); REQUIRE_RET(str != NULL, "str cannot be NULL", -1);
return buffer_append(buf, str, strlen(str));
}
/* ==================== IO UTILS ==================== */
static ssize_t send_all(int fd, const void *buf, size_t len, int timeout_sec) {
REQUIRE_RET(fd >= 0, "invalid fd", -1); REQUIRE_RET(buf != NULL || len == 0, "buf cannot be NULL", -1);
if (timeout_sec > 0) {
#ifdef _WIN32
int timeout_ms = timeout_sec * 1000;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout_ms, (int)sizeof(timeout_ms));
#else
struct timeval tv; tv.tv_sec = timeout_sec; tv.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
#endif
}
size_t total = 0; const char *p = (const char *)buf;
while (total < len) {
ssize_t sent = send(fd, p + total, len - total, MSG_NOSIGNAL);
if (sent <= 0) { if (errno == EINTR) continue; log_debug("Send failed: %s", strerror(errno)); return -1; }
total += (size_t)sent;
}
return (ssize_t)total;
}
static ssize_t recv_all(int fd, void *buf, size_t len, int timeout_sec) {
REQUIRE_RET(fd >= 0, "invalid fd", -1); REQUIRE_RET(buf != NULL || len == 0, "buf cannot be NULL", -1);
if (timeout_sec > 0) {
#ifdef _WIN32
int timeout_ms = timeout_sec * 1000;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout_ms, (int)sizeof(timeout_ms));
#else
struct timeval tv; tv.tv_sec = timeout_sec; tv.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
#endif
}
size_t total = 0; char *p = (char *)buf;
while (total < len) {
ssize_t received = recv(fd, p + total, len - total, 0);
if (received <= 0) { if (received == 0) return 0; if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) continue; log_debug("Recv failed: %s", strerror(errno)); return -1; }
total += (size_t)received;
}
return (ssize_t)total;
}
static ssize_t read_line(int fd, char *buf, size_t maxlen, int timeout_sec) {
REQUIRE_RET(fd >= 0, "invalid fd", -1); REQUIRE_RET(buf != NULL, "buf cannot be NULL", -1); REQUIRE_RET(maxlen > 0, "maxlen must be > 0", -1);
if (timeout_sec > 0) {
#ifdef _WIN32
int timeout_ms = timeout_sec * 1000;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout_ms, (int)sizeof(timeout_ms));
#else
struct timeval tv; tv.tv_sec = timeout_sec; tv.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
#endif
}
size_t i = 0; char c = 0;
while (i + 1 < maxlen) {
ssize_t n = recv(fd, &c, 1, 0);
if (n <= 0) { if (n == 0) return 0; if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) continue; log_debug("Recv line failed: %s", strerror(errno)); return -1; }
buf[i++] = c;
if (i >= 2 && buf[i - 2] == '\r' && buf[i - 1] == '\n') { buf[i] = '\0'; return (ssize_t)i; }
}
buf[maxlen - 1] = '\0'; return -1;
}
/* ==================== MIME TYPES ==================== */
static const char *guess_mime(const char *path) {
REQUIRE_RET(path != NULL, "path cannot be NULL", "application/octet-stream");
const char *ext = strrchr(path, '.'); if (!ext) return "application/octet-stream"; ext++;
struct mime_map { const char *ext; const char *mime; } mimes[] = {
{"html", "text/html; charset=utf-8"}, {"htm", "text/html; charset=utf-8"},
{"txt", "text/plain; charset=utf-8"}, {"css", "text/css; charset=utf-8"},
{"js", "application/javascript; charset=utf-8"}, {"json", "application/json; charset=utf-8"},
{"xml", "application/xml; charset=utf-8"}, {"jpg", "image/jpeg"}, {"jpeg", "image/jpeg"},
{"png", "image/png"}, {"gif", "image/gif"}, {"bmp", "image/bmp"}, {"svg", "image/svg+xml"},
{"pdf", "application/pdf"}, {"zip", "application/zip"}, {"tar", "application/x-tar"},
{"gz", "application/gzip"}, {"mp3", "audio/mpeg"}, {"wav", "audio/wav"},
{"mp4", "video/mp4"}, {"webm", "video/webm"}, {NULL, NULL}
};
for (int i = 0; mimes[i].ext; i++) {
if (strcasecmp(ext, mimes[i].ext) == 0) return mimes[i].mime;
}
return "application/octet-stream";
}
/* ==================== FILE OPERATIONS ==================== */
static int create_parent_dirs(const char *path) {
REQUIRE_RET(path != NULL, "path cannot be NULL", -1);
char parent[MAX_PATH + 1]; strncpy(parent, path, sizeof(parent) - 1); parent[sizeof(parent) - 1] = '\0';
char *p = parent + strlen(parent); while (p > parent && *p != '/') p--;
if (p <= parent) return 0;
*p = '\0';
struct stat st; if (stat(parent, &st) == 0) { if (S_ISDIR(st.st_mode)) return 0; log_error("Parent not dir: %s", parent); return -1; }
if (create_parent_dirs(parent) != 0) return -1;
if (mkdir(parent, 0755) != 0 && errno != EEXIST) { log_error("mkdir failed: %s (%s)", parent, strerror(errno)); return -1; }
return 0;
}
static int recursive_delete(const char *path) {
REQUIRE_RET(path != NULL, "path cannot be NULL", -1);
struct stat st; if (lstat(path, &st) != 0) { if (errno == ENOENT) return 0; log_error("lstat failed: %s (%s)", path, strerror(errno)); return -1; }
if (!S_ISDIR(st.st_mode)) return unlink(path);
DIR *d = opendir(path); if (!d) { log_error("opendir failed: %s (%s)", path, strerror(errno)); return -1; }
struct dirent *e; while ((e = readdir(d))) {
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
char sub[MAX_PATH + 1]; if (snprintf(sub, sizeof(sub), "%s/%s", path, e->d_name) >= (int)sizeof(sub)) { closedir(d); return -1; }
if (recursive_delete(sub) != 0) { closedir(d); return -1; }
}
closedir(d); return rmdir(path);
}
static int recursive_copy(const char *src, const char *dest) {
REQUIRE_RET(src != NULL, "src cannot be NULL", -1); REQUIRE_RET(dest != NULL, "dest cannot be NULL", -1);
struct stat st; if (lstat(src, &st) != 0) return -1;
if (S_ISDIR(st.st_mode)) {
if (mkdir(dest, st.st_mode) != 0 && errno != EEXIST) return -1;
DIR *d = opendir(src); if (!d) return -1;
struct dirent *e; while ((e = readdir(d))) {
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
char ssub[MAX_PATH + 1], dsub[MAX_PATH + 1];
if (snprintf(ssub, sizeof(ssub), "%s/%s", src, e->d_name) >= (int)sizeof(ssub) ||
snprintf(dsub, sizeof(dsub), "%s/%s", dest, e->d_name) >= (int)sizeof(dsub)) { closedir(d); return -1; }
if (recursive_copy(ssub, dsub) != 0) { closedir(d); return -1; }
}
closedir(d); return 0;
} else {
int fdsrc = open(src, O_RDONLY); if (fdsrc < 0) return -1;
int fddest = open(dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode); if (fddest < 0) { close(fdsrc); return -1; }
char buf[8192]; ssize_t r; while ((r = read(fdsrc, buf, sizeof(buf))) > 0) {
if (write(fddest, buf, (size_t)r) != r) { close(fdsrc); close(fddest); return -1; }
}
close(fdsrc); close(fddest); return 0;
}
}
/* ==================== HTTP RESPONSE ==================== */
static const char *status_reason(http_status_t code) {
switch (code) {
case HTTP_200_OK: return "OK"; case HTTP_201_CREATED: return "Created";
case HTTP_204_NO_CONTENT: return "No Content"; case HTTP_206_PARTIAL_CONTENT: return "Partial Content";
case HTTP_207_MULTI_STATUS: return "Multi-Status"; case HTTP_303_SEE_OTHER: return "See Other";
case HTTP_304_NOT_MODIFIED: return "Not Modified"; case HTTP_400_BAD_REQUEST: return "Bad Request";
case HTTP_401_UNAUTHORIZED: return "Unauthorized"; case HTTP_403_FORBIDDEN: return "Forbidden";
case HTTP_404_NOT_FOUND: return "Not Found"; case HTTP_405_METHOD_NOT_ALLOWED: return "Method Not Allowed";
case HTTP_409_CONFLICT: return "Conflict"; case HTTP_412_PRECONDITION_FAILED: return "Precondition Failed";
case HTTP_413_PAYLOAD_TOO_LARGE: return "Payload Too Large"; case HTTP_416_RANGE_NOT_SATISFIABLE: return "Range Not Satisfiable";
case HTTP_423_LOCKED: return "Locked"; case HTTP_429_TOO_MANY_REQUESTS: return "Too Many Requests";
case HTTP_500_INTERNAL_SERVER_ERROR: return "Internal Server Error"; case HTTP_501_NOT_IMPLEMENTED: return "Not Implemented";
case HTTP_503_SERVICE_UNAVAILABLE: return "Service Unavailable"; case HTTP_507_INSUFFICIENT_STORAGE: return "Insufficient Storage";
default: return "Unknown";
}
}
static bool append_header(char *buf, size_t buf_size, int *len, const char *fmt, ...) {
va_list ap; va_start(ap, fmt);
int written = vsnprintf(buf + *len, buf_size - (size_t)(*len), fmt, ap);
va_end(ap);
if (written < 0 || written >= (int)(buf_size - (size_t)(*len))) return false;
*len += written;
return true;
}
static void send_response(int fd, http_status_t code, headers_t *extra_headers, const char *body, size_t body_len) {
REQUIRE(fd >= 0, "invalid fd"); log_debug("Sending response: %d %s", code, status_reason(code));
char header_buf[8192]; int header_len = 0;
if (!append_header(header_buf, sizeof(header_buf), &header_len,
"HTTP/1.1 %d %s\r\nServer: mini-webdav/1.0\r\nDate: %s\r\n",
code, status_reason(code), http_time(time(NULL)))) return;
if (extra_headers) {
for (int i = 0; i < extra_headers->count; i++) {
if (!append_header(header_buf, sizeof(header_buf), &header_len, "%s: %s\r\n", extra_headers->keys[i], extra_headers->vals[i])) return;
}
}
if (!append_header(header_buf, sizeof(header_buf), &header_len,
"Content-Length: %zu\r\nConnection: close\r\n\r\n", body_len)) return;
send_all(fd, header_buf, (size_t)header_len, TIMEOUT);
if (body_len > 0 && body) send_all(fd, body, body_len, TIMEOUT);
}
static void send_error(int fd, http_status_t code, const char *message) {
REQUIRE(fd >= 0, "invalid fd");
headers_t headers; headers_init(&headers);
headers_set(&headers, "Content-Type", "text/plain; charset=utf-8");
send_response(fd, code, &headers, message, strlen(message));
}
/* ==================== HTML INTERFACE COM TAILWIND ==================== */
static void generate_directory_html(buffer_t *html, const char *reqpath, DIR *d, const char *fs_path) {
REQUIRE(html != NULL, "html cannot be NULL");
REQUIRE(reqpath != NULL, "reqpath cannot be NULL");
// Favicon
buffer_append_str(html, "<!DOCTYPE html>\n<html lang=\"pt-BR\">\n<head>\n");
buffer_append_str(html, " <meta charset=\"UTF-8\">\n");
buffer_append_str(html, " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">\n");
buffer_append_str(html, " <meta name=\"theme-color\" content=\"#3b82f6\">\n");
buffer_append_str(html, " <title>WebDAV Server - ");
buffer_append_str(html, reqpath);
buffer_append_str(html, "</title>\n");
buffer_append_str(html, " <link rel=\"icon\" href=\"data:;base64,iVBORw0KGgo=\">\n");
buffer_append_str(html, " <script src=\"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4\"></script>\n");
buffer_append_str(html, " <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css\">\n");
buffer_append_str(html, " <style>\n");
buffer_append_str(html, " @media (prefers-color-scheme: dark) {\n");
buffer_append_str(html, " body { background-color: #0f172a; color: #f1f5f9; }\n");
buffer_append_str(html, " .modal-content { background-color: #1e293b; color: #f1f5f9; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (prefers-color-scheme: light) {\n");
buffer_append_str(html, " .modal-content { background-color: #ffffff; color: #1e293b; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .action-btn {\n");
buffer_append_str(html, " transition: all 0.2s;\n");
buffer_append_str(html, " padding: 8px 12px;\n");
buffer_append_str(html, " border-radius: 6px;\n");
buffer_append_str(html, " margin: 2px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .action-btn:hover { transform: scale(1.05); }\n");
buffer_append_str(html, " .action-btn i { font-size: 16px; }\n");
buffer_append_str(html, " .modal {\n");
buffer_append_str(html, " display: none;\n");
buffer_append_str(html, " position: fixed;\n");
buffer_append_str(html, " inset: 0;\n");
buffer_append_str(html, " background: rgba(0,0,0,0.7);\n");
buffer_append_str(html, " z-index: 1000;\n");
buffer_append_str(html, " align-items: center;\n");
buffer_append_str(html, " justify-content: center;\n");
buffer_append_str(html, " padding: 16px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .modal-content {\n");
buffer_append_str(html, " padding: 24px;\n");
buffer_append_str(html, " border-radius: 12px;\n");
buffer_append_str(html, " width: 100%;\n");
buffer_append_str(html, " max-width: 450px;\n");
buffer_append_str(html, " box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04);\n");
buffer_append_str(html, " animation: modalFadeIn 0.3s ease-out;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @keyframes modalFadeIn {\n");
buffer_append_str(html, " from { opacity: 0; transform: translateY(-20px); }\n");
buffer_append_str(html, " to { opacity: 1; transform: translateY(0); }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .toast {\n");
buffer_append_str(html, " position: fixed;\n");
buffer_append_str(html, " bottom: 20px;\n");
buffer_append_str(html, " right: 20px;\n");
buffer_append_str(html, " left: 20px;\n");
buffer_append_str(html, " padding: 16px 24px;\n");
buffer_append_str(html, " border-radius: 8px;\n");
buffer_append_str(html, " color: white;\n");
buffer_append_str(html, " z-index: 2000;\n");
buffer_append_str(html, " min-width: 280px;\n");
buffer_append_str(html, " max-width: 90%;\n");
buffer_append_str(html, " margin: 0 auto;\n");
buffer_append_str(html, " box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n");
buffer_append_str(html, " animation: toastSlideIn 0.3s ease-out;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @keyframes toastSlideIn {\n");
buffer_append_str(html, " from { opacity: 0; transform: translateY(50px); }\n");
buffer_append_str(html, " to { opacity: 1; transform: translateY(0); }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .toast-success { background: #10b981; }\n");
buffer_append_str(html, " .toast-error { background: #ef4444; }\n");
buffer_append_str(html, " .file-row.selected, .file-card.selected {\n");
buffer_append_str(html, " background-color: #dbeafe !important;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (prefers-color-scheme: dark) {\n");
buffer_append_str(html, " .file-row.selected, .file-card.selected {\n");
buffer_append_str(html, " background-color: #1e3a8a !important;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (max-width: 768px) {\n");
buffer_append_str(html, " .desktop-only { display: none !important; }\n");
buffer_append_str(html, " .mobile-only { display: block !important; }\n");
buffer_append_str(html, " .mobile-hidden { display: none !important; }\n");
buffer_append_str(html, " .action-container {\n");
buffer_append_str(html, " position: fixed;\n");
buffer_append_str(html, " bottom: 0;\n");
buffer_append_str(html, " left: 0;\n");
buffer_append_str(html, " right: 0;\n");
buffer_append_str(html, " background: linear-gradient(to top, rgba(255,255,255,0.95) 80%, transparent);\n");
buffer_append_str(html, " padding: 12px 16px;\n");
buffer_append_str(html, " border-top: 1px solid #e2e8f0;\n");
buffer_append_str(html, " z-index: 100;\n");
buffer_append_str(html, " box-shadow: 0 -2px 10px rgba(0,0,0,0.1);\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (prefers-color-scheme: dark) {\n");
buffer_append_str(html, " .action-container {\n");
buffer_append_str(html, " background: linear-gradient(to top, rgba(15,23,42,0.95) 80%, transparent);\n");
buffer_append_str(html, " border-top: 1px solid #334155;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .mobile-actions {\n");
buffer_append_str(html, " display: flex;\n");
buffer_append_str(html, " gap: 8px;\n");
buffer_append_str(html, " justify-content: center;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .mobile-action-btn {\n");
buffer_append_str(html, " flex: 1;\n");
buffer_append_str(html, " padding: 14px 8px;\n");
buffer_append_str(html, " border-radius: 10px;\n");
buffer_append_str(html, " font-size: 12px;\n");
buffer_append_str(html, " text-align: center;\n");
buffer_append_str(html, " cursor: pointer;\n");
buffer_append_str(html, " transition: all 0.2s;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .mobile-action-btn:disabled {\n");
buffer_append_str(html, " opacity: 0.5 !important;\n");
buffer_append_str(html, " pointer-events: none !important;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .file-card {\n");
buffer_append_str(html, " display: block;\n");
buffer_append_str(html, " padding: 16px;\n");
buffer_append_str(html, " margin-bottom: 8px;\n");
buffer_append_str(html, " background: white;\n");
buffer_append_str(html, " border-radius: 12px;\n");
buffer_append_str(html, " box-shadow: 0 2px 4px rgba(0,0,0,0.05);\n");
buffer_append_str(html, " transition: all 0.2s;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (prefers-color-scheme: dark) {\n");
buffer_append_str(html, " .file-card { background: #1e293b; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .file-card:hover {\n");
buffer_append_str(html, " transform: translateY(-2px);\n");
buffer_append_str(html, " box-shadow: 0 4px 8px rgba(0,0,0,0.1);\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .file-info {\n");
buffer_append_str(html, " display: flex;\n");
buffer_append_str(html, " align-items: center;\n");
buffer_append_str(html, " gap: 12px;\n");
buffer_append_str(html, " margin-bottom: 12px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .file-details {\n");
buffer_append_str(html, " flex: 1;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .file-actions {\n");
buffer_append_str(html, " display: flex;\n");
buffer_append_str(html, " gap: 6px;\n");
buffer_append_str(html, " margin-top: 12px;\n");
buffer_append_str(html, " padding-top: 12px;\n");
buffer_append_str(html, " border-top: 1px solid #e2e8f0;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (prefers-color-scheme: dark) {\n");
buffer_append_str(html, " .file-actions { border-top: 1px solid #334155; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .file-actions .action-btn {\n");
buffer_append_str(html, " padding: 6px 10px;\n");
buffer_append_str(html, " font-size: 12px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .breadcrumb-item {\n");
buffer_append_str(html, " font-size: 13px;\n");
buffer_append_str(html, " padding: 4px 8px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .breadcrumb-separator {\n");
buffer_append_str(html, " margin: 0 4px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " table { display: none; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (min-width: 769px) {\n");
buffer_append_str(html, " .mobile-only { display: none !important; }\n");
buffer_append_str(html, " .mobile-hidden { display: block !important; }\n");
buffer_append_str(html, " .action-container { display: none !important; }\n");
buffer_append_str(html, " .file-card { display: none !important; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .checkbox-cell {\n");
buffer_append_str(html, " min-width: 50px;\n");
buffer_append_str(html, " width: 50px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " .name-cell { min-width: 250px; }\n");
buffer_append_str(html, " .size-cell, .date-cell, .type-cell { min-width: 120px; }\n");
buffer_append_str(html, " .actions-cell { min-width: 200px; }\n");
buffer_append_str(html, " @media (max-width: 1024px) {\n");
buffer_append_str(html, " .name-cell { min-width: 200px; }\n");
buffer_append_str(html, " .size-cell, .date-cell, .type-cell { min-width: 100px; font-size: 13px; }\n");
buffer_append_str(html, " .actions-cell { min-width: 180px; }\n");
buffer_append_str(html, " .action-btn { padding: 4px 6px; }\n");
buffer_append_str(html, " .action-btn i { font-size: 14px; }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " input[type=\"text\"], input[type=\"file\"] {\n");
buffer_append_str(html, " width: 100%;\n");
buffer_append_str(html, " padding: 12px;\n");
buffer_append_str(html, " font-size: 16px;\n");
buffer_append_str(html, " border-radius: 8px;\n");
buffer_append_str(html, " border: 1px solid #cbd5e1;\n");
buffer_append_str(html, " margin-bottom: 16px;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " @media (prefers-color-scheme: dark) {\n");
buffer_append_str(html, " input[type=\"text\"], input[type=\"file\"] {\n");
buffer_append_str(html, " background-color: #1e293b;\n");
buffer_append_str(html, " border-color: #334155;\n");
buffer_append_str(html, " color: #f1f5f9;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " button, .action-btn {\n");
buffer_append_str(html, " font-size: 16px;\n");
buffer_append_str(html, " font-weight: 600;\n");
buffer_append_str(html, " cursor: pointer;\n");
buffer_append_str(html, " touch-action: manipulation;\n");
buffer_append_str(html, " -webkit-tap-highlight-color: transparent;\n");
buffer_append_str(html, " }\n");
buffer_append_str(html, " </style>\n");
buffer_append_str(html, "</head>\n<body class=\"bg-gray-50 dark:bg-slate-900 dark:text-slate-100 transition-colors duration-200\">\n");
// Header
buffer_append_str(html, " <header class=\"bg-gradient-to-r from-blue-600 to-indigo-700 text-white shadow-lg\">\n");
buffer_append_str(html, " <div class=\"container mx-auto px-4 py-4\">\n");
buffer_append_str(html, " <div class=\"flex items-center justify-between\">\n");
buffer_append_str(html, " <div class=\"flex items-center space-x-3\">\n");
buffer_append_str(html, " <svg class=\"w-8 h-8\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n");
buffer_append_str(html, " <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z\"></path>\n");
buffer_append_str(html, " </svg>\n");
buffer_append_str(html, " <h1 class=\"text-2xl font-bold hidden sm:block\">WebDAV Server</h1>\n");
buffer_append_str(html, " </div>\n");
buffer_append_str(html, " <div class=\"flex items-center space-x-2\">\n");
buffer_append_str(html, " <button onclick=\"showCreateFolderModal()\" class=\"flex items-center bg-white text-blue-600 hover:bg-blue-50 px-3 py-2 rounded-lg shadow transition-colors text-sm\">\n");
buffer_append_str(html, " <i class=\"fas fa-folder-plus mr-1 sm:mr-2\"></i>\n");
buffer_append_str(html, " <span class=\"hidden xs:inline\">Nova Pasta</span>\n");
buffer_append_str(html, " </button>\n");
buffer_append_str(html, " <button onclick=\"document.getElementById('fileInput').click()\" class=\"flex items-center bg-green-500 hover:bg-green-600 text-white px-3 py-2 rounded-lg shadow transition-colors text-sm\">\n");
buffer_append_str(html, " <i class=\"fas fa-upload mr-1 sm:mr-2\"></i>\n");
buffer_append_str(html, " <span class=\"hidden xs:inline\">Upload</span>\n");
buffer_append_str(html, " </button>\n");
buffer_append_str(html, " </div>\n");
buffer_append_str(html, " </div>\n");
buffer_append_str(html, " <div class=\"mt-3\">\n");
buffer_append_str(html, " <p class=\"text-sm opacity-90\">Diretório: <span class=\"font-mono bg-black bg-opacity-20 px-2 py-1 rounded text-xs sm:text-sm\">");
buffer_append_str(html, reqpath);
buffer_append_str(html, "</span></p>\n");
buffer_append_str(html, " </div>\n");
buffer_append_str(html, " </div>\n");
buffer_append_str(html, " </header>\n");
// Hidden file input
buffer_append_str(html, " <input type=\"file\" id=\"fileInput\" multiple style=\"display:none\" onchange=\"handleFileUpload(event)\">\n");
// Main Content
buffer_append_str(html, " <main class=\"container mx-auto px-3 sm:px-4 py-6\">\n");
// Breadcrumb Navigation
buffer_append_str(html, " <nav class=\"mb-4\" aria-label=\"Breadcrumb\">\n");
buffer_append_str(html, " <ol class=\"flex flex-wrap items-center gap-1 text-xs sm:text-sm\">\n");
buffer_append_str(html, " <li class=\"breadcrumb-item\">\n");
buffer_append_str(html, " <a href=\"/\" class=\"text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors flex items-center\">\n");
buffer_append_str(html, " <svg class=\"w-3 h-3 sm:w-4 sm:h-4 inline-block mr-1\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n");
buffer_append_str(html, " <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6\"></path>\n");
buffer_append_str(html, " </svg>\n");
buffer_append_str(html, " <span class=\"hidden xs:inline\">Início</span>\n");
buffer_append_str(html, " </a>\n");
buffer_append_str(html, " </li>\n");
// Gerar breadcrumbs dinamicamente
if (strcmp(reqpath, "/") != 0) {
char temp_path[MAX_PATH];
strncpy(temp_path, reqpath, sizeof(temp_path) - 1);
temp_path[sizeof(temp_path) - 1] = '\0';
char *token = strtok(temp_path, "/");
char current_path[MAX_PATH] = "/";
while (token != NULL) {
buffer_append_str(html, " <li class=\"breadcrumb-separator\">\n");