-
Notifications
You must be signed in to change notification settings - Fork 0
/
http2sip.go
446 lines (397 loc) · 10.9 KB
/
http2sip.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
package main
import (
_ "embed"
"errors"
"flag"
"fmt"
"html"
"log"
"net"
"net/http"
"os"
"time"
"http2sip/auth"
"github.com/jart/gosip/dialog"
"github.com/jart/gosip/sdp"
"github.com/jart/gosip/sip"
"github.com/jart/gosip/util"
"gopkg.in/yaml.v3"
)
type config struct {
HttpPort string `yaml:"httpPort"`
PenaltyTime time.Duration `yaml:"penaltyTime"`
SipCallNumber string `yaml:"sipCallNumber"`
SipServer string `yaml:"sipServer"`
SipPort uint16 `yaml:"sipPort"`
SipUser string `yaml:"sipUser"`
SipPassword string `yaml:"sipPassword"`
SipReregisterTime time.Duration `yaml:"sipReregisterTime"`
}
var (
registered = false
calling = false
penalty = false
cfg config
cfgPath string
//go:embed "configExample.txt"
configExample string
sipAllow = "INVITE, ACK, BYE, CANCEL, UPDATE, INFO, NOTIFY, OPTIONS"
registerPkt = &sip.Msg{}
invitePkt = &sip.Msg{}
sipTo = &sip.Addr{}
sipFrom = &sip.Addr{}
sipContact = &sip.Addr{}
sipCseq int
sipAuthRegisterRetry int
sipAuthInviteRetry int
)
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
func ternary(condition bool, a, b interface{}) interface{} {
if condition {
return a
}
return b
}
// sipHandler goroutine for handling messages and exit only on code failures
func sipHandler(transport *dialog.Transport) {
log.Println("Starting sipHandler()...")
var msg *sip.Msg
var err error
getAuth := func(answer *sip.Msg, request *sip.Msg, uri sip.URI, method string) (err error) {
if answer.WWWAuthenticate != "" {
request.Authorization, err = auth.GetDigestString(answer.WWWAuthenticate, cfg.SipUser, cfg.SipPassword, uri.String(), method)
} else if answer.ProxyAuthenticate != "" {
request.ProxyAuthorization, err = auth.GetDigestString(answer.ProxyAuthenticate, cfg.SipUser, cfg.SipPassword, uri.String(), method)
} else {
err = errors.New("WWW-Authenticate or Proxy-Authenticate headers NOT FOUND")
}
return err
}
for {
select {
case err = <-transport.E:
log.Println("SIP recv failed:", err)
case msg = <-transport.C:
log.Printf("SIP MESSAGE: %s -> %d (%s)\n", msg.CSeqMethod, msg.Status, sip.Phrase(msg.Status))
if msg.IsResponse() {
switch msg.Status {
case sip.StatusUnauthorized:
msg.Contact = sipContact
if msg.CSeq == registerPkt.CSeq {
registered = false
registerPkt.Authorization = ""
if sipAuthRegisterRetry > 0 {
sipCseq++
registerPkt.CSeq = sipCseq
// ACK not needed on REGISTER
uri := sip.URI{Scheme: "sip", Host: cfg.SipServer}
err = getAuth(msg, registerPkt, uri, sip.MethodRegister)
if err != nil {
log.Println(err)
break
}
err = transport.Send(registerPkt)
if err != nil {
log.Println(err)
}
time.Sleep(1 * time.Second)
sipAuthRegisterRetry--
} else {
log.Println("Number of Authorization requests exceeded (wrong password?)")
}
}
if msg.CSeq == invitePkt.CSeq {
// send ACK for unauthorized message
invitePkt.Authorization = ""
err = transport.Send(dialog.NewAck(msg, invitePkt))
if err != nil {
log.Fatal("SIP send failed:", err)
}
if sipAuthInviteRetry > 0 {
sipCseq++
invitePkt.CSeq = sipCseq
uri := sip.URI{Scheme: "sip", User: cfg.SipCallNumber, Host: cfg.SipServer}
err = getAuth(msg, invitePkt, uri, sip.MethodInvite)
if err != nil {
log.Println(err)
break
}
err = transport.Send(invitePkt)
if err != nil {
log.Println(err)
}
time.Sleep(1 * time.Second)
sipAuthInviteRetry--
} else {
log.Println("Number of Authorization requests exceeded (wrong password?)")
}
}
case sip.StatusSessionProgress:
log.Printf("Probably Ringing!")
if msg.CSeq == invitePkt.CSeq {
// send SIP CANCEL
invitePkt.Authorization = ""
cancel := dialog.NewCancel(invitePkt)
err = transport.Send(cancel)
if err != nil {
log.Println("SIP send failed:", err)
}
}
case sip.StatusOK:
if msg.CSeq == registerPkt.CSeq {
switch msg.CSeqMethod {
case sip.MethodRegister:
log.Println("Registered!")
log.Println("Expires: ", msg.Expires)
registered = true
case sip.MethodInvite:
log.Println("Answered!")
case sip.MethodBye:
log.Println("Hungup!")
case sip.MethodCancel:
log.Println("Cancelled!")
}
}
if msg.CSeq == invitePkt.CSeq {
switch msg.CSeqMethod {
case sip.MethodRegister:
log.Println("Registered!")
case sip.MethodInvite:
log.Println("Answered!")
invitePkt.Authorization = ""
cancel := dialog.NewCancel(invitePkt)
err = transport.Send(cancel)
if err != nil {
log.Println("SIP send failed:", err)
}
case sip.MethodBye:
log.Println("Hungup!")
case sip.MethodCancel:
log.Println("Cancelled!")
calling = false
msg.Contact = sipContact
err = transport.Send(dialog.NewAck(msg, invitePkt))
if err != nil {
log.Println("SIP send failed:", err)
}
}
}
case sip.StatusRequestTerminated:
msg.Contact = sipContact
err = transport.Send(dialog.NewAck(msg, invitePkt))
if err != nil {
log.Println("SIP send failed:", err)
}
case sip.StatusForbidden:
if msg.CSeq == invitePkt.CSeq {
// on forbidden reset register and calling states
registered = false
calling = false
}
}
} else {
if msg.Method == "BYE" {
log.Printf("%s: Remote Hangup!\n", msg.Method)
err = transport.Send(dialog.NewResponse(msg, sip.StatusOK))
if err != nil {
log.Println("SIP send failed:", err)
}
}
}
}
}
}
// Register send REGISTER and resend it after configured time interval
func Register(transport *dialog.Transport) {
sipAuthRegisterRetry = 3
// REGISTER packet
regSipTo := sipTo
regSipTo.Uri.User = cfg.SipUser
registerPkt = dialog.NewRequest(transport, sip.MethodRegister, regSipTo, sipFrom)
registerPkt.Expires = 300
registerPkt.Allow = sipAllow
registerPkt.CSeq = sipCseq
err := transport.Send(registerPkt)
if err != nil {
log.Println(err)
}
resends := 1
resend := registerPkt
resendTimer := time.After(cfg.SipReregisterTime)
for {
select {
case <-resendTimer:
sipCseq++
resend.CSeq = sipCseq
registerPkt = resend
err = transport.Send(resend)
if err != nil {
log.Println("SIP send failed:", err)
}
log.Printf("RE-REGISTER NUMBER: %d\n", resends)
sipAuthRegisterRetry = 1 // for RE-REGISTER work
resends++
resendTimer = time.After(cfg.SipReregisterTime)
}
}
}
// Call make a SIP call (INVITE) to configured phone number
func Call(number string, transport *dialog.Transport) {
if calling {
log.Println("Already calling...")
return
}
sipAuthInviteRetry = 3
calling = true
log.Println("REGISTERED:", registered)
// INVITE packet
inviteSipTo := sipTo
inviteSipTo.Uri.User = number
invitePkt = dialog.NewRequest(transport, sip.MethodInvite, inviteSipTo, sipFrom)
invitePkt.Allow = sipAllow
invitePkt.Payload = sdp.New(&net.UDPAddr{IP: GetOutboundIP(), Port: 20000}, sdp.ULAWCodec, sdp.DTMFCodec)
sipCseq++
invitePkt.CSeq = sipCseq
exitTimeout := false
exitTime := 15 * time.Second
exitTimer := time.AfterFunc(exitTime, func() {
exitTimeout = true
})
defer exitTimer.Stop()
// reset calling state on timeout
deathTime := 30 * time.Second
time.AfterFunc(deathTime, func() {
if calling {
log.Println("Seems calling timed out, resetting states.")
calling = false
}
})
try := 1
waitTime := 5 * time.Second
for registered == false {
log.Printf("Not registered (%d try), waiting %v\n", try, waitTime)
try++
time.Sleep(waitTime)
if exitTimeout {
log.Println("Timeout registration, calling failed.")
calling = false
return
}
}
// make call
log.Println("Calling...")
err := transport.Send(invitePkt)
if err != nil {
log.Println(err)
calling = false
return
}
return
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
// loading settings from config.yml
flag.StringVar(&cfgPath, "cfg", "config.yml", "path to config file")
flag.Parse()
file, err := os.Open(cfgPath)
if os.IsNotExist(err) {
fmt.Print("Config doesn't exist, example content of config.yml: \n\n")
fmt.Println(configExample)
return
}
if err != nil {
log.Fatalf("Error: %v", err)
}
log.Printf("using config file '%s'\n", file.Name())
d := yaml.NewDecoder(file)
// Start YAML decoding from file
if err := d.Decode(&cfg); err != nil {
return
}
err = file.Close()
if err != nil {
return
}
// publishing SIP data
sipTo = &sip.Addr{
Uri: &sip.URI{
//User: cfg.SipUser,
Host: cfg.SipServer,
Port: cfg.SipPort,
},
}
sipFrom = &sip.Addr{
Uri: &sip.URI{
User: cfg.SipUser,
Host: cfg.SipServer,
},
}
sipContact = &sip.Addr{ // replace contact for properly work NewAck() method
Uri: &sip.URI{
User: cfg.SipUser,
Host: cfg.SipServer,
Port: cfg.SipPort,
},
}
myContact := &sip.Addr{
Uri: &sip.URI{
User: cfg.SipUser,
Host: GetOutboundIP().String(),
Param: &sip.URIParam{Name: "ob"},
},
}
sipCseq = util.GenerateCSeq()
// making SIP transport
transport, err := dialog.NewTransport(myContact)
if err != nil {
log.Println(err)
return
}
// running message handler and SIP REGISTER initialization
go sipHandler(transport)
go Register(transport)
http.HandleFunc("/open", func(w http.ResponseWriter, r *http.Request) {
clientRemote := ternary(len(r.Header.Get("X-Forwarded-For")) > 0, r.Header.Get("X-Forwarded-For"), r.RemoteAddr)
log.Printf("HTTP %s : %s (%s) -> %s", r.Method, clientRemote, r.UserAgent(), html.EscapeString(r.URL.Path))
if penalty {
log.Println("Penalty ACTIVE, ignoring request.")
_, err := fmt.Fprintf(w, fmt.Sprintf("ERROR: Too fast (1 per %v), maybe gate allready opened? ;-o", cfg.PenaltyTime))
if err != nil {
log.Printf("error: %s", err)
return
}
return
}
if !calling {
_, err := fmt.Fprintf(w, "Opening... ;-P")
if err != nil {
log.Printf("error: %s\n", err)
return
}
penalty = true
time.AfterFunc(cfg.PenaltyTime, func() {
log.Println("Penalty time over.")
penalty = false
})
log.Printf("Will call to %v\n", cfg.SipCallNumber)
// making call
go Call(cfg.SipCallNumber, transport)
} else {
_, err := fmt.Fprintf(w, "ERROR: Someone allready opening now or internal error ;-E")
if err != nil {
log.Printf("error: %s\n", err)
return
}
}
})
log.Printf("Listening on any: %s", cfg.HttpPort)
log.Fatal(http.ListenAndServe(":"+cfg.HttpPort, nil))
}