-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttp.c
More file actions
3039 lines (2844 loc) · 81 KB
/
http.c
File metadata and controls
3039 lines (2844 loc) · 81 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 __FreeBSD__
#define _XOPEN_SOURCE 500
#endif
#include "gatling.h"
#include "buffer.h"
#include "fmt.h"
#include "ip6.h"
#include "mmap.h"
#include "str.h"
#include "textcode.h"
#include "scan.h"
#include "socket.h"
#include "case.h"
#include "ip4.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#ifdef __dietlibc__
#include <md5.h>
#elif defined(USE_POLARSSL)
#include <polarssl/md5.h>
#define MD5_CTX md5_context
#define MD5Init md5_starts
#define MD5Update md5_update
#define MD5Final(out,ctx) md5_finish(ctx,out)
#else
#include <openssl/md5.h>
#define MD5Init MD5_Init
#define MD5Update MD5_Update
#define MD5Final MD5_Final
#endif
#include <errno.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <ctype.h>
#include <sys/socket.h>
#include <limits.h>
#include "havealloca.h"
char* defaultindex;
MD5_CTX md5_ctx;
char* http_header_blob(char* b,long l,char* h) {
long i;
long sl=str_len(h);
for (i=0; i+sl+2<l; ++i)
if (b[i]=='\n' && b[i+sl+1]==':' && case_equalb(b+i+1,sl,h)) {
b+=i+sl+2;
while (*b==' ' || *b=='\t') ++b;
return b;
}
return 0;
}
char* http_header(struct http_data* r,char* h) {
return http_header_blob(array_start(&r->r),array_bytes(&r->r),h);
}
static inline int issafe(unsigned char c) {
return (c!='"' && c!='%' && (c>=' ' && c<0x7f) && c!='+' && c!=':' && c!='#');
}
size_t fmt_urlencoded(char* dest,const char* src,size_t len) {
register const unsigned char* s=(const unsigned char*) src;
size_t written=0,i;
for (i=0; i<len; ++i) {
if (!issafe(s[i])) {
if (dest) {
dest[written]='%';
dest[written+1]=fmt_tohex(s[i]>>4);
dest[written+2]=fmt_tohex(s[i]&15);
}
written+=3;
} else {
if (dest) dest[written]=s[i]; ++written;
}
}
return written;
}
void catencoded(array* a,char* s) {
unsigned int len=str_len(s);
char* buf=alloca(fmt_urlencoded(0,s,len));
array_catb(a,buf,fmt_urlencoded(buf,s,len));
}
void cathtml(array* a,char* s) {
unsigned int len=str_len(s);
char* buf=alloca(fmt_html(0,s,len));
array_catb(a,buf,fmt_html(buf,s,len));
}
void cathtmlutf8(array* a,char* s) {
/* The purpose of this function is to convert a file name into UTF-8
* and escape HTML-relevant characters such as '<' and '&'. Chars that
* are not valid UTF-8 are assumed to be latin1 and converted */
size_t i,l,r;
char* buf;
r=0;
/* This will be a short string, a file name, so assuming all chars are
* '&', the max expansion is '&', i.e. *5. */
l=strlen(s);
buf=alloca(l*5);
for (i=0; i<l; ++i) {
if (s[i]&0x80) {
size_t n=scan_utf8(s+i,l-i,NULL);
if (n==0) {
r+=fmt_utf8(buf+r,(unsigned char)(s[i]));
} else {
memcpy(buf+r,s+i,n);
i+=n-1;
r+=n;
}
} else {
const char* x=0;
size_t n;
switch (s[i]) {
case '&': x="&"; n=5; break;
case '<': x="<"; n=4; break;
case '>': x=">"; n=4; break;
case '\n': x="<br>"; n=4; break;
}
if (x) {
memcpy(buf+r,x,n);
r+=n;
} else
buf[r++]=s[i];
}
}
array_catb(a,buf,r);
}
int http_dirlisting(struct http_data* h,DIR* D,const char* path,const char* arg) {
long i,o,n;
struct dirent* d;
int (*sortfun)(de*,de*);
array a,b,c;
de* ab;
byte_zero(&a,sizeof(a));
byte_zero(&b,sizeof(b));
byte_zero(&c,sizeof(c));
o=n=0;
while ((d=readdir(D))) {
de* x=array_allocate(&a,sizeof(de),n);
if (!x) break;
x->name=o;
#ifdef __MINGW32__
if (stat(d->d_name,&x->ss)==-1) continue;
#else
if (lstat(d->d_name,&x->ss)==-1) continue;
if (S_ISLNK(x->ss.st_mode)) {
struct stat tmp;
if (stat(d->d_name,&tmp)==0)
if (S_ISDIR(tmp.st_mode))
x->todir=1;
}
#endif
array_cats0(&b,d->d_name);
o+=str_len(d->d_name)+1;
++n;
}
closedir(D);
if (array_failed(&a) || array_failed(&b)) {
array_reset(&a);
array_reset(&b);
return 0;
}
base=array_start(&b);
sortfun=sort_name_a;
if (arg) {
if (str_equal(arg,"N=D")) sortfun=sort_name_d;
else if (str_equal(arg,"N=A")) sortfun=sort_name_a;
else if (str_equal(arg,"M=A")) sortfun=sort_mtime_a;
else if (str_equal(arg,"M=D")) sortfun=sort_mtime_d;
else if (str_equal(arg,"S=A")) sortfun=sort_size_a;
else if (str_equal(arg,"S=D")) sortfun=sort_size_d;
}
qsort(array_start(&a),n,sizeof(de),(int(*)(const void*,const void*))sortfun);
array_cats(&c,"<title>Index of ");
array_cats(&c,path);
array_cats(&c,"</title>\n<h1>Index of ");
array_cats(&c,path);
{
char* tmp=http_header(h,"User-Agent");
/* don't give wget the column sorting interface so wget -m does not
* mirror it needlessly */
if (tmp && byte_equal(tmp,5,"Wget/"))
array_cats(&c,"</h1>\n<table><tr><th>Name<th>Last Modified<th>Size\n");
else {
array_cats(&c,"</h1>\n<table><tr><th><a href=\"?N=");
array_cats(&c,sortfun==sort_name_a?"D":"A");
array_cats(&c,"\">Name</a><th><a href=\"?M=");
array_cats(&c,sortfun==sort_mtime_a?"D":"A");
array_cats(&c,"\">Last Modified</a><th><a href=\"?S=");
array_cats(&c,sortfun==sort_size_a?"D":"A");
array_cats(&c,"\">Size</a>\n");
}
}
ab=array_start(&a);
for (i=0; i<n; ++i) {
char* name=base+ab[i].name;
char buf[31];
int j;
struct tm* x=localtime(&ab[i].ss.st_mtime);
if (name[0]=='.') {
if (name[1]==0) continue; /* skip "." */
if (name[1]!='.' || name[2]!=0) /* skip dot-files */
continue;
}
if (name[0]==':') name[0]='.';
array_cats(&c,"<tr><td><a href=\"");
catencoded(&c,base+ab[i].name);
if (S_ISDIR(ab[i].ss.st_mode) || ab[i].todir) array_cats(&c,"/");
array_cats(&c,"\">");
cathtmlutf8(&c,base+ab[i].name);
#ifndef __MINGW32__
if (S_ISLNK(ab[i].ss.st_mode)) array_cats(&c,"@"); else
#endif
if (S_ISDIR(ab[i].ss.st_mode)) array_cats(&c,"/");
array_cats(&c,"</a><td>");
j=fmt_2digits(buf,x->tm_mday);
j+=fmt_str(buf+j,"-");
byte_copy(buf+j,3,months+3*x->tm_mon); j+=3;
j+=fmt_str(buf+j,"-");
j+=fmt_2digits(buf+j,(x->tm_year+1900)/100);
j+=fmt_2digits(buf+j,(x->tm_year+1900)%100);
j+=fmt_str(buf+j," ");
j+=fmt_2digits(buf+j,x->tm_hour);
j+=fmt_str(buf+j,":");
j+=fmt_2digits(buf+j,x->tm_min);
array_catb(&c,buf,j);
array_cats(&c,"<td align=right>");
array_catb(&c,buf,fmt_humank(buf,ab[i].ss.st_size));
}
array_cats(&c,"</table>");
array_reset(&a);
array_reset(&b);
if (array_failed(&c)) return 0;
h->bodybuf=array_start(&c);
h->blen=array_bytes(&c);
return 1;
}
int buffer_putlogstr(buffer* b,const char* s) {
unsigned long l;
char* x;
for (l=0; s[l] && s[l]!='\r' && s[l]!='\n'; ++l) ;
if (!l) return 0;
x=alloca(l);
return buffer_put(b,x,fmt_foldwhitespace(x,s,l));
}
#ifdef SUPPORT_PROXY
int add_proxy(const char* c) {
struct cgi_proxy* x=malloc(sizeof(struct cgi_proxy));
int i;
if (!x) return -1;
byte_zero(x,sizeof(struct cgi_proxy));
if (c[1]=='/') {
if (c[0]=='F')
x->proxyproto=FASTCGI;
else if (c[0]=='S')
x->proxyproto=SCGI;
else if (c[0]=='H')
x->proxyproto=HTTP;
else
goto nixgut;
c+=2;
}
if (*c=='|') {
const char* d;
++c;
d=strchr(c,'|');
if (!d) goto nixgut;
if (d-c>sizeof(x->uds.sun_path)) goto nixgut;
x->port=-1;
x->uds.sun_family=AF_UNIX;
memcpy(x->uds.sun_path,c,d-c);
c=d+1;
} else {
uint16 tmp;
i=scan_ip6if(c,x->ip,&x->scope_id);
if (c[i]!='/') { nixgut: free(x); return -1; }
c+=i+1;
i=scan_ushort(c,&tmp);
x->port=tmp;
if (c[i]!='/') goto nixgut;
c+=i+1;
}
if (regcomp(&x->r,c,REG_EXTENDED)) goto nixgut;
if (!last)
cgis=last=x;
else
last->next=x; last=x;
return 0;
}
static size_t fmt_strblob(char* dst,const char* str,const char* blob,size_t n) {
size_t x;
if (!dst) return strlen(str)+n+1;
x=fmt_str(dst,str);
memcpy(dst+x,blob,n);
x+=n;
dst[x]='\n';
return x+1;
}
static size_t fmt_cgivars(char* dst,struct http_data* h,const char* uri,size_t urilen,const char* vhostdir,size_t* headers) {
/* input:
* dst: destination buffer, may be NULL
* h: http context, used to get to HTTP request
* uri: pointer to decoded URI, truncated at '?', after leading '/'
* urilen: last char in regex match
* uri="script.php/path_info"
* ^ uri+urilen
* vhostdir: virtual hosting dir, e.g. "www.fefe.de:80" or "default"
* needs global: char serverroot[]
* output:
* returns number of bytes written to dst
* if dst is NULL, returns number of buffer size needed
* writes environment entries to dst, separated by \n
* writes count of headers written to *headers if non-NULL
*/
char remoteaddr[IP6_FMT];
char myaddr[IP6_FMT];
char tmp[FMT_ULONG];
size_t n,s,hc;
s=0;
while (urilen && uri[0]=='/') { ++uri; --urilen; }
remoteaddr[fmt_ip6c(remoteaddr,h->peerip)]=0;
myaddr[fmt_ip6c(myaddr,h->myip)]=0;
{
char* x=http_header(h,"Content-Length");
if (x) {
size_t j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
n=fmt_strblob(dst,"CONTENT_LENGTH=",x,j);
} else {
n=fmt_str(dst,"CONTENT_LENGTH=0\n");
}
s+=n; if (dst) dst+=n;
}
n=fmt_strm(dst,"SERVER_SOFTWARE=gatling\n"); s+=n; if (dst) dst+=n;
{
char* x=http_header(h,"Host");
if (x) {
size_t j;
for (j=0; x[j]!=':' && x[j]!='\r' && x[j]!='\n'; ++j) ;
n=fmt_strblob(dst,"SERVER_NAME=",x,j);
} else
n=fmt_strm(dst,"SERVER_NAME=",remoteaddr,"\n");
s+=n; if (dst) dst+=n;
}
n=fmt_strm(dst,"SERVER_ADDR=",myaddr,"\n"); s+=n; if (dst) dst+=n;
tmp[fmt_ulong(tmp,h->myport)]=0;
n=fmt_strm(dst,"SERVER_PORT=",tmp,"\n"); s+=n; if (dst) dst+=n;
n=fmt_strm(dst,"REMOTE_ADDR=",remoteaddr,"\n"); s+=n; if (dst) dst+=n;
tmp[fmt_ulong(tmp,h->peerport)]=0;
n=fmt_strm(dst,"REMOTE_PORT=",tmp,"\n"); s+=n; if (dst) dst+=n;
n=fmt_strm(dst,"DOCUMENT_ROOT=",serverroot,"/",vhostdir,"\n"); s+=n; if (dst) dst+=n;
n=fmt_strm(dst,"GATEWAY_INTERFACE=CGI/1.1\nSERVER_PROTOCOL=HTTP/1.1\n"); s+=n; if (dst) dst+=n;
{
char* x=array_start(&h->r);
size_t z,y=str_chr(x,' ');
n=fmt_strblob(dst,"REQUEST_METHOD=",x,y); s+=n; if (dst) dst+=n;
x+=y+1;
y=str_chr(x,' ');
/* REQUEST_URI is not actually part of the CGI 1.1 spec (RFC3875) */
n=fmt_strblob(dst,"REQUEST_URI=",x,y); s+=n; if (dst) dst+=n;
z=byte_chr(x,y,'?')+1;
if (z<y) {
n=fmt_strblob(dst,"QUERY_STRING=",x+z,y-z); s+=n; if (dst) dst+=n;
}
n=fmt_strblob(dst,"SCRIPT_NAME=/",uri,urilen); s+=n; if (dst) dst+=n;
n=fmt_strm(dst,"SCRIPT_FILENAME=",serverroot,"/",vhostdir); s+=n; if (dst) dst+=n;
n=fmt_strblob(dst,"/",uri,urilen); s+=n; if (dst) dst+=n;
if (uri[urilen]=='/') { /* we have a PATH_INFO */
/* the situation is like this:
uri="script.cgi/pathinfo"
^urilen
*/
n=fmt_strm(dst,"PATH_INFO=",uri+urilen,"\n"); s+=n; if (dst) dst+=n;
/* PATH_TRANSLATED is "$PWD$PATH_INFO" */
while (uri[urilen]=='/') ++urilen;
n=fmt_strm(dst,"PATH_TRANSLATED=",serverroot,"/",vhostdir,"/",uri+urilen,"\n"); s+=n; if (dst) dst+=n;
}
}
hc=17;
if (h->proxyproto==SCGI) {
n=fmt_strm(dst,"SCGI=1\n"); s+=n; if (dst) dst+=n;
++hc;
}
#ifdef SUPPORT_HTTPS
if (h->t == HTTPSPOST) {
n=fmt_strm(dst,"HTTPS=1\n"); s+=n; if (dst) dst+=n;
++hc;
}
#endif
/* now translate all header lines into HTTP_* */
/* for example Accept: -> HTTP_ACCEPT= */
{
char* x=array_start(&h->r);
char* max=x+array_bytes(&h->r);
for (; x<max && *x!='\n'; ++x) ;
while (x) {
char* olddst=dst;
++x;
if (*x<=' ') break;
if (!case_starts(x,"Content-Length:") && !case_starts(x,"Content-Type:")) {
n=fmt_strm(dst,"HTTP_"); s+=n; if (dst) dst+=n;
}
while (*x!=':') {
char c=*x;
if (c>='a' && c<='z') c-='a'-'A'; /* toupper */
if (c=='-') c='_'; else
if (c<'A' || c>'Z') {
dst=olddst;
goto skipheader;
}
if (dst) { *dst=c; ++dst; } ++s;
++x;
}
if (dst) { *dst='='; ++dst; } ++s;
++x; while (*x==' ') ++x;
{
char* start=x;
while (*x && *x!='\r' && *x!='\n') ++x;
n=x-start;
if (dst) { byte_copy(dst,n,start); dst+=n+1; dst[-1]='\n'; } s+=n+1;
}
++hc;
skipheader:
x=strchr(x,'\n');
}
if (headers) *headers=hc;
}
return s;
}
static int proxy_connection(int sockfd,char* c,const char* dir,struct http_data* ctx_for_sockfd,int isexec,const char* args) {
/* c is the filename
* dir is the virtual hosting dir ("www.fefe.de:80")
* the current working directory is inside the virtual hosting dir */
struct cgi_proxy* x=cgis;
struct stat ss;
regmatch_t matches;
/* if isexec is set, we already found that .proxy is there */
if (!isexec && stat(".proxy",&ss)==-1) return -3;
while (x) {
if (x->file_executable && (!isexec || x->port)) {
x=x->next;
continue;
}
matches.rm_so=matches.rm_eo=0;
if (x->file_executable || regexec(&x->r,c,1,&matches,0)==0) {
/* if the port is zero, then use local execution proxy mode instead */
int fd_to_gateway;
struct http_data* ctx_for_gatewayfd;
char* d=c;
while (*d=='/') ++d;
ctx_for_sockfd->proxyproto=x->proxyproto;
if (!(ctx_for_gatewayfd=(struct http_data*)malloc(sizeof(struct http_data)))) return -1;
byte_zero(ctx_for_gatewayfd,sizeof(struct http_data));
ctx_for_gatewayfd->filefd=-1;
if (!x->file_executable) {
#if 0
printf("%u %u\n",matches.rm_so,matches.rm_eo);
printf("got data \"%s\"\n",c+matches.rm_eo);
#endif
/* for SCGI and FASTCGI we expect the file to exist */
if (x->proxyproto == SCGI || x->proxyproto == FASTCGI) {
struct stat ss;
/* does the file actually exist? */
if (stat(d,&ss)) {
if (errno==ENOTDIR) { /* we have PATH_INFO */
char save=c[matches.rm_eo];
int r;
c[matches.rm_eo]=0;
r=stat(d,&ss);
c[matches.rm_eo]=save;
if (r) goto freeandfail;
} else {
freeandfail:
free(ctx_for_gatewayfd);
return -1;
}
}
}
ctx_for_gatewayfd->proxyproto=x->proxyproto;
if (x->proxyproto == SCGI) {
size_t l=fmt_cgivars(0,ctx_for_sockfd,c,matches.rm_eo,dir,0);
char* x,* y;
/* array_allocate gets the index of the last element you want
* to access, not the number of bytes; so +1, not +2 */
if (!array_allocate(&ctx_for_gatewayfd->r,1,l+fmt_ulong(0,l)+1))
goto freeandfail;
x=array_start(&ctx_for_gatewayfd->r);
x+=fmt_ulong(x,l);
*x++=':';
y=x;
x+=fmt_cgivars(x,ctx_for_sockfd,c,matches.rm_eo,dir,0);
/* fmt_cgivars uses "FOO=bar\n" but we want "FOO\000bar\000" */
while (y<x) {
if (*y=='=') {
*y=0;
while (y<x) {
if (*y=='\n') { *y=0; break; }
++y;
}
}
++y;
}
*x=',';
} else if (x->proxyproto == FASTCGI) {
size_t hc;
size_t l=fmt_cgivars(0,ctx_for_sockfd,c,matches.rm_eo,dir,&hc);
char* x,* y;
/* fmt_cgivars writes "FOO=barbaz\n" but we need
* "\003\006FOObarbaz"; if a key or value is longer than 127,
* the length takes up four bytes instead of one. A
* conservative upper bound on additional space used is
* thus the number of headers (hc) times 6. */
/* space calculation with fastcgi boilerplate overhead:
* 16 for {FCGI_BEGIN_REQUEST, 1, {FCGI_RESPONDER, 0}}
* 8 for {FCGI_PARAMS, 1, ...}
* l for the actual params
* 8 for {FCGI_PARAMS, 1, ""}
* 8 for {FCGI_STDIN, 1, ""}
*/
if (!array_allocate(&ctx_for_gatewayfd->r,1,l+hc*6+16+8+8+8+2))
goto freeandfail;
x=array_start(&ctx_for_gatewayfd->r);
byte_copy(x,24,"\x01\x01\x00\x01\x00\x08\x00\x00" /* FCGI_Record: FCGI_BEGIN_REQUEST (1) */
"\x00\x01\x00\x00\x00\x00\x00\x00" /* FCGI_BeginRequestBody */
"\x01\x04\x00\x01\x00\x00\x00\x00" /* FCGI_Record: FCGI_PARAMS (4) */
);
/* We need to convert the key-value pairs, but unfortunately
* that expansion may require more space than the unexpanded
* version. So we allocate for the worst case and write the
* original towards the end of the allocated space, so we can
* expand inside the same buffer. */
y=x+hc*6+16+8+8+8+2;
fmt_cgivars(y,ctx_for_sockfd,c,matches.rm_eo,dir,&hc);
x+=24;
{
size_t a=0;
size_t b;
size_t kl,vl,prev;
for (b=kl=vl=prev=0; b<l; ++b) {
if (y[b]=='=' && kl==0) {
kl=b-prev;
prev=b+1;
} else if (y[b]=='\n') {
vl=b-prev;
prev=b+1;
if (kl<127) {
x[a]=kl;
++a;
} else {
uint32_pack_big(x+a,kl|0x80000000u);
a+=4;
}
if (vl<127) {
x[a]=vl;
++a;
} else {
uint32_pack_big(x+a,vl|0x80000000u);
a+=4;
}
byte_copy(x+a,kl,y+b-vl-kl-1); a+=kl;
byte_copy(x+a,vl,y+b-vl); a+=vl;
kl=0; vl=0;
}
}
x[a]=x[a+1]=0; a+=2;
x[-4]=a>>8; /* adjust length field in FCGI_Record */
x[-3]=a&0xff;
array_truncate(&ctx_for_gatewayfd->r,1,a+24+8+8);
x+=a;
byte_copy(x,8,"\x01\x04\x00\x01\x00\x00\x00\x00"); /* FCGI_Record: FCGI_PARAMS (4) */
x+=8;
{
char* cl=http_header(ctx_for_sockfd,"Content-Length");
unsigned long long content_length=0;
if (cl) {
char c;
if ((c=cl[scan_ulonglong(cl,&content_length)])!='\r' && c!='\n') content_length=0;
}
if (content_length)
array_truncate(&ctx_for_gatewayfd->r,1,a+24+8); /* shave off 8 bytes */
else {
byte_copy(x,8,"\x01\x05\x00\x01\x00\x00\x00\x00"); /* FCGI_Record: FCGI_STDIN (5) */
x+=8;
}
}
}
} else if (x->proxyproto==HTTP) {
size_t size_of_header=header_complete(ctx_for_sockfd,sockfd);
size_t i;
char* x=array_start(&ctx_for_sockfd->r);
for (i=0; i<size_of_header && x[i]!='\n'; ++i)
if (x[i]==0) x[i]=' ';
array_catb(&ctx_for_gatewayfd->r,x,size_of_header);
}
}
if (logging) {
char buf[IP6_FMT+10];
char* tmp;
const char* method="???";
{
int x;
x=fmt_ip6c(buf,ctx_for_gatewayfd->myip);
x+=fmt_str(buf+x,"/");
x+=fmt_ulong(buf+x,ctx_for_gatewayfd->myport);
buf[x]=0;
}
tmp=array_start(&ctx_for_sockfd->r);
#ifdef SUPPORT_HTTPS
switch (*tmp) {
case 'H': method=(ctx_for_sockfd->t==HTTPREQUEST)?"HEAD":"HEAD/SSL"; break;
case 'G': method=(ctx_for_sockfd->t==HTTPREQUEST)?"GET":"GET/SSL"; break;
case 'P':
if (tmp[1]=='O')
method=(ctx_for_sockfd->t==HTTPREQUEST)?"POST":"POST/SSL";
#ifdef SUPPORT_DAV
else if (tmp[1]=='R')
method=(ctx_for_sockfd->t==HTTPREQUEST)?"PROPFIND":"PROPFIND/SSL";
#endif
else
method=(ctx_for_sockfd->t==HTTPREQUEST)?"PUT":"PUT/SSL";
break;
}
#else
switch (*tmp) {
case 'H': method="HEAD"; break;
case 'G': method="GET"; break;
case 'P': method=(tmp[1]=='O')?"POST":
#ifdef SUPPORT_DAV
((tmp[1]=='R')?"PROPFIND":"PUT");
#else
"PUT";
#endif
break;
}
#endif
buffer_putm(buffer_1,method,x->port?"/PROXY ":"/CGI ");
buffer_putulong(buffer_1,sockfd);
buffer_puts(buffer_1," ");
buffer_putlogstr(buffer_1,c);
if (args) {
buffer_puts(buffer_1,"?");
buffer_putlogstr(buffer_1,args);
}
buffer_puts(buffer_1," 0 ");
buffer_putlogstr(buffer_1,(tmp=http_header(ctx_for_sockfd,"User-Agent"))?tmp:"[no_user_agent]");
buffer_puts(buffer_1," ");
buffer_putlogstr(buffer_1,(tmp=http_header(ctx_for_sockfd,"Referer"))?tmp:"[no_referrer]");
buffer_puts(buffer_1," ");
buffer_putlogstr(buffer_1,(tmp=http_header(ctx_for_sockfd,"Host"))?tmp:buf);
buffer_putsflush(buffer_1,"\n");
}
++rps1;
if (x->port) {
/* proxy mode */
if (x->port>0xffff) { /* unix domain socket mode */
fd_to_gateway=socket(AF_UNIX,SOCK_STREAM,0);
} else
fd_to_gateway=socket_tcp6();
#ifdef STATE_DEBUG
ctx_for_gatewayfd->myfd=fd_to_gateway;
#endif
if (fd_to_gateway==-1) goto punt2;
changestate(ctx_for_gatewayfd,PROXYSLAVE);
if (!io_fd(fd_to_gateway)) {
punt:
io_close(fd_to_gateway);
punt2:
array_reset(&ctx_for_gatewayfd->r);
free(ctx_for_gatewayfd);
return -1;
}
io_block(fd_to_gateway);
io_eagain(fd_to_gateway);
if (x->port>0xffff) {
if (connect(fd_to_gateway,(struct sockaddr*)&x->uds,sizeof(x->uds))==-1)
if (errno!=EINPROGRESS)
goto punt;
} else {
if (socket_connect6(fd_to_gateway,x->ip,x->port,x->scope_id)==-1)
if (errno!=EINPROGRESS)
goto punt;
}
io_fd_canwrite(fd_to_gateway);
if (logging) {
char tmp[100];
char bufsockfd[FMT_ULONG];
char bufs[FMT_ULONG];
char bufport[FMT_ULONG];
bufsockfd[fmt_ulong(bufsockfd,sockfd)]=0;
bufs[fmt_ulong(bufs,fd_to_gateway)]=0;
if (x->port>0xffff) {
buffer_putm(buffer_1,"proxy_connect ",bufsockfd," ",bufs," ",x->uds.sun_path," ");
} else {
bufport[fmt_ulong(bufport,x->port)]=0;
tmp[fmt_ip6ifc(tmp,x->ip,x->scope_id)]=0;
buffer_putm(buffer_1,"proxy_connect ",bufsockfd," ",bufs," ",tmp,"/",bufport," ");
}
buffer_putlogstr(buffer_1,c);
buffer_putnlflush(buffer_1);
}
io_wantwrite(fd_to_gateway);
#ifdef SUPPORT_CGI
} else {
/* local CGI mode */
uint32 a,len; uint16 b;
pid_t pid;
size_t reqlen;
char* req=array_start(&ctx_for_sockfd->r); /* "GET /t.cgi/foo/bar?fnord HTTP/1.0\r\nHost: localhost:80\r\n\r\n"; */
char ra[IP6_FMT];
req[strlen(req)]=' ';
{
char* tmp;
reqlen=0;
for (tmp=req; tmp; tmp=strchr(tmp,'\n')) {
if (tmp[1]=='\r' && tmp[2]=='\n') {
reqlen=tmp+2-req;
break;
} else if (tmp[1]=='\n') {
reqlen=tmp+1-req;
break;
}
++tmp;
}
}
ctx_for_sockfd->keepalive=0;
ra[fmt_ip6c(ra,ctx_for_sockfd->peerip)]=0;
a=reqlen; write(forksock[0],&a,4);
a=strlen(dir); write(forksock[0],&a,4);
a=strlen(ra); write(forksock[0],&a,4);
write(forksock[0],req,reqlen);
write(forksock[0],dir,strlen(dir));
write(forksock[0],ra,strlen(ra));
b=ctx_for_sockfd->peerport; write(forksock[0],&b,2);
b=ctx_for_sockfd->myport; write(forksock[0],&b,2);
#ifdef SUPPORT_HTTPS
{
char ssl=ctx_for_sockfd->t==HTTPSREQUEST;
write(forksock[0],&ssl,1);
}
#endif
read(forksock[0],&a,4); /* code; 0 means OK */
read(forksock[0],&len,4); /* length of error message */
read(forksock[0],&pid,sizeof(pid));
if (len) {
char* c=alloca(len+1);
read(forksock[0],c,len);
c[len]=0;
httperror(ctx_for_sockfd,"502 Gateway Broken",c,*ctx_for_sockfd->r.p=='H'?1:0);
free(ctx_for_gatewayfd);
return -1;
} else {
fd_to_gateway=io_receivefd(forksock[0]);
#ifdef STATE_DEBUG
ctx_for_gatewayfd->myfd=fd_to_gateway;
#endif
changestate(ctx_for_gatewayfd,PROXYPOST);
if (fd_to_gateway==-1) {
buffer_putsflush(buffer_2,"received no file descriptor for CGI\n");
free(ctx_for_gatewayfd);
return -1;
}
if (!io_fd_canwrite(fd_to_gateway)) {
httperror(ctx_for_sockfd,"502 Gateway Broken",c,*ctx_for_sockfd->r.p=='H'?1:0);
io_close(fd_to_gateway);
free(ctx_for_gatewayfd);
return -1;
}
}
#ifdef SUPPORT_HTTPS
if (ctx_for_sockfd->t==HTTPSREQUEST)
changestate(ctx_for_sockfd,HTTPSPOST);
else
#endif
changestate(ctx_for_sockfd,HTTPPOST);
if (logging) {
char bufsfd[FMT_ULONG];
char bufs[FMT_ULONG];
char bufpid[FMT_ULONG];
bufsfd[fmt_ulong(bufsfd,sockfd)]=0;
bufs[fmt_ulong(bufs,fd_to_gateway)]=0;
bufpid[fmt_ulong(bufpid,pid)]=0;
buffer_putmflush(buffer_1,"cgi_fork ",bufsfd," ",bufs," ",bufpid,"\n");
}
#endif
}
ctx_for_gatewayfd->buddy=sockfd;
ctx_for_sockfd->buddy=fd_to_gateway;
io_setcookie(fd_to_gateway,ctx_for_gatewayfd);
/* Have:
* - the header and possibly some data left in ctx_for_sockfd->r.
* Want:
* - leave the data (not the header) in ctx_for_sockfd->r.
* - set ctx_for_gatewayfd->still_to_copy to Content-Length.
* - set ctx_for_sockfd->still_to_copy to Content-Length -
* the size of the copied data. If that is non-zero, set t to
* HTTPPOST.
*/
{
char* cl=http_header(ctx_for_sockfd,"Content-Length");
unsigned long long content_length=0;
if (cl) {
char c;
if ((c=cl[scan_ulonglong(cl,&content_length)])!='\r' && c!='\n') content_length=0;
}
ctx_for_gatewayfd->still_to_copy=content_length;
/* If the client sent "Expect: 100-continue", do so */
{
char* e=http_header(ctx_for_sockfd,"Expect");
if (e && byte_equal(e,4,"100-")) {
const char contmsg[]="HTTP/1.1 100 Continue\r\n\r\n";
/* if this fails, tough luck. I'm not bloating my state
* engine for this crap. */
#ifdef SUPPORT_HTTPS
if (ctx_for_sockfd->t==HTTPSREQUEST)
#if defined(USE_OPENSSL)
SSL_write(ctx_for_sockfd->ssl,contmsg,sizeof(contmsg)-1);
#elif defined(USE_POLARSSL)
ssl_write(&ctx_for_sockfd->ssl,(const unsigned char*)contmsg,sizeof(contmsg)-1);
#else
#warn fixme update SSL code in http.c
#endif
else
#endif
io_trywrite(sockfd,contmsg,sizeof(contmsg)-1);
}
}
/* figure out how much data we have */
{
size_t size_of_header=header_complete(ctx_for_sockfd,sockfd);
size_t size_of_data_in_packet=array_bytes(&ctx_for_sockfd->r) - size_of_header - 1;
/* the -1 is for the \0 we appended */
// printf("proxy_connection: size_of_header=%lu, size_of_data_in_packet=%lu, content_length=%lu\n",size_of_header,size_of_data_in_packet,content_length);
#ifdef SUPPORT_HTTPS
if (ctx_for_sockfd->t==HTTPSREQUEST)
changestate(ctx_for_sockfd,HTTPSPOST);
if (ctx_for_sockfd->t!=HTTPSPOST)
#endif
changestate(ctx_for_sockfd,HTTPPOST);
/* slight complication: we might have more data already than
* we need for this request, if the content length is small
* and the client uses pipelining and added the next request
* already. */
if (size_of_data_in_packet > content_length)
size_of_data_in_packet = content_length;
if (size_of_data_in_packet) {
byte_copy(array_start(&ctx_for_sockfd->r),
size_of_data_in_packet,
array_start(&ctx_for_sockfd->r)+size_of_header);
array_truncate(&ctx_for_sockfd->r,1,size_of_data_in_packet);
} else
array_trunc(&ctx_for_sockfd->r);
ctx_for_sockfd->still_to_copy=content_length;
if (ctx_for_gatewayfd->still_to_copy && array_bytes(&ctx_for_sockfd->r))
io_wantwrite(fd_to_gateway);
else
io_wantread(fd_to_gateway);
if (ctx_for_sockfd->still_to_copy)
io_wantread(sockfd);
else
io_dontwantread(sockfd);
// printf("proxy_connection: ctx_for_sockfd->still_to_copy=%lu, ctx_for_gatewayfd->still_to_copy=%lu\n",ctx_for_sockfd->still_to_copy, ctx_for_gatewayfd->still_to_copy);
}
}
if (timeout_secs)
io_timeout(fd_to_gateway,next);
return fd_to_gateway;
}
x=x->next;
}
return -2;
}
int proxy_write_header(int sockfd,struct http_data* h) {
/* assume we can write the header in full. */
/* slight complication: we need to turn keep-alive off and we need to
* add a X-Forwarded-For header so the handling web server can write
* the real IP to the log file. */
struct http_data* H=io_getcookie(h->buddy);
int i,j=0;
long hlen=array_bytes(&h->r);
char* hdr=array_start(&h->r);
char* newheader=0;
if (h->proxyproto==HTTP) {
newheader=alloca(hlen+200);
for (i=j=0; i<hlen; ) {
int k=str_chr(hdr+i,'\n');
if (k==0) break;
if (case_starts(hdr+i,"Connection: ") || case_starts(hdr+i,"X-Forwarded-For: "))
i+=k+1;
else {
byte_copy(newheader+j,k+1,hdr+i);
i+=k+1;
j+=k+1;
}
}
if (j) j-=2;
H->keepalive=0;
j+=fmt_str(newheader+j,"Connection: close\r\nX-Forwarded-For: ");
j+=fmt_ip6c(newheader+j,H->peerip);
j+=fmt_str(newheader+j,"\r\n\r\n");
} else if (h->proxyproto==FASTCGI || h->proxyproto==SCGI) {
newheader=array_start(&h->r);
j=array_bytes(&h->r);
}
if (write(sockfd,newheader,j)!=j)
return -1;
if (h->proxyproto==SCGI)
array_trunc(&h->r);
H->sent+=j;
return 0;
}
int proxy_is_readable(int sockfd,struct http_data* H) {
/* read data from proxy and queue it for writing to browser
* connection, also add "HTTP/1.0 200 OK" header if necessary */
char Buf[8194];
char* buf=Buf+1;
int i;
char* x;
struct http_data* peer=io_getcookie(H->buddy);
if (!peer) return -1;
i=read(sockfd,buf,sizeof(Buf)-2);
if (i==-1) return -1;
H->sent+=i;
/* TODO: need to parse fastcgi packets from proxy, remove fastcgi
* headers */
if (i==0) {
eof:
if (logging) {
char numbuf[FMT_ULONG];