-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
sipexer.go
2184 lines (2034 loc) · 72.2 KB
/
sipexer.go
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
/**
* SIP (RFC3261) Command Line Tool
* (C) Copyright 2021-2022 Daniel-Constantin Mierla (asipto.com)
* License: GPLv3
*/
package main
import (
"bytes"
"crypto/md5"
cryptorand "crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"log"
mathrand "math/rand"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/google/uuid"
"github.com/miconda/sipexer/sgsip"
"golang.org/x/net/websocket"
)
const sipexerVersion = "1.1.0"
// exit, return and error code values
const (
SIPExerRetOK = 0
SIPExerRetDone = 1
SIPExerRetErr = -1
// errors
SIPExerErrTemplateRead = -1000
SIPExerErrTemplateData = -1001
SIPExerErrFieldsFileRead = -1020
SIPExerErrFieldsFileFormat = -1021
SIPExerErrFieldsDefaultFormat = -1022
SIPExerErrExpiresValue = -1030
SIPExerErrArgumentsNumber = -1050
SIPExerErrDestinationFormat = -1060
SIPExerErrURIFormat = -1070
SIPExerErrSIPMessageFormat = -1080
SIPExerErrSIPMessageToString = -1081
SIPExerErrSIPMessageFirstLine = -1082
SIPExerErrSIPMessageResponse = -1083
SIPExerErrProtocolUnsuported = -1090
SIPExerErrHeaderAuthGet = -1100
SIPExerErrHeaderAuthParse = -1101
SIPExerErrResolveSrcUDPAddr = -1120
SIPExerErrResolveDstUDPAddr = -1121
SIPExerErrUDPSocket = -1122
SIPExerErrUDPDial = -1123
SIPExerErrUDPWrite = -1124
SIPExerErrUDPSetTimeout = -1125
SIPExerErrUDPICMPTimeout = -1126
SIPExerErrUDPReceiveTimeout = -1127
SIPExerErrResolveSrcTCPAddr = -1140
SIPExerErrResolveDstTCPAddr = -1141
SIPExerErrTCPDial = -1142
SIPExerErrTCPWrite = -1143
SIPExerErrTCPSetWriteTimeout = -1144
SIPExerErrTCPSetReadTimeout = -1145
SIPExerErrTCPRead = -1146
SIPExerErrTLSReadCertificates = -1150
SIPExerErrTLSDial = -1151
SIPExerErrTLSWrite = -1152
SIPExerErrTLSSetReadTimeout = -1153
SIPExerErrTLSRead = -1154
SIPExerErrWSURLFormat = -1160
SIPExerErrWSOrigin = -1161
SIPExerErrWSDial = -1162
SIPExerErrWSWrite = -1163
SIPExerErrWSSetReadTimeout = -1164
SIPExerErrWSRead = -1165
SIPExerErrRandomKey = -1170
)
var templateDefaultText string = `{{.method}} {{.ruri}} SIP/2.0
Via: SIP/2.0/{{.viaproto}} {{.viaaddr}}{{.rport}};{{.viaparams}}branch=z9hG4bKSG.{{.viabranch}}
From: {{if .fromuri}}{{.fromuri}}{{else}}{{if .fname}}"{{.fname}}" {{end}}<sip:{{if .fuser}}{{.fuser}}@{{end}}{{.fdomain}}>{{end}};tag={{.fromtag}}
To: {{if .touri}}{{.touri}}{{else}}{{if .tname}}"{{.tname}}" {{end}}<sip:{{if .tuser}}{{.tuser}}@{{end}}{{.tdomain}}>{{end}}{{if .totag}};tag={{.totag}}{{end}}
Call-ID: {{.callid}}
CSeq: {{.cseqnum}} {{.method}}
{{if .subject}}Subject: {{.subject}}{{else}}$rmeol{{end}}
{{if .date}}Date: {{.date}}{{else}}$rmeol{{end}}
{{if .contacturi}}Contact: {{.contacturi}}{{if .contactparams}};{{.contactparams}}{{end}}{{else}}$rmeol{{end}}
{{if .expires}}Expires: {{.expires}}{{else}}$rmeol{{end}}
{{if .useragent}}User-Agent: {{.useragent}}{{else}}$rmeol{{end}}
{{if .maxforwards}}Max-Forwards: {{.maxforwards}}{{else}}$rmeol{{end}}
{{if .contenttype}}Content-Type: {{.contenttype}}{{else}}$rmeol{{end}}
Content-Length: 0
`
var templateDefaultMessageBody string = `Hello there!{{if .date}} The date is: {{.date}}.{{end}}`
var templateDefaultInviteBody string = `v=0{{.cr}}
o={{.sdpuser}} {{.sdpsessid}} {{.sdpsessversion}} IN {{.sdpaf}} {{.localip}}{{.cr}}
s=call{{.cr}}
c=IN {{.sdpaf}} {{.localip}}{{.cr}}
t=0 0{{.cr}}
m=audio {{.sdprtpport}} RTP/AVP 0 8 101{{.cr}}
a=rtpmap:0 pcmu/8000{{.cr}}
a=rtpmap:8 pcma/8000{{.cr}}
a=rtpmap:101 telephone-event/8000{{.cr}}
a=sendrecv{{.cr}}
`
var templateBody string = ""
var templateDefaultJSONFields string = `{
"method": "OPTIONS",
"fuser": "alice",
"fdomain": "localhost",
"tuser": "bob",
"tdomain": "localhost",
"viabranch": "$uuid",
"viaparams": "",
"rport": ";rport",
"fromtag": "$uuid",
"totag": "",
"callid": "$uuid",
"cseqnum": "$randseq",
"contenttype": "",
"date": "$daterfc1123",
"maxforwards": "10",
"sdpuser": "sipexer",
"sdpsessid": "$timestamp",
"sdpsessversion": "$timestamp",
"sdpaf": "IP4",
"sdprtpport": "$rand(20000,40000)"
}`
var templateFields = map[string]map[string]interface{}{
"FIELDS:EMPTY": {},
}
const (
SIPExerDialogInit = 0
SIPExerDialogStarted = 1
SIPExerDialogEarly = 2
SIPExerDialogAnswered = 3
SIPExerDialogConfirmed = 4
SIPExerDialogCancelled = 5
SIPExerDialogTerminated = 6
)
type SIPExerConnUDP struct {
SrcAddr *net.UDPAddr
DstAddr *net.UDPAddr
Conn *net.UDPConn
}
type SIPExerConnTCP struct {
SrcAddr *net.TCPAddr
DstAddr *net.TCPAddr
Conn *net.TCPConn
}
type SIPExerConnTLS struct {
Conn *tls.Conn
}
type SIPExerConnWSS struct {
Conn *websocket.Conn
}
type SIPExerDialog struct {
Proto string
ProtoId int
LocalAddr string
TargetAddr string
RecvAddr string
AType int
Method string
MethodId int
LocalCSeq int
State int
FirstRequest *sgsip.SGSIPMessage
LastRequest *sgsip.SGSIPMessage
AckRequest *sgsip.SGSIPMessage
LastResponse *sgsip.SGSIPMessage
ConnUDP *SIPExerConnUDP
ConnTCP *SIPExerConnTCP
ConnTLS *SIPExerConnTLS
ConnWSS *SIPExerConnWSS
RecvBuf []byte
RecvN int
TimeoutStep int
TimeoutVal int
Resend bool
SkipAuth bool
}
type paramFieldsType map[string]string
func (m paramFieldsType) String() string {
b := new(bytes.Buffer)
for key, value := range m {
fmt.Fprintf(b, "%s:%s\n", key, value)
}
return b.String()
}
func (m paramFieldsType) Set(value string) error {
z := strings.SplitN(value, ":", 2)
if len(z) > 1 {
m[z[0]] = z[1]
}
return nil
}
var paramFields = make(paramFieldsType)
type headerFieldsType [][2]string
func (m *headerFieldsType) String() string {
b := new(bytes.Buffer)
for _, z := range *m {
fmt.Fprintf(b, "%s:%s\n", z[0], z[1])
}
return b.String()
}
func (m *headerFieldsType) Set(value string) error {
z := strings.SplitN(value, ":", 2)
if len(z) > 1 {
*m = append(*m, [2]string{z[0], z[1]})
}
return nil
}
var headerFields = make(headerFieldsType, 0)
type iVarMapType map[string]int
func (m iVarMapType) String() string {
b := new(bytes.Buffer)
for key, value := range m {
fmt.Fprintf(b, "%s:%d\n", key, value)
}
return b.String()
}
func (m iVarMapType) Set(value string) error {
z := strings.SplitN(value, ":", 2)
if len(z) > 1 {
m[z[0]], _ = strconv.Atoi(z[1])
}
return nil
}
var iVarMap = make(iVarMapType)
// CLIOptions - structure for command line options
type CLIOptions struct {
method string
register bool
message bool
options bool
invite bool
info bool
subscribe bool
publish bool
notify bool
cancel bool
ack bool
kdmq bool
ruri string
ruser string
fuser string
fromuri string
tuser string
fdomain string
tdomain string
touri string
body string
nobody bool
contenttype string
localaddress string
useragent string
template string
templatebody string
templaterun bool
fields string
fieldseval bool
nocrlf bool
flagdefaults bool
templatedefaults bool
timert1 int
timert2 int
timeout int
timeoutwrite int
buffersize int
connectudp bool
af int
setdomains bool
setuser bool
tlsinsecure bool
tlscertificate string
tlskey string
wsorigin string
wsproto string
authuser string
authapassword string
noval string
contacturi string
contactbuild bool
registerparty bool
expires string
raw bool
noparse bool
verbosity int
nagios bool
ha1 bool
coloroutput bool
colormessage bool
sessionwait int
runcount int
helpcommands bool
dnssrvprint bool
lateoffer bool
version bool
}
var cliops = CLIOptions{
method: "",
ruri: "",
fuser: "",
fromuri: "",
tuser: "",
touri: "",
fdomain: "",
tdomain: "",
body: "",
nobody: false,
contenttype: "",
localaddress: "",
useragent: "",
template: "",
templatebody: "",
templaterun: false,
fields: "",
fieldseval: false,
nocrlf: false,
flagdefaults: false,
templatedefaults: false,
timert1: 500,
timert2: 4000,
timeout: 32000,
timeoutwrite: 4000,
buffersize: 32 * 1024,
connectudp: false,
af: 0,
setdomains: false,
setuser: false,
tlsinsecure: false,
tlscertificate: "",
tlskey: "",
wsorigin: "http://127.0.0.1",
wsproto: "sip",
authuser: "",
authapassword: "",
noval: "no",
contacturi: "",
contactbuild: false,
expires: "",
register: false,
message: false,
options: false,
invite: false,
info: false,
subscribe: false,
publish: false,
notify: false,
cancel: false,
ack: false,
kdmq: false,
registerparty: false,
raw: false,
noparse: false,
verbosity: 2,
nagios: false,
ha1: false,
coloroutput: false,
colormessage: false,
sessionwait: 0,
runcount: 1,
dnssrvprint: false,
lateoffer: false,
helpcommands: false,
version: false,
}
func sipexer_help_commands() {
fmt.Fprintf(os.Stderr, " Examples:\n\n")
fmt.Fprintf(os.Stderr, " %s sipserver.com\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " %s tcp:sipserver.com:5060\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " %s -sd -xh \"X-My-Header:abcdefgh\" udp:sipserver.com:5060\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " %s -message -mb 'Hello!' -fuser alice -tuser bob -sd udp:sipserver.com:5060\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " %s -message -mb 'Hello!' -fuser alice -fv fname:Alice -tuser bob -fv tname:Bob -sd udp:sipserver.com:5060\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " %s -register -vl 3 -co -com -ex 60 -fuser alice -cb -ap \"abab...\" -ha1 -sd udp:sipserver.com:5060\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " %s -invite -vl 3 -co -com -fuser alice -tuser bob -cb -ap \"abab...\" -ha1 -sw 10000 -sd -su udp:sipserver.com:5060\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, "\n")
}
func printCLIOptions() {
type CLIOptionDef struct {
Ops []string
Usage string
DefValue string
VType string
}
var items []CLIOptionDef
flag.VisitAll(func(f *flag.Flag) {
var found bool = false
for idx, it := range items {
if it.Usage == f.Usage {
found = true
it.Ops = append(it.Ops, f.Name)
items[idx] = it
}
}
if !found {
items = append(items, CLIOptionDef{
Ops: []string{f.Name},
Usage: f.Usage,
DefValue: f.DefValue,
VType: fmt.Sprintf("%T", f.Value),
})
}
})
sort.Slice(items, func(i, j int) bool { return strings.ToLower(items[i].Ops[0]) < strings.ToLower(items[j].Ops[0]) })
for _, val := range items {
vtype := "val"
if strings.HasSuffix(val.VType, "Value") {
vtype = val.VType[6 : len(val.VType)-5]
} else if strings.HasSuffix(val.VType, "Type") {
vtype = val.VType[6 : len(val.VType)-4]
}
if strings.HasSuffix(vtype, "64") {
vtype = vtype[:len(vtype)-2]
}
for _, opt := range val.Ops {
if vtype == "bool" {
fmt.Printf(" -%s\n", opt)
} else {
fmt.Printf(" -%s %s\n", opt, vtype)
}
}
if vtype != "bool" && len(val.DefValue) > 0 {
fmt.Printf(" %s [default: %s]\n", val.Usage, val.DefValue)
} else {
fmt.Printf(" %s\n", val.Usage)
}
}
}
// initialize application components
func init() {
// command line arguments
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s (v%s):\n\n", filepath.Base(os.Args[0]), sipexerVersion)
fmt.Fprintf(os.Stderr, " %s [options] [target]\n\n", filepath.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, " * target can be: 'host', 'proto:host', 'host:port', 'proto:host:port' or sip-uri\n")
fmt.Fprintf(os.Stderr, " * some options have short and long version\n\n")
printCLIOptions()
fmt.Fprintf(os.Stderr, "\n")
sipexer_help_commands()
SIPExerExit(1)
}
flag.StringVar(&cliops.authapassword, "ap", cliops.authapassword, "authentication password")
flag.StringVar(&cliops.authapassword, "auth-password", cliops.authapassword, "authentication password")
flag.StringVar(&cliops.authuser, "au", cliops.authuser, "authentication user")
flag.StringVar(&cliops.authuser, "auth-user", cliops.authuser, "authentication user")
flag.StringVar(&cliops.body, "mb", cliops.body, "message body")
flag.StringVar(&cliops.body, "message-body", cliops.body, "message body")
flag.StringVar(&cliops.contacturi, "contact-uri", cliops.contacturi, "contact header uri")
flag.StringVar(&cliops.contacturi, "cu", cliops.contacturi, "contact header uri")
flag.StringVar(&cliops.contenttype, "content-type", cliops.contenttype, "content type")
flag.StringVar(&cliops.contenttype, "ct", cliops.contenttype, "content type")
flag.StringVar(&cliops.expires, "ex", cliops.expires, "expires header value")
flag.StringVar(&cliops.expires, "expires", cliops.expires, "expires header value")
flag.StringVar(&cliops.fdomain, "fd", cliops.fdomain, "From header URI domain")
flag.StringVar(&cliops.fdomain, "fdomain", cliops.fdomain, "From header URI domain")
flag.StringVar(&cliops.fields, "ff", cliops.fields, "path to the json fields file")
flag.StringVar(&cliops.fields, "fields-file", cliops.fields, "path to the json fields file")
flag.StringVar(&cliops.fromuri, "from-uri", cliops.fromuri, "From header URI")
flag.StringVar(&cliops.fuser, "fu", cliops.fuser, "From header URI username")
flag.StringVar(&cliops.fuser, "fuser", cliops.fuser, "From header URI username")
flag.StringVar(&cliops.localaddress, "laddr", cliops.localaddress, "local address (`ip:port` or `:port`)")
flag.StringVar(&cliops.method, "method", cliops.method, "SIP method")
flag.StringVar(&cliops.method, "mt", cliops.method, "SIP method")
flag.StringVar(&cliops.noval, "no-val", cliops.noval, "no value string")
flag.StringVar(&cliops.ruri, "ru", cliops.ruri, "request uri (r-uri)")
flag.StringVar(&cliops.ruri, "ruri", cliops.ruri, "request uri (r-uri)")
flag.StringVar(&cliops.ruser, "rn", cliops.ruser, "request uri username for destination proxy address")
flag.StringVar(&cliops.ruser, "ruser", cliops.ruser, "request uri username for destination proxy address")
flag.StringVar(&cliops.tdomain, "td", cliops.tdomain, "To header URI domain")
flag.StringVar(&cliops.tdomain, "tdomain", cliops.tdomain, "To header URI domain")
flag.StringVar(&cliops.template, "template-file", cliops.template, "path to template file")
flag.StringVar(&cliops.template, "tf", cliops.template, "path to template file")
flag.StringVar(&cliops.templatebody, "tbf", cliops.templatebody, "path to template file for body")
flag.StringVar(&cliops.templatebody, "template-body-file", cliops.templatebody, "path to template file for body")
flag.StringVar(&cliops.tlscertificate, "tc", cliops.tlscertificate, "path to TLS public certificate")
flag.StringVar(&cliops.tlscertificate, "tls-certificate", cliops.tlscertificate, "path to TLS public certificate")
flag.StringVar(&cliops.tlskey, "tk", cliops.tlskey, "path to TLS private key")
flag.StringVar(&cliops.tlskey, "tls-key", cliops.tlskey, "path to TLS private key")
flag.StringVar(&cliops.touri, "to-uri", cliops.touri, "To header URI")
flag.StringVar(&cliops.tuser, "tu", cliops.tuser, "To header URI username")
flag.StringVar(&cliops.tuser, "tuser", cliops.tuser, "To header URI username")
flag.StringVar(&cliops.useragent, "ua", cliops.useragent, "user agent value")
flag.StringVar(&cliops.useragent, "user-agent", cliops.useragent, "user agent value")
flag.StringVar(&cliops.wsorigin, "websocket-origin", cliops.wsorigin, "websocket origin http url")
flag.StringVar(&cliops.wsorigin, "wso", cliops.wsorigin, "websocket origin http url")
flag.StringVar(&cliops.wsproto, "websocket-proto", cliops.wsproto, "websocket sub-protocol")
flag.StringVar(&cliops.wsproto, "wsp", cliops.wsproto, "websocket sub-protocol")
flag.BoolVar(&cliops.ack, "ack", cliops.ack, "set method to ACK")
flag.BoolVar(&cliops.cancel, "cancel", cliops.cancel, "set method to CANCEL")
flag.BoolVar(&cliops.colormessage, "color-message", cliops.colormessage, "color SIP message output")
flag.BoolVar(&cliops.colormessage, "com", cliops.colormessage, "color SIP message output")
flag.BoolVar(&cliops.coloroutput, "co", cliops.coloroutput, "color output")
flag.BoolVar(&cliops.coloroutput, "color-output", cliops.coloroutput, "color output")
flag.BoolVar(&cliops.connectudp, "connect-udp", cliops.connectudp, "attempt first a connect for UDP (dial ICMP connect)")
flag.BoolVar(&cliops.contactbuild, "cb", cliops.contactbuild, "build contact header based on local address")
flag.BoolVar(&cliops.contactbuild, "contact-build", cliops.contactbuild, "build contact header based on local address")
flag.BoolVar(&cliops.dnssrvprint, "dns-srv-print", cliops.dnssrvprint, "print DNS SRV records")
flag.BoolVar(&cliops.fieldseval, "fe", cliops.fieldseval, "evaluate expression in fields file")
flag.BoolVar(&cliops.fieldseval, "fields-eval", cliops.fieldseval, "evaluate expression in fields file")
flag.BoolVar(&cliops.flagdefaults, "flag-defaults", cliops.flagdefaults, "print flag (cli param) default values")
flag.BoolVar(&cliops.flagdefaults, "fvd", cliops.flagdefaults, "print flag (cli param) default values")
flag.BoolVar(&cliops.ha1, "ha1", cliops.ha1, "authentication password is in HA1 format")
flag.BoolVar(&cliops.info, "info", cliops.info, "set method to INFO")
flag.BoolVar(&cliops.invite, "i", cliops.invite, "set method to INVITE")
flag.BoolVar(&cliops.invite, "invite", cliops.invite, "set method to INVITE")
flag.BoolVar(&cliops.kdmq, "kdmq", cliops.kdmq, "set method to KDMQ")
flag.BoolVar(&cliops.lateoffer, "late-offer", cliops.lateoffer, "enable SDP late offer mode")
flag.BoolVar(&cliops.message, "m", cliops.message, "set method to MESSAGE")
flag.BoolVar(&cliops.message, "message", cliops.message, "set method to MESSAGE")
flag.BoolVar(&cliops.nagios, "nagios", cliops.nagios, "nagios plugin exit codes")
flag.BoolVar(&cliops.nobody, "no-body", cliops.nobody, "no body for message or invite")
flag.BoolVar(&cliops.nocrlf, "no-crlf", cliops.nocrlf, "do not replace '\\n' with '\\r\\n' inside the data to be sent (true|false)")
flag.BoolVar(&cliops.noparse, "no-parse", cliops.noparse, "no SIP message parsing of input template result")
flag.BoolVar(&cliops.notify, "notify", cliops.notify, "set method to NOTIFY")
flag.BoolVar(&cliops.options, "o", cliops.options, "set method to OPTIONS")
flag.BoolVar(&cliops.options, "options", cliops.options, "set method to OPTIONS")
flag.BoolVar(&cliops.publish, "publish", cliops.publish, "set method to PUBLISH")
flag.BoolVar(&cliops.raw, "raw", cliops.registerparty, "sent raw template content (no evaluation)")
flag.BoolVar(&cliops.register, "r", cliops.register, "set method to REGISTER")
flag.BoolVar(&cliops.register, "register", cliops.register, "set method to REGISTER")
flag.BoolVar(&cliops.registerparty, "register-party", cliops.registerparty, "register a third party To user")
flag.BoolVar(&cliops.setdomains, "sd", cliops.setdomains, "set From/To domains based on R-URI")
flag.BoolVar(&cliops.setdomains, "set-domains", cliops.setdomains, "set From/To domains based on R-URI")
flag.BoolVar(&cliops.setuser, "set-user", cliops.setuser, "set R-URI user to To-URI user for destination proxy address")
flag.BoolVar(&cliops.setuser, "su", cliops.setuser, "set R-URI user to To-URI user for destination proxy address")
flag.BoolVar(&cliops.subscribe, "subscribe", cliops.subscribe, "set method to SUBSCRIBE")
flag.BoolVar(&cliops.templatedefaults, "template-defaults", cliops.templatedefaults, "print default (internal) template data")
flag.BoolVar(&cliops.templatedefaults, "tpd", cliops.templatedefaults, "print default (internal) template data")
flag.BoolVar(&cliops.templaterun, "template-run", cliops.templaterun, "run template execution and print the result")
flag.BoolVar(&cliops.templaterun, "tpr", cliops.templaterun, "run template execution and print the result")
flag.BoolVar(&cliops.tlsinsecure, "ti", cliops.tlsinsecure, "skip tls certificate validation (true|false)")
flag.BoolVar(&cliops.tlsinsecure, "tls-insecure", cliops.tlsinsecure, "skip tls certificate validation (true|false)")
flag.IntVar(&cliops.af, "af", cliops.af, "enforce address family for socket (4 or 6)")
flag.IntVar(&cliops.runcount, "rc", cliops.runcount, "how many times to recreate and send the message")
flag.IntVar(&cliops.runcount, "run-count", cliops.runcount, "how many times to recreate and send the message")
flag.IntVar(&cliops.sessionwait, "sessionwait", cliops.sessionwait, "time in millisecons to wait for a session")
flag.IntVar(&cliops.sessionwait, "sw", cliops.sessionwait, "time in millisecons to wait for a session")
flag.IntVar(&cliops.timeout, "timeout", cliops.timeout, "timeout waiting to receice data (milliseconds)")
flag.IntVar(&cliops.timeoutwrite, "timeout-write", cliops.timeoutwrite, "timeout to write data to socket (milliseconds)")
flag.IntVar(&cliops.timert1, "timer-t1", cliops.timert1, "value of t1 timer (milliseconds)")
flag.IntVar(&cliops.timert2, "timer-t2", cliops.timert2, "value of t2 timer (milliseconds)")
flag.IntVar(&cliops.verbosity, "verbosity", cliops.verbosity, "verbosity level (0..3)")
flag.IntVar(&cliops.verbosity, "vl", cliops.verbosity, "verbosity level (0..3)")
flag.Var(&headerFields, "extra-header", "extra header in format 'name:body' (can be provided many times)")
flag.Var(&headerFields, "xh", "extra header in format 'name:body' (can be provided many times)")
flag.Var(&iVarMap, "int-val", "integer value in format 'name:value' (can be provided many times)")
flag.Var(&iVarMap, "iv", "integer value in format 'name:value' (can be provided many times)")
flag.Var(¶mFields, "field-val", "field value in format 'name:value' (can be provided many times)")
flag.Var(¶mFields, "fv", "field value in format 'name:value' (can be provided many times)")
flag.BoolVar(&cliops.helpcommands, "help-commands", cliops.helpcommands, "print help with command examples")
flag.BoolVar(&cliops.helpcommands, "hc", cliops.helpcommands, "print help with command examples")
flag.BoolVar(&cliops.version, "version", cliops.version, "print version")
flag.BoolVar(&cliops.version, "v", cliops.version, "print version")
}
// sipexer application
func main() {
var err error
var ok bool
var tret int
flag.Parse()
fmt.Printf("\n")
if cliops.version {
fmt.Printf("%s v%s\n\n", filepath.Base(os.Args[0]), sipexerVersion)
SIPExerExit(SIPExerRetDone)
}
if cliops.helpcommands {
sipexer_help_commands()
SIPExerExit(SIPExerRetDone)
}
if cliops.templatedefaults {
fmt.Printf(" - Default SIP request template:\n\n")
fmt.Println(templateDefaultText)
fmt.Printf("\n - Default field values:\n\n")
fmt.Println(templateDefaultJSONFields)
fmt.Printf("\n - Default SIP MESSAGE body template:\n\n")
fmt.Println(templateDefaultMessageBody)
fmt.Printf("\n - Default SIP INVITE body template:\n\n")
fmt.Println(templateDefaultInviteBody)
SIPExerExit(SIPExerRetDone)
}
if cliops.flagdefaults {
flag.PrintDefaults()
SIPExerExit(SIPExerRetDone)
}
// enable file name and line numbers in logging
log.SetFlags(log.LstdFlags | log.Lshortfile)
if cliops.dnssrvprint {
if len(flag.Args()) < 1 {
SIPExerPrintf(SIPExerLogError, "domain argument not provided\n")
SIPExerExit(SIPExerRetErr)
}
var dqProtos []string
if len(flag.Args()) == 1 {
dqProtos = append(dqProtos, "udp", "tcp", "tls", "sctp")
} else {
dqProtos = append(dqProtos, flag.Arg(0))
}
for _, proto := range dqProtos {
cname, srvs, err := net.LookupSRV("sip", proto, flag.Arg(len(flag.Args())-1))
if err != nil {
SIPExerPrintf(SIPExerLogError, "\nerror: %v\n\n", err)
} else {
fmt.Printf("cname: %s\n", cname)
for _, srv := range srvs {
fmt.Printf("_sip.%s.%s => %v:%v (%d:%d)\n", proto, flag.Arg(len(flag.Args())-1),
srv.Target, srv.Port, srv.Priority, srv.Weight)
}
}
}
SIPExerExit(SIPExerRetDone)
}
var tplstr = ""
if len(cliops.template) > 0 {
tpldata, err1 := os.ReadFile(cliops.template)
if err1 != nil {
SIPExerPrintf(SIPExerLogError, "error: %v\n", err1)
SIPExerExit(SIPExerErrTemplateRead)
}
tplstr = string(tpldata)
} else if len(templateDefaultText) > 0 {
tplstr = templateDefaultText
} else {
SIPExerPrintf(SIPExerLogError, "missing data template file ('-tf' or '--template' parameter must be provided)\n")
SIPExerExit(SIPExerErrTemplateData)
}
if len(cliops.templatebody) > 0 {
tpldata, err1 := os.ReadFile(cliops.templatebody)
if err1 != nil {
SIPExerPrintf(SIPExerLogError, "error: %v\n", err1)
SIPExerExit(SIPExerErrTemplateRead)
}
templateBody = string(tpldata)
}
if cliops.runcount > 1 && len(cliops.localaddress) > 0 {
SIPExerPrintf(SIPExerLogError, "local address parameter is ignored when run count is greater than 1\n")
cliops.localaddress = ""
}
for r := 0; r < cliops.runcount; r++ {
tplfields := make(map[string]interface{})
SIPExerPrepareTemplateFields(tplfields)
var wsurlp *url.URL = nil
dstAddr := "udp:127.0.0.1:5060"
if len(flag.Args()) > 0 {
if len(flag.Args()) == 1 {
dstAddr = flag.Arg(0)
if strings.HasPrefix(dstAddr, "wss://") ||
strings.HasPrefix(dstAddr, "ws://") {
wsurlp, err = url.Parse(dstAddr)
if err != nil {
SIPExerPrintf(SIPExerLogError, "invalid websocket target: %v\n", dstAddr)
SIPExerExit(SIPExerErrWSURLFormat)
}
if strings.HasPrefix(dstAddr, "wss://") {
dstAddr = "wss:" + wsurlp.Host
} else {
dstAddr = "ws:" + wsurlp.Host
}
}
} else if len(flag.Args()) == 2 {
dstAddr = "udp:" + flag.Arg(0) + ":" + flag.Arg(1)
} else if len(flag.Args()) == 3 {
dstAddr = flag.Arg(0) + ":" + flag.Arg(1) + ":" + flag.Arg(2)
} else {
SIPExerPrintf(SIPExerLogError, "invalid number of arguments : %d\n", len(flag.Args()))
SIPExerExit(SIPExerErrArgumentsNumber)
}
}
var dstSockAddr = sgsip.SGSIPSocketAddress{}
var dstURI = sgsip.SGSIPURI{}
if sgsip.SGSIPParseSocketAddress(dstAddr, &dstSockAddr) != sgsip.SGSIPRetOK {
if sgsip.SGSIPParseURI(dstAddr, &dstURI) != sgsip.SGSIPRetOK {
SIPExerPrintf(SIPExerLogError, "invalid destination address: %s\n", dstAddr)
SIPExerExit(SIPExerErrDestinationFormat)
} else {
SIPExerPrintf(SIPExerLogDebug, "parsed SIP URI argument (%+v)\n", dstURI)
sgsip.SGSIPURIToSocketAddress(&dstURI, &dstSockAddr)
}
} else {
SIPExerPrintf(SIPExerLogDebug, "parsed socket address argument (%+v)\n", dstSockAddr)
if cliops.setuser {
_, ok = tplfields["tuser"]
if ok {
sgsip.SGSocketAddressToSIPURI(&dstSockAddr, fmt.Sprint(tplfields["tuser"]), 0, &dstURI)
} else {
sgsip.SGSocketAddressToSIPURI(&dstSockAddr, cliops.ruser, 0, &dstURI)
}
} else {
sgsip.SGSocketAddressToSIPURI(&dstSockAddr, cliops.ruser, 0, &dstURI)
}
}
if len(cliops.ruri) > 0 {
tplfields["ruri"] = cliops.ruri
} else {
_, ok = tplfields["ruri"]
if !ok {
tplfields["ruri"] = dstURI.Val
}
}
if cliops.setdomains {
var rURI = sgsip.SGSIPURI{}
if sgsip.SGSIPParseURI(fmt.Sprint(tplfields["ruri"]), &rURI) != sgsip.SGSIPRetOK {
SIPExerPrintf(SIPExerLogError, "invalid ruri: %v\n", tplfields["ruri"])
SIPExerExit(SIPExerErrURIFormat)
}
tplfields["fdomain"] = rURI.Addr
tplfields["tdomain"] = rURI.Addr
}
if cliops.templaterun {
lTAddr := ""
if len(cliops.localaddress) > 0 {
lTAddr = cliops.localaddress
} else {
lTAddr = "127.0.0.1:55060"
}
var msgVal sgsip.SGSIPMessage = sgsip.SGSIPMessage{}
var smsg string = ""
tret = SIPExerPrepareMessage(tplstr, tplfields, dstSockAddr.Proto, lTAddr, dstSockAddr.Addr+":"+dstSockAddr.Port, &msgVal)
if tret != 0 {
SIPExerExit(tret)
}
smsg = msgVal.Data
msgVal = sgsip.SGSIPMessage{}
if sgsip.SGSIPParseMessage(smsg, &msgVal) != sgsip.SGSIPRetOK {
SIPExerPrintf(SIPExerLogError, "failed to parse sip message\n%+v\n\n", smsg)
SIPExerExit(SIPExerErrSIPMessageFormat)
}
if cliops.verbosity > 0 {
fmt.Printf("%+v\n\n", smsg)
fmt.Printf("%+v\n\n", msgVal)
}
if cliops.runcount > 1 {
tret = SIPExerRetDone
continue
}
SIPExerExit(SIPExerRetDone)
}
if (dstSockAddr.ProtoId != sgsip.ProtoUDP) && (dstSockAddr.ProtoId != sgsip.ProtoTCP) &&
(dstSockAddr.ProtoId != sgsip.ProtoTLS) && (dstSockAddr.ProtoId != sgsip.ProtoWSS) {
SIPExerPrintf(SIPExerLogError, "transport protocol not supported yet for target %s\n", dstAddr)
SIPExerExit(SIPExerErrProtocolUnsuported)
}
tchan := make(chan int, 1)
if dstSockAddr.ProtoId == sgsip.ProtoTCP {
go SIPExerSendTCP(dstSockAddr, tplstr, tplfields, tchan)
} else if dstSockAddr.ProtoId == sgsip.ProtoTLS {
go SIPExerSendTLS(dstSockAddr, tplstr, tplfields, tchan)
} else if dstSockAddr.ProtoId == sgsip.ProtoWSS {
go SIPExerSendWSS(dstSockAddr, wsurlp, tplstr, tplfields, tchan)
} else {
go SIPExerSendUDP(dstSockAddr, tplstr, tplfields, tchan)
}
tret = <-tchan
close(tchan)
}
SIPExerExit(tret)
}
func SIPExerExit(ret int) {
var nret int
nret = ret
if cliops.nagios {
if ret == SIPExerRetOK || ret == SIPExerRetDone || (ret >= 200 && ret <= 299) {
nret = 0
} else if ret >= 400 && ret <= 499 {
nret = 1
} else {
nret = 3
}
}
if ret != nret {
SIPExerPrintf(SIPExerLogDebug, "initial return code: %d\n\n", ret)
}
SIPExerPrintf(SIPExerLogDebug, "return code: %d\n\n", nret)
os.Exit(nret)
}
func SIPExerPrepareTemplateFields(tplfields map[string]interface{}) int {
var err error
var ival int
var ok bool
if len(cliops.fields) > 0 {
fieldsdata, err1 := os.ReadFile(cliops.fields)
if err1 != nil {
SIPExerPrintf(SIPExerLogError, "error: %v\n", err1)
SIPExerExit(SIPExerErrFieldsFileRead)
}
err = json.Unmarshal(fieldsdata, &tplfields)
if err != nil {
SIPExerPrintf(SIPExerLogError, "error: %v\n", err)
SIPExerExit(SIPExerErrFieldsFileFormat)
}
} else if len(templateDefaultJSONFields) > 0 {
err = json.Unmarshal([]byte(templateDefaultJSONFields), &tplfields)
if err != nil {
SIPExerPrintf(SIPExerLogError, "error: %v\n", err)
SIPExerExit(SIPExerErrFieldsDefaultFormat)
}
cliops.fieldseval = true
} else {
tplfields = templateFields["FIELDS:EMPTY"]
}
if cliops.fieldseval {
for k := range tplfields {
switch tplfields[k].(type) {
case string:
if tplfields[k] == "$uuid" {
tplfields[k] = uuid.New().String()
} else if tplfields[k] == "$randseq" {
tplfields[k] = strconv.Itoa(1 + mathrand.Intn(999999))
} else if tplfields[k] == "$datefull" {
tplfields[k] = time.Now().String()
} else if tplfields[k] == "$daterfc1123" {
tplfields[k] = time.Now().Format(time.RFC1123)
} else if tplfields[k] == "$dateunix" {
tplfields[k] = time.Now().Format(time.UnixDate)
} else if tplfields[k] == "$dateansic" {
tplfields[k] = time.Now().Format(time.ANSIC)
} else if tplfields[k] == "$timestamp" {
tplfields[k] = strconv.FormatInt(time.Now().Unix(), 10)
} else if tplfields[k] == "$timems" {
tplfields[k] = strconv.FormatInt(time.Now().UnixMilli(), 10)
} else if tplfields[k] == "$pid" {
tplfields[k] = strconv.Itoa(os.Getpid())
} else if tplfields[k] == "$cr" {
tplfields[k] = "\r"
} else if tplfields[k] == "$lf" {
tplfields[k] = "\n"
} else {
sVal := fmt.Sprint(tplfields[k])
if strings.Index(sVal, "$rand(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[6 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
if len(sArr) == 1 {
nVal, _ := strconv.Atoi(sArr[0])
tplfields[k] = strconv.Itoa(mathrand.Intn(nVal))
} else {
nValA, _ := strconv.Atoi(sArr[0])
nValB, _ := strconv.Atoi(sArr[1])
tplfields[k] = strconv.Itoa(nValA + mathrand.Intn(nValB-nValA))
}
} else if strings.Index(sVal, "$randstr(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[9 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
if len(sArr) == 1 {
nVal, _ := strconv.Atoi(sArr[0])
tplfields[k] = SIPExerRandAlphaString(nVal)
} else {
nValA, _ := strconv.Atoi(sArr[0])
nValB, _ := strconv.Atoi(sArr[1])
tplfields[k] = SIPExerRandAlphaString(nValA + mathrand.Intn(nValB-nValA))
}
} else if strings.Index(sVal, "$randan(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[9 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
if len(sArr) == 1 {
nVal, _ := strconv.Atoi(sArr[0])
tplfields[k] = SIPExerRandAlphaNumString(nVal)
} else {
nValA, _ := strconv.Atoi(sArr[0])
nValB, _ := strconv.Atoi(sArr[1])
tplfields[k] = SIPExerRandAlphaNumString(nValA + mathrand.Intn(nValB-nValA))
}
} else if strings.Index(sVal, "$randnum(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[9 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
if len(sArr) == 1 {
nVal, _ := strconv.Atoi(sArr[0])
tplfields[k] = SIPExerRandNumString(nVal)
} else {
nValA, _ := strconv.Atoi(sArr[0])
nValB, _ := strconv.Atoi(sArr[1])
tplfields[k] = SIPExerRandNumString(nValA + mathrand.Intn(nValB-nValA))
}
} else if strings.Index(sVal, "$randhex(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[9 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
if len(sArr) == 1 {
nVal, _ := strconv.Atoi(sArr[0])
tplfields[k] = SIPExerRandHexString(nVal)
} else {
nValA, _ := strconv.Atoi(sArr[0])
nValB, _ := strconv.Atoi(sArr[1])
tplfields[k] = SIPExerRandHexString(nValA + mathrand.Intn(nValB-nValA))
}
} else if strings.Index(sVal, "$env(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
eVal, ok := os.LookupEnv(sVal[5 : len(sVal)-1])
if ok {
tplfields[k] = eVal
}
} else if strings.Index(sVal, "$add(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[5 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
eVal, ok := iVarMap[sArr[0]]
if !ok {
eVal = 0
}
aVal := 1
if len(sArr) == 2 {
aVal, _ = strconv.Atoi(sArr[1])
}
eVal += aVal
iVarMap[sArr[0]] = eVal
tplfields[k] = strconv.Itoa(eVal)
} else if strings.Index(sVal, "$sub(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[5 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
eVal, ok := iVarMap[sArr[0]]
if !ok {
eVal = 0
}
aVal := 1
if len(sArr) == 2 {
aVal, _ = strconv.Atoi(sArr[1])
}
eVal -= aVal
iVarMap[sArr[0]] = eVal
tplfields[k] = strconv.Itoa(eVal)
} else if strings.Index(sVal, "$inc(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[5 : len(sVal)-1]
sArr := strings.Split(sVal, ",")
eVal, ok := iVarMap[sArr[0]]
if !ok {
if len(sArr) == 1 {
eVal = 0
} else {
eVal, _ = strconv.Atoi(sArr[1])
}
}
eVal++
iVarMap[sArr[0]] = eVal
tplfields[k] = strconv.Itoa(eVal)
} else if strings.Index(sVal, "$dec(") == 0 && strings.LastIndex(sVal, ")") == len(sVal)-1 {
sVal = sVal[5 : len(sVal)-1]