-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cxx
1350 lines (1178 loc) · 46.5 KB
/
main.cxx
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
/*
* main.cxx
*
* H.323 call generator
*
* Copyright (c) 2008-2018 Jan Willamowius <[email protected]>
* Copyright (c) 2001 Benny L. Prijono <[email protected]>
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* https://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is CallGen323.
*
* The Initial Developer of the Original Code is Benny L. Prijono
*
* Contributor(s): Equivalence Pty. Ltd.
*
*/
#include <ptlib.h>
#include "main.h"
#include "version.h"
#include <ptclib/random.h>
#include <ptlib/video.h>
#include <h323neg.h>
#ifndef _WIN32
#include <signal.h>
#endif
PCREATE_PROCESS(CallGen);
///////////////////////////////////////////////////////////////////////////////
CallGen::CallGen()
: PProcess("H323Plus", "CallGen", MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER),
console(PConsoleChannel::StandardInput)
{
totalAttempts = 0;
totalEstablished = 0;
h323 = NULL;
}
void CallGen::Main()
{
#ifndef _WIN32
signal(SIGCHLD, SIG_IGN); // avoid zombies from H.264 plugin helper
#endif
PArgList & args = GetArguments();
args.Parse("a-access-token-oid:"
"b-bandwidth:"
"c-cdr:"
"C-cycle."
"D-disable:"
"f-fast-disable."
"g-gatekeeper:"
#ifdef H323_H235
"-mediaenc:"
"-maxtoken:"
#endif
#ifdef H323_H46017
"k-h46017:"
#endif
#ifdef H323_H46018
"-h46018enable."
#endif
#ifdef H323_H46019M
"-h46019multiplexenable."
#endif
#ifdef H323_H46023
"-h46023enable."
#endif
#ifdef H323_H239
"-h239enable."
"-h239videopattern:"
"-h239delay:"
"-h239duration:"
#endif
"I-in-dir:"
"i-interface:"
"l-listen."
"m-max:"
" -mcu."
"n-no-gatekeeper."
"O-out-msg:"
"o-output:"
"P-prefer:"
"p-password:"
"r-repeat:"
"-require-gatekeeper."
"T-h245tunneldisable."
"t-trace."
#ifdef H323_VIDEO
"v-video."
"-videopattern:"
"R-framerate:"
"-maxframe:"
#endif
#ifdef H323_TLS
"-tls."
"-tls-cafile:"
"-tls-cert:"
"-tls-privkey:"
"-tls-passphrase:"
"-tls-listenport:"
#endif
"-tmaxest:"
"-tmincall:"
"-tmaxcall:"
"-tminwait:"
"-tmaxwait:"
"-tcp-base:"
"-tcp-max:"
"-udp-base:"
"-udp-max:"
"-rtp-base:"
"-rtp-max:"
"u-user:"
"-fuzzing."
"-fuzz-header:"
"-fuzz-media:"
"-fuzz-rtcp:"
, FALSE);
if (args.GetCount() == 0 && !args.HasOption('l')) {
cout << "Usage:\n"
" callgen [options] -l\n"
" callgen [options] destination [ destination ... ]\n"
"where options:\n"
" -l Passive/listening mode\n"
" -m --max num Maximum number of simultaneous calls\n"
" --mcu Pose as MCU (to always win master/slave neg.)\n"
" -r --repeat num Repeat calls n times\n"
" -C --cycle Each simultaneous call cycles through destination list\n"
" -t --trace Trace enable (use multiple times for more detail)\n"
" -o --output file Specify filename for trace output [stdout]\n"
" -i --interface addr Specify IP address and port listen on [*:1720]\n"
" -g --gatekeeper host Specify gatekeeper host [auto-discover]\n"
#ifdef H323_H235
" --mediaenc Enable Media encryption (value max cipher 128, 192 or 256)\n"
" --maxtoken Set max token size for H.235.6 (1024, 2048, 4096, ...)\n"
#endif
#ifdef H323_H46017
" -k --h46017 Use H.460.17 Gatekeeper\n"
#endif
#ifdef H323_H46018
" --h46018enable Enable H.460.18/.19\n"
#endif
#ifdef H323_H46019M
" --h46019multiplexenable Enable H.460.19 RTP multiplexing\n"
#endif
#ifdef H323_H46023
" --h46023enable Enable H.460.23/.24\n"
#endif
#ifdef H323_H239
" --h239enable Enable sending and receiving H.239 presentations\n"
" --h239videopattern Set video pattern to send for H.239, eg. 'Fake', 'Fake/BouncingBoxes' or 'Fake/MovingBlocks'\n"
" --h239delay Delay the start of the H.239 transmission in seconds [1 sec]\n"
" --h239duration Duration the H.239 transmission in seconds [-1 - unlimited]\n"
#endif
" -n --no-gatekeeper Disable gatekeeper discovery [false]\n"
" --require-gatekeeper Exit if gatekeeper discovery fails [false]\n"
" -u --user username Specify local username [login name]\n"
" -p --password pwd Specify gatekeeper H.235 password [none]\n"
" -P --prefer codec Set codec preference (use multiple times) [none]\n"
" -D --disable codec Disable codec (use multiple times) [none]\n"
" -b -- bandwidth kbps Specify bandwidth per call\n"
#ifdef H323_VIDEO
" -v --video Enable Video Support\n"
" --videopattern Set video pattern to send, eg. 'Fake', 'Fake/BouncingBoxes' or 'Fake/MovingBlocks'\n"
" -R --framerate n Set frame rate for outgoing video (fps)\n"
" --maxframe name Maximum Frame Size (qcif, cif, 4cif, 16cif, 480i, 720p, 1080i)\n"
#endif
#ifdef H323_TLS
" --tls TLS Enabled (must be set for TLS).\n"
" --tls-cafile TLS Certificate Authority File.\n"
" --tls-cert TLS Certificate File.\n"
" --tls-privkey TLS Private Key File.\n"
" --tls-passphrase TLS Private Key PassPhrase.\n"
" --tls-listenport TLS listen port (default: 1300).\n"
#endif
" -f --fast-disable Disable fast start\n"
" -T --h245tunneldisable Disable H245 tunneling\n"
" -O --out-msg file Specify PCM16 WAV file for outgoing message [ogm.wav]\n"
" -I --in-dir dir Specify directory for incoming WAV files [disabled]\n"
" -c --cdr file Specify Call Detail Record file [none]\n"
" --tcp-base port Specific the base TCP port to use\n"
" --tcp-max port Specific the maximum TCP port to use\n"
" --udp-base port Specific the base UDP port to use\n"
" --udp-max port Specific the maximum UDP port to use\n"
" --rtp-base port Specific the base RTP/RTCP pair of UDP port to use\n"
" --rtp-max port Specific the maximum RTP/RTCP pair of UDP port to use\n"
" --tmaxest secs Maximum time to wait for \"Established\" [0]\n"
" --tmincall secs Minimum call duration in seconds [10]\n"
" --tmaxcall secs Maximum call duration in seconds [30]\n"
" --tminwait secs Minimum interval between calls in seconds [10]\n"
" --tmaxwait secs Maximum interval between calls in seconds [30]\n"
" --fuzzing Enable RTP fuzzing\n"
" --fuzz-header Percentage of RTP header to randomly overwrite [50]\n"
" --fuzz-media Percentage of RTP media to randomly overwrite [0]\n"
" --fuzz-rtcp Percentage of RTCP to randomly overwrite [5]\n"
"\n"
"Notes:\n"
" If --tmaxest is set a non-zero value then --tmincall is the time to leave\n"
" the call running once established. If zero (the default) then --tmincall\n"
" is the length of the call from initiation. The call may or may not be\n"
" \"answered\" within that time.\n"
"\n";
return;
}
#if PTRACING
PTrace::Initialise(args.GetOptionCount('t'),
args.HasOption('o') ? (const char *)args.GetOptionString('o') : NULL,
PTrace::DateAndTime | PTrace::TraceLevel | PTrace::FileAndLine);
#endif
h323 = new MyH323EndPoint();
outgoingMessageFile = args.GetOptionString('O', "ogm.wav");
if (outgoingMessageFile.IsEmpty())
cout << "Not using outgoing message file." << endl;
else if (PFile::Exists(outgoingMessageFile))
cout << "Using outgoing message file: " << outgoingMessageFile << endl;
else {
cout << "Outgoing message file \"" << outgoingMessageFile << "\" does not exist!" << endl;
PTRACE(1, "CallGen\tOutgoing message file \"" << outgoingMessageFile << "\" does not exist");
outgoingMessageFile = PString::Empty();
}
incomingAudioDirectory = args.GetOptionString('I');
if (incomingAudioDirectory.IsEmpty())
cout << "Not saving incoming audio data." << endl;
else if (PDirectory::Exists(incomingAudioDirectory) ||
PDirectory::Create(incomingAudioDirectory)) {
incomingAudioDirectory = PDirectory(incomingAudioDirectory);
cout << "Using incoming audio directory: " << incomingAudioDirectory << endl;
}
else {
cout << "Could not create incoming audio directory \"" << incomingAudioDirectory << "\"!" << endl;
PTRACE(1, "CallGen\tCould not create incoming audio directory \"" << incomingAudioDirectory << '"');
incomingAudioDirectory = PString::Empty();
}
// start the H.323 listener
H323ListenerTCP * listener = NULL;
PIPSocket::Address interfaceAddress(INADDR_ANY);
WORD listenPort = H323EndPoint::DefaultTcpPort;
if (args.HasOption('i')) {
PString interface = args.GetOptionString('i');
PINDEX colon = interface.Find(":");
if (colon != P_MAX_INDEX) {
interfaceAddress = interface.Left(colon);
listenPort = interface.Mid(colon + 1).AsUnsigned();
} else {
interfaceAddress = interface;
}
}
listener = new H323ListenerTCP(*h323, interfaceAddress, listenPort);
if (!h323->StartListener(listener)) {
cout << "Could not open H.323 listener port on " << interfaceAddress << ":" << listener->GetListenerPort() << endl;
delete listener;
return;
}
cout << "H.323 listening on: " << setfill(',') << h323->GetListeners() << setfill(' ') << endl;
if (args.HasOption('c')) {
if (cdrFile.Open(args.GetOptionString('c'), PFile::WriteOnly, PFile::Create)) {
cdrFile.SetPosition(0, PFile::End);
PTRACE(1, "CallGen\tSetting CDR to \"" << cdrFile.GetFilePath() << '"');
cout << "Sending Call Detail Records to \"" << cdrFile.GetFilePath() << '"' << endl;
}
else {
cout << "Could not open \"" << cdrFile.GetFilePath() << "\"!" << endl;
}
}
if (args.HasOption("tcp-base"))
h323->SetTCPPorts(args.GetOptionString("tcp-base").AsUnsigned(),
args.GetOptionString("tcp-max").AsUnsigned());
if (args.HasOption("udp-base"))
h323->SetUDPPorts(args.GetOptionString("udp-base").AsUnsigned(),
args.GetOptionString("udp-max").AsUnsigned());
if (args.HasOption("rtp-base"))
h323->SetRtpIpPorts(args.GetOptionString("rtp-base").AsUnsigned(),
args.GetOptionString("rtp-max").AsUnsigned());
#ifdef H323_H239
if (args.HasOption("h239enable")) {
cout << "Enabling H.239" << endl;
if (!args.HasOption('l')) {
h323->SetStartH239(true); // only the calling call generator starts a H.239 channel
int delay = (args.HasOption("h239delay")) ? args.GetOptionString("h239delay").AsInteger() : 1;
h323->SetH239Delay(delay);
int duration = (args.HasOption("h239duration")) ? args.GetOptionString("h239duration").AsInteger() : -1;
h323->SetH239Duration(duration);
}
} else {
cout << "Disabling H.239" << endl;
h323->RemoveCapabilities(PStringArray("H.239"));
}
#endif
h323->RemoveCapabilities(args.GetOptionString('D').Lines());
h323->ReorderCapabilities(args.GetOptionString('P').Lines());
cout << "Local capabilities:\n" << h323->GetCapabilities() << endl;
// set local username, is necessary
if (args.HasOption('u')) {
PStringArray aliases = args.GetOptionString('u').Lines();
h323->SetLocalUserName(aliases[0]);
for (PINDEX i = 1; i < aliases.GetSize(); ++i)
h323->AddAliasName(aliases[i]);
}
cout << "Local username: \"" << h323->GetLocalUserName() << '"' << endl;
if (args.HasOption("mcu")) {
h323->SetTerminalType(H323EndPoint::e_MCUWithAVMP); // pose as MCU to always win H.245 master/slave negotiation
cout << "Posing as MCU" << endl;
}
if (args.HasOption('p')) {
h323->SetGatekeeperPassword(args.GetOptionString('p'));
cout << "Using H.235 security." << endl;
}
#ifdef H323_TLS // Initialize TLS
bool useTLS = args.HasOption("tls");
if (useTLS) {
h323->DisableH245Tunneling(false); // Tunneling must be used with TLS
if (args.HasOption("tls-cafile"))
useTLS = h323->TLS_SetCAFile(args.GetOptionString("tls-cafile"));
if (useTLS && args.HasOption("tls-cert"))
useTLS = h323->TLS_SetCertificate(args.GetOptionString("tls-cert"));
if (useTLS && args.HasOption("tls-privkey")) {
PString passphrase = PString();
if (args.HasOption("tls-passphrase"))
passphrase = args.GetOptionString("tls-passphrase");
useTLS = h323->TLS_SetPrivateKey(args.GetOptionString("tls-privkey"), passphrase);
}
WORD tlsListenPort = (WORD)args.GetOptionString("tls-listenport", "1300").AsUnsigned();
if (useTLS && h323->TLS_Initialise(interfaceAddress, tlsListenPort)) {
cout << "Enabled TLS signal security." << endl;
} else {
cerr << "Could not enable TLS signal security." << endl;
}
}
#endif
if (args.HasOption('a')) {
h323->SetGkAccessTokenOID(args.GetOptionString('a'));
cout << "Set Access Token OID to \"" << h323->GetGkAccessTokenOID() << '"' << endl;
}
// process gatekeeper registration options
#ifdef H323_H46017
if (args.HasOption('k')) {
PString gk17 = args.GetOptionString('k');
if (h323->H46017CreateConnection(gk17, false)) {
PTRACE(2, "Using H.460.17 Gatekeeper Tunneling.");
} else {
cout << "Error: H.460.17 Gatekeeper Tunneling Failed: Gatekeeper=" << gk17 << endl;
return;
}
} else
#endif
{
if (args.HasOption('g')) {
#ifdef H323_H46018
cout << "H.460.18/.19: " << (args.HasOption("h46018enable") ? "enabled" : "disabled") << endl;
h323->H46018Enable(args.HasOption("h46018enable"));
#endif
#ifdef H323_H46019M
cout << "H.460.19 RTP multiplexing: " << (args.HasOption("h46019multiplexenable") ? "enabled" : "disabled") << endl;
h323->H46019MEnable(args.HasOption("h46019multiplexenable"));
h323->H46019MSending(args.HasOption("h46019multiplexenable"));
#endif
#ifdef H323_H46023
cout << "H.460.23/.24: " << (args.HasOption("h46023enable") ? "enabled" : "disabled") << endl;
h323->H46023Enable(args.HasOption("h46023enable"));
#endif
PString gkAddr = args.GetOptionString('g');
cout << "Registering with gatekeeper \"" << gkAddr << "\" ..." << flush;
if (h323->SetGatekeeper(gkAddr, new H323TransportUDP(*h323, interfaceAddress))) {
cout << "\nGatekeeper set to \"" << *h323->GetGatekeeper() << '"' << endl;
} else {
cout << "\nError registering with gatekeeper at \"" << gkAddr << '"' << endl;
return;
}
}
else if (!args.HasOption('n')) {
cout << "Searching for gatekeeper ..." << flush;
if (h323->UseGatekeeper())
cout << "\nGatekeeper found: " << *h323->GetGatekeeper() << endl;
else {
cout << "\nNo gatekeeper found." << endl;
if (args.HasOption("require-gatekeeper"))
return;
}
}
}
if (args.HasOption('f'))
h323->DisableFastStart(TRUE);
if (args.HasOption('T'))
h323->DisableH245Tunneling(TRUE);
#ifdef H323_H235
if (args.HasOption("mediaenc")) {
H323EndPoint::H235MediaCipher ncipher = H323EndPoint::encypt128;
#ifdef H323_H235_AES256
unsigned maxtoken = 2048;
unsigned cipher = args.GetOptionString("mediaenc").AsInteger();
if (cipher >= H323EndPoint::encypt192) ncipher = H323EndPoint::encypt192;
if (cipher >= H323EndPoint::encypt256) ncipher = H323EndPoint::encypt256;
if (args.HasOption("maxtoken")) {
maxtoken = args.GetOptionString("maxtoken").AsInteger();
}
#else
unsigned maxtoken = 1024;
#endif
h323->SetH235MediaEncryption(H323EndPoint::encyptRequest, ncipher, maxtoken);
cout << "Enabled Media Encryption AES" << ncipher << endl;
}
#endif
unsigned bandwidth = 768; // default to 768 kbps
if (args.HasOption('b')) {
bandwidth = args.GetOptionString('b').AsUnsigned();
}
cout << "Per call bandwidth: " << bandwidth << " kbps" << endl;
h323->SetPerCallBandwidth(bandwidth);
#ifdef H323_VIDEO
if (!args.HasOption('v')) {
cout << "Video is disabled" << endl;
h323->RemoveCapability(H323Capability::e_Video);
}
PString videoPattern = "Fake/MovingBlocks";
if (args.HasOption("videopattern")) {
// options for demo pattern include: Fake, Fake/MovingLine, Fake/BouncingBoxes
videoPattern = args.GetOptionString("videopattern");
}
h323->SetVideoPattern(videoPattern);
PString h239VideoPattern = "Fake";
if (args.HasOption("h239videopattern")) {
// options for demo pattern include: Fake, Fake/MovingLine, Fake/BouncingBoxes
h239VideoPattern = args.GetOptionString("h239videopattern");
}
h323->SetVideoPattern(h239VideoPattern, true);
if (args.HasOption('R')) {
h323->SetFrameRate(args.GetOptionString('R').AsUnsigned());
}
if (args.HasOption("maxframe")) {
PCaselessString maxframe = args.GetOptionString("maxframe");
if (maxframe == "qcif")
h323->SetVideoFrameSize(H323Capability::qcifMPI);
else if (maxframe == "cif")
h323->SetVideoFrameSize(H323Capability::cifMPI);
else if (maxframe == "4cif")
h323->SetVideoFrameSize(H323Capability::cif4MPI);
else if (maxframe == "16cif")
h323->SetVideoFrameSize(H323Capability::cif16MPI);
else if (maxframe == "480i")
h323->SetVideoFrameSize(H323Capability::i480MPI);
else if (maxframe == "720p")
h323->SetVideoFrameSize(H323Capability::p720MPI);
else if (maxframe == "1080i")
h323->SetVideoFrameSize(H323Capability::i1080MPI);
else {
cerr << "Unknown maxframe value: " << maxframe << endl;
return;
}
}
#endif
if (args.HasOption("fuzzing")) {
h323->SetFuzzing(true);
}
if (args.HasOption("fuzz-header")) {
h323->SetPercentBadRTPHeader(args.GetOptionString("fuzz-header").AsUnsigned());
}
if (args.HasOption("fuzz-media")) {
h323->SetPercentBadRTPMedia(args.GetOptionString("fuzz-media").AsUnsigned());
}
if (args.HasOption("fuzz-rtcp")) {
h323->SetPercentBadRTCP(args.GetOptionString("fuzz-rtcp").AsUnsigned());
}
if (args.HasOption('l')) {
cout << "Endpoint is listening for incoming calls, press ENTER to exit.\n";
console.ReadChar();
h323->ClearAllCalls();
}
else {
CallParams params(*this);
params.tmax_est .SetInterval(0, args.GetOptionString("tmaxest", "0" ).AsUnsigned());
params.tmin_call.SetInterval(0, args.GetOptionString("tmincall", "10").AsUnsigned());
params.tmax_call.SetInterval(0, args.GetOptionString("tmaxcall", "60").AsUnsigned());
params.tmin_wait.SetInterval(0, args.GetOptionString("tminwait", "10").AsUnsigned());
params.tmax_wait.SetInterval(0, args.GetOptionString("tmaxwait", "30").AsUnsigned());
if (params.tmin_call == 0 ||
params.tmin_wait == 0 ||
params.tmin_call > params.tmax_call ||
params.tmin_wait > params.tmax_wait) {
cerr << "Invalid times entered!\n";
return;
}
unsigned number = args.GetOptionString('m').AsUnsigned();
if (number == 0)
number = 1;
cout << "Endpoint starting " << number << " simultaneous call";
if (number > 1)
cout << 's';
cout << ' ';
params.repeat = args.GetOptionString('r', "10").AsUnsigned();
if (params.repeat != 0)
cout << params.repeat;
else
cout << "infinite";
cout << " time";
if (params.repeat != 1)
cout << 's';
if (params.repeat != 0)
cout << ", grand total of " << number*params.repeat << " calls";
cout << '.' << endl;
// create some threads to do calls, but start them randomly
for (unsigned idx = 0; idx < number; idx++) {
if (args.HasOption('C'))
threadList.Append(new CallThread(idx+1, args.GetParameters(), params));
else {
PINDEX arg = idx % args.GetCount();
threadList.Append(new CallThread(idx+1, args.GetParameters(arg, arg), params));
}
}
PThread::Create(PCREATE_NOTIFIER(Cancel), 0);
for (;;) {
threadEnded.Wait();
PThread::Sleep(100);
PBoolean finished = TRUE;
for (PINDEX i = 0; i < threadList.GetSize(); i++) {
if (!threadList[i].IsTerminated()) {
finished = FALSE;
break;
}
}
if (finished) {
cout << "\nAll call sets completed." << endl;
console.Close();
break;
}
}
}
if (totalAttempts > 0)
cout << "Total calls: " << totalAttempts << " attempted, " << totalEstablished << " established\n";
// delete endpoint object so we unregister cleanly
delete h323;
}
void CallGen::Cancel(PThread &, INT)
{
PTRACE(3, "CallGen\tCancel thread started.");
coutMutex.Wait();
cout << "Press ENTER at any time to quit.\n" << endl;
coutMutex.Signal();
// wait for a keypress
while (console.ReadChar() != '\n') {
if (!console.IsOpen()) {
PTRACE(3, "CallGen\tCancel thread ended.");
return;
}
}
PTRACE(2, "CallGen\tCancelling calls.");
coutMutex.Wait();
cout << "\nAborting all calls ..." << endl;
coutMutex.Signal();
// stop threads
for (PINDEX i = 0; i < threadList.GetSize(); i++)
threadList[i].Stop();
// stop all calls
CallGen::Current().ClearAll();
PTRACE(1, "CallGen\tCancelled calls.");
}
///////////////////////////////////////////////////////////////////////////////
CallThread::CallThread(unsigned _index, const PStringArray & _destinations, const CallParams & _params)
: PThread(1000, NoAutoDeleteThread, NormalPriority, psprintf("CallGen %u", _index)),
destinations(_destinations),
index(_index),
params(_params)
{
Resume();
}
static unsigned RandomRange(PRandom & rand, const PTimeInterval & tmin, const PTimeInterval & tmax)
{
unsigned umax = tmax.GetInterval();
unsigned umin = tmin.GetInterval();
return rand.Generate() % (umax - umin + 1) + umin;
}
#define START_OUTPUT(index, token) \
{ \
CallGen::Current().coutMutex.Wait(); \
cout << setw(3) << index << ": " << setw(20) << token.Left(20) << ": "
#define END_OUTPUT() \
cout << endl; \
CallGen::Current().coutMutex.Signal(); \
}
#define OUTPUT(index, token, info) START_OUTPUT(index, token) << info; END_OUTPUT()
void CallThread::Main()
{
PTRACE(2, "CallGen\tStarted thread " << index);
CallGen & callgen = CallGen::Current();
PRandom rand(PRandom::Number());
PTimeInterval delay = RandomRange(rand, (index-1)*500, (index+1)*500);
OUTPUT(index, PString::Empty(), "Initial delay of " << delay << " seconds");
if (exit.Wait(delay)) {
PTRACE(2, "CallGen\tAborted thread " << index);
callgen.threadEnded.Signal();
return;
}
// Loop "repeat" times for (repeat > 0), or loop forever for (repeat == 0)
unsigned count = 1;
do {
PString destination = destinations[(index-1 + count-1) % destinations.GetSize()];
// trigger a call
PString token;
PTRACE(1, "CallGen\tMaking call to " << destination);
unsigned totalAttempts = ++callgen.totalAttempts;
if (!callgen.Start(destination, token))
PError << setw(3) << index << ": Call creation to " << destination << " failed" << endl;
else {
PBoolean stopping = FALSE;
delay = RandomRange(rand, params.tmin_call, params.tmax_call);
START_OUTPUT(index, token) << "Making call " << count;
if (params.repeat)
cout << " of " << params.repeat;
cout << " (total=" << totalAttempts
<< ") for " << delay << " seconds to "
<< destination;
END_OUTPUT();
if (params.tmax_est > 0) {
OUTPUT(index, token, "Waiting " << params.tmax_est << " seconds for establishment");
PTimer timeout = params.tmax_est;
while (!callgen.IsEstablished(token)) {
stopping = exit.Wait(100);
if (stopping || !timeout.IsRunning() || !callgen.Exists(token)) {
delay = 0;
break;
}
}
}
if (delay > 0) {
// wait for a random time
PTRACE(1, "CallGen\tWaiting for " << delay);
stopping = exit.Wait(delay);
}
// end the call
OUTPUT(index, token, "Clearing call");
callgen.Clear(token);
if (stopping)
break;
}
count++;
if (params.repeat > 0 && count > params.repeat)
break;
// wait for a random delay
delay = RandomRange(rand, params.tmin_wait, params.tmax_wait);
OUTPUT(index, PString::Empty(), "Delaying for " << delay << " seconds");
PTRACE(1, "CallGen\tDelaying for " << delay);
// wait for a random time
} while (!exit.Wait(delay));
OUTPUT(index, PString::Empty(), "Completed call set.");
PTRACE(2, "CallGen\tFinished thread " << index);
callgen.threadEnded.Signal();
}
void CallThread::Stop()
{
if (!IsTerminated())
OUTPUT(index, PString::Empty(), "Stopping.");
exit.Signal();
}
///////////////////////////////////////////////////////////////////////////////
void CallDetail::Drop(H323Connection & connection)
{
PTextFile & cdrFile = CallGen::Current().cdrFile;
if (!cdrFile.IsOpen())
return;
static PMutex cdrMutex;
cdrMutex.Wait();
if (cdrFile.GetLength() == 0)
cdrFile << "Call Start Time,"
"Total duration,"
"Media open transmit time,"
"Media open received time,"
"Media received time,"
"ALERTING time,"
"CONNECT time,"
"Call End Reason,"
"Remote party,"
"Signaling gateway,"
"Media gateway,"
"Call Id,"
"Call Token\n";
PTime setupTime = connection.GetSetupUpTime();
cdrFile << setupTime.AsString("yyyy/M/d hh:mm:ss") << ','
<< setprecision(1) << (connection.GetConnectionEndTime() - setupTime) << ',';
if (openedTransmitMedia.IsValid())
cdrFile << (openedTransmitMedia - setupTime);
cdrFile << ',';
if (openedReceiveMedia.IsValid())
cdrFile << (openedReceiveMedia - setupTime);
cdrFile << ',';
if (receivedMedia.IsValid())
cdrFile << (receivedMedia - setupTime);
cdrFile << ',';
if (connection.GetAlertingTime().IsValid())
cdrFile << (connection.GetAlertingTime() - setupTime);
cdrFile << ',';
if (connection.GetConnectionStartTime().IsValid())
cdrFile << (connection.GetConnectionStartTime() - setupTime);
cdrFile << ',';
cdrFile << connection.GetCallEndReason() << ','
<< connection.GetRemotePartyName() << ','
<< connection.GetRemotePartyAddress() << ','
<< mediaGateway << ','
<< connection.GetCallIdentifier() << ','
<< connection.GetCallToken()
<< endl;
cdrMutex.Signal();
}
void CallDetail::OnRTPStatistics(const RTP_Session & session, const PString & token)
{
if (session.GetSessionID() == 1 && !receivedAudio) {
receivedAudio = true;
OUTPUT("", token, "Received audio");
}
if (session.GetSessionID() == 2 && !receivedVideo) {
receivedVideo = true;
OUTPUT("", token, "Received video");
}
if (receivedMedia.GetTimeInSeconds() == 0 && session.GetPacketsReceived() > 0) {
receivedMedia = PTime();
const RTP_UDP * udpSess = dynamic_cast<const RTP_UDP *>(&session);
if (udpSess != NULL)
mediaGateway = H323TransportAddress(udpSess->GetRemoteAddress(), udpSess->GetRemoteDataPort());
}
}
///////////////////////////////////////////////////////////////////////////////
MyH323EndPoint::MyH323EndPoint()
{
// load plugins for H.460.17, .18 etc.
LoadBaseFeatureSet();
useJitterBuffer = false; // save a little processing time
AddAllCapabilities(0, P_MAX_INDEX, "*");
AddAllUserInputCapabilities(0, P_MAX_INDEX);
SetPerCallBandwidth(384);
SetFrameRate(30);
m_maxFrameSize = H323Capability::i1080MPI;
SetFuzzing(false);
SetPercentBadRTPHeader(50);
SetPercentBadRTPMedia(0);
SetPercentBadRTCP(5);
SetStartH239(false);
SetH239Delay(1);
SetH239Duration(-1);
}
PBoolean MyH323EndPoint::SetVideoFrameSize(H323Capability::CapabilityFrameSize frameSize, int frameUnits)
{
m_maxFrameSize = frameSize;
return H323EndPoint::SetVideoFrameSize(frameSize, frameUnits);
}
H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference)
{
return new MyH323Connection(*this, callReference);
}
static PString TidyRemotePartyName(const H323Connection & connection)
{
PString name = connection.GetRemotePartyName();
PINDEX bracket = name.FindLast('[');
if (bracket == 0 || bracket == P_MAX_INDEX)
return name;
return name.Left(bracket).Trim();
}
void MyH323EndPoint::OnConnectionEstablished(H323Connection & connection, const PString & token)
{
OUTPUT("", token, "Established \"" << TidyRemotePartyName(connection) << "\""
" " << connection.GetControlChannel().GetRemoteAddress() <<
" active=" << connectionsActive.GetSize() <<
" total=" << ++CallGen::Current().totalEstablished);
}
void MyH323EndPoint::OnConnectionCleared(H323Connection & connection, const PString & token)
{
OUTPUT("", token, "Cleared \"" << TidyRemotePartyName(connection) << "\""
" " << connection.GetControlChannel().GetRemoteAddress() <<
" reason=" << connection.GetCallEndReason());
((MyH323Connection&)connection).details.Drop(connection);
}
PBoolean MyH323EndPoint::OnStartLogicalChannel(H323Connection & connection, H323Channel & channel)
{
(channel.GetDirection() == H323Channel::IsTransmitter
? ((MyH323Connection&)connection).details.openedTransmitMedia
: ((MyH323Connection&)connection).details.openedReceiveMedia) = PTime();
OUTPUT("", connection.GetCallToken(),
"Opened " << (channel.GetDirection() == H323Channel::IsTransmitter ? "transmitter" : "receiver")
<< " for " << channel.GetCapability());
return H323EndPoint::OnStartLogicalChannel(connection, channel);
}
///////////////////////////////////////////////////////////////////////////////
MyH323Connection::MyH323Connection(MyH323EndPoint & ep, unsigned callRef)
: H323Connection(ep, callRef)
, endpoint(ep)
, videoChannelIn(NULL)
, videoChannelOut(NULL)
, m_isH239ready(false)
, m_haveStartedH239(false)
{
detectInBandDTMF = FALSE; // turn off in-band DTMF detection (uses a huge amount of CPU)
}
MyH323Connection::~MyH323Connection()
{
delete videoChannelIn;
delete videoChannelOut;
}
PBoolean MyH323Connection::OnSendSignalSetup(H323SignalPDU & setupPDU)
{
// set outgoing bearer capability to unrestricted information transfer + transfer rate
PBYTEArray caps;
caps.SetSize(4);
caps[0] = 0x88;
caps[1] = 0x18;
caps[2] = 0x80 | endpoint.GetRateMultiplier();
caps[3] = 0xa5;
setupPDU.GetQ931().SetIE(Q931::BearerCapabilityIE, caps);
return H323Connection::OnSendSignalSetup(setupPDU);
}
H323Channel * MyH323Connection::CreateRealTimeLogicalChannel(const H323Capability & capability, H323Channel::Directions dir,
unsigned sessionID, const H245_H2250LogicalChannelParameters * param, RTP_QOS * rtpqos)
{
if (endpoint.IsFuzzing()) {
WORD rtpPort = 0;
map<unsigned, WORD>::const_iterator iter = m_sessionPorts.find(sessionID);
if (iter != m_sessionPorts.end()) {
rtpPort = iter->second;
} else {
rtpPort = endpoint.GetRtpIpPortPair();
m_sessionPorts[sessionID] = rtpPort;
}
return new RTPFuzzingChannel(endpoint, *this, capability, dir, sessionID, rtpPort, rtpPort+1);
} else {
// call super class
return H323Connection::CreateRealTimeLogicalChannel(capability, dir, sessionID, param, rtpqos);
}
}
void MyH323Connection::OnRTPStatistics(const RTP_Session & session) const
{
((MyH323Connection *)this)->details.OnRTPStatistics(session, GetCallToken());
}
PBoolean MyH323Connection::OpenAudioChannel(PBoolean isEncoding, unsigned bufferSize, H323AudioCodec & codec)
{
unsigned frameDelay = bufferSize / 16; // assume 16 bit PCM
PIndirectChannel * channel;
if (isEncoding)
channel = new PlayMessage(CallGen::Current().outgoingMessageFile, frameDelay, bufferSize);
else {
PString wavFileName;
if (!CallGen::Current().incomingAudioDirectory) {
PString token = GetCallToken();
token.Replace("/", "_", TRUE);
wavFileName = CallGen::Current().incomingAudioDirectory + token;
}
channel = new RecordMessage(wavFileName, frameDelay, bufferSize);
}
codec.AttachChannel(channel);
return TRUE;
}
#ifdef H323_VIDEO
PBoolean MyH323Connection::OpenVideoChannel(PBoolean isEncoding, H323VideoCodec & codec)
{
bool isH239 = false;
#if (H323PLUS_VER >= 1271)
isH239 = codec.GetRTPSessionID() > 2;
#endif
PString deviceName = isEncoding ? endpoint.GetVideoPattern(isH239) : "NULL";
PVideoDevice * device = isEncoding ? (PVideoDevice *)PVideoInputDevice::CreateDeviceByName(deviceName)
: (PVideoDevice *)PVideoOutputDevice::CreateDeviceByName(deviceName);
// codec needs a list of possible formats, otherwise the frame size isn't negotiated properly
if (isEncoding) {
#if PTLIB_VER >= 2110
PVideoInputDevice::Capabilities videoCaps;
if (((PVideoInputDevice *)device)->GetDeviceCapabilities(deviceName, deviceDriver, &videoCaps)) {
codec.SetSupportedFormats(videoCaps.framesizes);
} else
#endif // PTLIB_VER
{
// set fixed list of resolutions for PTLib < 2.11 and for drivers that don't provide a list
PVideoInputDevice::Capabilities caps;