-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
test.net.proto.pas
1603 lines (1565 loc) · 57.2 KB
/
test.net.proto.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
/// regression tests for Several Network Protocols
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit test.net.proto;
interface
{$I ..\src\mormot.defines.inc}
uses
sysutils,
mormot.core.base,
mormot.core.os,
mormot.core.text,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.datetime,
mormot.core.rtti,
mormot.core.data,
mormot.core.variants,
mormot.core.json,
mormot.core.log,
mormot.core.test,
mormot.core.perf,
mormot.core.threads,
mormot.crypt.core,
mormot.crypt.secure,
mormot.net.sock,
mormot.net.http,
mormot.net.client,
mormot.net.server,
mormot.net.async,
mormot.net.ws.core,
mormot.net.openapi,
mormot.net.ldap,
mormot.net.dns,
mormot.net.rtsphttp,
mormot.net.tunnel;
type
/// this test case will validate several low-level protocols
TNetworkProtocols = class(TSynTestCase)
protected
// for _TUriTree
one, two: RawUtf8;
three: boolean;
request: integer;
four: Int64;
// for _TTunnelLocal
session: Int64;
appsec: RawUtf8;
options: TTunnelOptions;
tunnelexecutedone: boolean;
tunnelexecuteremote, tunnelexecutelocal: TNetPort;
procedure TunnelExecute(Sender: TObject);
procedure TunnelExecuted(Sender: TObject);
procedure TunnelTest(const clientcert, servercert: ICryptCert);
// several methods used by _TUriTree
function DoRequest_(Ctxt: THttpServerRequestAbstract): cardinal;
function DoRequest0(Ctxt: THttpServerRequestAbstract): cardinal;
function DoRequest1(Ctxt: THttpServerRequestAbstract): cardinal;
function DoRequest2(Ctxt: THttpServerRequestAbstract): cardinal;
function DoRequest3(Ctxt: THttpServerRequestAbstract): cardinal;
function DoRequest4(Ctxt: THttpServerRequestAbstract): cardinal;
// this is the main method called by RtspOverHttp[BufferedWrite]
procedure DoRtspOverHttp(options: TAsyncConnectionsOptions);
published
/// Engine.IO and Socket.IO regression tests
procedure _SocketIO;
/// validate mormot.net.openapi unit
procedure OpenAPI;
/// validate TUriTree high-level structure
procedure _TUriTree;
/// validate DNS and LDAP clients (and NTP/SNTP)
procedure DNSAndLDAP;
/// RTSP over HTTP, as implemented in mormot.net.rtsphttp unit
procedure RTSPOverHTTP;
/// RTSP over HTTP, with always temporary buffering
procedure RTSPOverHTTPBufferedWrite;
/// validate mormot.net.tunnel
procedure _TTunnelLocal;
/// validate IP processing functions
procedure IPAddresses;
/// validate THttpPeerCache process
procedure _THttpPeerCache;
end;
implementation
procedure TNetworkProtocols._SocketIO;
var
m: TSocketIOMessage;
begin
// validate low-level Socket.IO message decoder
Check(not m.Init(''));
Check(not m.Init('z'));
Check(m.Init('0'));
Check(m.PacketType = sioOpen);
Check(m.NameSpaceIs('/'));
CheckEqual(m.Data, nil);
Check(m.DataIs(''));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('0/test,{}'));
Check(m.PacketType = sioOpen);
Check(m.NameSpaceIs('/test'));
Check(m.DataIs('{}'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('1'));
Check(m.PacketType = sioDisconnect);
Check(m.NameSpaceIs('/'));
CheckEqual(m.Data, nil);
Check(m.DataIs(''));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('1/admin,'));
Check(m.PacketType = sioDisconnect);
Check(m.NameSpaceIs('/admin'));
Check(not m.NameSpaceIs('/admi'));
Check(not m.NameSpaceIs('/admiN'));
CheckEqual(m.Data, nil);
Check(m.DataIs(''));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('0/admin,{"sid":"oSO0OpakMV_3jnilAAAA"}'));
Check(m.PacketType = sioOpen);
Check(m.NameSpaceIs('/admin'));
Check(m.DataIs('{"sid":"oSO0OpakMV_3jnilAAAA"}'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('4{"message":"Not authorized"}'));
Check(m.PacketType = sioConnectError);
Check(m.NameSpaceIs('/'));
Check(m.DataIs('{"message":"Not authorized"}'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('2["foo"]'));
Check(m.PacketType = sioEvent);
Check(m.NameSpaceIs('/'));
Check(m.DataIs('["foo"]'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('2/admin,["bar"]'));
Check(m.PacketType = sioEvent);
Check(m.NameSpaceIs('/admin'));
Check(m.DataIs('["bar"]'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('212["foo"]'));
Check(m.PacketType = sioEvent);
Check(m.NameSpaceIs('/'));
Check(m.DataIs('["foo"]'));
CheckEqual(m.ID, 12);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('3/admin,13["bar"]'));
Check(m.PacketType = sioAck);
Check(m.NameSpaceIs('/admin'));
Check(m.DataIs('["bar"]'));
CheckEqual(m.ID, 13);
CheckEqual(m.BinaryAttachment, 0);
Check(m.Init('51-["baz",{"_placeholder":true,"num":0}]'));
Check(m.PacketType = sioBinaryEvent);
Check(m.NameSpaceIs('/'));
Check(m.DataIs('["baz",{"_placeholder":true,"num":0}]'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 1);
Check(m.Init('52-/admin,["baz",{"_placeholder":true,"num":0},{"_placeholder":true,"num":1}]'));
Check(m.PacketType = sioBinaryEvent);
Check(m.NameSpaceIs('/admin'));
Check(m.DataIs('["baz",{"_placeholder":true,"num":0},{"_placeholder":true,"num":1}]'));
CheckEqual(m.ID, 0);
CheckEqual(m.BinaryAttachment, 2);
Check(m.Init('61-15["bar",{"_placeholder":true,"num":0}]'));
Check(m.PacketType = sioBinaryAck);
Check(m.NameSpaceIs('/'));
Check(m.DataIs('["bar",{"_placeholder":true,"num":0}]'));
CheckEqual(m.ID, 15);
CheckEqual(m.BinaryAttachment, 1);
Check(m.Init('61-/admin,1[{"_placeholder":true,"num":0}]'));
Check(m.PacketType = sioBinaryAck);
Check(m.NameSpaceIs('/admin'));
Check(m.DataIs('[{"_placeholder":true,"num":0}]'));
CheckEqual(m.ID, 1);
CheckEqual(m.BinaryAttachment, 1);
end;
type
TMyEnum = (eNone, e1, e2);
const
MYENUM2TXT: array[TMyEnum] of RawUtf8 = ('', 'one', 'and 2');
const
// some reference from https://github.com/OAI/OpenAPI-Specification
OpenApiRef: array[0..1] of RawUtf8 = (
'v2.0/json/petstore-simple.json',
'v3.0/petstore.json');
procedure TNetworkProtocols.OpenAPI;
var
i: PtrInt;
fn: TFileName;
u, ud, uc, url: RawUtf8;
pets: TRawUtf8DynArray;
oa: TOpenApiParser;
begin
CheckEqual(FindCustomEnum(MYENUM2TXT, 'and 2'), 2);
CheckEqual(FindCustomEnum(MYENUM2TXT, 'one'), 1);
CheckEqual(FindCustomEnum(MYENUM2TXT, ''), 0);
CheckEqual(FindCustomEnum(MYENUM2TXT, 'and'), 0);
CheckEqual(FindCustomEnum(MYENUM2TXT, 'and 3'), 0);
for i := 1 to high(RESERVED_KEYWORDS) do
CheckUtf8(StrComp(pointer(RESERVED_KEYWORDS[i - 1]),
pointer(RESERVED_KEYWORDS[i])) < 0, RESERVED_KEYWORDS[i]);
for i := 0 to high(RESERVED_KEYWORDS) do
begin
u := RESERVED_KEYWORDS[i];
Check(IsReservedKeyWord(u));
inc(u[1], 32); // lowercase
Check(IsReservedKeyWord(u));
LowerCaseSelf(u);
Check(IsReservedKeyWord(u));
u := u + 's';
Check(not IsReservedKeyWord(u));
Check(not IsReservedKeyWord(UInt32ToUtf8(i)));
end;
SetLength(pets, length(OpenApiRef));
for i := 0 to high(OpenApiRef) do
begin
fn := FormatString('%petstore%.json', [WorkDir, i + 1]);
pets[i] := StringFromFile(fn);
if pets[i] = '' then
begin
url := OpenApiRef[i];
if not IdemPChar(pointer(url), 'HTTP') then
url := 'https://raw.githubusercontent.com/OAI/' +
'OpenAPI-Specification/main/examples/' + url;
JsonBufferReformat(pointer(
HttpGet(url, nil, false, nil, 0, {forcesock:}false, {igncerterr:}true)),
pets[i]);
if pets[i] <> '' then
FileFromString(pets[i], fn);
end;
end;
for i := 0 to high(pets) do
if pets[i] <> '' then
begin
oa := TOpenApiParser.Create(FormatUtf8('Pets%', [i + 1]));
try
oa.ParseJson(pets[i]);
ud := oa.GenerateDtoUnit;
Check(ud <> '', 'DTO');
uc := oa.GenerateClientUnit;
Check(uc <> '', 'CLIENT');
//ConsoleWrite(ud);
//ConsoleWrite(uc);
finally
oa.Free;
end;
end;
end;
procedure RtspRegressionTests(proxy: TRtspOverHttpServer; test: TSynTestCase;
clientcount, steps: integer);
type
TReq = record
get: THttpSocket;
post: TCrtSocket;
stream: TCrtSocket;
session: RawUtf8;
end;
var
streamer: TCrtSocket;
req: array of TReq;
procedure Shutdown;
var
r, rmax: PtrInt;
log: ISynLog;
timer, one: TPrecisionTimer;
begin
log := proxy.Log.Enter(proxy, 'Shutdown');
// first half deletes POST first, second half deletes GET first
timer.Start;
rmax := clientcount - 1;
for r := 0 to rmax shr 1 do
req[r].post.Free;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 1 %', [timer.Stop], proxy);
timer.Start;
req[0].stream.Free; // validates remove POST when RTSP already down
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 2 %', [timer.Stop], proxy);
timer.Start;
for r := (rmax shr 1) + 1 to rmax do
req[r].get.Free;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 3 %', [timer.Stop], proxy);
timer.Start;
for r := 0 to rmax shr 1 do
req[r].get.Free;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 4 %', [timer.Stop], proxy);
timer.Start;
for r := (rmax shr 1) + 1 to rmax do
req[r].post.Free;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 5 %', [timer.Stop], proxy);
timer.Start;
sleep(10);
//proxy.Shutdown; // don't make any difference
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 6 %', [timer.Stop], proxy);
for r := 1 to rmax do
begin
one.Start;
//req[r].stream.OnLog := TSynLog.DoLog;
req[r].stream.Free;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests SHUTDOWN 6-% %', [r, one.Stop], proxy);
end;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests % SHUTDOWN 7 %', [timer.Stop], proxy);
timer.Start;
streamer.Free;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests ENDED %', [timer.Stop], proxy);
end;
var
rmax, r, i: PtrInt;
text: RawUtf8;
log: ISynLog;
begin
// here we follow the steps and content stated by https://goo.gl/CX6VA3
log := proxy.Log.Enter(proxy, 'Tests');
if (proxy = nil) or
(proxy.RtspServer <> '127.0.0.1') then
test.Check(false, 'expect a running proxy on 127.0.0.1')
else
try
rmax := clientcount - 1;
streamer := TCrtSocket.Bind(proxy.RtspPort);
try
if log <> nil then
log.Log(sllCustom1, 'RegressionTests % GET', [clientcount], proxy);
SetLength(req, clientcount);
for r := 0 to rmax do
with req[r] do
begin
session := TSynTestCase.RandomIdentifier(20 + r and 15);
get := THttpSocket.Open('localhost', proxy.Server.Port, nlTcp, 1000);
get.SndLow('GET /sw.mov HTTP/1.0'#13#10 +
'User-Agent: QTS (qtver=4.1;cpu=PPC;os=Mac 8.6)'#13#10 +
'x-sessioncookie: ' + session + #13#10 +
'Accept: ' + RTSP_MIME + #13#10 +
'Pragma: no-cache'#13#10 +
'Cache-Control: no-cache'#13#10#13#10);
get.SockRecvLn(text);
test.Check(text = 'HTTP/1.0 200 OK');
get.GetHeader(false);
test.Check(hfConnectionClose in get.Http.HeaderFlags);
test.Check(get.SockConnected);
test.Check(get.Http.ContentType = RTSP_MIME);
end;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests % POST', [clientcount], proxy);
for r := 0 to rmax do
with req[r] do
begin
test.Check(get.SockConnected);
post := TCrtSocket.Open('localhost', proxy.Server.Port);
post.SndLow('POST /sw.mov HTTP/1.0'#13#10 +
'User-Agent: QTS (qtver=4.1;cpu=PPC;os=Mac 8.6)'#13#10 +
'x-sessioncookie: ' + session + #13#10 +
'Content-Type: ' + RTSP_MIME + #13#10 +
'Pragma: no-cache'#13#10 +
'Cache-Control: no-cache'#13#10 +
'Content-Length: 32767'#13#10 +
'Expires: Sun, 9 Jan 1972 00:00:00 GMT'#13#10#13#10);
if log <> nil then
log.Log(sllTrace, 'req[%].get=% connected=%',
[r, get.Sock, get.SockConnected], proxy);
test.Check(get.SockConnected);
stream := streamer.AcceptIncoming(nil, {async=}false);
if stream = nil then
begin
test.Check(false);
exit;
end;
stream.Sock.SetLinger(0); // otherwise shutdown takes 40ms with epoll
test.Check(get.SockConnected);
test.Check(post.SockConnected);
end;
for i := 0 to steps do
begin
if log <> nil then
log.Log(sllCustom1, 'RegressionTests % RUN #%', [clientcount, i], proxy);
// send a RTSP command once in a while to the POST request
if i and 7 = 0 then
begin
for r := 0 to rmax do
req[r].post.SndLow(
'REVTQ1JJQkUgcnRzcDovL3R1Y2tydS5hcHBsZS5jb20vc3cubW92IFJUU1AvMS4w'#13#10 +
'DQpDU2VxOiAxDQpBY2NlcHQ6IGFwcGxpY2F0aW9uL3NkcA0KQmFuZHdpZHRoOiAx'#13#10 +
'NTAwMDAwDQpBY2NlcHQtTGFuZ3VhZ2U6IGVuLVVTDQpVc2VyLUFnZW50OiBRVFMg'#13#10 +
'KHF0dmVyPTQuMTtjcHU9UFBDO29zPU1hYyA4LjYpDQoNCg==');
for r := 0 to rmax do
test.check(req[r].stream.SockReceiveString =
'DESCRIBE rtsp://tuckru.apple.com/sw.mov RTSP/1.0'#13#10 +
'CSeq: 1'#13#10 +
'Accept: application/sdp'#13#10 +
'Bandwidth: 1500000'#13#10 +
'Accept-Language: en-US'#13#10 +
'User-Agent: QTS (qtver=4.1;cpu=PPC;os=Mac 8.6)'#13#10#13#10);
end;
// stream output should be redirected to the GET request
for r := 0 to rmax do
req[r].stream.SndLow(req[r].session); // session text as video stream
if log <> nil then
log.Log(sllCustom1, 'RegressionTests % RUN #% SndLow',
[clientcount, i], proxy);
for r := 0 to rmax do
with req[r] do
begin
text := get.SockReceiveString;
//if log <> nil then
// log.Log(sllCustom1, 'RegressionTests % #%/% received %',
// [clientcount, r, rmax, text], proxy);
test.CheckEqual(text, session);
end;
end;
if log <> nil then
log.Log(sllCustom1, 'RegressionTests % SHUTDOWN', [clientcount], proxy);
finally
Shutdown;
end;
except
on E: Exception do
test.Check(false, E.ClassName);
end;
end;
procedure TNetworkProtocols.DoRtspOverHttp(options: TAsyncConnectionsOptions);
var
N: integer;
proxy: TRtspOverHttpServer;
begin
{$ifdef OSDARWIN}
N := 10;
{$else}
N := 100;
{$endif OSDARWIN}
proxy := TRtspOverHttpServer.Create(
'127.0.0.1', '3999', '3998', TSynLog, nil, nil, options, {threads=}1);
// threads=1 is the safest & fastest - but you may set 16 for testing
try
proxy.WaitStarted(10);
RtspRegressionTests(proxy, self, N, 10);
finally
proxy.Free;
end;
end;
const
//ASYNC_OPTION = ASYNC_OPTION_DEBUG;
ASYNC_OPTION = ASYNC_OPTION_VERBOSE;
procedure TNetworkProtocols.RTSPOverHTTP;
begin
DoRtspOverHttp(ASYNC_OPTION);
end;
procedure TNetworkProtocols.RTSPOverHTTPBufferedWrite;
begin
DoRtspOverHttp(ASYNC_OPTION + [acoWritePollOnly]);
end;
function TNetworkProtocols.DoRequest_(Ctxt: THttpServerRequestAbstract): cardinal;
begin
one := Ctxt['one'];
Ctxt.RouteUtf8('two', two);
three := Ctxt.RouteEquals('three', '3');
if not Ctxt.RouteInt64('four', four) then
four := -1;
result := HTTP_SUCCESS;
end;
function TNetworkProtocols.DoRequest0(Ctxt: THttpServerRequestAbstract): cardinal;
begin
result := DoRequest_(Ctxt);
request := 0;
end;
function TNetworkProtocols.DoRequest1(Ctxt: THttpServerRequestAbstract): cardinal;
begin
result := DoRequest_(Ctxt);
request := 1;
end;
function TNetworkProtocols.DoRequest2(Ctxt: THttpServerRequestAbstract): cardinal;
begin
result := DoRequest_(Ctxt);
request := 2;
end;
function TNetworkProtocols.DoRequest3(Ctxt: THttpServerRequestAbstract): cardinal;
begin
result := DoRequest_(Ctxt);
request := 3;
end;
function TNetworkProtocols.DoRequest4(Ctxt: THttpServerRequestAbstract): cardinal;
begin
result := DoRequest_(Ctxt);
request := 4;
end;
const
NODES: array[0..10] of RawUtf8 = (
'water', 'slow', 'slower', 'waste', 'watch', 'water',
'toaster', 'team', 'tester', 't', 'toast');
procedure TNetworkProtocols._TUriTree;
var
tree: TUriTree;
router: TUriRouter;
ctxt: THttpServerRequest;
i: PtrInt;
n: TRadixTreeNode;
timer: TPrecisionTimer;
rnd: array[0..999] of RawUtf8;
procedure Call(const uri, exp1, exp2: RawUtf8; exp3: boolean = false;
exp4: Int64 = -1; expstatus: integer = HTTP_SUCCESS;
const met: RawUtf8 = 'GET');
begin
request := -1;
one := '';
two := '';
three := false;
four := -1;
ctxt.Method := met;
ctxt.Url := uri;
CheckEqual(router.Process(ctxt), expstatus);
CheckEqual(one, exp1);
CheckEqual(two, exp2);
Check(three = exp3);
CheckEqual(four, exp4);
end;
procedure Compute(const uri, expected: RawUtf8; const met: RawUtf8 = 'POST';
expstatus: integer = 0);
begin
ctxt.Method := met;
ctxt.Url := uri;
CheckEqual(router.Process(ctxt), expstatus);
if expected <> '' then
CheckEqual(ctxt.Url, expected);
end;
begin
tree := TUriTree.Create(TUriTreeNode);
try
tree.insert('romane');
tree.insert('romanus');
tree.insert('romulus');
tree.insert('rubens');
tree.insert('ruber');
tree.insert('rubicon');
tree.insert('rubicundus');
CheckHash(tree.ToText, $0946B9A0);
CheckEqual(tree.Root.Lookup('rubens', nil).FullText, 'rubens');
Check(tree.Root.Lookup('Rubens', nil) = nil);
finally
tree.Free;
end;
tree := TUriTree.Create(TUriTreeNode, [rtoCaseInsensitiveUri]);
try
tree.insert('romanus');
tree.insert('romane');
tree.insert('rubicundus');
tree.insert('rubicon');
tree.insert('ruber');
tree.insert('romulus');
tree.insert('rubens');
CheckHash(tree.ToText, $305E57F1);
CheckEqual(tree.Root.Lookup('rubens', nil).FullText, 'rubens');
CheckEqual(tree.Root.Lookup('Rubens', nil).FullText, 'rubens');
finally
tree.Free;
end;
tree := TUriTree.Create(TUriTreeNode);
try
tree.insert('/plaintext');
tree.insert('/');
tree.insert('/plain');
//writeln(tree.ToText);
CheckHash(tree.ToText, $B3522B86);
finally
tree.Free;
end;
tree := TUriTree.Create(TUriTreeNode);
try
for i := 0 to high(NODES) do
CheckEqual(tree.Insert(NODES[i]).FullText, NODES[i]);
//writeln(tree.ToText);
CheckHash(tree.ToText, $CC40347C);
for i := 0 to high(NODES) do
begin
n := tree.Find(NODES[i]);
CheckUtf8(n <> nil, NODES[i]);
CheckEqual(n.FullText, NODES[i]);
end;
for i := 0 to high(NODES) do
CheckEqual(tree.Insert(NODES[i]).FullText, NODES[i]);
tree.AfterInsert; // sort by depth
//writeln(tree.ToText);
CheckHash(tree.ToText, $200CAEEB);
for i := 0 to high(NODES) do
CheckEqual(tree.Find(NODES[i]).FullText, NODES[i]);
finally
tree.Free;
end;
tree := TUriTree.Create(TUriTreeNode);
try
for i := 0 to high(rnd) do
rnd[i] := RandomIdentifier(Random32(24) * 2 + 1);
for i := 0 to high(rnd) do
CheckEqual(tree.Insert(rnd[i]).FullText, rnd[i]);
timer.Start;
for i := 0 to high(rnd) do
CheckEqual(tree.Find(rnd[i]).FullText, rnd[i]);
NotifyTestSpeed('big tree lookups', length(rnd), 0, @timer);
finally
tree.Free;
end;
ctxt := THttpServerRequest.Create(nil, 0, nil, 0, [], nil);
router := TUriRouter.Create(TUriTreeNode);
try
Call('/plaintext', '', '', false, -1, 0);
Call('/', '', '', false, -1, 0);
router.Get('/plaintext', DoRequest_);
router.Get('/plaintext', DoRequest_);
CheckEqual(request, -1);
Call('/plaintext', '', '');
Call('/', '', '', false, -1, 0);
//writeln(router.Tree[urmGet].ToText);
router.Get('/', DoRequest0);
Call('/plaintext', '', '');
CheckEqual(request, -1);
Call('/', '', '', false);
CheckEqual(request, 0);
router.Get('/do/<one>/pic/<two>', DoRequest0);
router.Get('/do/<one>', DoRequest1);
router.Get('/do/<one>/pic', DoRequest2);
router.Get('/do/<one>/pic/<two>/', DoRequest3);
router.Get('/da/<one>/<two>/<three>/<four>/', DoRequest4);
//writeln(router.Tree[urmGet].ToText);
Call('/do/a', 'a', '');
CheckEqual(request, 1);
Call('/do/123', '123', '');
CheckEqual(request, 1);
Call('/do/toto/pic', 'toto', '');
CheckEqual(request, 2);
Call('/do/toto/pic/titi/', 'toto', 'titi');
CheckEqual(request, 3);
Call('/do/toto/pic/titi', 'toto', 'titi');
CheckEqual(request, 0);
Call('/do/toto/pic/titi/', 'toto', 'titi');
CheckEqual(request, 3);
Call('/da/1/2/3/4', '', '', false, -1, 0);
CheckEqual(request, -1);
Call('/da/1/2/3/4/', '1', '2', true, 4);
CheckEqual(request, 4);
Call('/da/a1/b2/3/47456/', 'a1', 'b2', true, 47456);
CheckEqual(request, 4);
Compute('/static', '/static');
Compute('/static2', '/static2');
Compute('/', '/');
router.Post('/static', '/some/static');
Compute('/static', '/some/static');
Compute('/static2', '/static2');
Compute('/', '/');
router.Post('/static2', '/some2/static');
router.Post('/', '/index');
Compute('/static', '/some/static');
Compute('/static2', '/some2/static');
Compute('/', '/index');
Compute('/stat', '/stat');
router.Post('/user/<id>', '/root/user.new?id=<id>');
Compute('/user/1234', '/root/user.new?id=1234');
Compute('/user/1234/', '/user/1234/');
router.Post('/user/<id>/picture', '/root/user.newpic?id=<id>&pic=');
router.Post('/user/<id>/picture/<pic>', '/root/user.newpic?pic=<pic>&id=<id>');
Compute('/user/1234/picture', '/root/user.newpic?id=1234&pic=');
Compute('/user/1234/picture/5', '/root/user.newpic?pic=5&id=1234');
Compute('/user/1234/picture/', '/user/1234/picture/');
Compute('/user/1234', '/root/user.new?id=1234');
Compute('/user/1234/', '/user/1234/');
Compute('/static', '/some/static');
Compute('/static2', '/some2/static');
Compute('/', '/index');
Compute('/stat', '/stat');
timer.Start;
for i := 1 to 1000 do
CheckEqual(router.Tree[urmPost].Find('/static').FullText, '/static');
NotifyTestSpeed('URI lookups', 1000, 0, @timer);
timer.Start;
for i := 1 to 1000 do
Compute('/static', '/some/static');
NotifyTestSpeed('URI static rewrites', 1000, 0, @timer);
timer.Start;
for i := 1 to 1000 do
Compute('/user/1234', '/root/user.new?id=1234');
NotifyTestSpeed('URI parametrized rewrites', 1000, 0, @timer);
timer.Start;
for i := 1 to 1000 do
Compute('/plaintext', '', 'GET', 200);
NotifyTestSpeed('URI static execute', 1000, 0, @timer);
timer.Start;
for i := 1 to 1000 do
Compute('/do/toto/pic', '', 'GET', 200);
NotifyTestSpeed('URI parametrized execute', 1000, 0, @timer);
router.Put('/index.php', '404');
router.Put('/index.php', '404');
router.Put('/admin.php', '404');
Compute('/index.php', '/index.php', 'PUT', 404);
Compute('/admin.php', '/admin.php', 'PUT', 404);
router.Delete('/*', '/static/*');
router.Delete('/root1/<path:url>', '/roota/<url>');
router.Delete('/root2/*', '/rootb/*');
router.Delete('/root3/<url>', '/rootc/<url>');
router.Delete('/root4/<int:id>', '/rootd/<id>');
Compute('/root1/one', '/roota/one', 'DELETE');
Compute('/root1/one/', '/roota/one/', 'DELETE');
Compute('/root1/one/two', '/roota/one/two', 'DELETE');
Compute('/root2/one', '/rootb/one', 'DELETE');
Compute('/root2/one/', '/rootb/one/', 'DELETE');
Compute('/root2/one/two', '/rootb/one/two', 'DELETE');
Compute('/root3/one', '/rootc/one', 'DELETE');
Compute('/root3/one/', '/static/root3/one/', 'DELETE');
Compute('/root3/one/two', '/static/root3/one/two', 'DELETE');
Compute('/root4/one', '/static/root4/one', 'DELETE');
Compute('/root4/1', '/rootd/1', 'DELETE');
Compute('/root4/123', '/rootd/123', 'DELETE');
Compute('/roota/one', '/static/roota/one', 'DELETE');
Compute('/one', '/static/one', 'DELETE');
Compute('/one/two', '/static/one/two', 'DELETE');
//writeln(router.Tree[urmGet].ToText);
//writeln(router.Tree[urmPost].ToText);
//writeln(router.Tree[urmPut].ToText);
//writeln(router.Tree[urmDelete].ToText);
CheckHash(router.Tree[urmGet].ToText, $18A0BF58);
CheckHash(router.Tree[urmPost].ToText, $E173FBB0);
CheckHash(router.Tree[urmPut].ToText, $80F7A0EF);
CheckHash(router.Tree[urmDelete].ToText, $39501147);
router.Clear([urmPost]);
Call('/plaintext', '', '');
Compute('/static', '/static');
router.Clear;
Call('/plaintext', '', '', false, -1, 0);
Compute('/static', '/static');
finally
router.Free;
ctxt.Free;
end;
end;
procedure TNetworkProtocols.DNSAndLDAP;
var
ip, u, v, sid: RawUtf8;
o: TAsnObject;
c: cardinal;
withntp: boolean;
guid: TGuid;
i, j, k, n: PtrInt;
dns, clients, a: TRawUtf8DynArray;
le: TLdapError;
rl, rl2: TLdapResultList;
r: TLdapResult;
at: TLdapAttributeType;
ats, ats2: TLdapAttributeTypes;
sat: TSamAccountType;
gt: TGroupType;
gts: TGroupTypes;
ua: TUserAccountControl;
uas: TUserAccountControls;
sf: TSystemFlag;
sfs: TSystemFlags;
l: TLdapClientSettings;
one: TLdapClient;
res: TLdapResult;
utc1, utc2: TDateTime;
ntp, usr, pwd, ku, main, txt: RawUtf8;
dn: TNameValueDNs;
hasinternet: boolean;
begin
// validate NTP/SNTP client using NTP_DEFAULT_SERVER = time.google.com
if not Executable.Command.Get('ntp', ntp) then
ntp := NTP_DEFAULT_SERVER;
withntp := not Executable.Command.Option('nontp');
hasinternet := DnsLookups('yahoo.com') <> nil; // avoid waiting for nothing
if hasinternet then
begin
utc1 := GetSntpTime(ntp);
//writeln(DateTimeMSToString(utc), ' = ', DateTimeMSToString(NowUtc));
if utc1 <> 0 then
begin
utc2 := NowUtc;
AddConsole('% : % = %', [ntp, DateTimeMSToString(utc1), DateTimeMSToString(utc2)]);
// only make a single GetSntpTime call - most servers refuse to scale
if withntp then
CheckSame(utc1, utc2, 1, 'NTP system A'); // allow 1 day diff
end;
end
else
AddConsole('no Internet connection');
// validate some IP releated process
Check(not NetIsIP4(nil));
Check(not NetIsIP4('1'));
Check(not NetIsIP4('1.2'));
Check(not NetIsIP4('1.2.3'));
Check(not NetIsIP4('1.2.3.'));
Check(not NetIsIP4('1.2.3.4.'));
Check(not NetIsIP4('1.2.3.4.5'));
Check(NetIsIP4('1.2.3.4'));
Check(NetIsIP4('12.3.4.5'));
Check(NetIsIP4('12.34.5.6'));
Check(NetIsIP4('12.34.56.7'));
Check(NetIsIP4('12.34.56.78'));
Check(NetIsIP4('112.134.156.178'));
Check(not NetIsIP4('312.34.56.78'));
Check(not NetIsIP4('12.334.56.78'));
Check(not NetIsIP4('12.34.256.78'));
Check(not NetIsIP4('12.34.56.278'));
c := 0;
Check(NetIsIP4('1.2.3.4', @c));
CheckEqual(c, $04030201);
// validate DNS client with some known values
CheckEqual(DnsLookup(''), '');
CheckEqual(DnsLookup('localhost'), '127.0.0.1');
CheckEqual(DnsLookup('LocalHost'), '127.0.0.1');
CheckEqual(DnsLookup('::1'), '127.0.0.1');
CheckEqual(DnsLookup('1.2.3.4'), '1.2.3.4');
if hasinternet then
begin
ip := DnsLookup('synopse.info');
CheckEqual(ip, '62.210.254.173', 'dns1');
ip := DnsLookup('blog.synopse.info');
CheckEqual(ip, '62.210.254.173', 'dns2');
CheckEqual(DnsReverseLookup(ip), '62-210-254-173.rev.poneytelecom.eu', 'rev');
end;
// validate LDAP distinguished name conversion (no client)
CheckEqual(DNToCN('CN=User1,OU=Users,OU=London,DC=xyz,DC=local'),
'xyz.local/London/Users/User1');
CheckEqual(DNToCN(
'cn=JDoe,ou=Widgets,ou=Manufacturing,dc=USRegion,dc=OrgName,dc=com'),
'USRegion.OrgName.com/Manufacturing/Widgets/JDoe');
CheckEqual(DNToCN(
'OU=d..zaf(fds )da\,z \"\"((''\\/ df\3D\3Dez,OU=test_wapt,OU=computers,' +
'OU=tranquilit,DC=ad,DC=tranquil,DC=it'),
'ad.tranquil.it/tranquilit/computers/test_wapt/d\.\.zaf(fds )da,z ""((''\\\/ df==ez');
CheckEqual(DNToCN('dc=ad,dc=company,dc=it'), 'ad.company.it');
CheckEqual(DNToCN('cn=foo, ou=bar'), '/bar/foo');
CheckEqual(NormalizeDN('cn=foo, ou = bar'), 'CN=foo,OU=bar');
Check(ParseDn('dc=ad, dc=company, dc = it', dn));
CheckEqual(length(dn), 3);
CheckEqual(dn[0].Name, 'dc');
CheckEqual(dn[0].Value, 'ad');
CheckEqual(dn[1].Name, 'dc');
CheckEqual(dn[1].Value, 'company');
CheckEqual(dn[2].Name, 'dc');
CheckEqual(dn[2].Value, 'it');
Check(ParseDn('uid=33\,test\=dans le nom,ou=Users,ou=montaigu,dc=sermo,dc=fr', dn));
CheckEqual(length(dn), 5);
CheckEqual(dn[0].Name, 'uid');
CheckEqual(dn[0].Value, '33\,test\=dans le nom');
CheckEqual(dn[1].Name, 'ou');
CheckEqual(dn[1].Value, 'Users');
CheckEqual(dn[2].Name, 'ou');
CheckEqual(dn[2].Value, 'montaigu');
CheckEqual(dn[3].Name, 'dc');
CheckEqual(dn[3].Value, 'sermo');
CheckEqual(dn[4].Name, 'dc');
CheckEqual(dn[4].Value, 'fr');
Check(not ParseDn('dc=ad, dc=company, dc', dn, {noraise=}true));
// validate LDAP error recognition
Check(RawLdapError(-1) = leUnknown);
Check(RawLdapError(LDAP_RES_TOO_LATE) = leUnknown);
Check(RawLdapError(10000) = leUnknown);
Check(RawLdapError(LDAP_RES_AUTHORIZATION_DENIED) = leAuthorizationDenied);
for le := low(le) to high(le) do
begin
Check(LDAP_ERROR_TEXT[le] <> '');
if le <> leUnknown then
CheckUtf8(RawLdapError(LDAP_RES_CODE[le]) = le, LDAP_ERROR_TEXT[le]);
end;
CheckEqual(LDAP_ERROR_TEXT[leUnknown], 'Unknown');
CheckEqual(LDAP_ERROR_TEXT[leCompareTrue], 'Compare true');
// validate LDAP escape/unescape
for c := 0 to 200 do
begin
u := RandomIdentifier(c); // alphanums are never escaped
CheckEqual(LdapEscape(u), u);
CheckEqual(LdapUnescape(u), u);
if u <> '' then
CheckEqual(LdapEscapeName(u), u);
CheckEqual(LdapEscapeCN(u), u);
u := RandomAnsi7(c);
CheckEqual(LdapUnescape(LdapEscape(u)), u);
end;
CheckEqual(LdapUnescape('abc\>'), 'abc>');
CheckEqual(LdapUnescape('abc\>e'), 'abc>e');
CheckEqual(LdapUnescape('abc\'), 'abc');
Check(LdapSafe(''));
Check(LdapSafe('abc'));
Check(LdapSafe('ab cd'));
Check(LdapSafe('@abc'));
Check(not LdapSafe('\abc'));
Check(not LdapSafe('abc*'));
Check(not LdapSafe('a(bc'));
Check(not LdapSafe('abc)'));
Check(not LdapSafe('*'));
Check(not LdapSafe('()'));
// validate LDIF format
Check(IsLdifSafe(nil, 0));
Check(IsLdifSafe('toto', 0));
Check(IsLdifSafe(nil, -1));
Check(IsLdifSafe('toto', -1));
Check(IsLdifSafe('toto', 1));
Check(IsLdifSafe('toto', 2));
Check(IsLdifSafe('toto', 3));
Check(IsLdifSafe('toto', 4));
Check(not IsLdifSafe('toto', 5), 'ending #0');
Check(not IsLdifSafe(':oto', 4));
Check(IsLdifSafe('t:to', 4));
Check(IsLdifSafe('tot:', 4));
Check(not IsLdifSafe(' oto', 4));
Check(IsLdifSafe('t to', 4));
Check(not IsLdifSafe('tot ', 4));
Check(not IsLdifSafe('<oto', 4));
Check(IsLdifSafe('t<to', 4));
Check(IsLdifSafe('tot<', 4));
Check(not IsLdifSafe(#0'oto', 4));
Check(not IsLdifSafe('t'#0'to', 4));
Check(not IsLdifSafe('tot', 4));
Check(IsLdifSafe(#1'oto', 4));
Check(IsLdifSafe('t'#1'to', 4));
Check(IsLdifSafe('tot'#1'', 4));
Check(not IsLdifSafe(#10'oto', 4));
Check(not IsLdifSafe('t'#10'to', 4));
Check(not IsLdifSafe('tot'#10'', 4));
Check(not IsLdifSafe(#13'oto', 4));
Check(not IsLdifSafe('t'#13'to', 4));
Check(not IsLdifSafe('tot'#13'', 4));
k := 100;
u := RandomIdentifier(k);
for i := 0 to k + 1 do
Check(IsLdifSafe(pointer(u), i) = (i <= k));
Append(u, ' '); // trailing space is unsafe
for i := 0 to k + 2 do
Check(IsLdifSafe(pointer(u), i) = (i <= k));
// validate LDAP filter text parsing
// against https://ldap.com/ldapv3-wire-protocol-reference-search reference
CheckEqual(RawLdapTranslateFilter('', {noraise=}true), '');
CheckEqual(RawLdapTranslateFilter('', {noraise=}false), '');
o := RawLdapTranslateFilter('(attr=toto)');
CheckHash(o, $E2C7F47C);
o := RawLdapTranslateFilter('&(attr=toto)');
CheckHash(o, $7B08F48C);
o := RawLdapTranslateFilter('(&(attr1=a)(attr2=b)(attr3=c)(attr4=d))');
CheckHash(o, $1AAB9884);
o := RawLdapTranslateFilter('&(attr1=a)(attr2=b)(attr3=c)(attr4=d)');
CheckHash(o, $1AAB9884);
o := RawLdapTranslateFilter('(& ( attr1=a) (attr2=b) (attr3=c) (attr4=d))');
CheckHash(o, $1AAB9884);
o := RawLdapTranslateFilter('( & (attr1=a)(attr2=b)(attr3=c)(attr4=d) )');
CheckHash(o, $1AAB9884);
o := RawLdapTranslateFilter('(&(attr1=a)(&(attr2=b)(&(attr3=c)(attr4=d))))');
CheckHash(o, $B1BB5EE1);
o := RawLdapTranslateFilter('(&(givenName=John)(sn=Doe))');
CheckHash(o, $372C9EF2);
o := RawLdapTranslateFilter('(&)');
CheckHash(o, $00A000A0, 'absolute true');
o := RawLdapTranslateFilter('(|(givenName=John)(givenName=Jonathan))');
CheckHash(o, $A9670687);
o := RawLdapTranslateFilter('|(givenName=John)(givenName=Jonathan)');
CheckHash(o, $A9670687);
o := RawLdapTranslateFilter('(!(givenName=John))');
CheckHash(o, $231C39EF);
o := RawLdapTranslateFilter('(|)');
CheckHash(o, $00A100A1, 'absolute false');
o := RawLdapTranslateFilter('*');
CheckHash(o, $01AD0187, 'present1');
o := RawLdapTranslateFilter('(*)');
CheckHash(o, $01AD0187, 'present2');
o := RawLdapTranslateFilter('(uid:=jdoe)');
CheckHash(o, $C93ADF87);