-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGHTTPServer.pas
More file actions
1697 lines (1490 loc) · 53.1 KB
/
GHTTPServer.pas
File metadata and controls
1697 lines (1490 loc) · 53.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
{
GHTTPServer - Simple HTTP Server Component
Author: Gecko71
Copyright: 2025
LICENSE:
========
This code is provided for non-commercial use only. The code is provided "as is"
without warranty of any kind, either expressed or implied, including but not
limited to the implied warranties of merchantability and fitness for a particular
purpose.
You are free to:
- Use this code for personal, educational, or non-commercial purposes
- Modify, adapt, or build upon this code as needed
- Share the code with others under the same license terms
You may not:
- Use this code for commercial purposes without explicit permission
- Remove this license notice from any copies or derivatives
THE AUTHOR(S) SHALL NOT BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE
OF THIS SOFTWARE.
By using this code, you acknowledge that you have read and understood
this license and agree to its terms.
}
unit GHTTPServer;
interface
uses
{$IFDEF MSWINDOWS}
WinSock, Windows,
{$ENDIF}
{$IFDEF LINUX}
Posix.SysSocket, Posix.NetinetIn, Posix.ArpaInet, Posix.Unistd, Posix.NetDB,
{$ENDIF}
SysUtils, Classes, SyncObjs, System.Threading, Logger, System.StrUtils,
HttpServerUtils, HTTPResponseBuilder, HTTPRequest, System.JSON, System.NetEncoding,
System.DateUtils, System.Hash;
type
TClientInfo = record
IP: string;
StartTime: TDateTime;
TotalBytesReceived: Integer;
HeaderEndPos: Integer;
ContentLength: Integer;
ContentLengthValid: Boolean;
HasContentLength: Boolean;
PostDataReceived: Integer;
ConnectionClosed: Boolean;
IsHTTP10: Boolean;
TimeoutValue: Double;
end;
TAuthorizationType = (atNone, atJWTBearer);
TJWTToken = record
Header: string;
Payload: string;
Signature: string;
Raw: string;
Decoded: TJSONObject;
ExpirationTime: TDateTime;
IsValid: Boolean;
Subject: string;
Issuer: string;
function GetClaim(const Name: string): string;
end;
TJWTManager = class
private
FSecretKey: string;
FIssuer: string;
FTokenExpiration: Integer; // in minutes
public
constructor Create(const ASecretKey, AIssuer: string; ATokenExpiration: Integer = 60);
function ValidateToken(const Token: string; out JWT: TJWTToken): Boolean;
function CreateToken(const Subject: string; const CustomClaims: TJSONObject = nil): string;
function ExtractTokenFromAuthHeader(const AuthHeader: string): string;
property SecretKey: string read FSecretKey write FSecretKey;
property Issuer: string read FIssuer write FIssuer;
property TokenExpiration: Integer read FTokenExpiration write FTokenExpiration;
end;
TGHTTPServer = class;
TEndpointEvent = procedure(Sender: TObject;
ARequestParser: THTTPRequestParser;
AResponseBuilder: THTTPResponseBuilder;
ASerwer:TGHTTPServer) of object;
TEndpointEventProc = reference to procedure(Sender: TObject;
ARequestParser: THTTPRequestParser;
AResponseBuilder: THTTPResponseBuilder; ASerwer:TGHTTPServer) ;
TEndpointItem = class(TCollectionItem)
private
FEndpoint: string;
FMethod: string;
FOnRequest: TEndpointEvent;
FOnRequestProc: TEndpointEventProc;
FAuthorizationType: TAuthorizationType;
FRoles: TStringList;
procedure SetEndpoint(const Value: string);
procedure SetMethod(const Value: string);
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
published
property Endpoint: string read FEndpoint write SetEndpoint;
property Method: string read FMethod write SetMethod;
property OnRequest: TEndpointEvent read FOnRequest write FOnRequest;
property OnRequestProc: TEndpointEventProc read FOnRequestProc write FOnRequestProc;
property AuthorizationType: TAuthorizationType read FAuthorizationType write FAuthorizationType default atNone;
property Roles: TStringList read FRoles;
end;
TEndpointCollection = class(TCollection)
private
FOwner: TGHTTPServer;
function GetItem(Index: Integer): TEndpointItem;
procedure SetItem(Index: Integer; Value: TEndpointItem);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TGHTTPServer);
function Add: TEndpointItem;
function FindEndpoint(const AEndpoint, AMethod: string): TEndpointItem;
property Items[Index: Integer]: TEndpointItem read GetItem write SetItem; default;
end;
TGHTTPServer = class(TComponent)
private
FPort: Integer;
FMaxConnections: Integer;
FListening: Boolean;
FServerSocket: TSocket;
FActiveConnections: Integer;
FConnectionLock: TCriticalSection;
FThreadPool: TThreadPool;
HttpLogger: THttpLogger;
FBaseDirectory: string;
FTmpBaseDirectory: string;
FMimeTypes: TStringList;
FMaxHeaderSize: Integer;
FMaxRequestTime: Double;
FMaxPostSize: Integer;
FMaxWorkerThreads: Integer;
FMinWorkerThreads: Integer;
FBufferSize: Integer;
FSendTimeout: Integer;
FFileTransferTimeout: Double;
FEndpoints:TEndpointCollection;
FGlobalIPMonitor: TIPMonitor;
FJWTManager: TJWTManager;
procedure SetServerSocket(const Value: TSocket);
procedure SetMaxWorkerThreads(const Value: Integer);
procedure SetMinWorkerThreads(const Value: Integer);
procedure SetBaseDirectory(const Value: string);
procedure SetTmpBaseDirectory(const Value: string);
procedure SetEndpoints(const Value: TEndpointCollection);
protected
procedure ProcessClientRequestNew(ClientSocket: TSocket); virtual;
function GetClientIP(ClientSocket: TSocket): string; virtual;
procedure DoHandleClient(ClientSocket: TSocket); virtual;
function ExtractUserAgent(const Request: TBytes): string; virtual;
function IsSuspiciousUserAgent(const UserAgent: string): Boolean; virtual;
function WaitForSocketReady(Socket: TSocket; ForReading: Boolean; TimeoutMs: Integer): Boolean; virtual;
procedure InitializeMimeTypes; virtual;
function CreateResponseNew(const Request: TBytes; ClientSocket: TSocket;
out Response: TBytes; AClientIP:String): Boolean; virtual;
function SocketErrorToString(ErrorCode: Integer): string;
procedure SendErrorResponse(ClientSocket: TSocket; StatusCode: Integer; Message: string; ExtraHeaders: string = ''); virtual;
public
constructor Create(AOwner: TComponent; Port: Integer; MaxConnections: Integer = 100; AHttpLogger: THttpLogger = nil);reintroduce; virtual;
destructor Destroy; override;
function GetMimeType(const FileName: string): string; virtual;
function AcceptConnection(var ClientAddr: TSockAddrIn): TSocket; virtual;
procedure SetSocketNonBlocking(Socket: TSocket); virtual;
procedure InitializeSocketLibrary; virtual;
procedure FinalizeSocketLibrary; virtual;
procedure IncrementConnections; virtual;
procedure DecrementConnections; virtual;
procedure WriteLog(log: string); virtual;
procedure HandleClient(ClientSocket: TSocket); virtual;
function ExtractBoundary(const ContentType: string): string; virtual;
procedure Start; virtual;
procedure Stop; virtual;
function GetActiveConnections: Integer; virtual;
function AddEndpoint(const AEndpoint, AMethod: string;
const AHandler: TEndpointEvent;
const AAuthorizationType: TAuthorizationType;
const ARoles: array of string): TEndpointItem; virtual;
function AddEndpointProc(const AEndpoint, AMethod: string;
const AHandler: TEndpointEventProc;
const AAuthorizationType: TAuthorizationType;
const ARoles: array of string): TEndpointItem; virtual;
procedure ConfigureJWT(const ASecretKey, AIssuer: string; AExpirationMinutes: Integer);
property ServerSocket: TSocket read FServerSocket write SetServerSocket;
property GlobalIPMonitor: TIPMonitor read FGlobalIPMonitor;
property ThreadPool: TThreadPool read FThreadPool;
property Port: Integer read FPort write FPort;
property MaxConnections: Integer read FMaxConnections write FMaxConnections;
property BaseDirectory: string read FBaseDirectory write SetBaseDirectory;
property TmpBaseDirectory: string read FTmpBaseDirectory write SetTmpBaseDirectory;
property MaxHeaderSize: Integer read FMaxHeaderSize write FMaxHeaderSize;
property MaxRequestTime: Double read FMaxRequestTime write FMaxRequestTime;
property MaxPostSize: Integer read FMaxPostSize write FMaxPostSize;
property MaxWorkerThreads: Integer read FMaxWorkerThreads write SetMaxWorkerThreads;
property MinWorkerThreads: Integer read FMinWorkerThreads write SetMinWorkerThreads;
property BufferSize: Integer read FBufferSize write FBufferSize;
property SendTimeout: Integer read FSendTimeout write FSendTimeout;
property FileTransferTimeout: Double read FFileTransferTimeout write FFileTransferTimeout;
property Endpoints: TEndpointCollection read FEndpoints write SetEndpoints;
property Listening: Boolean read FListening write FListening;
property JWTManager: TJWTManager read FJWTManager;
end;
function FindBytes(const Haystack, Needle: TBytes; StartPos: Integer = 0): Integer;
function FindHeaderEnd(const Data: TBytes; StartPos, EndPos: Integer): Integer;
function AppendBytes(const Source: TBytes; Buffer: Pointer; BytesCount: Integer): TBytes;
function BytesStartWith(const Bytes, Pattern: TBytes): Boolean;
function BytesContains(const Bytes, Pattern: TBytes): Boolean;
implementation
uses
System.IOUtils, System.Generics.Collections,
GHTTPConstants;
function BytesStartWith(const Bytes, Pattern: TBytes): Boolean;
var
i: Integer;
begin
Result := False;
if Length(Pattern) > Length(Bytes) then
Exit;
Result := True;
for i := 0 to Length(Pattern) - 1 do
if Bytes[i] <> Pattern[i] then
begin
Result := False;
Break;
end;
end;
function BytesContains(const Bytes, Pattern: TBytes): Boolean;
begin
Result := BytesPos(Bytes, Pattern) > 0;
end;
function FindBytes(const Haystack, Needle: TBytes; StartPos: Integer = 0): Integer;
var
SkipTable: array[0..255] of Integer;
i, j, NeedleLen, HaystackLen: Integer;
begin
Result := -1;
HaystackLen := Length(Haystack);
NeedleLen := Length(Needle);
if (NeedleLen = 0) or (HaystackLen = 0) or
(StartPos + NeedleLen > HaystackLen) then
Exit;
for i := 0 to 255 do
SkipTable[i] := NeedleLen;
for i := 0 to NeedleLen - 2 do
SkipTable[Needle[i]] := NeedleLen - 1 - i;
i := StartPos;
while i <= HaystackLen - NeedleLen do
begin
j := NeedleLen - 1;
while (j >= 0) and (Haystack[i + j] = Needle[j]) do
Dec(j);
if j < 0 then
begin
Result := i;
Exit;
end;
Inc(i, SkipTable[Haystack[i + NeedleLen - 1]]);
end;
end;
function FindHeaderEnd(const Data: TBytes; StartPos, EndPos: Integer): Integer;
var
i: Integer;
begin
Result := -1;
for i := StartPos to EndPos - 4 do
begin
if (Data[i] = 13) and (Data[i + 1] = 10) and
(Data[i + 2] = 13) and (Data[i + 3] = 10) then
begin
Result := i;
Exit;
end;
end;
end;
function AppendBytes(const Source: TBytes; Buffer: Pointer; BytesCount: Integer): TBytes;
var
SourceLen, NewSize: Integer;
begin
SourceLen := Length(Source);
NewSize := SourceLen + BytesCount;
SetLength(Result, NewSize);
if SourceLen > 0 then
Move(Source[0], Result[0], SourceLen);
if BytesCount > 0 then
Move(Buffer^, Result[SourceLen], BytesCount);
end;
{ TJWTToken }
function TJWTToken.GetClaim(const Name: string): string;
var
Value: TJSONValue;
begin
Result := '';
if Assigned(Decoded) then
begin
Value := Decoded.FindValue(Name);
if Assigned(Value) then
Result := Value.Value;
end;
end;
{ TJWTManager }
constructor TJWTManager.Create(const ASecretKey, AIssuer: string; ATokenExpiration: Integer);
begin
inherited Create;
FSecretKey := ASecretKey;
FIssuer := AIssuer;
FTokenExpiration := ATokenExpiration;
end;
function TJWTManager.ExtractTokenFromAuthHeader(const AuthHeader: string): string;
begin
Result := '';
if StartsText('Bearer ', AuthHeader) then
Result := Trim(Copy(AuthHeader, 8, MaxInt));
end;
function TJWTManager.ValidateToken(const Token: string; out JWT: TJWTToken): Boolean;
var
TokenParts: TArray<string>;
HeaderStr, PayloadStr, SignatureStr: string;
ExpectedSignature: string;
PayloadObj: TJSONObject;
ExpClaim, IssuerClaim, SubjectClaim: TJSONValue;
ExpTime: Int64;
IssuerValue, SubjectValue: string;
PayloadBytes: TBytes;
JsonStr: string;
begin
Result := False;
JWT.IsValid := False;
JWT.Raw := Token;
JWT.Decoded := nil;
TokenParts := Token.Split(['.']);
if Length(TokenParts) <> 3 then
Exit;
HeaderStr := TokenParts[0];
PayloadStr := TokenParts[1];
SignatureStr := TokenParts[2];
try
ExpectedSignature := TNetEncoding.Base64Url.EncodeBytesToString(
THashSHA2.GetHashBytes(HeaderStr + '.' + PayloadStr + FSecretKey, THashSHA2.TSHA2Version.SHA256));
except
Exit;
end;
if ExpectedSignature <> SignatureStr then
Exit;
JWT.Signature := SignatureStr;
try
JWT.Header := HeaderStr;
JWT.Payload := PayloadStr;
PayloadBytes := TNetEncoding.Base64Url.DecodeStringToBytes(PayloadStr);
JsonStr := '';
try
JsonStr := TEncoding.UTF8.GetString(PayloadBytes);
except
on E: EEncodingError do
begin
JsonStr := TEncoding.ANSI.GetString(PayloadBytes);
end;
end;
except
on E: Exception do
begin
Exit;
end;
end;
PayloadObj := nil;
try
try
PayloadObj := TJSONObject.ParseJSONValue(JsonStr) as TJSONObject;
if not Assigned(PayloadObj) then
Exit;
ExpClaim := PayloadObj.FindValue('exp');
if Assigned(ExpClaim) and ExpClaim.TryGetValue<Int64>(ExpTime) then
begin
JWT.ExpirationTime := UnixToDateTime(ExpTime);
if Now > JWT.ExpirationTime then
Exit;
end;
IssuerValue := '';
SubjectValue := '';
IssuerClaim := PayloadObj.FindValue('iss');
if Assigned(IssuerClaim) then
IssuerValue := IssuerClaim.Value;
SubjectClaim := PayloadObj.FindValue('sub');
if Assigned(SubjectClaim) then
SubjectValue := SubjectClaim.Value;
if (FIssuer <> '') and (IssuerValue <> FIssuer) then
Exit;
JWT.Decoded := PayloadObj;
JWT.Subject := SubjectValue;
JWT.Issuer := IssuerValue;
JWT.IsValid := True;
Result := True;
if Result then
PayloadObj := nil;
except
on E: Exception do
begin
Result := False;
end;
end;
finally
if Assigned(PayloadObj) then
FreeAndNil(PayloadObj);
end;
end;
function TJWTManager.CreateToken(const Subject: string; const CustomClaims: TJSONObject): string;
var
Header, Payload: TJSONObject;
HeaderBase64, PayloadBase64, Signature: string;
begin
Header := TJSONObject.Create;
Payload := TJSONObject.Create;
try
Header.AddPair('alg', 'HS256');
Header.AddPair('typ', 'JWT');
Payload.AddPair('sub', Subject);
Payload.AddPair('iss', FIssuer);
Payload.AddPair('iat', TJSONNumber.Create(DateTimeToUnix(Now)));
Payload.AddPair('exp', TJSONNumber.Create(DateTimeToUnix(IncMinute(Now, FTokenExpiration))));
if Assigned(CustomClaims) then
begin
for var Pair in CustomClaims do
Payload.AddPair(Pair.JsonString.Value, Pair.JsonValue.Clone as TJSONValue);
end;
HeaderBase64 := TNetEncoding.Base64Url.Encode(Header.ToString);
PayloadBase64 := TNetEncoding.Base64Url.Encode(Payload.ToString);
Signature := TNetEncoding.Base64Url.EncodeBytesToString(
THashSHA2.GetHashBytes(HeaderBase64 + '.' + PayloadBase64 + FSecretKey, THashSHA2.TSHA2Version.SHA256));
Result := HeaderBase64 + '.' + PayloadBase64 + '.' + Signature;
finally
Header.Free;
Payload.Free;
end;
end;
{ TEndpointItem }
constructor TEndpointItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FEndpoint := ENDPOINT_DEFAULT;
FMethod := HTTP_METHOD_GET;
FOnRequest := nil;
FOnRequestProc := nil;
FAuthorizationType := atNone;
FRoles := TStringList.Create;
FRoles.Sorted := True;
FRoles.Duplicates := dupIgnore;
end;
destructor TEndpointItem.Destroy;
begin
FRoles.Free;
inherited;
end;
procedure TEndpointItem.SetEndpoint(const Value: string);
begin
if FEndpoint <> Value then
begin
FEndpoint := Value;
Changed(False);
end;
end;
procedure TEndpointItem.SetMethod(const Value: string);
begin
if FMethod <> Value then
begin
FMethod := UpperCase(Value);
Changed(False);
end;
end;
function TEndpointItem.GetDisplayName: string;
begin
Result := Format('%s %s', [FMethod, FEndpoint]);
end;
{ TEndpointCollection }
constructor TEndpointCollection.Create(AOwner: TGHTTPServer);
begin
inherited Create(TEndpointItem);
FOwner := AOwner;
end;
function TEndpointCollection.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TEndpointCollection.GetItem(Index: Integer): TEndpointItem;
begin
Result := TEndpointItem(inherited GetItem(Index));
end;
procedure TEndpointCollection.SetItem(Index: Integer; Value: TEndpointItem);
begin
inherited SetItem(Index, Value);
end;
function TEndpointCollection.Add: TEndpointItem;
begin
Result := TEndpointItem(inherited Add);
end;
function TEndpointCollection.FindEndpoint(const AEndpoint, AMethod: string): TEndpointItem;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
begin
if (Items[I].Endpoint = AEndpoint) and (Items[I].Method = AMethod) then
begin
Result := Items[I];
Break;
end;
end;
end;
{ TGHTTPServer }
constructor TGHTTPServer.Create(AOwner: TComponent; Port: Integer;
MaxConnections: Integer = 100; AHttpLogger: THttpLogger = nil);
begin
inherited Create(AOwner);
FEndpoints := TEndpointCollection.Create(self);
FGlobalIPMonitor := TIPMonitor.Create(AHttpLogger);
HttpLogger := AHttpLogger;
FPort := Port;
FMaxConnections := MaxConnections;
FListening := False;
FActiveConnections := 0;
FConnectionLock := TCriticalSection.Create;
FThreadPool := TThreadPool.Create;
FJWTManager := TJWTManager.Create('DefaultSecretKey', 'GHTTPServer', 60);
FMaxWorkerThreads := 100;
FMinWorkerThreads := 10;
FMaxHeaderSize := 8192;
FMaxRequestTime := 30 / (24 * 3600); // 30 seconds for headers
FFileTransferTimeout := 300 / (24 * 3600); // 5 minutes for file transfers
FMaxPostSize := 100 * 1024 * 1024; // 100 MB
FBufferSize := 65536; // 64KB chunks
FSendTimeout := 10000; // 10 seconds
FThreadPool.SetMaxWorkerThreads(FMaxWorkerThreads);
FThreadPool.SetMinWorkerThreads(FMinWorkerThreads);
FBaseDirectory := TPath.Combine(ExtractFilePath(ParamStr(0)), DEFAULT_FILES_DIR);
FTmpBaseDirectory := TPath.Combine(ExtractFilePath(ParamStr(0)), DEFAULT_TMP_DIR);
if not TDirectory.Exists(FBaseDirectory) then
begin
if not ForceDirectories(FBaseDirectory) then
raise Exception.Create(ERROR_DIRECTORY_CREATE_FAILED + FBaseDirectory);
end;
FBaseDirectory := IncludeTrailingPathDelimiter(FBaseDirectory);
if not TDirectory.Exists(FTmpBaseDirectory) then
begin
if not ForceDirectories(FTmpBaseDirectory) then
raise Exception.Create(ERROR_DIRECTORY_CREATE_FAILED + FTmpBaseDirectory);
end;
FTmpBaseDirectory := IncludeTrailingPathDelimiter(FTmpBaseDirectory);
FMimeTypes := TStringList.Create;
InitializeMimeTypes;
end;
destructor TGHTTPServer.Destroy;
begin
Stop;
FConnectionLock.Free;
FThreadPool.Free;
FMimeTypes.Free;
FJWTManager.Free;
GlobalIPMonitor.Free;
FEndpoints.Free;
inherited;
end;
procedure TGHTTPServer.SetServerSocket(const Value: TSocket);
begin
FServerSocket := Value;
end;
procedure TGHTTPServer.SetBaseDirectory(const Value: string);
begin
FBaseDirectory := TPath.Combine(ExtractFilePath(ParamStr(0)), DEFAULT_FILES_DIR);
if not TDirectory.Exists(FBaseDirectory) then
begin
if not ForceDirectories(FBaseDirectory) then
raise Exception.Create(ERROR_DIRECTORY_CREATE_FAILED + FBaseDirectory);
end;
FBaseDirectory := IncludeTrailingPathDelimiter(FBaseDirectory);
WriteLog(Format(MSG_BASE_DIRECTORY_SET, [FBaseDirectory]));
end;
procedure TGHTTPServer.SetTmpBaseDirectory(const Value: string);
begin
FTmpBaseDirectory := TPath.Combine(ExtractFilePath(ParamStr(0)), DEFAULT_FILES_DIR);
if not TDirectory.Exists(FTmpBaseDirectory) then
begin
if not ForceDirectories(FTmpBaseDirectory) then
raise Exception.Create(ERROR_DIRECTORY_CREATE_FAILED + FTmpBaseDirectory);
end;
FBaseDirectory := IncludeTrailingPathDelimiter(FTmpBaseDirectory);
WriteLog(Format(MSG_BASE_DIRECTORY_SET, [FTmpBaseDirectory]));
end;
procedure TGHTTPServer.SetEndpoints(const Value: TEndpointCollection);
begin
FEndpoints.Assign(Value);
end;
procedure TGHTTPServer.SetMaxWorkerThreads(const Value: Integer);
begin
if Value > 0 then
begin
FMaxWorkerThreads := Value;
if Assigned(FThreadPool) then
FThreadPool.SetMaxWorkerThreads(Value);
end;
end;
procedure TGHTTPServer.SetMinWorkerThreads(const Value: Integer);
begin
if Value > 0 then
begin
FMinWorkerThreads := Value;
if Assigned(FThreadPool) then
FThreadPool.SetMinWorkerThreads(Value);
end;
end;
procedure TGHTTPServer.SetSocketNonBlocking(Socket: TSocket);
{$IFDEF MSWINDOWS}
var
NonBlocking: u_long;
{$ENDIF}
{$IFDEF LINUX}
var
Flags: Integer;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
NonBlocking := 1;
ioctlsocket(Socket, FIONBIO, NonBlocking);
{$ENDIF}
{$IFDEF LINUX}
Flags := fcntl(Socket, F_GETFL, 0);
fcntl(Socket, F_SETFL, Flags or O_NONBLOCK);
{$ENDIF}
end;
function TGHTTPServer.WaitForSocketReady(Socket: TSocket; ForReading: Boolean; TimeoutMs: Integer): Boolean;
var
FDSet: TFDSet;
TimeVal: TTimeVal;
SelectResult: Integer;
begin
FD_ZERO(FDSet);
FD_SET(Socket, FDSet);
TimeVal.tv_sec := TimeoutMs div 1000;
TimeVal.tv_usec := (TimeoutMs mod 1000) * 1000;
if ForReading then
SelectResult := select(Socket + 1, @FDSet, nil, nil, @TimeVal)
else
SelectResult := select(Socket + 1, nil, @FDSet, nil, @TimeVal);
Result := SelectResult > 0;
end;
procedure TGHTTPServer.InitializeSocketLibrary;
{$IFDEF MSWINDOWS}
var
WSAData: TWSAData;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
if WSAStartup($202, WSAData) <> 0 then
raise Exception.Create(ERROR_WSA_STARTUP);
{$ENDIF}
end;
procedure TGHTTPServer.FinalizeSocketLibrary;
begin
{$IFDEF MSWINDOWS}
WSACleanup;
{$ENDIF}
end;
procedure TGHTTPServer.WriteLog(log: string);
begin
try
HttpLogger.Log(log);
except
end;
end;
function TGHTTPServer.GetClientIP(ClientSocket: TSocket): string;
var
SockAddr: TSockAddr;
AddrLen: Integer;
IPAddrStr: PAnsiChar;
begin
AddrLen := SizeOf(SockAddr);
Result := IP_ANY_ADDRESS;
if getpeername(ClientSocket, SockAddr, AddrLen) = 0 then
begin
if SockAddr.sa_family = AF_INET then
begin
IPAddrStr := inet_ntoa(PSockAddrIn(@SockAddr)^.sin_addr);
Result := string(IPAddrStr);
end
else
begin
Result := IP_VALUE_UNKNOWN;
end;
end;
WriteLog(Format(LOG_CONNECTION_FROM_IP, [Result]));
end;
procedure TGHTTPServer.Start;
var
ServerAddr: TSockAddrIn;
ClientAddr: TSockAddrIn;
OptVal: Integer;
begin
InitializeSocketLibrary;
FServerSocket := socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if FServerSocket = INVALID_SOCKET then
raise Exception.Create(ERROR_SOCKET_CREATION);
OptVal := 1;
setsockopt(FServerSocket, SOL_SOCKET, SO_REUSEADDR, @OptVal, SizeOf(OptVal));
ServerAddr.sin_family := AF_INET;
ServerAddr.sin_addr.s_addr := INADDR_ANY;
ServerAddr.sin_port := htons(FPort);
if bind(FServerSocket, ServerAddr, SizeOf(ServerAddr)) = SOCKET_ERROR then
raise Exception.Create(ERROR_BIND_FAILED);
if listen(FServerSocket, SOMAXCONN) = SOCKET_ERROR then
raise Exception.Create(ERROR_LISTEN_FAILED);
FListening := True;
WriteLog(Format(LOG_SERVER_STARTED, [FPort]));
while FListening do
begin
var ClientSocket := AcceptConnection(ClientAddr);
if ClientSocket = INVALID_SOCKET then
Continue;
SetSocketNonBlocking(ClientSocket);
if GetActiveConnections >= FMaxConnections then
begin
WriteLog(LOG_TOO_MANY_CONNECTIONS);
{$IFDEF MSWINDOWS}
closesocket(ClientSocket);
{$ENDIF}
{$IFDEF LINUX}
__close(ClientSocket);
{$ENDIF}
Continue;
end;
HandleClient(ClientSocket);
end;
end;
function TGHTTPServer.AcceptConnection(var ClientAddr: TSockAddrIn): TSocket;
{$IFDEF MSWINDOWS}
var
AddrLen: Integer;
{$ENDIF}
{$IFDEF LINUX}
type
socklen_t = UInt32;
var
AddrLen: socklen_t;
{$ENDIF}
begin
AddrLen := SizeOf(ClientAddr);
Result := accept(FServerSocket, @ClientAddr, @AddrLen);
end;
procedure TGHTTPServer.HandleClient(ClientSocket: TSocket);
begin
IncrementConnections;
DoHandleClient(ClientSocket);
end;
procedure TGHTTPServer.DoHandleClient(ClientSocket: TSocket);
begin
TTask.Run(procedure
begin
try
ProcessClientRequestNew(ClientSocket);
finally
DecrementConnections;
{$IFDEF MSWINDOWS}
closesocket(ClientSocket);
{$ENDIF}
{$IFDEF LINUX}
__close(ClientSocket);
{$ENDIF}
end;
end, FThreadPool);
end;
procedure TGHTTPServer.IncrementConnections;
begin
FConnectionLock.Enter;
try
Inc(FActiveConnections);
finally
FConnectionLock.Leave;
end;
end;
procedure TGHTTPServer.DecrementConnections;
begin
FConnectionLock.Enter;
try
Dec(FActiveConnections);
finally
FConnectionLock.Leave;
end;
end;
procedure TGHTTPServer.Stop;
begin
FListening := False;
if FServerSocket <> INVALID_SOCKET then
begin
{$IFDEF MSWINDOWS}
shutdown(FServerSocket, SD_BOTH);
closesocket(FServerSocket);
{$ENDIF}
{$IFDEF LINUX}
shutdown(FServerSocket, SHUT_RDWR);
__close(FServerSocket);
{$ENDIF}
FServerSocket := INVALID_SOCKET;
end;
FinalizeSocketLibrary;
WriteLog(LOG_SERVER_STOPPED);
end;
function TGHTTPServer.GetActiveConnections: Integer;
begin
FConnectionLock.Enter;
try
Result := FActiveConnections;
finally
FConnectionLock.Leave;
end;
end;
function TGHTTPServer.ExtractBoundary(const ContentType: string): string;
var
BoundaryPos: Integer;
begin
Result := '';
BoundaryPos := Pos(HEADER_BOUNDARY_PREFIX, ContentType);
if BoundaryPos > 0 then
begin
Result := Copy(ContentType, BoundaryPos + 9, MaxInt);
if (Result <> '') and (Result[1] = '"') then
Result := Copy(Result, 2, Length(Result) - 2);
end;
end;
function TGHTTPServer.AddEndpoint(const AEndpoint, AMethod: string;
const AHandler: TEndpointEvent;
const AAuthorizationType: TAuthorizationType;
const ARoles: array of string): TEndpointItem;
begin
Result := FEndpoints.Add;
Result.Endpoint := AEndpoint;
Result.Method := AMethod;
Result.OnRequest := AHandler;
Result.AuthorizationType := AAuthorizationType;
for var Role in ARoles do
Result.Roles.Add(Role);
end;
function TGHTTPServer.AddEndpointProc(const AEndpoint, AMethod: string;
const AHandler: TEndpointEventProc;
const AAuthorizationType: TAuthorizationType;
const ARoles: array of string): TEndpointItem;
begin
Result := FEndpoints.Add;
Result.Endpoint := AEndpoint;
Result.Method := AMethod;
Result.OnRequestProc := AHandler;
Result.AuthorizationType := AAuthorizationType;
for var Role in ARoles do
Result.Roles.Add(Role);
end;
procedure TGHTTPServer.ConfigureJWT(const ASecretKey, AIssuer: string; AExpirationMinutes: Integer);
begin
FJWTManager.SecretKey := ASecretKey;
FJWTManager.Issuer := AIssuer;
FJWTManager.TokenExpiration := AExpirationMinutes;
end;
procedure TGHTTPServer.SendErrorResponse(ClientSocket: TSocket; StatusCode: Integer; Message: string; ExtraHeaders: string = '');
var
ResponseText: string;
ResponseBytes: TBytes;
ErrorCode: Integer;
begin
ResponseText := Format(HTTP_RESPONSE_FORMAT,
[StatusCode, Message, Length(Message)]);
if ExtraHeaders <> '' then
ResponseText := ResponseText + ExtraHeaders + #13#10;
ResponseText := ResponseText + #13#10 + Message;
ResponseBytes := TEncoding.ASCII.GetBytes(ResponseText);
ErrorCode := send(ClientSocket, ResponseBytes[0], Length(ResponseBytes), 0);
if ErrorCode = SOCKET_ERROR then
WriteLog(Format(LOG_ERROR_SENDING_RESPONSE, [StatusCode]));
end;
procedure TGHTTPServer.ProcessClientRequestNew(ClientSocket: TSocket);