-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSynHttpSrv.pas
3333 lines (3132 loc) · 87 KB
/
SynHttpSrv.pas
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
{--------------------------------------------------------------}
{ SynHttpSrv.pas - HTTP server over Synapse }
{ Author: Semi }
{ Started: 070528 }
{--------------------------------------------------------------}
unit SynHttpSrv;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ELSE}
SynaUtil,
{$ENDIF}
SysUtils,
Classes,
blcksock,
SynSrv;
//-------------------------------------------------------------
{$undef DEBUG}
//{$define DEBUG}
type
// Result: True=found/stop, False=continue
THeaderEnum = function(const Value: string; LParam: NativeUInt): boolean of object;
THeaderList = class(TStringList)
private
function GetValueByName(const Name: string): string;
procedure SetValueByName(const Name, Value: string);
function GetNameByIndex(Index: integer): string;
function GetValueByIndex(Index: integer): string;
function CheckHttpFindValue(const Value: string; LParam: NativeUInt): boolean;
function GetSubValue(const Name, SubName: string): string;
procedure SetSubValue(const Name, SubName, Value: string);
protected
procedure Put(Index: integer; const S: string); override;
public
property Values[const Name: string]: string Read GetValueByName Write SetValueByName; default;
//
property Names[Index: integer]: string Read GetNameByIndex;
property ValuesByIndex[Index: integer]: string Read GetValueByIndex;
property SubValues[const Name, SubName: string]: string Read GetSubValue Write SetSubValue;
// for 'ContentType: text/html; charset="Windows-1250"', SubValues['Content-Type','charset']
//
function IndexOfName(const Name: string): integer; reintroduce;
procedure AddValue(const Name, Value: string); // add (possibly duplicate) value...
function RemoveValue(const Name: string): boolean; // used also by writing Values[Name]:='';
//
// Enumerates duplicated or comma-separated headers:
procedure EnumHeaders(const Name: string; const Enum: THeaderEnum; const Sep: char; LParam: NativeUInt = 0);
function HasValue(const Name, Value: string): boolean; // Connection: upgrade, close
function Add(const S: string): integer; override;
procedure Insert(Index: integer; const S: string); override;
end;
THttpCookie = class(TCollectionItem)
private
FName: string;
FValue: string;
FDomain: string;
FPath: string;
FExpires: string;
FVersion: string;
FMaxAge: string;
FComment: string;
FSecure: boolean;
FSameSite:boolean;
function GetText: string;
public
property Name: string Read FName Write FName;
property Value: string Read FValue Write FValue;
property Text: string Read GetText;
//
property Domain: string Read FDomain Write FDomain;
property Path: string Read FPath Write FPath;
property Version: string Read FVersion Write FVersion;
property MaxAge: string Read FMaxAge Write FMaxAge;
property Comment: string Read FComment Write FComment;
property Secure: boolean Read FSecure Write FSecure;
property SameSite: boolean Read FSameSite Write FSameSite;
property Expires: string Read FExpires Write FExpires; // obsolette...
//
procedure DeleteCookie; // set MaxAge:='0'; so that client will delete the cookie...
//
procedure Assign(Source: TPersistent); override;
//
function GetServerCookie: string; // Set-Cookie: format... (for sending server->client)
function GetClientCookie: string; // Cookie: format... (for sending client->server)
function ParseValue(Line: string; Version: NativeUInt): boolean;
// parse either Cookie: or SetCookie: header part, 1 cookie at a time...
function MatchPath(const aPath: string): boolean; // is it cookie for this path?
end;
{ THttpCookies }
THttpCookies = class(TCollection)
private
function GetCookieItem(Index: integer): THttpCookie;
function AddCookieValue(const Value: string; LParam: NativeUInt): boolean;
function GetValue(const Name: string): string;
procedure SetValue(const Name, Value: string);
function GetCommaText: string;
public
constructor Create;
//
property Cookies[Index: integer]: THttpCookie Read GetCookieItem; default;
function IndexOf(const Name: string): integer;
function Find(const Name: string): THttpCookie;
//
// Load cookies from client, used in server... (Cookie: headers)
procedure LoadClientCookies(Headers: THeaderList);
// Save cookies to client, used in server...
procedure SaveServerCookies(Headers: THeaderList; const DefaultDomain, DefaultPath: string);
//
// Load cookies from server, used in client... (Set-Cookie: headers)
procedure LoadServerCookies(Headers: THeaderList);
// Save cookies to server, used in client...
procedure SaveClientCookies(Headers: THeaderList; const Path: string);
//
// Other client-side functions:
procedure MergeCookies(Source: THttpCookies);
procedure SetDefaultPath;
procedure SetSameSite;
property Values[const Name: string]: string Read GetValue Write SetValue;
property CommaText: string Read GetCommaText;
end;
// HTTP request and response object
{ THttpRequest }
THttpRequest = class(TPersistent)
private
FHeaders: THeaderList;
FCookies: THttpCookies;
FParams: TStringList;
FPostStream: TStream;
FUrl: string;
FMethod: string;
FProtocol: string;
FContent: string;
//FContentStream: TStream;
FStatusCode: integer;
FStatusMsg: string;
FConnection: TObject;
FFlags: integer;
FResponseSent: boolean;
FCharSet: string;
FDocument: string;
procedure SetHeaders(Value: THeaderList);
procedure SetCookies(Value: THttpCookies);
procedure SetStatusCode(Value: integer);
function GetFlagBool(Index: integer): boolean;
procedure SetFlagBool(Index: integer; Value: boolean);
function GetStrProp(Index: integer): string;
procedure SetStrProp(Index: integer; const Value: string);
function GetDateProp(Index: integer): TDateTime;
procedure SetDateProp(Index: integer; const Value: TDateTime);
//
procedure ApplyHeaders(bnIsServer: boolean); virtual;
// parse Cookies and possibly other things from Headers... used by TSynHttpServer.ReadRequest
function AddMultiPartFormItem(Headers: THeaderList; const FieldName, Content: string): boolean;
procedure SetCharSet(const Value: string);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
//
property Headers: THeaderList Read FHeaders Write SetHeaders; // Set assigns copy...
//
property Cookies: THttpCookies Read FCookies Write SetCookies; // Set assigns copy...
//
property Url: string Read FUrl; // '/index.html'
property Document: string Read FDocument;
property Method: string Read FMethod; // 'GET'
property Protocol: string Read FProtocol; // 'HTTP/1.1'
// also MUST include Headers['Host'] value...
//
property StatusCode: integer Read FStatusCode Write SetStatusCode; // 200
property StatusMsg: string Read FStatusMsg Write FStatusMsg; // 'OK'
//
property Content: string Read FContent Write FContent;
//property ContentStream: TStream Read FContentStream Write FContentStream; // stream is owned by the Request...
property SendChunked: boolean index 1 Read GetFlagBool Write SetFlagBool;
// set to True to prevent asking Stream.Size and send in chunked mode (without Content-length)
//
property Connection: TObject Read FConnection Write FConnection; // TSynTcpSrvConnection usually...
//
// Params contain 'Name=Value' for parameters in ?params in url and for POST params inside content:
// When posting files, Params does NOT contain file data, only FileName, use GetPostFormParam to retrieve file data...
property Params: TStringList Read FParams; // use Request.Params.Values[ParamName]
property PostStream: TStream Read FPostStream Write FPostStream;
function GetPostFormParam(const ParamName: string; var ParamData: string): boolean;
// get 1 param from multipart/form-data or application/x-www-form-urlencoded...
//
// Common operations for application for making reply:
procedure ServeFile(const LocalFileName: string);
// open file in ContentStream, set Last-Modified, Content-Length, Content-Type
procedure Redirect(const aUrl: string); // set 302 redirection and Location: header
//
// Functions used by server/client:
procedure ParseFirstRequestLine(Line: string); // parse: 'GET /index.html HTTP/1.1' // used by server
procedure ParseFirstResponseLine(Line: string); // parse: 'HTTP/1.1 200 OK' // used by client
function GetFirstResponseLine: string; // format: 'HTTP/1.1 200 OK' // used by server
function GetFirstRequestLine: string; // format: 'GET /index.html HTTP/1.1' // used by client
procedure ParsePostFormData;
// parse Content string into Params, used usually by Server (for POST requests with propper Content-Type)
//
function MatchTag(Etags: string): boolean;
// Etags may have multiple tags, comma-separated... returns True, if some of them is identical with Etag...
//
// Common Header properties:
property ContentType: string index 0 Read GetStrProp Write SetStrProp; // 'text/html; charset="Windows-1250"'
property BaseContentType: string index 1 Read GetStrProp; // 'text/html'
property CharSet: string Read FCharSet Write SetCharSet;
property ContentDisposition: string index 2 Read GetStrProp Write SetStrProp;
// 'attachment; filename=targetfile.html'
property TargetFileName: string index 3 Read GetStrProp Write SetStrProp;
// name, by which this should be saved by client (in Content-Disposition)
property Location: string index 4 Read GetStrProp Write SetStrProp; // Location: header
property Etag: string index 5 Read GetStrProp Write SetStrProp;
// Etag is used for caches, so that they may know, that their copy is exactly identical with current data (having same Etag for same URL means it is exactly identical...)
property Host: string index 6 Read GetStrProp Write SetStrProp; // must be in Request
property Referer: string index 7 Read GetStrProp Write SetStrProp;
property UserAgent: string index 8 Read GetStrProp Write SetStrProp;
property Vary: string index 9 Read GetStrProp Write SetStrProp;
// list of headers, for which the response varies... used by caches...
property WwwAuthenticate: string index 10 Read GetStrProp Write SetStrProp;
// authentication challenge, used with 401 status-code... see RFC2617...
property Authorization: string index 11 Read GetStrProp Write SetStrProp; // Authorization: value, sent by client
property Boundary: string index 12 Read GetStrProp Write SetStrProp;
// Content-Type: multipart/any; boundary=0123456789
property ContentEncoding: string index 13 Read GetStrProp Write SetStrProp;
property CacheControl: string index 14 Read GetStrProp Write SetStrProp;
property Pragma: string index 15 Read GetStrProp Write SetStrProp;
property ServerSoftware: string index 16 Read GetStrProp Write SetStrProp;
property AcceptEncoding: string index 17 Read GetStrProp Write SetStrProp;
property ContentLength: string index 18 Read GetStrProp Write SetStrProp;
property TransferEncoding: string index 19 Read GetStrProp Write SetStrProp;
//
property Date: TDateTime index 0 Read GetDateProp Write SetDateProp;
// local date of serving the request (is converted to UTC) (filled by Server)
property LastModified: TDateTime index 1 Read GetDateProp Write SetDateProp;
// local date of file modification (is converted to UTC) (filled by ServeFile method)
property LastModifiedUTC: TDateTime index 2 Read GetDateProp Write SetDateProp;
// UTC date of file modification (filled by ServeFile method)
property Expires: TDateTime index 3 Read GetDateProp Write SetDateProp;
// UTC date of expiration (for caches, allows caching of otherwise-non-cacheable responses)
property ResponseSent: boolean Read FResponseSent Write FResponseSent;
end;
TSynOnHttpGet = procedure(Sender: TObject; Connection: TSynTcpSrvConnection;
Request, Response: THttpRequest) of object;
TSynOnHttpExpect = procedure(Sender: TObject; Request: THttpRequest; var bnContinue: boolean) of object;
TSynHTTPCreatePostStream = procedure(Sender: TObject; Request: THttpRequest; var PostStream: TStream) of object;
// Virtual HTTP server.
// This level does some RFC2616 stuff for you,
// but it does NOT resolve URL->filename, which must be done in OnHttpGet method.
{ TSynHttpServer }
TSynHttpServer = class(TSynTcpServer)
private
FOnCreatePostStream: TSynHTTPCreatePostStream;
FOnHttpGet: TSynOnHttpGet;
FOnExpect: TSynOnHttpExpect;
FCertFile: string;
FKeyFile: string;
FKeyPass: string;
FCaCertFile: string;
procedure HandleClientCommand(Connection: TSynTcpSrvConnection; Command: string);
procedure CreatePostStream(Request: THttpRequest);
protected
procedure ReadRequest(Connection: TSynTcpSrvConnection; Request, Reply: THttpRequest; Command: string); virtual;
procedure DoHttpGet(Connection: TSynTcpSrvConnection; Request, Reply: THttpRequest); virtual;
procedure SetActive(Value: boolean); override;
public
constructor Create(AOwner: TComponent); override;
//
procedure InitHttps(const CertFile, KeyFile, KeyPassword, CaCertFile: string);
procedure SendReply(Connection: TSynTcpSrvConnection; Request, Reply: THttpRequest); virtual;
//
published
property Port;//default '80';
//
property OnHttpGet: TSynOnHttpGet Read FOnHttpGet Write FOnHttpGet;
property OnExpect: TSynOnHttpExpect Read FOnExpect Write FOnExpect;
property OnCreatePostStream: TSynHTTPCreatePostStream Read FOnCreatePostStream Write FOnCreatePostStream;
end;
var
// Value for Server: header...
ServerValue: string = 'SynHttpSrv/1.0';
function ReadHeadersFromSocket(Socket: TTCPBlockSocket; Headers: THeaderList; LineTimeout: integer = 0): boolean;
function SendSocketStream(Socket: TTcpBlockSocket; Stream: TStream; MaxSize: int64 = -1;
bnHttpChunked: boolean = False): boolean;
const
cProtoHttp10 = 'HTTP/1.0';
cProtoHttp11 = 'HTTP/1.1';
function GetHttpStatusMsg(StatusCode: integer; var StatusMsg: string): boolean;
//-----------------------------------------------------------------------------
// string utility functions:
// Trim(Copy(S,Pos,Count));
function TrimCopy(const S: string; Pos, Count: integer): string;
// trim inplace:
procedure DoTrim(var S: string);
// remove first token, no quoting:
function FetchToken(var Line: string; const Sep: string; bnTrim: boolean): string;
// "Quote value, using \" and \\ inside..."
function QuoteValue(const Value: string): string;
// remove first comma-separated value, possibly quoted
function FetchQSepValue(var Line: string; const Sep: string): string;
// for parsing: remove first Name="Value", separators either ";" or ","
function FetchDequoted(var Line: string; out Name, Value: string): boolean;
// get value from Name="Value" in multi-prop header value: (from 'text/html; charset="Windows-1250"' can extract charset...)
function GetHeaderSubValue(Header: string; const Name: string): string;
procedure ReplaceHeaderSubValue(var Header: string; const Name, Value: string);
function CombineStrings(Strings: TStrings; const Separator: string): string;
// SameHead == SameText(Copy(Str,1,Length(SHead)),SHead)
function SameHead(const Str, SHead: string): boolean;
// multipart parsing...
type
// Result: True=found/stop, False=continue
TMultipartEnumCallback = function(Headers: THeaderList; const FieldName, Content: string): boolean of object;
procedure EnumMultiPart(ContentData, Boundary: string; const Enum: TMultipartEnumCallback);
// Date - in HTTP (RFC2616), all dates MUST be in GMT (utc) format...
function FormatHttpDate(LocalDate: TDateTime; bnIsLocal: boolean): string;
function ParseHttpDate(Str: string; out DateTime: TDateTime): boolean;
function LocalToUtcDateTime(LocalDate: TDateTime): TDateTime;
function UtcToLocalDateTime(UtcDate: TDateTime): TDateTime;
function TimeZoneBiasTime: TDateTime;
function GetFileDateUtc(const FileName: string): TDateTime;
// Content-Type detection used by THttpRequest.ServeFile
function DetectContentType(const FileName: string): string;
function GetContentTypeByExt(const Ext: string): string;
// RegisterContentType can be used to register content-types by extension from user configuration:
procedure RegisterContentType(const Ext, ContentType: string);
{$ifdef MSWINDOWS}
// Automatically register content-types for all file extensions from registry...
procedure RegisterContentTypesFromRegistry;
{$endif MSWINDOWS}
// convert 'Documents%20and%20Settings' to 'Documents and Settings', also handles utf8 encoded in %C4%8D...
function ConvertUrlChars(Url: string): string;
procedure TryDecodeUtf8(var Url: string); // used by ConvertUrlChars...
var
// location of /error.html file, used by THttpRequest.ServerFile:
Error404Url: string;
// contents of 404 error doc, used by THttpRequest.ServerFile, only if Error404Url is empty:
Error404DocText: string;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TSynHttpServer]);
end;
function SendSocketStream(Socket: TTcpBlockSocket; Stream: TStream; MaxSize: int64; bnHttpChunked: boolean): boolean;
var
Buffer: array[0..16383] of char;
BlockSize, Size: integer;
label
_Complete;
begin
if (MaxSize < 0) then
MaxSize := $10000000000; // 16Gb...
//
// Send Stream, without asking its Size... This allows sending from TDecompressionStream etc...
BlockSize := Socket.SendMaxChunk;
if (BlockSize > SizeOf(Buffer)) then
BlockSize := SizeOf(Buffer); // no real need to send >4k packets...
//
while True do
begin
if (BlockSize > MaxSize) then
begin
// Last block...
if (MaxSize = 0) then
begin
Result := True;
goto _Complete;
end;
BlockSize := MaxSize;
end;
//
Size := Stream.Read(Buffer[0], BlockSize);
if (Size <= 0) then
begin
// EOF
Result := (Size = 0); // stream complete...
_Complete:
if Result and bnHttpChunked then
begin
Socket.SendString('0'#13#10#13#10);
Result := True;
end;
exit;
end;
//
if bnHttpChunked then
Socket.SendString(UTF8Encode(Format('%x'#13#10, [Size])));
//
Socket.SendBuffer(@Buffer, Size);
if (Socket.LastError <> 0) then
break;
end;
// Failed due to LastError
Result := False;
end;
// read header lines until empty line is received...
function ReadHeadersFromSocket(Socket: TTCPBlockSocket; Headers: THeaderList; LineTimeout: integer): boolean;
var
Line: string;
begin
if (LineTimeout = 0) then
LineTimeout := SynSrv.cDefLineTimeout; // default 2 minutes...
//
while True do
begin
Line := string(Socket.RecvString(LineTimeout));
if (Line = '') then
begin
if (Socket.LastError <> 0) then
begin
// error (either timeout or client disconnected)
Result := False;
exit;
end;
// Headers complete (terminated by empty line)
{$ifdef DEBUG}
Debug('Request headers:'#13#10'%s',[Headers.Text]);
{$endif DEBUG}
Result := True;
exit;
end;
Headers.Add(Line);
end;
end;
function TrimCopy(const S: string; Pos, Count: integer): string;
var
len, maxlen: integer;
begin
//Result:=Trim(Copy(S,Pos,Count));
// Optimized - trim before allocating result:
len := Length(S);
while (Pos <= len) and (S[Pos] <= ' ') do
Inc(Pos);
if (Pos <= len) then
begin
maxlen := len - Pos + 1;
if (Count > maxlen) then
Count := maxlen;
while (Count > 0) and (S[Pos + Count - 1] <= ' ') do
Dec(Count);
end;
Result := Copy(S, Pos, Count);
end;
procedure DoTrim(var S: string);
var
len: integer;
begin
len := Length(S);
if (len > 0) and ((S[1] <= ' ') or (S[len] <= ' ')) then
S := Trim(S);
end;
function FetchToken(var Line: string; const Sep: string; bnTrim: boolean): string;
var
p: integer;
begin
p := Pos(Sep, Line);
if (p > 0) then
begin
// give part until separator:
if bnTrim then
begin
Result := TrimCopy(Line, 1, p - 1);
Delete(Line, 1, p + Length(Sep) - 1);
DoTrim(Line);
end else
begin
Result := Copy(Line, 1, p - 1);
Delete(Line, 1, p + Length(Sep) - 1);
end;
end else
begin
// give all rest:
Result := Line;
Line := '';
if bnTrim then
DoTrim(Result);
end;
end;
procedure AdjustHeaderLine(var Line: string);
var
p, len: integer;
Name: string;
begin
// Right-trim:
len := Length(Line);
if (len = 0) then
Exit;
if (Line[1] <= ' ') then
Line := Trim(Line)
else
if (Line[len] <= ' ') then
Line := TrimRight(Line);
// Normalize arround ":"...
p := Pos(':', Line);
if (p > 1) and (p < Length(Line) - 1) then
if (Line[p - 1] <= ' ') or not (Line[p + 1] <= ' ') or (Line[p + 2] <= ' ') then
begin
// Needs normalize...
Name := FetchToken(Line, ':', True);
//
Line := Name + ': ' + Line;
end;
end;
// for parsing: remove first Name="Value", separators either ";" or ","
// Value may be quoted, but does not need to be quoted
// Name may be missing (if no "=" is found, whole is Value)
function FetchDequoted(var Line: string; out Name, Value: string): boolean;
var
len, startname, lenname, startvalue, lenvalue, Skip, rest, p: integer;
bnName, bnSlash: boolean;
begin
len := Length(Line);
// LTrim name:
startname := 1;
while (startname <= len) and (Line[startname] <= ' ') do
Inc(startname);
startvalue := startname;
//
if (startname > len) then
begin
// Line was empty (or blank)...
Line := '';
Name := '';
Value := '';
Result := False;
exit;
end;
//
// Seek end of name:
bnName := False;
lenname := 0;
lenvalue := 0;
while (startname + lenname <= len) do
begin
case Line[startname + lenname] of
';', ',', '"': break;
'=':
begin
// End of name:
startvalue := startname + lenname + 1;
bnName := True;
break;
end;
end;
Inc(lenname);
end;
if not bnName then
begin
// no name...
//startvalue:=startname; // already...
lenvalue := lenname;
lenname := 0;
end;
Name := TrimCopy(Line, startname, lenname);
//
Skip := 0;
bnSlash := False;
if (lenvalue = 0) then
begin
// ltrim:
while (startvalue <= len) and (Line[startvalue] <= ' ') do
Inc(startvalue);
lenvalue := 0;
if (Line[startvalue] = '"') then
begin
// quoted:
Inc(startvalue);
lenvalue := 0;
while (startvalue + lenvalue <= len) do
begin
case Line[startvalue + lenvalue] of
'\':
begin
bnSlash := True;
Inc(lenvalue);
end;
'"':
begin
// end-quote...
Skip := 1;
break;
end;
end;
Inc(lenvalue);
end;
end else
while (startvalue + lenvalue <= len) do
begin
case Line[startvalue + lenvalue] of
';', ',': break;
end;
Inc(lenvalue);
end// separated:
;
end;
Value := TrimCopy(Line, startvalue, lenvalue);
//
rest := startvalue + lenvalue + Skip;
while (rest <= len) and (Line[rest] <= ' ') do
Inc(rest);
if (rest <= len) and (CharInSet(Line[rest], [';', ','])) then
Inc(rest);
Line := TrimCopy(Line, rest, Length(Line) - rest + 1);
//
if bnSlash then
begin
// Remove middle quoting markup:
len := Length(Value);
p := 1;
while (p <= len) do
begin
if (Value[p] = '\') then
begin
Delete(Value, p, 1);
Dec(len);
end;
Inc(p);
end;
end;
//
Result := True;
end;
function GetHeaderSubValue(Header: string; const Name: string): string;
var
S: string;
begin
Result := '';
while (Header <> '') do
begin
FetchDequoted(Header, S, Result);
if SameText(S, Name) then
break;//exit;
Result := '';
end;
end;
procedure ReplaceHeaderSubValue(var Header: string; const Name, Value: string);
var
Parts: TStringList;
S, S2: string;
ls2: integer;
begin
// find existing Name="Value", value may be quoted and may be not quoted, Name= may occur inside other quoted value so may not use simple Pos()...
Parts := TStringList.Create;
try
S2 := Name + '=';
ls2 := Length(S2);
//
while (Header <> '') do
begin
S := Trim(FetchQSepValue(Header, ';'));
//
if (S <> '') and (ls2 >= Length(S)) and (S[ls2] = '=') and SameHead(S, S2)
//and SameText(Copy(S,1,ls2),S2)
then
begin
// Replace this:
S := S2 + QuoteValue(Value);
ls2 := 0;
end;
//
Parts.Add(S);
end;
//
if (ls2 > 0) then
Parts.Add(S2 + QuoteValue(Value))// was not found...
;
//
// Combine into string:
Header := CombineStrings(Parts, '; ');
//
finally
Parts.Free;
end;
end;
function CombineStrings(Strings: TStrings; const Separator: string): string;
var
S: string;
i: integer;
begin
Result := '';
for i := 0 to Strings.Count - 1 do
begin
S := Strings[i];
if (i > 0) then
Result := Result + Separator + S
else
Result := Result + S;
end;
end;
function SameHead(const Str, SHead: string): boolean;
begin
Result := SameText(Copy(Str, 1, Length(SHead)), SHead);
end;
const
// SysUtils.ShortDayNames may be translated with resources... here use constants:
UsShortDayNames: array[1..7] of string = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
UsShortMonthNames: array[1..12] of string =
('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
function FormatHttpDate(LocalDate: TDateTime; bnIsLocal: boolean): string;
var
UtcDate: TDateTime;
d, m, y, h, n, s, z: word;
begin
if (LocalDate <= 1) then
begin
Result := '';
exit;
end;
// This format is recomended by RFC2616. it MUST be in GMT time-zone...
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
if bnIsLocal then
UtcDate := LocalToUtcDateTime(LocalDate)
else
UtcDate := LocalDate;
DecodeDate(UtcDate, y, m, d);
DecodeTime(UtcDate, h, n, s, z);
Result := Format('%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT', [UsShortDayNames[DayOfWeek(UtcDate)],
d, UsShortMonthNames[m], y, h, n, s]);
end;
function LocalToUtcDateTime(LocalDate: TDateTime): TDateTime;
begin
// UTC = local_time + bias
if (LocalDate <> 0) then
Result := LocalDate + TimeZoneBiasTime()
else
Result := 0;
end;
function UtcToLocalDateTime(UtcDate: TDateTime): TDateTime;
begin
// local_time = UTC - bias
if (UtcDate <> 0) then
Result := UtcDate - TimeZoneBiasTime()
else
Result := 0;
end;
const
cMinuteToDateTime = 1 / (24 * 60);
{$undef WIN32FILETIME}
{$undef WIN32TZ}
{$ifdef MSWINDOWS} {$ifndef CIL}
{$define WIN32TZ}
function TimeZoneBiasTime: TDateTime;
var
tzi: TTimeZoneInformation;
Bias: integer;
begin
case GetTimeZoneInformation(tzi) of
TIME_ZONE_ID_UNKNOWN: Bias := tzi.Bias;
TIME_ZONE_ID_STANDARD: Bias := tzi.Bias + tzi.StandardBias;
TIME_ZONE_ID_DAYLIGHT: Bias := tzi.Bias + tzi.DaylightBias;
else
Bias := 0;
end;
if (Bias <> 0) then
Result := Bias * cMinuteToDateTime
else
Result := 0;
end;
{$define WIN32FILETIME}
function FileTimeToUtcDateTime(const FileTime: TFileTime): TDateTime;
var
Sys: TSystemTime;
begin
if FileTimeToSystemTime(FileTime, Sys) then
Result := EncodeDate(Sys.wYear, Sys.wMonth, Sys.wDay) + EncodeTime(Sys.wHour, Sys.wMinute,
Sys.wSecond, Sys.wMilliseconds)
else
Result := 0;
end;
{$endif}{$endif}
//
{$ifndef WIN32TZ} // fallback for dotnet & linux:
//const
// cMinuteToDateTime=1/(24*60);
function TimeZoneBiasTime: TDateTime;
begin
Result := SynaUtil.TimeZoneBias*cMinuteToDateTime;
end;
{$endif}
function GetFileDateUtc(const FileName: string): TDateTime;
var
SR: TSearchRec;
begin
// This could work on linux also?
if (FindFirst(FileName, faAnyFile, SR) = 0) then
begin
FindClose(SR);
//
{$ifdef WIN32FILETIME}// WIN32
// Here we have directly UTC date-time:
Result := FileTimeToUtcDateTime(SR.FindData.ftLastWriteTime);
{$else ->fallback}
Result:=LocalToUtcDateTime(FileDateToDateTime(SR.Time));
{$endif}
end else
Result := 0;
end;
function ParseShortMonthName(const Token: string): integer;
var
i: integer;
begin
for i := 1 to 12 do
if SameText(Token, UsShortMonthNames[i]) then
begin
Result := i;
exit;
end;
Result := 0;
end;
function ParseHttpDate(Str: string; out DateTime: TDateTime): boolean;
var
Token: string;
Int, y, m, d, h, n, s, tzh, tzm, tokencount: integer;
TzOffset: double;
begin
DateTime := 0;
// This format is recomended by RFC2616. it MUST be in GMT time-zone...
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
// These formats are also possible:
// Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
// Anyhow due to robustness we will parse +0000 and -0000 timezones also...
y := 0;
m := 0;
d := 0;
h := 0;
n := 0;
s := 0;
tokencount := 0;
TzOffset := 0;
while (Str <> '') do
begin
Token := FetchToken(Str, ' ', True);
if (Token = '') then
continue;
//
Inc(tokencount);
if (tokencount > 31) then
break;
//
Int := -1;
if (CharInSet(Token[1], ['0'..'9'])) then
Int := StrToIntDef(Token, -1);
//
case Length(Token) of
1, 2: if (d = 0) and (Int > 0) then
d := Int;// Day...
3: if (m = 0) and (Int < 0) then
m := ParseShortMonthName(Token);// Sun, GMT, Nov
4: if (y = 0) and (Int >= 1900) and (Int <= 2200) then
y := Int;// 1999
5: if (CharInSet(Token[1], ['-', '+'])) and (CharInSet(Token[2], ['0'..'2'])) then
begin
// +0200, -0200
tzh := StrToIntDef(Copy(Token, 2, 2), -1);
tzm := StrToIntDef(Copy(Token, 4, 2), -1);
if (tzh >= 0) and (tzm >= 0) then
begin
TzOffset := (tzh * (1 / 24)) + (tzm * (1 / (24 * 60)));
if (Token[1] = '+') then
TzOffset := -TzOffset;
end;
end;
else
if (Pos(':', Token) > 0) then
begin
// Time...
h := StrToIntDef(FetchToken(Token, ':', True), 0);
n := StrToIntDef(FetchToken(Token, ':', True), 0);
s := StrToIntDef(FetchToken(Token, ':', True), 0);
end else
if (d = 0) and (Pos('-', Token) > 0) then
begin
// 06-Nov-94
d := StrToIntDef(FetchToken(Token, '-', True), 0);
m := ParseShortMonthName(FetchToken(Token, '-', True));
if (m <> 0) then
begin
y := StrToIntDef(Token, -1);
if (y >= 0) then
if (y > 50) then
Inc(y, 1900)
else
Inc(y, 2000);
end;
end;
end;
end;
//
if (m > 0) and (m <= 12) and (y >= 1900) and (d > 0) and (d <= MonthDays[IsLeapYear(y), m]) then
begin
// Valid date...
DateTime := EncodeDate(y, m, d);
// Check time:
if (h >= 0) and (h <= 23) and (n >= 0) and (n <= 59) and (s >= 0) and (s <= 59) then
DateTime := DateTime + EncodeTime(h, n, s, 0) + TzOffset;
Result := True;
end else
Result := False;
end;
{$ifdef MSWINDOWS} {$ifndef CIL} {$define LOCALUTF} {$endif}{$endif}
{$ifdef LOCALUTF}
//For compatibility with Delphi5, use our and kernel functions...
//U+00000000 - U+0000007F 0xxxxxxx
//U+00000080 - U+000007FF 110xxxxx 10xxxxxx
//U+00000800 - U+0000FFFF 1110xxxx 10xxxxxx 10xxxxxx
//U+00010000 - U+001FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
//U+00200000 - U+03FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
//U+04000000 - U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
function GetUtfCharLen(pc: PChar): integer;
var
b: byte;
begin
b := Ord(pc[0]);
case b and $C0 of
0, $40: Result := 1;
$C0: case b and $30 of
$00, $10: if (Ord(pc[1]) and $C0 = $80) then
Result := 2
else
Result := 0;// 2 bytes:
$20: if (Ord(pc[1]) and $C0 = $80) and (Ord(pc[2]) and $C0 = $80) then
Result := 3
else
Result := 0;// 3 bytes: