forked from gigablast/open-source-search-engine
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathHttpRequest.cpp
1713 lines (1562 loc) · 51.3 KB
/
HttpRequest.cpp
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
#include "gb-include.h"
#include "HttpRequest.h"
#include "ip.h"
HttpRequest::HttpRequest () { m_cgiBuf = NULL; m_cgiBuf2 = NULL; reset(); }
HttpRequest::~HttpRequest() { reset(); }
char HttpRequest::getReplyFormat() {
if ( m_replyFormatValid ) return m_replyFormat;
char *formatStr = getString("format");
char format = -1;//FORMAT_HTML;
// what format should search results be in? default is html
if ( formatStr && strcmp(formatStr,"html") == 0 ) format = FORMAT_HTML;
if ( formatStr && strcmp(formatStr,"json") == 0 ) format = FORMAT_JSON;
if ( formatStr && strcmp(formatStr,"xml") == 0 ) format = FORMAT_XML;
if ( formatStr && strcmp(formatStr,"csv") == 0 ) format = FORMAT_CSV;
if ( formatStr && strcmp(formatStr,"iframe")==0)
format=FORMAT_WIDGET_IFRAME;
if ( formatStr && strcmp(formatStr,"ajax")==0)
format=FORMAT_WIDGET_AJAX;
if ( formatStr && strcmp(formatStr,"append")==0)
format=FORMAT_WIDGET_APPEND;
// support old api &xml=1 to mean &format=1
if ( getLong("xml",0) ) {
format = FORMAT_XML;
}
// also support &json=1
if ( getLong("json",0) ) {
format = FORMAT_JSON;
}
if ( getLong("csv",0) ) {
format = FORMAT_CSV;
}
if ( getLong("iframe",0) ) {
format = FORMAT_WIDGET_IFRAME;
}
if ( getLong("ajax",0) ) {
format = FORMAT_WIDGET_AJAX;
}
if ( getLong("append",0) ) {
format = FORMAT_WIDGET_APPEND;
}
// default to html
if ( format == -1 )
format = FORMAT_HTML;
m_replyFormat = format;
m_replyFormatValid = true;
return format;
}
void HttpRequest::reset() {
m_numFields = 0;
m_replyFormatValid = false;
//if ( m_cgiBuf ) mfree ( m_cgiBuf , m_cgiBufMaxLen , "HttpRequest");
m_cgiBufLen = 0;
m_cgiBuf = NULL;
m_cgiBufMaxLen = 0;
//m_buf[0] = '\0';
//m_bufLen = 0;
m_path = NULL;
m_plen = 0;
m_ucontent = NULL;
m_ucontentLen = 0;
m_cookiePtr = NULL;
m_cookieLen = 0;
m_userIP = 0;
m_isMSIE = false;
m_reqBufValid = false;
m_reqBuf.purge();
if (m_cgiBuf2) {
mfree(m_cgiBuf2, m_cgiBuf2Size, "extraParms");
m_cgiBuf2 = NULL;
}
m_cgiBuf2Size = 0;
}
// returns false with g_errno set on error
bool HttpRequest::copy ( class HttpRequest *r , bool stealBuf ) {
gbmemcpy ( this , r , sizeof(HttpRequest) );
// do not copy this over though in that way
m_reqBuf.m_capacity = 0;
m_reqBuf.m_length = 0;
//m_reqBuf.m_buf = NULL;
m_reqBuf.m_usingStack = false;
m_reqBuf.m_encoding = csUTF8;
if ( stealBuf ) {
// if he's on the stack, that's a problem!
if ( r->m_reqBuf.m_usingStack ) { char *xx=NULL;*xx=0; }
// copy the safebuf member var directly
gbmemcpy ( &m_reqBuf , &r->m_reqBuf , sizeof(SafeBuf) );
// do not let it free anything
r->m_reqBuf.m_usingStack = true;
// that's it!
return true;
}
// otherwise we copy it and update the ptrs below
if ( ! m_reqBuf.safeMemcpy ( &r->m_reqBuf ) )
return false;
// fix ptrs
char *sbuf = r->m_reqBuf.getBufStart();
char *dbuf = m_reqBuf.getBufStart();
for ( int32_t i = 0 ; i < m_numFields ; i++ ) {
m_fields [i] = dbuf + (r->m_fields [i] - sbuf);
m_fieldValues[i] = NULL;
if ( r->m_fieldValues[i] )
m_fieldValues[i] = dbuf + (r->m_fieldValues[i] - sbuf);
}
m_cookiePtr = dbuf + (r->m_cookiePtr - sbuf );
m_metaCookie = dbuf + (r->m_metaCookie - sbuf );
m_ucontent = dbuf + (r->m_ucontent - sbuf );
m_path = dbuf + (r->m_path - sbuf );
m_cgiBuf = dbuf + (r->m_cgiBuf - sbuf );
// not supported yet. we'd have to allocate it
if ( m_cgiBuf2 ) { char *xx=NULL;*xx=0; }
return true;
}
#define RT_GET 0
#define RT_HEAD 1
#define RT_POST 2
#define RT_CONNECT 3
// TODO: ensure not sent to a proxy server since it will expect us to close it
// TODO: use chunked transfer encodings to do HTTP/1.1
// . form an HTTP request
// . use size 0 for HEAD requests
// . use size -1 for GET whole doc requests
// . fill in your own offset/size for partial GET requests
// . returns false and sets g_errno on error
// . NOTE: http 1.1 uses Keep-Alive by default (use Connection: close to not)
bool HttpRequest::set (char *url,int32_t offset,int32_t size,time_t ifModifiedSince,
char *userAgent , char *proto , bool doPost ,
char *cookie , char *additionalHeader ,
// if posting something, how many bytes is it?
int32_t postContentLen ,
// are we sending the request through an http proxy?
// if so this will be non-zero
int32_t proxyIp ,
char *proxyUsernamePwd ) {
m_reqBufValid = false;
int32_t hlen ;
int32_t port = 80;
char *hptr = getHostFast ( url , &hlen , &port );
char *path = getPathFast ( url );
// . use the full url if sending to an http proxy
// . HACK: do NOT do this if it is httpS because we end up
// using the http tunnel using the CONNECT cmd and the squid proxy
// will just forward/proxy just the entire tcp packets.
if ( proxyIp && strncmp(url,"https://",8) != 0 ) path = url;
char *pathEnd = NULL;
char *postData = NULL;
if ( doPost ) {
pathEnd = strstr(path,"?");
if ( pathEnd ) {
*pathEnd = '\0';
postData = pathEnd + 1;
}
}
// if no legit host
if ( hlen <= 0 || ! hptr ) { g_errno = EBADURL; return false; }
// sanity check. port is only 16 bits
if ( port > (int32_t)0xffff ) { g_errno = EBADURL; return false; }
// return false and set g_errno if url too big
//if ( url->getUrlLen() + 400 >= MAX_REQ_LEN ) {
// g_errno = EURLTOOBIG; return false;}
// assume request type is a GET
m_requestType = RT_GET;//0;
// get the host NULL terminated
char host[1024+8];
//int32_t hlen = url->getHostLen();
strncpy ( host , hptr , hlen );
host [ hlen ] = '\0';
// then port
//uint16_t port = url->getPort();
if ( port != 80 ) {
sprintf ( host + hlen , ":%"UINT32"" , (uint32_t)port );
hlen += gbstrlen ( host + hlen );
}
// the if-modified-since field
char ibuf[64];
char *ims = "";
if ( ifModifiedSince ) {
// NOTE: ctime appends a \n
sprintf(ibuf,"If-Modified-Since: %s UTC",
asctime(gmtime(&ifModifiedSince)));
// get the length
int32_t ilen = gbstrlen(ibuf);
// hack off \n from ctime - replace with \r\n\0
ibuf [ ilen - 1 ] = '\r';
ibuf [ ilen ] = '\n';
ibuf [ ilen + 1 ] = '\0';
// set ims to this string
ims = ibuf;
}
// . until we fix if-modified-since, take it out
// . seems like we are being called with it as true when should not be
ims="";
// . use one in conf file if caller did not provide
// . this is usually Gigabot/1.0
if ( ! userAgent ) userAgent = g_conf.m_spiderUserAgent;
// accept only these
char *accept = "*/*";
/*
"text/html, "
"text/plain, "
"text/xml, "
"application/pdf, "
"application/msword, "
"application/vnd.ms-excel, "
"application/mspowerpoint, "
"application/postscript";
*/
char *cmd = "GET";
if ( size == 0 ) cmd = "HEAD";
if ( doPost ) cmd = "POST";
// crap, can't spider nyt.com if we are 1.0, so use 1.0 but also
// note Connection: Close\r\n when making requests
//proto = "HTTP/1.1";
SafeBuf tmp;
char *up = "";
if ( proxyUsernamePwd && proxyUsernamePwd[0] ) {
tmp.safePrintf("Proxy-Authorization: Basic ");
tmp.base64Encode (proxyUsernamePwd,gbstrlen(proxyUsernamePwd));
tmp.safePrintf("\r\n");
up = tmp.getBufStart();
}
// . now use "Accept-Language: en" to tell servers we prefer english
// . i removed keep-alive connection since some connections close on
// non-200 ok http statuses and we think they're open since close
// signal (read 0 bytes) may have been delayed
char* acceptEncoding = "";
// the scraper is getting back gzipped search results from goog,
// so disable this for now
// i am re-enabling now for testing...
if(g_conf.m_gzipDownloads)
acceptEncoding = "Accept-Encoding: gzip;q=1.0\r\n";
// i thought this might stop wikipedia from forcing gzip on us
// but it did not!
// else
// acceptEncoding = "Accept-Encoding:\r\n";
// char *p = m_buf;
// init the safebuf to point to this buffer in our class to avoid
// a potential alloc
// m_reqBuf.setBuf ( m_buf , MAX_REQ_LEN , 0 , false, csUTF8 );
m_reqBuf.purge();
// indicate this is good
m_reqBufValid = true;
if ( size == 0 ) {
// 1 for HEAD requests
m_requestType = RT_HEAD;
m_reqBuf.safePrintf (
"%s %s %s\r\n"
"Host: %s\r\n"
"%s"
"User-Agent: %s\r\n"
"Connection: Close\r\n"
//"Connection: Keep-Alive\r\n"
"Accept-Language: en\r\n"
//"Accept: */*\r\n\r\n" ,
"Accept: %s\r\n"
"%s"
,
cmd,
path , proto, host ,
ims , userAgent , accept , up );
}
else if ( size != -1 )
m_reqBuf.safePrintf (
"%s %s %s\r\n"
"Host: %s\r\n"
"%s"
"User-Agent: %s\r\n"
"Connection: Close\r\n"
//"Connection: Keep-Alive\r\n"
"Accept-Language: en\r\n"
//"Accept: */*\r\n"
"Accept: %s\r\n"
"Range: bytes=%"INT32"-%"INT32"\r\n"
"%s"
,
cmd,
path ,
proto ,
host ,
ims ,
userAgent ,
accept ,
offset ,
offset + size ,
up);
else if ( offset > 0 && size == -1 )
m_reqBuf.safePrintf (
"%s %s %s\r\n"
"Host: %s\r\n"
"%s"
"User-Agent: %s\r\n"
"Connection: Close\r\n"
//"Connection: Keep-Alive\r\n"
"Accept-Language: en\r\n"
//"Accept: */*\r\n"
"Accept: %s\r\n"
"Range: bytes=%"INT32"-\r\n"
"%s"
,
cmd,
path ,
proto ,
host ,
ims ,
userAgent ,
accept ,
offset ,
up );
// Wget's request:
// GET / HTTP/1.0\r\nUser-Agent: Wget/1.10.2\r\nAccept: */*\r\nHost: 127.0.0.1:8000\r\nConnection: Keep-Alive\r\n\r\n
// firefox's request:
// GET /master?c=main HTTP/1.1\r\nHost: 10.5.1.203:8000\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.7) Gecko/20100715 Ubuntu/10.04 (lucid) Firefox/3.6.7\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nConnection: keep-alive\r\nReferer: http://10.5.0.2:8002/qpmdw.html\r\nCookie: __utma=267617550.1103353528.1269214594.1273256655.1276103782.12; __utmz=267617550.1269214594.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _incvi=qCffL7N8chFyJLwWrBDMbNz2Q3EWmAnf4uA; s_lastvisit=1269900225815; s_pers=%20s_getnr%3D1276103782254-New%7C1339175782254%3B%20s_nrgvo%3DNew%7C1339175782258%3B\r\n\r\n
else {
// until we fix if-modified-since, take it out
//ims="";
//userAgent = "Wget/1.10.2";
//userAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.7) Gecko/20100715 Ubuntu/10.04 (lucid) Firefox/3.6.7";
//proto = "HTTP/1.0";
m_reqBuf.safePrintf (
"%s %s %s\r\n"
"User-Agent: %s\r\n"
"Accept: */*\r\n"
"Host: %s\r\n"
"%s"
"Connection: Close\r\n"
//"Connection: Keep-Alive\r\n"
//"Accept-Language: en\r\n"
"%s"
"%s"
,
//"Accept: %s\r\n\r\n" ,
//"\r\n",
cmd,
path ,
proto ,
userAgent ,
host ,
ims ,
acceptEncoding,
up );
//accept );
}
if ( additionalHeader )
m_reqBuf.safePrintf("%s\r\n",additionalHeader );
// cookie here
if ( cookie )
m_reqBuf.safePrintf("Cookie: %s\r\n",cookie );
// print content-length: if post
if ( postData ) {
// dammit... recaptcha does not work without this!!!!
m_reqBuf.safePrintf (
"Content-Type: "
"application/x-www-form-urlencoded\r\n");
}
// we need this if doing a post even if postData is NULL
if ( doPost ) {
int32_t contentLen = 0;
if ( postData ) contentLen = strlen(postData);
// this overrides if provided. -1 is default
if ( postContentLen >= 0 ) contentLen = postContentLen;
m_reqBuf.safePrintf ("Content-Length: %"INT32"\r\n", contentLen );
m_reqBuf.safePrintf("\r\n");
if ( postData ) m_reqBuf.safePrintf("%s",postData);
// log it for debug
//log("captch: %s",m_buf);
}
if ( ! doPost ) { // ! postData ) {
m_reqBuf.safePrintf("\r\n");
}
// set m_bufLen
//m_bufLen = p - m_buf;//gbstrlen ( m_buf );
// sanity check
// if ( m_bufLen + 1 > MAX_REQ_LEN ) {
// log("build: HttpRequest buf is too small.");
// char *xx = NULL; *xx = 0;
// }
// debug it
// log("hreq: %s",m_reqBuf.getBufStart());
// restore url buffer
if ( pathEnd ) *pathEnd = '?';
return true;
}
// . parse an incoming request
// . return false and set g_errno on error
// . CAUTION: we destroy "req" by replacing it's last char with a \0
// . last char must be \n or \r for it to be a proper request anyway
bool HttpRequest::set ( char *origReq , int32_t origReqLen , TcpSocket *sock ) {
// reset number of cgi field terms
reset();
if ( ! m_reqBuf.reserve ( origReqLen + 1 ) ) {
log("http: failed to copy request: %s",mstrerror(g_errno));
return false;
}
// copy it to avoid mangling it
m_reqBuf.safeMemcpy ( origReq , origReqLen );
// NULL term
m_reqBuf.pushChar('\0');
m_reqBufValid = true;
// and point to that
char *req = m_reqBuf.getBufStart();
int32_t reqLen = m_reqBuf.length() - 1;
// save this
m_userIP = 0; if ( sock ) m_userIP = sock->m_ip;
m_isSSL = 0; if ( sock ) m_isSSL = (bool)sock->m_ssl;
// TcpServer should always give us a NULL terminated request
if ( req[reqLen] != '\0' ) { char *xx = NULL; *xx = 0; }
// how long is the first line, the primary request
// int32_t i;
// for ( i = 0 ; i<reqLen && i<MAX_REQ_LEN &&
// req[i]!='\n' && req[i]!='\r'; i++);
// . now fill up m_buf, used to log the request
// . make sure the url was encoded correctly
// . we don't want assholes encoding every char so we can't see what
// url they are submitting to be spidered/indexed
// . also, don't de-code encoded ' ' '+' '?' '=' '&' because that would
// change the meaning of the url
// . and finally, non-ascii chars that don't display correctly
// . this should NULL terminate m_buf, too
// . turn this off for now, just try to log a different way
// m_bufLen = urlNormCode ( m_buf , MAX_REQ_LEN - 1 , req , i );
// ensure it's big enough to be a valid request
if ( reqLen < 5 ) {
log("http: got reqlen %"INT32"<5 = %s",reqLen,req);
g_errno = EBADREQUEST;
return false;
}
int32_t cmdLen = 0;
// or if first line too long
//if ( i >= 1024 ) { g_errno = EBADREQUEST; return false; }
// get the type, must be GET or HEAD
if ( strncmp ( req , "GET " , 4 ) == 0 ) {
m_requestType = RT_GET;
cmdLen = 3;
}
// these means a compressed reply was requested. use by query
// compression proxies.
else if ( strncmp ( req , "ZET " , 4 ) == 0 ) {
m_requestType = RT_GET;
cmdLen = 3;
}
else if ( strncmp ( req , "HEAD " , 5 ) == 0 ) {
m_requestType = RT_HEAD;
cmdLen = 4;
}
else if ( strncmp ( req , "POST " , 5 ) == 0 ) {
m_requestType = RT_POST;
cmdLen = 4;
}
else if ( strncmp ( req , "CONNECT " , 8 ) == 0 ) {
// take this out until it stops losing descriptors and works
//m_requestType = RT_CONNECT;
//cmdLen = 7;
// we no longer insert section info. emmanuel gets section
// info when injecting a doc now i think in PageInject.cpp.
// we do not proxy https requests because we can't
// decrypt the page contents to cache them or to insert
// the sectiondb voting markup, so it's kinda pointless...
// and i'm not aiming to be a full-fledge squid proxy.
log("http: CONNECT request not supported because we "
"can't insert section markup and we can't cache: %s",req);
g_errno = EBADREQUEST;
return false;
}
else {
log("http: got bad request cmd: %s",req);
g_errno = EBADREQUEST;
return false;
}
// . NULL terminate the request (a destructive operation!)
// . this removes the last \n in the trailing \r\n
// . shit, but it fucks up POST requests
if ( m_requestType != RT_POST ) {
req [ reqLen - 1 ] = '\0';
reqLen--;
}
// POST requests can be absolutely huge if you are injecting a 100MB
// file, so limit our strstrs to the end of the mime
char *d = NULL;
char dc;
// check for body if it was a POST request
if ( m_requestType == RT_POST ) {
d = strstr ( req , "\r\n\r\n" );
if ( d ) { dc = *d; *d = '\0'; }
else log("http: Got POST request without \\r\\n\\r\\n.");
}
// is it a proxy request?
m_isSquidProxyRequest = false;
if ( strncmp ( req + cmdLen + 1, "http://" ,7) == 0 ||
strncmp ( req + cmdLen + 1, "https://",8) == 0 ) {
m_isSquidProxyRequest = true;
// set url parms for it
m_squidProxiedUrl = req + cmdLen + 1;
char *p = m_squidProxiedUrl + 7;
if ( *p == '/' ) p++; // https:// ?
// stop at whitespace or \0
for ( ; *p && ! is_wspace_a(*p) ; p++ );
// that's the length of it
m_squidProxiedUrlLen = p - m_squidProxiedUrl;
}
else if ( m_requestType == RT_CONNECT ) {
m_isSquidProxyRequest = true;
// set url parms for it
m_squidProxiedUrl = req + cmdLen + 1;
// usually its like CONNECT diffbot.com:443
char *p = m_squidProxiedUrl;
// stop at whitespace or \0
for ( ; *p && ! is_wspace_a(*p) ; p++ );
// that's the length of it
m_squidProxiedUrlLen = p - m_squidProxiedUrl;
}
// check authentication
char *auth = NULL;
if ( m_isSquidProxyRequest && req )
auth = strstr(req,"Proxy-authorization: Basic ");
//if ( m_isSquidProxyRequest && ! auth ) {
// log("http: no auth in proxy request %s",req);
// g_errno = EBADREQUEST;
// return false;
//}
SafeBuf tmp;
if ( auth ) {
// find end of it
char *p = auth;
for ( ; *p && *p != '\r' && *p != '\n' ; p++ );
tmp.base64Decode ( auth , p - auth );
}
// assume incorrect username/password
bool matched = false;
if ( m_isSquidProxyRequest ) {
// now try to match in g_conf.m_proxyAuth safebuf of
// username:password space-separated list
char *p = g_conf.m_proxyAuth.getBufStart();
// loop over those
for ( ; p && *p ; ) {
// skip initial white space
for ( ; *p && is_wspace_a(*p); p++ );
// skip to end of username:password thing
char *end = p;
for ( ; *end && !is_wspace_a(*end); end++);
// save
char *start = p;
// advance
p = end;
// this is always a match
if ( end-start == 3 && strncmp(start,"*:*",3)==0 ) {
matched = true;
break;
}
// compare now
if ( tmp.length() != end-start )
continue;
if ( strncmp(tmp.getBufStart(),start,end-start))
continue;
// we got a match
matched = true;
break;
}
}
// incorrect username:passwrod?
if ( m_isSquidProxyRequest && ! matched ) {
log("http: bad username:password in proxy request %s",req);
g_errno = EPERMDENIED;
return false;
}
// if proxy request to download a url through us, we are done
if ( m_isSquidProxyRequest ) return true;
bool multipart = false;
if ( m_requestType == 2 ) { // is POST?
char *cd ;
cd = gb_strcasestr(req,"Content-Type: multipart/form-data");
if ( cd ) multipart = true;
}
// . point to the file path
// . skip over the "GET "
int32_t filenameStart = 4 ;
// skip over extra char if it's a "HEAD " request
if ( m_requestType == RT_HEAD || m_requestType == RT_POST )
filenameStart++;
// are we a redirect?
int32_t i = filenameStart;
m_redirLen = 0;
if ( strncmp ( &req[i] , "/?redir=" , 8 ) == 0 ) {
for ( int32_t k = i+8; k<reqLen && m_redirLen<126 ; k++) {
if ( req[k] == '\r' ) break;
if ( req[k] == '\n' ) break;
if ( req[k] == '\t' ) break;
if ( req[k] == ' ' ) break;
m_redir[m_redirLen++] = req[k];
}
}
m_redir[m_redirLen] = '\0';
// find a \n space \r or ? that delimits the filename
for ( i = filenameStart ; i < reqLen ; i++ ) {
if ( is_wspace_a ( req [ i ] ) ) break;
if ( req [ i ] == '?' ) break;
}
// now calc the filename length
m_filenameLen = i - filenameStart;
// return false and set g_errno if it's 0
if ( m_filenameLen <= 0 ) {
log("http: got filenameLen<=0: %s",req);
g_errno = EBADREQUEST;
return false;
}
// . bitch if too big
// . leave room for strcatting "index.html" below
if ( m_filenameLen >= MAX_HTTP_FILENAME_LEN - 10 ) {
log("http: got filenameLen>=max");
g_errno = EBADREQUEST;
return false;
}
// . decode the filename into m_filename and reassign it's length
// . decode %2F to / , etc...
m_filenameLen = urlDecode(m_filename,req+filenameStart,m_filenameLen);
// NULL terminate m_filename
m_filename [ m_filenameLen ] = '\0';
// does it have a file extension AFTER the last / in the filename?
bool hasExtension = false;
for ( int32_t j = m_filenameLen-1 ; j >= 0 ; j-- ) {
if ( m_filename[j] == '.' ) { hasExtension = true; break; }
if ( m_filename[j] == '/' ) break;
}
// if it has no file extension append a /index.html
if ( ! hasExtension && m_filename [ m_filenameLen - 1 ] == '/' ) {
strcat ( m_filename , "index.html" );
m_filenameLen = gbstrlen ( m_filename );
}
// . uses the TcpSocket::m_readBuf
// . if *p was ? then keep going
m_origUrlRequest = origReq + filenameStart;
char *p = origReq + m_filenameLen;
for ( ; *p && ! is_wspace_a(*p) ; p++ );
m_origUrlRequestLen = p - m_origUrlRequest;
// set file offset/size defaults
m_fileOffset = 0;
// -1 means ALL the file from m_fileOffset onwards
m_fileSize = -1;
// "e" points to where the range actually starts, if any
//char *e;
// . TODO: speed up by doing one strstr for Range: and maybe range:
// . do they have a Range: 0-100\n in the mime denoting a partial get?
//char *s = strstr ( req ,"Range:bytes=" );
//e = s + 12;
// try alternate formats
//if ( ! s ) { s = strstr ( req ,"Range: bytes=" ); e = s + 13; }
//if ( ! s ) { s = strstr ( req ,"Range: " ); e = s + 7; }
// parse out the range if we got one
//if ( s ) {
// int32_t x = 0;
// sscanf ( e ,"%"INT32"-%"INT32"" , &m_fileOffset , &x );
// // get all file if range's 2nd number is non-existant
// if ( x == 0 ) m_fileSize = -1;
// else m_fileSize = x - m_fileOffset;
// // ensure legitimacy
// if ( m_fileOffset < 0 ) m_fileOffset = 0;
//}
// reset our hostname
m_hostLen = 0;
// assume request is NOT from local network
//m_isMasterAdmin = false;
m_isLocal = false;
// get the virtual hostname they want to use
char *s = strstr ( req ,"Host:" );
// try alternate formats
if ( ! s ) s = strstr ( req , "host:" );
// must be on its own line, otherwise it's not valid
if ( s && s > req && *(s-1) !='\n' ) s = NULL;
// parse out the host if we got one
if ( s ) {
// skip field name, host:
s += 5;
// skip e to beginning of the host name after "host:"
while ( *s==' ' || *s=='\t' ) s++;
// find end of the host name
char *end = s;
while ( *end && !is_wspace_a(*end) ) end++;
// . now *end should be \0, \n, \r, ' ', ...
// . get host len
m_hostLen = end - s;
// truncate if too big
if ( m_hostLen >= 255 ) m_hostLen = 254;
// copy into hostname
gbmemcpy ( m_host , s , m_hostLen );
}
// NULL terminate it
m_host [ m_hostLen ] = '\0';
// get Referer: field
s = strstr ( req ,"Referer:" );
// find another
if ( ! s ) s = strstr ( req ,"referer:" );
// must be on its own line, otherwise it's not valid
if ( s && s > req && *(s-1) !='\n' ) s = NULL;
// assume no referer
m_refLen = 0;
// parse out the referer if we got one
if ( s ) {
// skip field name, referer:
s += 8;
// skip e to beginning of the host name after ':'
while ( *s==' ' || *s=='\t' ) s++;
// find end of the host name
char *end = s;
while ( *end && !is_wspace_a(*end) ) end++;
// . now *end should be \0, \n, \r, ' ', ...
// . get len
m_refLen = end - s;
// truncate if too big
if ( m_refLen >= 255 ) m_refLen = 254;
// copy into m_ref
gbmemcpy ( m_ref , s , m_refLen );
}
// NULL terminate it
m_ref [ m_refLen ] = '\0';
// get User-Agent: field
s = strstr ( req ,"User-Agent:" );
// find another
if ( ! s ) s = strstr ( req ,"user-agent:" );
// must be on its own line, otherwise it's not valid
if ( s && s > req && *(s-1) !='\n' ) s = NULL;
// assume empty
int32_t len = 0;
// parse out the referer if we got one
if ( s ) {
// skip field name, referer:
s += 11;
// skip e to beginning of the host name after ':'
while ( *s==' ' || *s=='\t' ) s++;
// find end of the agent name
char *end = s;
while ( *end && *end!='\n' && *end!='\r' ) end++;
// . now *end should be \0, \n, \r, ' ', ...
// . get agent len
len = end - s;
// truncate if too big
if ( len > 127 ) len = 127;
// copy into m_userAgent
gbmemcpy ( m_userAgent , s , len );
}
// NULL terminate it
m_userAgent [ len ] = '\0';
m_isMSIE = false;
if ( strstr ( m_userAgent , "MSIE" ) )
m_isMSIE = true;
// get Cookie: field
s = strstr ( req, "Cookie:" );
// find another
if ( !s ) s = strstr ( req, "cookie:" );
// must be on its own line, otherwise it's not valid
if ( s && s > req && *(s-1) != '\n' ) s = NULL;
// assume empty
// m_cookieBufLen = 0;
m_cookiePtr = s;
// parse out the cookie if we got one
if ( s ) {
// skip field name, Cookie:
s += 7;
// skip s to beginning of cookie after ':'
while ( *s == ' ' || *s == '\t' ) s++;
// find end of the cookie
char *end = s;
while ( *end && *end != '\n' && *end != '\r' ) end++;
// save length
m_cookieLen = end - m_cookiePtr;
// get cookie len
//m_cookieBufLen = end - s;
// trunc if too big
//if (m_cookieBufLen > 1023) m_cookieBufLen = 1023;
// copy into m_cookieBuf
//gbmemcpy(m_cookieBuf, s, m_cookieBufLen);
}
// NULL terminate it
if ( m_cookiePtr ) m_cookiePtr[m_cookieLen] = '\0';
//m_cookieBuf[m_cookieBufLen] = '\0';
// convert every '&' in cookie to a \0 for parsing the fields
// for ( int32_t j = 0 ; j < m_cookieBufLen ; j++ )
// if ( m_cookieBuf[j] == '&' ) m_cookieBuf[j] = '\0';
// mark it as cgi if it has a ?
bool isCgi = ( req [ i ] == '?' ) ;
// reset m_filename length to exclude the ?* stuff
if ( isCgi ) {
// skip over the '?'
i++;
// find a space the delmits end of cgi
int32_t j;
for ( j = i; j < reqLen; j++) if (is_wspace_a(req[j])) break;
// now add it
if ( ! addCgi ( &req[i] , j-i ) ) return false;
// update i
i = j;
}
// . set path ptrs
// . the whole /cgi/14.cgi?coll=xxx&..... thang
m_path = req + filenameStart;
m_plen = i - filenameStart;
// we're local if hostname is 192.168.[0|1].y
//if ( strncmp(iptoa(sock->m_ip),"192.168.1.",10) == 0) {
// m_isMasterAdmin = true; m_isLocal = true; }
//if ( strncmp(iptoa(sock->m_ip),"192.168.0.",10) == 0) {
// m_isMasterAdmin = true; m_isLocal = true; }
//if(strncmp(iptoa(sock->m_ip),"192.168.1.",10) == 0) m_isLocal = true;
//if(strncmp(iptoa(sock->m_ip),"192.168.0.",10) == 0) m_isLocal = true;
if ( sock && strncmp(iptoa(sock->m_ip),"192.168.",8) == 0)
m_isLocal = true;
if ( sock && strncmp(iptoa(sock->m_ip),"10.",3) == 0)
m_isLocal = true;
// steve cook's comcast at home:
// if ( sock && strncmp(iptoa(sock->m_ip),"68.35.100.143",13) == 0)
// m_isLocal = true;
// procog's ip
// if ( sock && strncmp(iptoa(sock->m_ip),"216.168.36.21",13) == 0)
// m_isLocal = true;
// diffbot comcast
if ( sock && strncmp(iptoa(sock->m_ip),"50.168.3.61",11) == 0)
m_isLocal = true;
// matt comcast
if ( sock && strncmp(iptoa(sock->m_ip),"75.160.49.8",11) == 0)
m_isLocal = true;
// matt comcast #2
if ( sock && strncmp(iptoa(sock->m_ip),"69.181.136.143",14) == 0)
m_isLocal = true;
// titan
if ( sock && strncmp(iptoa(sock->m_ip),"66.162.42.131",13) == 0)
m_isLocal = true;
// gotta scan all ips in hosts.conf as well...
// if we are coming from any of our own hosts.conf c blocks
// consider ourselves local
uint32_t last = 0;
for ( int32_t i = 0 ; i < g_hostdb.m_numHosts ; i++ ) {
Host *h = g_hostdb.getHost(i);
// save time with this check
if ( h->m_ip == last ) continue;
// update it
last = h->m_ip;
// returns number of top bytes in comon
int32_t nt = ipCmp ( sock->m_ip , h->m_ip );
// at least be in the same c-block as a host in hosts.conf
if ( nt < 3 ) continue;
m_isLocal = true;
break;
}
// connectips/adminips
// for ( int32_t i = 0 ; i < g_conf.m_numConnectIps ; i++ ) {
// if ( sock->m_ip != g_conf.m_connectIps[i] ) continue;
// m_isLocal = true;
// break;
// }
// roadrunner ip
// if ( sock && strncmp(iptoa(sock->m_ip),"66.162.42.131",13) == 0)
// m_isLocal = true;
// cnsp ip
//if ( sock && strncmp(iptoa(sock->m_ip),"67.130.216.27",13) == 0)
// m_isLocal = true;
// emily parker
//if ( sock && strncmp(iptoa(sock->m_ip),"69.92.68.202",12) == 0)
//m_isLocal = true;
// 127.0.0.1
if ( sock && sock->m_ip == 16777343 )
m_isLocal = true;
// steve cook's webserver
//if ( sock && strncmp(iptoa(sock->m_ip),"216.168.36.21",13) == 0)
// m_isLocal = true;
// . also if we're coming from lenny at my house consider it local
// . this is a security risk, however... TODO: FIX!!!
//if ( sock->m_ip == atoip ("68.35.105.199" , 13 ) ) m_isMasterAdmin = true;
// . TODO: now add any cgi data from a POST.....
// . look after the mime
//char *d = NULL;
// check for body if it was a POST request
//if ( m_requestType == RT_POST ) d = strstr ( req , "\r\n\r\n" );
// now put d's char back, just in case... does it really matter?
if ( d ) *d = dc;
// return true now if no cgi stuff to parse
if ( d ) {
char *post = d + 4;
int32_t postLen = reqLen-(d+4-req) ;
// post sometimes has a \r or\n after it
while ( postLen > 0 && post[postLen-1]=='\r' ) postLen--;
// add it to m_cgiBuf, filter and everything
if ( ! addCgi ( post , postLen ) ) return false;
}
// sometimes i don't want to be admin
//if ( getLong ( "admin" , 1 ) == 0 ) m_isMasterAdmin = false;
// success
/////
// Handle Extra parms...
char *ep = g_conf.m_extraParms;
char *epend = g_conf.m_extraParms + g_conf.m_extraParmsLen;
char *qstr = m_cgiBuf;
int32_t qlen = m_cgiBufLen;
while (ep < epend){
char buf[AUTOBAN_TEXT_SIZE];
int32_t bufLen = 0;
// get next substring
while (*ep && ep < epend && *ep != ' ' && *ep != '\n'){
buf[bufLen++] = *ep++;
}
// skip whitespace
while (*ep && ep < epend && *ep == ' '){
ep++;
}
// null terminate
buf[bufLen] = '\0';
// No match
if (!bufLen ||
!strnstr2(qstr, qlen, buf)){