-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.c
2640 lines (2301 loc) · 73.9 KB
/
client.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
/*
* ryshttpd -- simple filesharing http server.
*
* ryshttpd is copyrighted:
* Copyright (C) 2018 Andrey Rys. All rights reserved.
*
* ryshttpd is licensed to you under the terms of std. MIT/X11 license:
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "httpd.h"
static char *client_read_pool;
static struct client_state *clstate;
static rh_yesno verify_ascii(const char *str, size_t maxl)
{
const char *s = str;
while (s-str < maxl) {
if (!*s) return NO;
if (!isprint(*s)
&& !isascii(*s)
&& !isspace(*s)) return NO;
s++;
}
return YES;
}
/*
* ryshttpd always parses Unix (LF) line endings of text requests.
* The point is that this function gives verdict about what line endings
* the client is talking in, and both LF and CRLF are supported (but not CR).
* It also verifies the request to be ASCII clean (at least urlencoded).
*/
static size_t read_raw_request(
struct client_info *cli, char *to, size_t tol, rh_yesno *crlf,
char **tail, size_t *sztail)
{
size_t x, y, z;
char *pblk, *s, *d;
if (!to || tol < 1) return NOSIZE;
rh_memzero(to, tol);
z = tol-1; pblk = to;
while (1) {
x = io_recv_data(cli, pblk, z, YES, YES);
if (x == 0) break;
if (x == NOSIZE) return NOSIZE;
pblk += x; z -= x;
if (pblk-to >= tol) return 0;
/* Find CRLF */
y = CSTR_SZ("\r\n\r\n");
s = strstr(to, "\r\n\r\n");
if (s) {
/* Verify to be ASCII clean/urlencoded */
if (!verify_ascii(to, s-to)) continue;
/* That's CRLF request */
*crlf = YES;
/*
* Win +2 NUL bytes so that strlxstr will not fail.
* ryshttpd works with LF only anyway.
*/
rh_memzero(s, y);
memcpy(s, "\n\n", CSTR_SZ("\n\n"));
/* Rewind to end of request */
s += y;
/* If it overflows then reject it */
if (s-to > tol-1) return 0;
/* Write the tail location (for clstate->tail) */
if ((pblk-to) > (s-to)) {
*tail = s;
*sztail = (pblk-to) - (s-to);
}
else {
*tail = NULL;
*sztail = s-to;
}
/* strlxstr gives exact new line length */
return rh_strlxstr(to, s-to, "\r\n", "\n");
}
/* Find LF */
y = CSTR_SZ("\n\n");
s = strstr(to, "\n\n");
if (s) {
if (!verify_ascii(to, s-to)) continue;
*crlf = NO;
s += y;
if (s-to > tol-1) return 0;
if ((pblk-to) > (s-to)) {
*tail = s;
*sztail = (pblk-to) - (s-to);
}
else {
*tail = NULL;
*sztail = s-to;
}
return s-to;
}
/* Try to verify a single HTTP/0.9 request line */
y = CSTR_SZ("\r\n");
s = strstr(to, "\r\n");
if (!s) {
y = CSTR_SZ("\n");
s = strstr(to, "\n");
}
if (s && (to+x-y) == s) {
d = strchr(to, ' ');
if (!d) continue;
d++;
if (strchr(d, ' ')) continue;
if (!verify_ascii(to, s-to)) continue;
if (y == CSTR_SZ("\r\n")) *crlf = YES;
else *crlf = NO;
rh_memzero(s, y);
memcpy(s, "\n", CSTR_SZ("\n"));
s += CSTR_SZ("\n");
/* No POST is allowed with HTTP/0.9, so not preserving tail. */
*tail = NULL;
*sztail = s-to;
return s-to;
}
}
return 0;
}
static void set_counter(TF_BYTE_TYPE *ctr, rh_fsize seekpt)
{
rh_fsize seekbytes = seekpt / TF_BLOCK_SIZE;
tf_ctr_set(ctr, &seekbytes, sizeof(rh_fsize));
}
static rh_yesno make_cryptctx(const char *cryptpw, struct tf_ctx *cryptctx)
{
rh_memzero(cryptctx, sizeof(struct tf_ctx));
/* hash a key from password string */
skeinhash(cryptctx->keyx, TF_KEY_SIZE, cryptpw, strlen(cryptpw));
skeinhash(cryptctx->keyz, TF_KEY_SIZE, cryptctx->keyx, TF_KEY_SIZE);
/* derive static counter directly from master key */
skeinhash(cryptctx->ctr, TF_BLOCK_SIZE, cryptctx->keyx, TF_KEY_SIZE);
return YES;
}
static void do_encrypt(struct tf_ctx *ctx, void *data, size_t szdata)
{
tf_xts_encrypt(ctx->keyx, ctx->keyz, ctx->ctr, data, data, szdata, 1);
}
static size_t do_stream_file_reader(void *clstate, void *data, size_t szdata)
{
struct client_state *uclstate = clstate;
return io_read_data(uclstate->file_fd, data, szdata, YES, NULL);
}
static size_t do_stream_file_writer(void *clstate, const void *data, size_t szdata)
{
struct client_state *uclstate = clstate;
return io_send_data(uclstate->clinfo, data, szdata, YES, NO);
}
static void do_stream_file_mangler(void *clstate, void *data, size_t szdata)
{
struct client_state *uclstate = clstate;
if (uclstate->cryptpw) do_encrypt(&uclstate->cryptctx, data, szdata);
}
static rh_fsize do_stream_file_seeker(void *clstate, rh_fsize offset)
{
struct client_state *uclstate = clstate;
if (uclstate->cryptpw) set_counter(uclstate->cryptctx.ctr, offset);
return (rh_fsize)lseek(uclstate->file_fd, (off_t)offset, SEEK_SET);
}
static void do_stream_file(struct client_state *clstate)
{
struct io_stream_args ios_args;
rh_yesno status;
rh_memzero(&ios_args, sizeof(struct io_stream_args));
ios_args.fn_args = clstate;
ios_args.rdfn = do_stream_file_reader;
ios_args.wrfn = do_stream_file_writer;
ios_args.mgfn = do_stream_file_mangler;
ios_args.skfn = do_stream_file_seeker;
ios_args.workbuf = clstate->workbuf;
ios_args.wkbufsz = clstate->wkbufsz;
ios_args.file_size = clstate->filesize;
ios_args.start_from = clstate->range_start;
ios_args.read_to = clstate->range_end;
status = io_stream_file(&ios_args);
clstate->iostate = ios_args.status;
clstate->ioerror = ios_args.error;
if (status == YES) {
clstate->range_start = ios_args.start_from;
clstate->range_end = ios_args.read_to;
}
clstate->sentbytes += ios_args.nr_written;
}
static char *client_header(const char *name)
{
return find_header_value(clstate->headers, name);
}
static char *client_arg(const char *name)
{
return find_arg_value(clstate->args, name);
}
static void tell_never_cache(struct client_state *clstate)
{
time_t t = (time_t)679779600L;
char *s;
if (rh_no_cache_headers == YES) return;
add_header(&clstate->sendheaders, "Cache-Control", "no-cache, no-store, must-revalidate");
add_header(&clstate->sendheaders, "Pragma", "no-cache");
s = getsdate(t, HTTP_DATE_FMT, YES);
add_header(&clstate->sendheaders, "Expires", s);
pfree(s);
}
static void tell_aggressive_cache(struct client_state *clstate)
{
char *s;
if (rh_no_cache_headers == YES) return;
add_header(&clstate->sendheaders, "Cache-Control", "public, max-age=31536000");
s = getsdate(clstate->request_time + 31536000L, HTTP_DATE_FMT, YES);
add_header(&clstate->sendheaders, "Expires", s);
pfree(s);
}
static void filter_special_htmlchars_sub(char **line, size_t sz, const char *chr, const char *schr)
{
_again: if (rh_strlxstr(*line, sz, chr, schr) >= sz) {
if (sz < RH_ALLOC_SMALL) sz = RH_ALLOC_SMALL;
sz /= 2; sz *= 3;
if (sz >= RH_XSALLOC_MAX)
xexits("failed to escape HTML characters!");
*line = rh_realloc(*line, sz);
goto _again;
}
}
static void filter_special_htmlchars(char **line)
{
size_t sz = rh_szalloc(*line);
filter_special_htmlchars_sub(line, sz, "&", "&");
filter_special_htmlchars_sub(line, sz, "<", "<");
filter_special_htmlchars_sub(line, sz, ">", ">");
filter_special_htmlchars_sub(line, sz, "\"", """);
filter_special_htmlchars_sub(line, sz, "'", "'");
filter_special_htmlchars_sub(line, sz, "%", "%25");
filter_special_htmlchars_sub(line, sz, "?", "?");
filter_special_htmlchars_sub(line, sz, "=", "=");
shrink_dynstr(line);
}
static const char *ppath(const char *ppath)
{
return ppath ? ppath : "";
}
/* strcasestr is so GNUish I cannot use it everywhere. */
static rh_yesno match_client_useragent(const char *agent, const char *agtpat)
{
void *rgx;
rh_yesno r = NO;
rgx = regex_compile(agtpat, YES, NO, YES);
if (regex_is_error(rgx)) {
regex_free(rgx);
return NO;
}
if (regex_exec(rgx, agent)) r = YES;
regex_free(rgx);
return r;
}
static rh_yesno xrealip_matches(const char *s_claddr, const char *s_xrealip)
{
struct netaddr claddr, xrealip;
if (!strncmp(s_xrealip, "unix:", CSTR_SZ("unix:")) && strchr(s_xrealip, ':') && strchr(s_xrealip, '.')) {
if (!strcmp(s_claddr, s_xrealip+CSTR_SZ("unix:"))) return YES;
}
if (rh_parse_addr(s_xrealip, &xrealip) == NO) return NO;
if (rh_parse_addr(s_claddr, &claddr) == NO) return NO;
return rh_match_addr(&xrealip, &claddr);
}
static void reset_client_state(struct client_state *clstate)
{
size_t sz, x;
clstate->request_time = (time_t)0L;
pfree(clstate->request_date);
pfree(clstate->tail);
clstate->sztail = NOSIZE;
sz = DYN_ARRAY_SZ(clstate->request_lines);
for (x = 0; x < sz; x++) pfree(clstate->request_lines[x]);
pfree(clstate->request_lines);
clstate->is_crlf = NO;
clstate->method = 0;
pfree(clstate->request);
pfree(clstate->protoversion);
pfree(clstate->path);
pfree(clstate->requri);
pfree(clstate->strargs);
pfree(clstate->args);
pfree(clstate->headers);
pfree(clstate->cryptpw);
rh_memzero(&clstate->cryptctx, sizeof(struct tf_ctx));
pfree(clstate->realpath);
clstate->filedir = 0;
clstate->wants_dir = NO;
if (clstate->file_fd != 0
&& clstate->file_fd != -1) {
close(clstate->file_fd);
clstate->file_fd = -1;
}
clstate->is_exec = NO;
clstate->is_rsrc = NO;
clstate->is_indx = NO;
clstate->cgi_mode = 0;
clstate->workbuf = NULL;
clstate->wkbufsz = 0;
clstate->filesize = 0;
clstate->range_start = 0;
clstate->range_end = 0;
clstate->recvbytes = 0;
clstate->sentbytes = 0;
clstate->iostate = 0;
clstate->ioerror = 0;
pfree(clstate->sendheaders);
clstate->was_rewritten = NO;
clstate->noindex = NO;
clstate->allow_tar = NO;
if (clstate->hideindex_rgx) {
regex_free(clstate->hideindex_rgx);
clstate->hideindex_rgx = NULL;
}
pfree(clstate->prevpath);
clstate->sent_response_already = NO;
pfree(clstate->status);
pfree(clstate->altlogline);
pfree(clstate->prepend_path);
if (rh_dir_prepend_path) clstate->prepend_path = rh_strdup(rh_dir_prepend_path);
}
static rh_yesno match_exec_pattern(const void *rgx, const char *root, const char *path)
{
if (!strcmp(root, "/")) goto _ret;
if (strncmp(path, root, strnlen(root, RH_XSALLOC_MAX)) != 0) return NO;
path += strnlen(root, RH_XSALLOC_MAX);
_ret: return regex_exec(rgx, path);
}
static rh_yesno is_status_line(const void *rdata, size_t rsz)
{
const char *us, *s;
char *S;
char tp[RH_ALLOC_SMALL];
us = rdata;
s = rh_memmem(us, rsz, "\r\n", CSTR_SZ("\r\n"));
if (!s) s = rh_memmem(us, rsz, "\n", CSTR_SZ("\n"));
if (!s) return NO;
rh_strlcpy_real(tp, us, s-us+1 > sizeof(tp) ? sizeof(tp) : s-us+1);
S = tp;
if (!strncmp(S, "HTTP/", CSTR_SZ("HTTP/"))) {
S += CSTR_SZ("HTTP/");
if (!strncmp(S, "0.9 ", CSTR_SZ("0.9 "))
|| !strncmp(S, "1.0 ", CSTR_SZ("1.0 "))
|| !strncmp(S, "1.1 ", CSTR_SZ("1.1 "))) {
S += CSTR_SZ("1.1 ");
S[CSTR_SZ("200")] = 0;
if (is_number(S, NO) == YES) {
unsigned stt = rh_str_uint(S, NULL);
s = find_response_string(stt);
if (!s) return NO;
S += CSTR_SZ("200 ");
s += CSTR_SZ("200 ");
if (!strcmp(S, s)) return YES;
}
}
}
return NO;
}
static size_t catch_cgi_status_code(struct client_state *clstate, unsigned *stt, const void *rdata, size_t rsz)
{
char t[4];
const char *us, *s, *d;
size_t x;
/* Lines matched should be at beginning - the very first line of CGI answer */
/* If already set, then do nothing! */
if (clstate->status) return 0;
/* Match "HTTP/1.1 404 Not Found" style line */
s = us = rdata;
if (!strncmp(s, "HTTP/", CSTR_SZ("HTTP/"))) {
s += CSTR_SZ("HTTP/");
x = strnlen(clstate->protoversion, RH_ALLOC_MAX);
if (!strncmp(clstate->protoversion, s, x) && s[x] == ' ') {
s += x+1;
rh_strlcpy_real(t, s, sizeof(t));
if (is_number(t, NO) == YES) {
*stt = rh_str_uint(t, NULL);
pfree(clstate->status);
clstate->status = rh_strdup(t);
}
x = clstate->is_crlf == YES ? CSTR_SZ("\r\n") : CSTR_SZ("\n");
d = rh_memmem(us, rsz,
clstate->is_crlf == YES ? "\r\n" : "\n", x);
if (d) s = d+x;
goto _done;
}
}
/* Match custom "Status: 404 Not Found" pseudoheader used by werc for example */
s = us = rdata;
if (!strncmp(s, "Status: ", CSTR_SZ("Status: "))) {
s += CSTR_SZ("Status: ");
rh_strlcpy_real(t, s, sizeof(t));
if (is_number(t, NO) == YES) {
*stt = rh_str_uint(t, NULL);
pfree(clstate->status);
clstate->status = rh_strdup(t);
}
x = clstate->is_crlf == YES ? CSTR_SZ("\r\n") : CSTR_SZ("\n");
d = rh_memmem(us, rsz,
clstate->is_crlf == YES ? "\r\n" : "\n", x);
if (d) s = d+x;
goto _done;
}
/* No header matched - continue as successful */
*stt = 200;
rh_asprintf(&clstate->status, "200");
_done: return s-us;
}
static void force_timeout_exit(int sig)
{
block_signals(YES, SIGALRM, 0);
if (clstate->nr_requests == 0) {
char *s = NULL;
getdatetime(&s, rh_timefmt);
rh_asprintf(&clstate->altlogline,
"[%s]:%s [%s] %u no data received before timeout",
clstate->ipaddr, clstate->clinfo->port, s, clstate->clinfo->pid);
pfree(s);
write_log_line(clstate);
}
rh_exit(0);
}
static void install_us_alarm(unsigned long long useconds)
{
struct itimerval it;
rh_memzero(&it, sizeof(struct itimerval));
useconds_to_timeval(useconds, &it.it_value);
setitimer(ITIMER_REAL, &it, NULL);
}
static void set_timeout_alarm(unsigned long secs)
{
install_us_alarm(0ULL);
if (secs > 0) {
signal(SIGALRM, force_timeout_exit);
install_us_alarm(secs * 1000000ULL);
}
else signal(SIGALRM, SIG_IGN);
}
static void client_atexit(int status)
{
close(clstate->clinfo->clfd);
if (clstate->clinfo->logfd != -1)
close(clstate->clinfo->logfd);
}
static void signal_exit(int sig)
{
block_signals(YES, sig, 0);
if (sig == SIGTERM
|| sig == SIGPIPE) { /* killed by CGI or improper pipe usage */
if (!clstate->status) rh_asprintf(&clstate->status, "200");
clstate->nr_requests++;
write_log_line(clstate);
}
xexits("client: exited by signal %d", sig);
}
static void destroy_argv(char ***argv)
{
size_t sz, x;
char **uargv = *argv;
sz = DYN_ARRAY_SZ(uargv);
for (x = 0; x < sz; x++)
pfree(*(uargv+x));
rh_free(uargv); *argv = NULL;
}
struct dir_items {
char *it_name; /* item file name, or relative path in tar archive */
int it_type; /* PATH_IS_FILE or PATH_IS_DIR */
rh_fsize it_size; /* item size */
mode_t it_mode; /* item Unix chmod */
uid_t it_owner; /* item Unix owner */
gid_t it_group; /* item Unix group */
time_t it_mtime; /* item modification time */
};
#define DI_SORTBY_NAME 1
#define DI_SORTBY_TYPE 2
#define DI_SORTBY_SIZE 3
#define DI_SORTBY_OWNER 4
#define DI_SORTBY_GROUP 5
#define DI_SORTBY_MTIME 6
static int di_sortby = DI_SORTBY_NAME;
static rh_yesno di_reverse_sort;
static int dir_sort_compare(const void *pdi1, const void *pdi2)
{
const struct dir_items *di1 = pdi1;
const struct dir_items *di2 = pdi2;
if (di_reverse_sort == YES) {
di1 = pdi2;
di2 = pdi1;
}
if (di_sortby == DI_SORTBY_NAME) {
_fallback: return strcmp(di1->it_name, di2->it_name);
}
else if (di_sortby == DI_SORTBY_TYPE) {
if (di1->it_type == PATH_IS_DIR && di2->it_type != PATH_IS_DIR) return -1;
else if (di1->it_type == di2->it_type) goto _fallback;
else return 1;
}
else if (di_sortby == DI_SORTBY_SIZE) {
if (di1->it_size > di2->it_size) return -1;
else if (di1->it_size == di2->it_size) goto _fallback;
else return 1;
}
else if (di_sortby == DI_SORTBY_OWNER) {
if (di1->it_owner < di2->it_owner) return -1;
else if (di1->it_owner == di2->it_owner) goto _fallback;
else return 1;
}
else if (di_sortby == DI_SORTBY_GROUP) {
if (di1->it_group < di2->it_group) return -1;
else if (di1->it_group == di2->it_group) goto _fallback;
else return 1;
}
else if (di_sortby == DI_SORTBY_MTIME) {
if (di1->it_mtime > di2->it_mtime) return -1;
else if (di1->it_mtime == di2->it_mtime) goto _fallback;
else return 1;
}
return 0;
}
static void free_dir_items(struct dir_items *di)
{
size_t sz, x;
sz = DYN_ARRAY_SZ(di);
if (sz == 0) return;
for (x = 0; x < sz; x++) pfree(di[x].it_name);
pfree(di);
}
/* TAR stuff */
struct __attribute__((__packed__)) tar_header {
char name[100];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[8];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char prefix[155];
char pad[12];
};
struct tar_fileargs {
int fd;
struct dir_items *this;
struct client_state *clstate;
size_t do_pad;
rh_yesno last_status;
};
static size_t do_tar_stream_file_reader(void *ta, void *data, size_t szdata)
{
struct tar_fileargs *uta = ta;
return io_read_data(uta->fd, data, szdata, YES, NULL);
}
static size_t do_tar_stream_file_writer(void *ta, const void *data, size_t szdata)
{
struct tar_fileargs *uta = ta;
return io_send_data(uta->clstate->clinfo, data, szdata, YES, NO);
}
static void do_tar_stream_file_mangler(void *ta, void *data, size_t szdata)
{
struct tar_fileargs *uta = ta;
if (uta->clstate->cryptpw) do_encrypt(&uta->clstate->cryptctx, data, szdata);
}
/* should be never invoked. */
static rh_fsize do_tar_stream_file_seeker(void *clstate, rh_fsize offset)
{
return NOSIZE;
}
static void do_tar_stream_file(struct tar_fileargs *ta)
{
struct io_stream_args ios_args;
size_t t;
rh_memzero(&ios_args, sizeof(struct io_stream_args));
ios_args.fn_args = ta;
ios_args.rdfn = do_tar_stream_file_reader;
ios_args.wrfn = do_tar_stream_file_writer;
ios_args.mgfn = do_tar_stream_file_mangler;
ios_args.skfn = do_tar_stream_file_seeker;
ios_args.workbuf = clstate->workbuf;
ios_args.wkbufsz = clstate->wkbufsz;
ios_args.file_size = ta->this->it_size;
ios_args.start_from = 0;
ios_args.read_to = ta->this->it_size;
ta->last_status = io_stream_file(&ios_args);
clstate->iostate = ios_args.status;
clstate->ioerror = ios_args.error;
clstate->sentbytes += ios_args.nr_written;
t = ios_args.nr_written % sizeof(struct tar_header);
ta->do_pad = (t > 0 ? sizeof(struct tar_header)-t : 0);
}
static void do_tar_pad(struct tar_fileargs *ta)
{
char pad[sizeof(struct tar_header)];
rh_memzero(pad, ta->do_pad);
if (ta->clstate->cryptpw) do_encrypt(&ta->clstate->cryptctx, pad, ta->do_pad);
response_send_data(clstate, pad, ta->do_pad);
}
static void do_tar_chksum(struct tar_header *tar)
{
unsigned char *t = (unsigned char *)tar;
size_t sum = 0, sz = sizeof(struct tar_header);
strcpy(tar->magic, "ustar ");
memset(tar->chksum, ' ', sizeof(tar->chksum));
do {
sum += *t;
t++;
} while (--sz);
rh_snprintf(tar->chksum, sizeof(tar->chksum), "%06o", sum);
}
static rh_yesno do_tar_longname(struct client_state *clstate, const char *path, const char *prependpfx, struct dir_items *di)
{
struct tar_header *tar = (struct tar_header *)((char *)clstate->workbuf + sizeof(struct tar_header));
char *t = (char *)tar + sizeof(struct tar_header);
size_t sz;
rh_memzero(tar, sizeof(struct tar_header));
rh_memzero(t, sizeof(struct tar_header));
if (!prependpfx) {
sz = rh_snprintf_real(t, sizeof(struct tar_header), "%s%s",
path, ((di->it_type == PATH_IS_DIR) ? "/" : ""));
}
else {
sz = rh_snprintf_real(t, sizeof(struct tar_header), "%s/%s%s",
prependpfx, path, ((di->it_type == PATH_IS_DIR) ? "/" : ""));
}
if (sz > sizeof(struct tar_header)) return NO;
strcpy(tar->name, "././@LongLink");
strcpy(tar->mode, "0000000");
strcpy(tar->uid, "0000000");
strcpy(tar->gid, "0000000");
strcpy(tar->mtime, "00000000000");
rh_snprintf(tar->size, sizeof(tar->size), "%011zo", sz);
tar->typeflag = 'L';
do_tar_chksum(tar);
if (clstate->cryptpw) do_encrypt(&clstate->cryptctx, tar, sizeof(struct tar_header));
response_send_data(clstate, tar, sizeof(struct tar_header));
if (clstate->cryptpw) do_encrypt(&clstate->cryptctx, t, sizeof(struct tar_header));
response_send_data(clstate, t, sizeof(struct tar_header));
return YES;
}
static rh_yesno do_tar_header(struct client_state *clstate, const char *path, const char *prependpfx, struct dir_items *di)
{
struct tar_header *tar = clstate->workbuf;
mode_t mfx;
size_t sz;
if (!strncmp(path, "./", CSTR_SZ("./"))) path += CSTR_SZ("./");
rh_memzero(tar, sizeof(struct tar_header));
if (!prependpfx) sz = rh_strlcpy_real(tar->name, path, sizeof(tar->name));
else sz = rh_snprintf_real(tar->name, sizeof(tar->name), "%s/%s", prependpfx, path);
mfx = di->it_mode & ~0177000;
rh_snprintf(tar->mode, sizeof(tar->mode), "%07o", mfx);
strcpy(tar->uid, "0000000");
strcpy(tar->gid, "0000000");
strcpy(tar->uname, "root");
strcpy(tar->gname, "wheel");
if (di->it_size <= 0x200000000ULL) {
rh_snprintf(tar->size, sizeof(tar->size), "%011llo", (size_t)di->it_size);
}
else {
char *p8 = tar->size + sizeof(tar->size);
rh_fsize fsz = di->it_size;
do {
*--p8 = (unsigned char)fsz;
fsz >>= 8;
} while (p8 != tar->size);
*p8 |= 0x80;
}
rh_snprintf(tar->mtime, sizeof(tar->mtime), "%011o", di->it_mtime);
if (di->it_type == PATH_IS_DIR) tar->typeflag = '5';
else tar->typeflag = '0';
if (sz >= (sizeof(tar->name)-1)) {
if (do_tar_longname(clstate, path, prependpfx, di) != YES) return NO;
}
else {
if (di->it_type == PATH_IS_DIR)
if (!tar->name[sizeof(tar->name)-1]) tar->name[sz] = '/';
}
do_tar_chksum(tar);
if (clstate->cryptpw) do_encrypt(&clstate->cryptctx, tar, sizeof(struct tar_header));
response_send_data(clstate, tar, sizeof(struct tar_header));
return YES;
}
#define DO_TAR_YES 0
#define DO_TAR_NO 1
#define DO_TAR_ERR -1
/*
* The following implementation of POSIX tar is very simple.
* It only reads files and recurses into directories, completely
* omitting any special files and not following (and ignoring) symlinks.
* The stat information is also somewhere forged.
* If file or directory is inaccessible, it is ignored.
*
* It does NOT handle hardlinks! If you have an http root filled with them,
* then sorry - unneeded waste of memory anyway.
*
* The recursive (and still, memory hungry) nature defaults to that this feature
* is not enabled by default and restricted.
*
* do_tar_* functions do use clstate shared temporary buffer.
* The required minimum size is three tar headers in a row (or 1536 bytes).
* Please never lower the size of temporary buffer below this number!
*/
static int do_recursive_tar(const char *dirpath, const char *prependpfx,
const char *tarincl, const char *tarexcl, rh_yesno filt_nocase)
{
DIR *dp;
struct dirent *de;
struct dir_items *di;
struct stat stst;
size_t sz, x;
struct tar_fileargs ta;
char *t;
int r = DO_TAR_NO;
/* safe to (re)set, because client code will exit or restart */
di_sortby = DI_SORTBY_TYPE;
di_reverse_sort = NO;
/* no action if impossible to read */
if (lstat(dirpath, &stst) == -1) return DO_TAR_NO;
dp = opendir(dirpath);
if (!dp) return DO_TAR_NO;
if (strcmp(dirpath, ".") != 0) {
struct dir_items dmi;
rh_memzero(&dmi, sizeof(struct dir_items));
dmi.it_type = PATH_IS_DIR;
dmi.it_size = (rh_fsize)0;
dmi.it_mode = stst.st_mode;
dmi.it_mtime = stst.st_mtime;
if (do_tar_header(clstate, dirpath, prependpfx, &dmi) != YES) goto _closeret;
}
di = NULL;
/* the code is nearly same as in ordinary dirlisting. */
while ((de = readdir(dp))) {
if (!strcmp(de->d_name, ".")
|| !strcmp(de->d_name, "..")
|| strstr(de->d_name, rh_htaccess_name)) continue;
if (clstate->hideindex_rgx
&& regex_exec(clstate->hideindex_rgx, de->d_name) == YES)
continue;
t = rh_strdup(de->d_name);
rh_prepend_str(&t, "/"); /* "/" -> "/name" */
rh_prepend_str(&t, dirpath); /* "dir/path" -> "dir/path/name" */
if (lstat(t, &stst) == -1) {
_next: pfree(t);
continue;
}
/* Not going to give special files including symlinks. */
if (!S_ISREG(stst.st_mode) && !S_ISDIR(stst.st_mode)) goto _next;
/* Skip the files not accepted by include filter set by user. */
if (tarincl && rh_fnmatch(tarincl, t, filt_nocase) != YES) goto _next;
/* Reverse of above. */
if (tarexcl && rh_fnmatch(tarexcl, t, filt_nocase) == YES) goto _next;
sz = DYN_ARRAY_SZ(di);
di = rh_realloc(di, (sz+1) * sizeof(struct dir_items));
di[sz].it_name = t;
if (S_ISDIR(stst.st_mode)) {
di[sz].it_type = PATH_IS_DIR;
di[sz].it_size = (rh_fsize)0;
}
else {
di[sz].it_type = PATH_IS_FILE;
di[sz].it_size = (rh_fsize)stst.st_size;
}
di[sz].it_mode = stst.st_mode;
di[sz].it_mtime = stst.st_mtime;
}
if (di == NULL) {
if (!strcmp(dirpath, ".")) r = DO_TAR_ERR;
else r = DO_TAR_NO;
goto _closeret;
}
sz = DYN_ARRAY_SZ(di);
qsort(di, sz, sizeof(struct dir_items), dir_sort_compare);
rh_memzero(&ta, sizeof(struct tar_fileargs));
ta.clstate = clstate;
for (x = 0; x < sz; x++) {
if (di[x].it_type == PATH_IS_DIR) {
if (do_recursive_tar(di[x].it_name, prependpfx, tarincl, tarexcl, filt_nocase) == DO_TAR_ERR) {
r = DO_TAR_ERR;
goto _closeret;
}
}
else {
#ifdef O_LARGEFILE
ta.fd = open(di[x].it_name, O_RDONLY | O_LARGEFILE);
#else
ta.fd = open(di[x].it_name, O_RDONLY);
#endif
if (ta.fd == -1) continue;
ta.this = &di[x];
if (do_tar_header(clstate, di[x].it_name, prependpfx, &di[x]) != YES) {
ta.last_status = YES;
goto _bad_tar_hdr;
}
do_tar_stream_file(&ta);
do_tar_pad(&ta);
_bad_tar_hdr: close(ta.fd);
ta.fd = -1;
if (ta.last_status != YES) {
r = DO_TAR_ERR;
goto _closeret;
}
}
}
r = DO_TAR_YES;
_closeret:
free_dir_items(di);
closedir(dp);
return r;
}
#define cgisetenv(to, fmt, ...) \
do { \
size_t sz; \
rh_asprintf(&to, fmt, __VA_ARGS__); \
sz = DYN_ARRAY_SZ(tenvp); \
tenvp = rh_realloc(tenvp, (sz+(sz == 0 ? 2 : 1)) * sizeof(char *)); \
if (sz) sz--; \
*(tenvp+sz) = rh_strdup(to); \
} while (0)
void run_client(struct client_info *clinfo)
{
size_t x, sz, n;
char *s, *d, *t;
const struct embedded_resource *rsrc;
struct embedded_resource *drsrc;
int err;
/* install client default signals */
for (err = 1; err < NSIG; err++) {
if (err == SIGPIPE