-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.pas
More file actions
2077 lines (1836 loc) · 62.1 KB
/
Copy pathhttpserver.pas
File metadata and controls
2077 lines (1836 loc) · 62.1 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
unit httpServer;
/////////////////////////////////////////////
//
// This unit is maintained by:
// rene tegel rene@dubaron.com
//
// Initially created by:
// rene@dubaron.com - july 2004 by rene tegel
//
//
// This file is released as 'Open Source' and to the 'Public Domain'
// As those terms have no legal status, this file is licensed under
// a number of OSI-approved licenses.
//
// You can use this unit as long as you meet the conditions of
// at least one(1) of the following licenses:
//
// MPL - Mozilla Public Lisence - http://www.mozilla.org/MPL/
// GPL - General Public License - Any version http://www.gnu.org/copyleft/gpl.html
// LGPL - Lesser General Public License - Any version http://www.gnu.org/copyleft/lgpl.html
//
//
// Usage of this code is entirely at own risk.
//
/////////////////////////////////////////////
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
//rfc 2616
//http://www.w3.org/Protocols/rfc2616/rfc2616.html
// USE AT YOUR OWN RISK //
// NOT GUARANTEED ON SECURITY ISSUES //
// NOT SUITABLE FOR PRODUCTION ENVIRONMENTS YET //
// by Rene Tegel 2004
// july 2004 - busy again with the server, in need for a http server so may finish this as well :)
interface
uses Classes, SysUtils, typinfo,
{$IFNDEF FPC}{$IFNDEF LINUX}filectrl, {$ENDIF}{$ENDIF}
blcksock, visualserverbase, inifiles, vstypedef, ExecCGI,
synacode, synautil, mimemess, authentication;
//implementation of a HTTP server.
//It just acts as a (partly implemented) HTTP/1.1 server
//But we loosely check commands to fulfill 0.9, 1.0 and 1.1 requests.
//Not fully qualified 1.1 commands (i.e. leaving the 'Host' parameter out of the header)
//is threated as 1.0 again.
//Response codes are HTTP/1.1. Server always responds 1.1
const
MAX_POST_DATA_SIZE=8192;
{$IFDEF LINUX}
PathDelim = '/';
{$ELSE}
PathDelim = '\';
{$ENDIF}
type
TEnumHTTPProtocols = (hpHEAD, hpGET, hpPUT, hpDELETE, hpPOST, hpTRACE, hpOPTIONS, hpCONNECT);
THTTPProtocols = set of TEnumHTTPProtocols;
//cmGET is default
//cmClose forces connection close
//cmDone marks all client IO as done, but keeps connection open if enabled
//cmConnect marks proxy
THttpConnectionMode = (cmWait, cmGET, cmPOST, cmPUT, cmCONNECT, cmReadCGI, cmCLOSE, cmDONE);
TCGIPath = class
CGIName:String;
ExePath:TFileName;
end;
TPreParser = class
ExePath:String;
Params: String;
end;
TvsHTTPResponse = class (TResponse)
procedure FixHeader; override;
end;
TvsVirtualDomain = class (TObject)
FDefaultDocument:String;
FDefaultDocuments:TStrings;
FHostName:String;
// FRootPath:TFileName;
FVirtualPath: TStrings;
FCGI: TStrings; //Array of TCGIPath;
FPreParser: TStrings; //Array TPreParser;
FManualURL: TStrings;
FMimeTypes: TStrings;
FAuthNeeded: TStrings;
constructor Create;
destructor Destroy; override;
end;
THTTPVars = record
FDoVirtualHosts:Boolean;
FDomain:TvsVirtualDomain;
FVirtualDomainRoot: String;
FPHPPath:TFileName;
FCaseSensitive:Boolean;
FServerName:String;
FVirtualDomains: TList;
FSupported: THTTPProtocols;
FAutomated: THTTPProtocols;
FErrorDocs: String;
end;
THTTPDocument = record
Headers: String;
Data: String;
end;
THTTPDoc = record
Command: TEnumHTTPProtocols;
Request,
Response: THTTPDocument;
end;
THostInfo = record
Host,
Port: String;
end;
// THTTPCallBack = procedure (Sender: TObject; Request, Response: THTTPDoc; Info: THostInfo) of Object;
TCallBack = record
FOnHead,
FOnGet,
FOnPut,
FOnPost,
FOnTrace,
FOnOptions: TOnRequest; //THTTPCallBack;
end;
//the component
TvsHTTPServer = class (TVisualServer)
protected
FVirtualServers:TList;
FHTTPVars:THTTPVars;
FCallBack: TCallBack;
//creates a virtual domain if not exists:
function GetVirtualDomain(Domain: String): TvsVirtualDomain;
public
class function ParseDomain(Domain: String): String; //cleans up a domain name
constructor Create (AOwner:TComponent); override;
procedure AddVirtualDomain (Domain:TvsVirtualDomain);
procedure RegisterDir (PhysicalDir: TFileName; VirtualDir: String; Domain: String=''; Recursive: Boolean=True);
procedure RegisterPreParser (Binary: TFileName; Extension: String; Domain: String=''; Params: String='"%s"');
procedure RegisterPHP (Binary: TFileName; Extension: String=''; Domain: String='');
procedure RegisterDefaultDoc (FileName: String; Domain: String='');
procedure RegisterMimeType (Extension, MimeType: String; Domain: String='');
procedure RegisterCGI (PhysicalDir: TFileName; VirtualDir: String='/cgi-bin'; Domain: String='');
procedure RegisterManualURL (URL: String; Domain: String='');
procedure RegisterAuthenticationDir (VirtualDir: String; Domain: String=''; Recursive: Boolean=True);
procedure ClearSettings;
// procedure WriteSettings (Stream: TStream);
// procedure ReadSettings (Stream: TStream);
function SaveSettings (FileName: TFileName): Boolean; override;
function LoadSettings (FileName: TFileName): Boolean; override;
published
property OnHead: TOnRequest read FCallBack.FOnHead write FCallBack.FOnHead;
property OnGet: TOnRequest read FCallBack.FOnGet write FCallBack.FOnGet;
property OnPost: TOnRequest read FCallBack.FOnPost write FCallBack.FOnPost;
property OnPut: TOnRequest read FCallBack.FOnPut write FCallBack.FOnPut;
property DoVirtualHosts:Boolean read FHTTPVars.FDoVirtualHosts write FHTTPVars.FDoVirtualHosts;
// property DefaultDocument:String read FHTTPVars.FDomain.FDefaultDocument write FHTTPVars.FDomain.FDefaultDocument;
property PHPPath:TFileName read FHTTPVars.FPHPPath write FHTTPVars.FPHPPath;
property CaseSensitive:Boolean read FHTTPVars.FCaseSensitive write FHTTPVars.FCaseSensitive;
property SupportedProtocols:THTTPProtocols read FHTTPVars.FSupported write FHTTPVars.FSupported;
property AutomatedProtocols:THTTPProtocols read FHTTPVars.FAutomated write FHTTPVars.FAutomated;
property ErrorDocs: String read FHTTPVars.FErrorDocs write FHTTPVars.FErrorDocs;
property VirtualDomainRoot: String read FHTTPVars.FVirtualDomainRoot write FHTTPVars.FVirtualDomainRoot;
end;
//the protocol handler
TvsHTTPHandler = class (TServerHandler)
protected
//Returns NIL on invalid domain:
function GetVirtualDomain(Domain: String): TvsVirtualDomain;
//support function
function Compare (V1, V2: String): Boolean; //compares string based on CaseSensitive property
//procedures to find back vars:
function GetCGIPath(URL: String; Domain: String=''): String;
function GetPreParser (URL: String; Domain: String=''): TPreParser;
function IsManualURL (URL: String; Domain: String=''): Boolean;
function MapVirtualDir (URL: String; Domain: String=''): TFileName;
function GetDefaultDoc (Path: TFileName; Domain: String=''): String;
function IsAuthenticationNeeded (URL: String; Domain: String=''): Boolean;
function IsAuthenticated: Boolean;
procedure CreateFileHeaders (FileName: TFileName);
//function to see if there are any parsers (pre-parsers, cgi)
//if so, call them
//if not, return false and do rest
function CheckGetHeadPostParser (Domain: String=''): Boolean;
procedure Report404; //speaks for itself..
public
Buf:String;
FMode: THttpConnectionMode;
FPSock: TTCPBlockSocket;
//vars shared with component:
FHTTPVars: THTTPVars;
FCallBack: TCallBack;
//internal use:
FCurrentGetFile: TFileName;
FRangeStart: Int64;
FRangeEnd: Int64;
FPostData: String;
FCGIInfo: TCGIResult;
FKeepAlive: Boolean;
procedure Init; override;
procedure CopyCustomVars; override;
procedure Handler; override;
procedure ProcessRequest (Header: String);
function GetGetPath:TFileName; //returns path of file or cgi
procedure ProcessGet;
procedure ProcessHead;
procedure ProcessPut;
procedure ProcessPost;
procedure ProcessConnect;
procedure ProcessDelete;
procedure ProcessTrace;
procedure ProcessOptions;
//Procedures to split url:
function GetFile (URL: String): String;
function GetFileNoPath (URL: String): String;
function GetPath (URL: String): String;
function GetParams (URL: String): String;
procedure ReadPostData;
procedure MakeResponseHeaders;
procedure MakeErrorDoc;
procedure MakeArgs;
function MergeURL (Path, FileName: String): String;
procedure ProcessGetHeadPost(Method: TEnumHTTPProtocols);
procedure CheckRanges;
end;
function HTTPCodeToMessage (Code:Integer):String;
implementation
//support function:
function HTTPCodeToMessage (Code:Integer):String;
//Code is expected to be >= 100 (3 digits);
var M:String;
begin
if (code<100) or (code>999) then
code := 500; //internal server error
case Code of
100: M:='Continue';
101: M:='Switching Protocols';
200: M:='Ok';
201: M:='Created';
202: M:='Accepted';
203: M:='Non-Authoritive Information';
204: M:='No Content';
205: M:='Reset Content';
206: M:='Partial Content';
300: M:='Multiple Choices';
301: M:='Moved Permanently';
302: M:='Found';
303: M:='See Other Method';
304: M:='Not Modified';
305: M:='Use Proxy';
307: M:='Temporary Redirect';
400: M:='Bad Request';
401: M:='Unauthorized';
402: M:='Payment required';
403: M:='Forbidden';
404: M:='Not Found';
405: M:='Method Not Allowed';
406: M:='Not Acceptable';
407: M:='Proxy Authentication Required';
408: M:='Request Timeout';
409: M:='Conflict';
410: M:='Gone';
411: M:='Length Required';
412: M:='Precondition Failed';
413: M:='Request Entity Too Large';
414: M:='Request-URI Too Long';
415: M:='Unsupported Media Type';
416: M:='Requested Range Not Satisfiable';
417: M:='Expectation Failed';
500: M:='Internal Error';
501: M:='Not Implemented';
502: M:='Bad Gateway';
503: M:='Service Unavailable';
504: M:='Gateway Timeout';
505: M:='HTTP Version Not Supported';
else
M := 'Unknown';
end;
M:=IntToStr(Code)+' '+M;
Result := M;
end;
function ListDirAsHTML(PhysicalDir, VirtualDir, Hostname:String):String;
//list a directory as HTML
var v,w: String;
sr: TSearchRec;
f: Integer;
begin
v := 'Index of //'+HostName+VirtualDir;
Result := '<html><head><title>'+v+'</title></head>'+
'<body><h2><i>'+v+'</i></h2><br>'#13#10'<table>'#13#10;
f := FindFirst (PhysicalDir+PathDelim+'*.*', faAnyFile - faHidden, sr);
while f = 0 do
begin
w := sr.Name;
if (sr.Attr and faDirectory)<>0 then
w := w + '/';
Result := Result + Format ( '<tr><td><a href="%s">%s</a></td><td>%d</td><td>%s</td></tr>',
[ '//'+HostName+VirtualDir+w,
VirtualDir+w,
sr.Size,
// RFC822DateTime (FileDateToDateTime(sr.Time))
DateTimeToStr (FileDateToDateTime(sr.Time))
]);
f := FindNext (sr);
end;
Result := Result + '</table>'#13#10'<hr>Visual Synapse HTTP Server</body>'#13#10'</html>';
FindClose (sr);
end;
{ THTTPServer }
procedure TvsHTTPServer.AddVirtualDomain(Domain: TvsVirtualDomain);
begin
end;
procedure TvsHTTPServer.ClearSettings;
var VD: TvsVirtualDomain;
i: Integer;
begin
//remove list of virtual domains:
for i:=0 to FHTTPVars.FVirtualDomains.Count - 1 do
TvsVirtualDomain(FHTTPVars.FVirtualDomains[i]).Free;
FHTTPVars.FVirtualDomains.Clear;
VD := TvsVirtualDomain.Create;
VD.FHostName := '*';
FHTTPVars.FVirtualDomains.Add (VD);
FHTTPVars.FVirtualDomainRoot := '';
end;
constructor TvsHTTPServer.Create(AOwner: TComponent);
var VD: TvsVirtualDomain;
begin
inherited;
FClientType := TvsHTTPHandler;
ListenPort := '80';
// DefaultDocument := 'index.*';
FSettings.FHasCustomVars := True;
FHTTPVars.FSupported := [hpHEAD, hpGET,{ hpPUT, hpDELETE,} hpPOST, hpTRACE, hpOPTIONS{, hpCONNECT}];
FHTTPVars.FAutomated := FHTTPVars.FSupported + [hpCONNECT];
FHTTPVars.FCaseSensitive := True;
FHTTPVars.FVirtualDomains := TList.Create;
ClearSettings;
end;
function TvsHTTPHandler.GetVirtualDomain(Domain: String): TvsVirtualDomain;
//don't confuse with the THTTPServer.GetVirtualDomain method
//which is slightly different.
var i: Integer;
begin
Domain := TvsHTTPServer.ParseDomain(Domain);
Result := nil;
for i:=0 to FHTTPVars.FVirtualDomains.Count - 1 do
if (TvsVirtualDomain (FHTTPVars.FVirtualDomains[i]).FHostName = Domain) or
(TvsVirtualDomain (FHTTPVars.FVirtualDomains[i]).FHostName = 'www.'+Domain) then
begin
Result := TvsVirtualDomain (FHTTPVars.FVirtualDomains[i]);
break;
end;
if (Result = nil) and (FHTTPVars.FVirtualDomainRoot <> '') then
begin
//dynamic virtual domain mapping
//parse virtual domain root
//if directory exists, map
if (pos ('/', Domain)<=0) and (pos ('\', domain)<=0) and
(DirectoryExists (FHTTPVars.FVirtualDomainRoot + PathSep + Domain) or
DirectoryExists (FHTTPVars.FVirtualDomainRoot + PathSep + 'www.'+Domain)) then
begin
//FHTTPVars.FVirtualDomains.Add ();
//todo: thread safety.
Result := TvsVirtualDomain.Create;
Result.FVirtualPath.AddObject ('+/', StrToObj(FHTTPVars.FVirtualDomainRoot + PathSep + Domain));
Result.FHostName := Domain;
//FHTTPVars.
// FHTTPVars.CS.Enter
FHTTPVars.FVirtualDomains.Add (Result);
// FHTTPVars.CS.Leave;
end;
end;
{
if (not Assigned (Result)) and CreateIfNotExists then
begin //add one
Result := TVirtualDomain.Create;
FHTTPVars.FVirtualDomains.Add (Result);
Result.FHostName := Domain;
end;
}
end;
class function TvsHTTPServer.ParseDomain(Domain: String): String;
begin
Result := lowercase (Domain);
if Result='' then
Result := '*';
end;
procedure TvsHTTPServer.RegisterCGI(PhysicalDir: TFileName; VirtualDir,
Domain: String);
var VD: TvsVirtualDomain;
begin
PhysicalDir := ExpandUNCFileName(PhysicalDir);
VD := GetVirtualDomain (Domain);
VD.FCGI.AddObject (VirtualDir, StrToObj(PhysicalDir));
end;
procedure TvsHTTPServer.RegisterDefaultDoc(FileName, Domain: String);
var VD: TvsVirtualDomain;
begin
VD := GetVirtualDomain (Domain);
if VD.FDefaultDocuments.IndexOf (FileName)<0 then
VD.FDefaultDocuments.Add (FileName);
end;
procedure TvsHTTPServer.RegisterDir(PhysicalDir: TFileName; VirtualDir,
Domain: String; Recursive: Boolean);
var VD: TvsVirtualDomain;
SR: TSearchRec;
f: Integer;
begin
//todo?
//check virtualdir for beginning slash
PhysicalDir := ExpandUNCFileName(PhysicalDir);
VD := GetVirtualDomain (Domain);
if Recursive then
VirtualDir := '+' + VirtualDir
else
VirtualDir := '-' + VirtualDir;
if VD.FVirtualPath.IndexOf (VirtualDir) < 0 then
VD.FVirtualPath.AddObject (VirtualDir, StrToObj(PhysicalDir));
{
if Recursive then
begin
f := FindFirst (PhysicalDir+'\*.*', faDirectory, SR);
while f = 0 do
begin
if ((SR.Attr and faDirectory)<>0) and
(SR.Name<>'.') and (SR.Name<>'..') then //call self recursively
RegisterDir (PhysicalDir+PathSep+SR.Name, VirtualDir+SR.Name+'/', Domain, True);
f := FindNext (SR);
end;
FindClose (SR);
end;
}
end;
procedure TvsHTTPServer.RegisterManualURL(URL, Domain: String);
var VD: TvsVirtualDomain;
begin
VD := GetVirtualDomain (Domain);
if VD.FManualURL.IndexOf(URL)<0 then
VD.FManualURL.Add (URL);
end;
procedure TvsHTTPServer.RegisterMimeType(Extension, MimeType: String; Domain: String='');
var VD: TvsVirtualDomain;
i: Integer;
begin
VD := GetVirtualDomain (Domain);
i := VD.FMimeTypes.IndexOf(Extension);
if i>=0 then
VD.FMimeTypes.Delete(i);
VD.FMimeTypes.AddObject (Extension, StrToObj (MimeType));
end;
procedure TvsHTTPServer.RegisterPreParser(Binary: TFileName; Extension: String;
Domain: String=''; Params: String='"%s"');
var VD: TvsVirtualDomain;
i: Integer;
PreParser: TPreParser;
begin
VD := GetVirtualDomain (Domain);
i := VD.FPreParser.IndexOf(Extension);
if i>=0 then
begin
VD.FPreParser.Objects[i].Free;
VD.FPreParser.Delete(i);
end;
PreParser := TPreParser.Create;
PreParser.ExePath := Binary;
PreParser.Params := Params;
VD.FPreParser.AddObject (Extension, PreParser);
end;
function TvsHTTPServer.LoadSettings(FileName: TFileName): Boolean;
var //FI: TIniFile;
sec, nv: TStrings;
i,j: Integer;
d,p,
n,v,
f : String;
r: Boolean;
pe,pp: String;
begin
Result := InitIniRead (FileName);
if not Result then
exit;
FHTTPVars.FVirtualDomainRoot := FIni.ReadString ('global', 'virtualdomainroot', '');
// if not Inherited LoadSettings (FileName) then
// exit;
sec := TStringList.Create;
nv := TStringList.Create;
FIni.ReadSections (sec);
for j := 0 to sec.Count - 1 do
if pos (':', sec[j])>0 then
begin
d := copy (sec[j],1, pos(':', sec[j])-1);
p := lowercase (copy (sec[j], length(d)+2, maxint));
if (p<>'') then
begin
nv.Clear;
FIni.ReadSectionValues(sec[j], nv);
for i:=0 to nv.count - 1 do
begin
n := nv.Names[i];
v := nv.Values[nv.Names[i]];
if(n<>'') and (n[1]<>'#') then //allow comments in ini file
begin
r := true;
if n<>'' then
begin
if n[1] in ['-', '+'] then
begin
r := n[1]='+';
f := copy (n,2,maxint);
end
else
f:=n;
end
else
f:='';
if pos ('|', v)>0 then
begin
pe := copy (v,1,pos('|',v)-1);
pp := copy (v, length(pe)+2, maxint);
end
else
begin
pe := v;
pp := '';
end;
//d-domain
//p-param/command
//n-'name'/key
//v-value
//f-filename
//r-recursive
if p='pathmapping' then
RegisterDir (v,f,d,r)
else
if p='cgi' then
RegisterCGI (v,f,d)
else
if p='preparser' then
RegisterPreParser (pe, n, d, pp)
else
if p='manualurl' then
RegisterManualURL (n, d)
else
if p='authenticationneeded' then
RegisterAuthenticationDir (f, d, r)
else
if p='defaultdocuments' then
RegisterDefaultDoc (n, d)
else
if p='mimetypes' then
RegisterMimeType (n, v, d)
;
end;
end;
end;
end;
FinishIni;
end;
function TvsHTTPServer.SaveSettings(FileName: TFileName): Boolean;
var i: Integer;
VD: TvsVirtualDomain;
h, hc: String;
sl: TStrings;
procedure StrObjToNameValue (so, nv: TStrings; Reverse: Boolean=False);
var i,n: Integer;
v: String;
begin
nv.Clear;
n := 0;
for i:=0 to so.Count-1 do
begin
v := '';
if so.Objects[i] is TString then
v := TString(so.Objects[i]).Value
else
if so.Objects[i] is TPreParser then
v := TPreParser(so.Objects[i]).ExePath+'|'+
TPreParser(so.Objects[i]).Params;
if Reverse then
begin
if so[i]='' then
so[i] := '=';
if v='' then
begin
inc (n);
v := 'n'+IntToStr(n); //Add a default name to this value.
end;
v := v+'='+so[i];
end
else
if so[i]<>'' then
begin
if v='' then
v := '='; //add a default value '=' to name with no value
v := so[i]+'='+v;
end;
if v<>'' then
nv.Add (v);
end;
if n<>0 then
nv.Add ('N='+IntToStr(n));
end;
begin
if not InitIniWrite (FileName) then
exit;
FIni.WriteString ('global', 'virtualdomainroot', FHTTPVars.FVirtualDomainRoot);
// if not inherited SaveSettings (FileName) then
// exit;
sl := TStringList.Create;
// FI.WriteString ('ssl',..);
for i := 0 to FHTTPVars.FVirtualDomains.Count - 1 do
begin
//h contains section id
vd := TvsVirtualDomain (FHTTPVars.FVirtualDomains[i]);
h := vd.FHostName + ':';
//Save help info
if vd.FHostName = '*' then
begin
sl.Text := '#0= [+|-]/virtual_dir/=d:\physicaldir'#10+
'#1= The plus or minus determinate if the directory is'#10+
'#2= mapped recursively. + = recursive on, - = off';
WriteSectionValues (h+'PathMapping', sl);
sl.Text := '#0= CGI directory, containing executable files.'#10+
'#1= those files will be executed'#10+
'#2= Directory listing of cgi directories is not allowed'#10+
'#3= Take extreme care with cgi directories (do not map against a ftp account)'#10+
'#4= Currently cgi are executed within the servers process space.';
WriteSectionValues (h+'CGI', sl);
sl.Text := '#0= Preparsers, like php and perl are defined here'#10+
'#1= The executable is seperated from it''s parameters'#10+
'#2= by a pipe character | (vertical line). This character is mandatory'#10+
'#3= on the command line you can fill in %s to denote the path to the file'#10+
'#4= to the file to be preparsed (absolute physical path)';
WriteSectionValues (h+'PreParser', sl);
sl.Text := '#0= Manual url''s are implemented by a custom-made webserver';
WriteSectionValues (h+'ManualURL', sl);
sl.Text := '#0= A list of virtual directories for which authentication is needed.'#10+
'#1= Make sure to put some characters (or comment) after the equal sign (=)';
WriteSectionValues (h+'AuthenticationNeeded', sl);
sl.Text := '#0= A list of default documents. If exist, client will get redirected'#10+
'#1= to this document. If default document is not found, the contents of'#10+
'#2= the directory are listed.'#10+
'#3= Make sure to put some characters (or comment) after the equal sign (=)';
WriteSectionValues (h+'DefaultDocuments', sl);
sl.Text := '#0= Define addition mime types here, like: ext=mime/type';
WriteSectionValues (h+'MimeType', sl);
end;
//save settings...
StrObjToNameValue (vd.FVirtualPath, sl);
if sl.Count > 0 then
WriteSectionValues (h+'PathMapping', sl);
StrObjToNameValue (vd.FCGI, sl);
if sl.Count > 0 then
WriteSectionValues (h+'CGI', sl);
StrObjToNameValue (vd.FPreParser, sl);
if sl.Count > 0 then
WriteSectionValues (h+'PreParser', sl);
StrObjToNameValue (vd.FManualURL, sl);
if sl.Count > 0 then
WriteSectionValues (h+'ManualURL', sl);
StrObjToNameValue (vd.FAuthNeeded, sl);
if sl.Count > 0 then
WriteSectionValues (h+'AuthenticationNeeded', sl);
StrObjToNameValue (vd.FDefaultDocuments, sl);
if sl.Count > 0 then
WriteSectionValues (h+'DefaultDocuments', sl);
StrObjToNameValue (vd.FMimeTypes, sl);
if sl.Count > 0 then
WriteSectionValues (h+'MimeType', sl);
end;
sl.Free;
FinishIni;
end;
procedure TvsHTTPServer.RegisterPHP (Binary: TFileName; Extension: String=''; Domain: String='');
begin
Binary := ExpandUNCFileName(Binary);
if Extension='' then
Extension := '.php';
RegisterPreParser (Binary, Extension, Domain, '-f "%s"');
end;
function TvsHTTPHandler.GetFile(URL: String): String;
var i: Integer;
begin
i := pos ('?', URL);
if i>0 then
Result := Copy (URL, 1, i-1)
else
Result := URL;
end;
function TvsHTTPHandler.GetParams(URL: String): String;
var i: Integer;
begin
i := pos ('?', URL);
if i>0 then
Result := Copy (URL, i+1, maxint)
else
Result := '';
end;
function TvsHTTPHandler.GetPreParser(URL, Domain: String): TPreParser;
var Ext: String;
i: Integer;
VD: TvsVirtualDomain;
begin
Result := nil;
Ext := ExtractFileExt (GetFile (URL));
// Compare
VD := GetVirtualDomain (Domain);
if Assigned (VD) then
i := VD.FPreParser.IndexOf (Ext) //we ignore case.. fix.
else
i := -1; //domain does not exist.
if i>=0 then
Result := TPreParser(VD.FPreParser.Objects[i])
else //not found
if Domain<>'' then //avoid endless lookups on empty (default) domain
Result := GetPreParser (URL); //fetch parser of default (''no'') domain.
end;
function TvsHTTPHandler.GetCGIPath(URL, Domain: String): String;
var Path: String;
VD: TvsVirtualDomain;
i: Integer;
begin
Path := GetPath (URL); //S _should_ (?) be in form /path/ or /full/path/name/
VD := GetVirtualDomain (Domain);
if Assigned (VD) then
i := VD.FCGI.IndexOf (Path) //we ignore case.. fix.
else
i := -1; //domain does not exist.
if i>=0 then
Result := TString(VD.FCGI.Objects[i]).Value+PathSep+Copy (GetFile(URL), Length(Path)+1, maxint)
else
if Domain <> '' then
Result := GetCGIPath (URL, '');
end;
function TvsHTTPHandler.IsManualURL(URL, Domain: String): Boolean;
var VD: TvsVirtualDomain;
i: Integer;
begin
VD := GetVirtualDomain (Domain);
if Assigned (VD) then
i := VD.FManualURL.IndexOf (GetFile(URL)) //yeah.. case insensitive again.. fix.
else
i := -1;
if (i < 0) and (Domain <> '') then
Result := IsManualURL (URL)
else
Result := i >= 0;
end;
function TvsHTTPHandler.Compare(V1, V2: String): Boolean;
begin
if FHTTPVars.FCaseSensitive then
Result := V1 = V2
else
Result := AnsiStrComp (PChar(V1), PChar(V2))=0;
end;
function TvsHTTPHandler.GetPath(URL: String): String;
var s: String;
i: Integer;
p,q: Integer;
begin
s := GetFile (URL);
i := length (s);
while i>1 do
if s[i]='/' then
break
else
dec(i);
if i>1 then //i holds position of last slash
Result := copy (URL, 1, i)
else
Result := '/';
//Now filter out dummy paths:
//strip '/./' directories:
Result := StringReplace (Result, '/./', '/', [rfReplaceAll]);
//strip '/../' directories:
while (pos ('/../', Result)) > 0 do
begin
p := pos ('/../', Result);
q := p - 1;
while (q>1) and (Result[q] <> '/') do
dec (q);
if (q>=1) and (Result[q] = '/') then
begin
Delete (Result, q, p - q +3);
end
else
begin
Result := ''; //invalid request
exit;
end;
end;
end;
function TvsHTTPServer.GetVirtualDomain(Domain: String): TvsVirtualDomain;
var i: Integer;
begin
Domain := ParseDomain(Domain);
Result := nil;
for i:=0 to FHTTPVars.FVirtualDomains.Count - 1 do
if TvsVirtualDomain (FHTTPVars.FVirtualDomains[i]).FHostName = Domain then
begin
Result := TvsVirtualDomain (FHTTPVars.FVirtualDomains[i]);
break;
end;
//Add one if not yet exist:
if (not Assigned (Result)) then
begin //add one
Result := TvsVirtualDomain.Create;
FHTTPVars.FVirtualDomains.Add (Result);
Result.FHostName := Domain;
end;
end;
procedure TvsHTTPServer.RegisterAuthenticationDir(VirtualDir, Domain: String;
Recursive: Boolean);
var r: String;
vd : TvsVirtualDomain;
begin
if VirtualDir='' then
VirtualDir := '/';
vd := GetVirtualDomain (Domain);
with VD.FAuthNeeded do
begin
if Recursive then
r := '+'
else
r := '-';
r := r + VirtualDir;
if IndexOf (r)<0 then
Add (r);
end;
end;
{ THTTPHandler }
procedure TvsHTTPHandler.CopyCustomVars;
begin
FHTTPVars := TvsHTTPServer(FSettings.Owner).FHTTPVars;
FCallBack := TvsHTTPServer(FSettings.Owner).FCallBack;
end;
function TvsHTTPHandler.GetGetPath: TFileName;
begin
//See if handler fits in some virtual domain
end;
procedure TvsHTTPHandler.Handler; //= Thread.Execute
//some local vars not shared with procedures:
var FS: TFileStream;
i: Integer;
begin
FMode := cmWait;
while not Terminated do
begin
//Read an HTTP header
case FMode of
cmWait: //this is not limited to GET
//but it porcesses the header
//if necessary, like PUT, POST or CONNECT it will change the mode
begin
Buf := FSock.RecvTerminated (FSettings.FTimeOut{30000}, CRLF+CRLF);
//for the time being, don't support keep-alive (fix this)
//fix: if connection keep-alive mode = get
//Unless otherwise set, we close the connection after processing.
FMode := cmClose;
if Buf<>'' then
begin
FResponse.ResponseCode := 0;
ProcessRequest (Buf);
if FResponse.ResponseCode = 0 then
FResponse.ResponseCode := 400; //Unknown request
if (FResponse.ResponseCode >= 400) and
(FResponse.Data='') then //generate error doc
MakeErrorDoc;
FKeepAlive := (FMode=cmDone) and
(FResponse.ResponseCode >= 200) and
(FResponse.ResponseCode < 500) and
// (FRequest.ProtoVersion = 'HTTP/1.1') and
(lowercase(FRequest.Header.Values['Connection']) = 'keep-alive');
FKeepAlive := False; //sorry, there are bugs currently.
//keep alive conditionals:
//the client must request it
//it must not be a parsed PHP script
//since there is no content-length available.
if (FResponse.ResponseCode <> 0) then
begin //We send data ourselves:
Log (Format ('%d %s %s %s',
[FResponse.ResponseCode,
FRequest.Command,
FRequest.Parameter,
FRequest.Domain,