-
Notifications
You must be signed in to change notification settings - Fork 6
/
sip_client.go
294 lines (243 loc) · 6.17 KB
/
sip_client.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
package main
import (
"context"
"fmt"
"github.com/ghettovoice/gosip/sip"
"github.com/lkmio/avformat/utils"
"math"
"net"
"strconv"
"time"
)
const (
KeepAliveBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\r\n" +
"<Notify>\r\n" +
"<CmdType>Keepalive</CmdType>\r\n" +
"<SN>%d</SN>\r\n" +
"<DeviceID>%s</DeviceID>\r\n" +
"<Status>OK</Status>\r\n" +
"</Notify>\r\n"
)
var (
UnregisterExpiresHeader = sip.Expires(0)
)
type SipClient interface {
doRegister(request sip.Request) bool
doUnregister()
doKeepalive() bool
Start()
Stop()
SetOnRegisterHandler(online, offline func())
}
type sipClient struct {
Username string
Domain string //注册域
Transport string
Password string //密码
RegisterExpires int //注册有效期
KeeAliveInterval int //心跳间隔
SeverId string //上级ID
ListenAddr string //UA的监听地址
NatAddr string //Nat地址
ua SipServer
exited bool
ctx context.Context
cancel context.CancelFunc
keepaliveFailedCount int
registerOK bool
registerOKTime time.Time //注册成功时间
registerOKRequest sip.Request
onlineCB func()
offlineCB func()
}
func (g *sipClient) doRegister(request sip.Request) bool {
hop, _ := request.ViaHop()
empty := sip.String{}
hop.Params.Add("rport", &empty)
hop.Params.Add("received", &empty)
for i := 0; i < 2; i++ {
//发起注册, 第一次未携带授权头, 第二次携带授权头
clientTransaction := g.ua.SendRequest(request)
//等待响应
responses := clientTransaction.Responses()
var response sip.Response
select {
case response = <-responses:
break
case <-g.ctx.Done():
break
}
if response == nil {
break
} else if response.StatusCode() == 200 {
g.registerOKRequest = request.Clone().(sip.Request)
viaHop, _ := response.ViaHop()
rport, _ := viaHop.Params.Get("rport")
received, _ := viaHop.Params.Get("received")
if rport != nil && received != nil {
g.NatAddr = net.JoinHostPort(received.String(), rport.String())
}
return true
} else if response.StatusCode() == 401 || response.StatusCode() == 407 {
authorizer := sip.DefaultAuthorizer{Password: sip.String{Str: g.Password}, User: sip.String{Str: g.Username}}
if err := authorizer.AuthorizeRequest(request, response); err != nil {
break
}
} else {
break
}
}
return false
}
func (g *sipClient) startNewRegister() bool {
builder := NewRequestBuilder(sip.REGISTER, g.Username, g.ListenAddr, g.SeverId, g.Domain, g.Transport)
expires := sip.Expires(g.RegisterExpires)
builder.SetExpires(&expires)
host, p, _ := net.SplitHostPort(g.ListenAddr)
port, _ := strconv.Atoi(p)
sipPort := sip.Port(port)
builder.SetTo(&sip.Address{
Uri: &sip.SipUri{
FUser: sip.String{Str: g.Username},
FHost: host,
FPort: &sipPort,
},
})
request, err := builder.Build()
if err != nil {
panic(err)
}
if ok := g.doRegister(request); ok {
g.registerOKRequest = request
return ok
}
return false
}
func CopySipRequest(old sip.Request) sip.Request {
//累加cseq number
cseq, _ := old.CSeq()
cseq.SeqNo++
request := old.Clone().(sip.Request)
//清空事务标记
hop, _ := request.ViaHop()
hop.Params.Remove("branch")
return request
}
func (g *sipClient) refreshRegister() bool {
request := CopySipRequest(g.registerOKRequest)
return g.doRegister(request)
}
func (g *sipClient) doUnregister() {
request := CopySipRequest(g.registerOKRequest)
request.RemoveHeader("Expires")
request.AppendHeader(&UnregisterExpiresHeader)
g.ua.SendRequest(request)
if g.offlineCB != nil {
go g.offlineCB()
}
}
func (g *sipClient) doKeepalive() bool {
body := fmt.Sprintf(KeepAliveBody, time.Now().UnixMilli()/1000, g.Username)
request, err := BuildMessageRequest(g.Username, g.ListenAddr, g.SeverId, g.Domain, g.Transport, body)
if err != nil {
panic(err)
}
transaction := g.ua.SendRequest(request)
responses := transaction.Responses()
var response sip.Response
select {
case response = <-responses:
break
case <-g.ctx.Done():
break
}
return response != nil && response.StatusCode() == 200
}
// IsExpires 是否临近注册有效期
func (g *sipClient) IsExpires() (bool, int) {
if !g.registerOK {
return false, 0
}
dis := g.RegisterExpires - int(time.Now().Sub(g.registerOKTime).Seconds())
return dis <= 10, dis - 10
}
// Refresh 处理Client的生命周期任务, 发起注册, 发送心跳,断开重连等, 并返回下次刷新任务时间
func (g *sipClient) Refresh() time.Duration {
expires, _ := g.IsExpires()
if !g.registerOK || expires {
if expires {
g.registerOK = g.refreshRegister()
} else {
g.registerOK = g.startNewRegister()
}
if g.registerOK {
g.registerOKTime = time.Now()
if g.onlineCB != nil {
go g.onlineCB()
}
}
}
// 注册失败后, 等待10秒钟再发起注册
if !g.registerOK {
return 10 * time.Second
}
// 发送心跳
if !g.doKeepalive() {
g.keepaliveFailedCount++
} else {
g.keepaliveFailedCount = 0
}
// 心跳失败, 重新发起注册
if g.keepaliveFailedCount > 0 {
g.keepaliveFailedCount = 0
g.registerOK = false
g.registerOKRequest = nil
g.NatAddr = ""
if g.offlineCB != nil {
go g.offlineCB()
}
// 立马发起注册
return 0
}
// 信令正常, 休眠心跳间隔时长
return time.Duration(g.KeeAliveInterval) * time.Second
}
func (g *sipClient) Start() {
utils.Assert(!g.exited)
g.ctx, g.cancel = context.WithCancel(context.Background())
go func() {
for !g.exited {
duration := g.Refresh()
expires, dis := g.IsExpires()
if duration < time.Second || expires {
continue
} else if g.registerOK {
duration = time.Duration(int(math.Min(duration.Seconds(), float64(dis)))) * time.Second
}
if g.exited {
return
}
select {
case <-time.After(duration):
break
case <-g.ctx.Done():
break
}
}
}()
}
func (g *sipClient) Stop() {
utils.Assert(!g.exited)
g.exited = true
g.cancel()
g.registerOK = false
g.onlineCB = nil
g.offlineCB = nil
if g.registerOK {
g.doUnregister()
}
}
func (g *sipClient) SetOnRegisterHandler(online, offline func()) {
g.onlineCB = online
g.offlineCB = offline
}