-
-
Notifications
You must be signed in to change notification settings - Fork 79
/
dialog_server.go
485 lines (406 loc) · 12.8 KB
/
dialog_server.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
package sipgo
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/emiago/sipgo/sip"
"github.com/icholy/digest"
)
type DialogServerSession struct {
Dialog
inviteTx sip.ServerTransaction
// s *DialogServer
ua *DialogUA
// onClose is temporarly fix to handle dialog Closing.
// Normally you want to have cleanup after dialog terminating or caller calling Close()
// In future this could be only subscribing to dialog state
onClose func()
}
// ReadAck changes dialog state to confiremed
func (s *DialogServerSession) ReadAck(req *sip.Request, tx sip.ServerTransaction) error {
// cseq must match to our last dialog cseq
if req.CSeq().SeqNo != s.lastCSeqNo.Load() {
return ErrDialogInvalidCseq
}
s.setState(sip.DialogStateConfirmed)
return nil
}
func (s *DialogServerSession) ReadBye(req *sip.Request, tx sip.ServerTransaction) error {
// Make sure this is bye for this dialog
if err := s.validateRequest(req); err != nil {
return err
}
defer s.Close()
defer s.inviteTx.Terminate() // Terminat`es Invite transaction
res := sip.NewResponseFromRequest(req, 200, "OK", nil)
if err := tx.Respond(res); err != nil {
return err
}
s.setState(sip.DialogStateEnded)
return nil
}
// ReadRequest is generic func to validate new request in dialog and update seq. Use it if there are no predefined
func (s *DialogServerSession) ReadRequest(req *sip.Request, tx sip.ServerTransaction) error {
if err := s.validateRequest(req); err != nil {
return err
}
s.lastCSeqNo.Store(req.CSeq().SeqNo)
return nil
}
func (s *DialogServerSession) Do(ctx context.Context, req *sip.Request) (*sip.Response, error) {
tx, err := s.TransactionRequest(ctx, req)
if err != nil {
return nil, err
}
defer tx.Terminate()
for {
select {
case res := <-tx.Responses():
if res.IsProvisional() {
continue
}
return res, nil
case <-tx.Done():
return nil, tx.Err()
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
// TransactionRequest is doing client DIALOG request based on RFC
// https://www.rfc-editor.org/rfc/rfc3261#section-12.2.1
// This ensures that you have proper request done within dialog
func (s *DialogServerSession) TransactionRequest(ctx context.Context, req *sip.Request) (sip.ClientTransaction, error) {
// Keep any request inside dialog
mustHaveHeaders := make([]sip.Header, 0, 5)
if h, invH := req.From(), s.InviteResponse; h == nil && invH != nil {
hh := invH.To().AsFrom()
// req.AppendHeader(&hh)
mustHaveHeaders = append(mustHaveHeaders, &hh)
}
if h, invH := req.To(), s.InviteRequest.From(); h == nil {
hh := invH.AsTo()
// req.AppendHeader(&hh)
mustHaveHeaders = append(mustHaveHeaders, &hh)
}
if h, invH := req.CallID(), s.InviteRequest.CallID(); h == nil {
// req.AppendHeader(sip.HeaderClone(invH))
mustHaveHeaders = append(mustHaveHeaders, sip.HeaderClone(invH))
}
if h := req.MaxForwards(); h == nil {
// req.AppendHeader(sip.HeaderClone(invH))
maxFwd := sip.MaxForwardsHeader(70)
mustHaveHeaders = append(mustHaveHeaders, &maxFwd)
}
cseq := req.CSeq()
if cseq == nil {
cseq = &sip.CSeqHeader{
SeqNo: s.InviteRequest.CSeq().SeqNo,
MethodName: req.Method,
}
// req.AppendHeader(cseq)
mustHaveHeaders = append(mustHaveHeaders, cseq)
}
if len(mustHaveHeaders) > 0 {
req.PrependHeader(mustHaveHeaders...)
}
// For safety make sure we are starting with our last dialog cseq num
cseq.SeqNo = s.lastCSeqNo.Load()
if !req.IsAck() && !req.IsCancel() {
// Do cseq increment within dialog
cseq.SeqNo++
}
// https://datatracker.ietf.org/doc/html/rfc3261#section-16.12.1.2
rrs := s.InviteRequest.GetHeaders("Record-Route")
for i := len(rrs) - 1; i >= 0; i-- {
recordRoute := rrs[i]
req.AppendHeader(sip.NewHeader("Route", recordRoute.Value()))
}
// Check Route Header
// Should be handled by transport layer but here we are making this explicit
if rr := req.Route(); rr != nil {
req.SetDestination(rr.Address.HostPort())
}
// TODO check correct behavior strict routing vs loose routing
// recordRoute := req.RecordRoute()
// if recordRoute != nil {
// if recordRoute.Address.UriParams.Has("lr") {
// bye.AppendHeader(&sip.RouteHeader{Address: recordRoute.Address})
// } else {
// /* TODO
// If the route set is not empty, and its first URI does not contain the
// lr parameter, the UAC MUST place the first URI from the route set
// into the Request-URI, stripping any parameters that are not allowed
// in a Request-URI. The UAC MUST add a Route header field containing
// the remainder of the route set values in order, including all
// parameters. The UAC MUST then place the remote target URI into the
// Route header field as the last value.
// */
// }
// }
s.lastCSeqNo.Store(cseq.SeqNo)
if h := req.Contact(); h == nil {
req.AppendHeader(sip.HeaderClone(&s.ua.ContactHDR))
}
if s.ua.RewriteContact && len(rrs) == 0 {
req.SetDestination(s.InviteRequest.Source())
}
// TODO check is contact header routable
// If not then we should force destination as source address
// Passing option to avoid CSEQ apply
return s.ua.Client.TransactionRequest(ctx, req, ClientRequestBuild)
}
func (s *DialogServerSession) WriteRequest(req *sip.Request) error {
return s.ua.Client.WriteRequest(req)
}
// Close is always good to call for cleanup or terminating dialog state
func (s *DialogServerSession) Close() error {
if s.onClose != nil {
s.onClose()
}
return nil
}
// Respond should be called for Invite request, you may want to call this multiple times like
// 100 Progress or 180 Ringing
// 2xx for creating dialog or other code in case failure
//
// In case Cancel request received: ErrDialogCanceled is responded
func (s *DialogServerSession) Respond(statusCode sip.StatusCode, reason string, body []byte, headers ...sip.Header) error {
// Must copy Record-Route headers. Done by this command
res := sip.NewResponseFromRequest(s.InviteRequest, statusCode, reason, body)
for _, h := range headers {
res.AppendHeader(h)
}
return s.WriteResponse(res)
}
// RespondSDP is just wrapper to call 200 with SDP.
// It is better to use this when answering as it provide correct headers
func (s *DialogServerSession) RespondSDP(sdp []byte) error {
if sdp == nil {
return fmt.Errorf("sdp not provided")
}
res := sip.NewSDPResponseFromRequest(s.InviteRequest, sdp)
return s.WriteResponse(res)
}
var errDialogUnauthorized = errors.New("unathorized")
func (s *DialogServerSession) authDigest(chal *digest.Challenge, opts digest.Options) error {
authorized := func() bool {
authorizationHDR := s.InviteRequest.GetHeader("Authorization")
if authorizationHDR == nil {
return false
}
hdrVal := authorizationHDR.Value()
creds, err := digest.ParseCredentials(hdrVal)
if err != nil {
return false
}
digCred, err := digest.Digest(chal, opts)
if err != nil {
return false
}
return creds.Response == digCred.Response
}()
if authorized {
return nil
}
hdrVal := chal.String()
hdr := sip.NewHeader("WWW-Authenticate", hdrVal)
res := sip.NewResponseFromRequest(s.InviteRequest, sip.StatusUnauthorized, "Unauthorized", nil)
res.AppendHeader(hdr)
if err := s.WriteResponse(res); err != nil {
return err
}
return errDialogUnauthorized
}
// WriteResponse allows passing you custom response
func (s *DialogServerSession) WriteResponse(res *sip.Response) error {
tx := s.inviteTx
if res.Contact() == nil {
// Add our default contact header
res.AppendHeader(&s.ua.ContactHDR)
}
s.Dialog.InviteResponse = res
// Do we have cancel in meantime
select {
case <-tx.Done():
// There must be some error
return tx.Err()
default:
}
if !res.IsSuccess() {
if res.IsProvisional() {
// This will not create dialog so we will just respond
return tx.Respond(res)
}
// For final response we want to set dialog ended state
if err := tx.Respond(res); err != nil {
return err
}
// We should wait ACK for cleaner exit
select {
case <-tx.Acks():
case <-tx.Done():
// This means tx moved to terminated state and no more invite retransmissions is accepted
}
s.setState(sip.DialogStateEnded)
return nil
}
id, err := sip.MakeDialogIDFromResponse(res)
if err != nil {
return err
}
if id != s.Dialog.ID {
// TODO. This can be panic
return fmt.Errorf("ID do not match. Invite request has changed headers?")
}
s.setState(sip.DialogStateEstablished)
if err := tx.Respond(res); err != nil {
return err
}
return nil
}
func (s *DialogServerSession) Bye(ctx context.Context) error {
req := s.Dialog.InviteRequest
cont := s.Dialog.InviteRequest.Contact()
// TODO Contact is has no resolvable address or TCP is used, then address should be source due TO NAT
bye := sip.NewRequest(sip.BYE, cont.Address)
bye.SetTransport(req.Transport())
return s.WriteBye(ctx, bye)
}
func (s *DialogServerSession) WriteBye(ctx context.Context, bye *sip.Request) error {
state := s.state.Load()
// In case dialog terminated
if sip.DialogState(state) == sip.DialogStateEnded {
return nil
}
if sip.DialogState(state) != sip.DialogStateConfirmed {
return nil
}
res := s.Dialog.InviteResponse
if !res.IsSuccess() {
return fmt.Errorf("can not send bye on NON success response")
}
// This is tricky
defer s.inviteTx.Terminate() // Terminates INVITE in all cases
// https://datatracker.ietf.org/doc/html/rfc3261#section-15
// However, the callee's UA MUST NOT send a BYE on a confirmed dialog
// until it has received an ACK for its 2xx response or until the server
// transaction times out.
for {
state = s.state.Load()
if sip.DialogState(state) < sip.DialogStateConfirmed {
select {
case <-s.inviteTx.Done():
// Wait until we timeout
case <-time.After(sip.T1):
// Recheck state
continue
case <-ctx.Done():
return ctx.Err()
}
}
break
}
tx, err := s.TransactionRequest(ctx, bye)
if err != nil {
return err
}
defer tx.Terminate() // Terminates current transaction
// Wait 200
select {
case res := <-tx.Responses():
if res.StatusCode != 200 {
return ErrDialogResponse{res}
}
s.setState(sip.DialogStateEnded)
return nil
case <-tx.Done():
return tx.Err()
case <-ctx.Done():
return ctx.Err()
}
}
func (dt *DialogServerSession) validateRequest(req *sip.Request) (err error) {
// Make sure this is bye for this dialog
// UAS SHOULD be
// prepared to receive and process requests with CSeq values more than
// one higher than the previous received request.
if req.CSeq().SeqNo < dt.lastCSeqNo.Load() {
return ErrDialogInvalidCseq
}
return nil
}
// DialogServerCache serves as quick way to start building dialog server
// It is not optimized version and it is recomended that you build own dialog caching
type DialogServerCache struct {
dialogs sync.Map // TODO replace with typed version
ua DialogUA
}
func (s *DialogServerCache) loadDialog(id string) *DialogServerSession {
val, ok := s.dialogs.Load(id)
if !ok || val == nil {
return nil
}
t := val.(*DialogServerSession)
return t
}
func (s *DialogServerCache) MatchDialogRequest(req *sip.Request) (*DialogServerSession, error) {
id, err := sip.UASReadRequestDialogID(req)
if err != nil {
return nil, errors.Join(ErrDialogOutsideDialog, err)
}
dt := s.loadDialog(id)
if dt == nil {
return nil, ErrDialogDoesNotExists
}
return dt, nil
}
// NewDialogServerCache provides simple cache layer for managing UAS dialog
// Contact hdr is default that is provided for responses.
// Client is needed for termination dialog session
// In case handling different transports you should have multiple instances per transport
//
// Using DialogUA is now better way for genereting dialogs without caching and giving you as caller whole control of dialog
func NewDialogServerCache(client *Client, contactHDR sip.ContactHeader) *DialogServerCache {
s := &DialogServerCache{
dialogs: sync.Map{},
ua: DialogUA{
Client: client,
ContactHDR: contactHDR,
},
}
return s
}
// ReadInvite should read from your OnInvite handler for which it creates dialog context
// You need to use DialogServerSession for all further responses
// Do not forget to add ReadAck and ReadBye for confirming dialog and terminating
func (s *DialogServerCache) ReadInvite(req *sip.Request, tx sip.ServerTransaction) (*DialogServerSession, error) {
dtx, err := s.ua.ReadInvite(req, tx)
if err != nil {
return nil, err
}
id := dtx.ID
dtx.onClose = func() {
s.dialogs.Delete(id)
}
s.dialogs.Store(id, dtx)
return dtx, nil
}
// ReadAck should read from your OnAck handler
func (s *DialogServerCache) ReadAck(req *sip.Request, tx sip.ServerTransaction) error {
dt, err := s.MatchDialogRequest(req)
if err != nil {
return err
}
return dt.ReadAck(req, tx)
}
// ReadBye should read from your OnBye handler. Returns error if it fails
func (s *DialogServerCache) ReadBye(req *sip.Request, tx sip.ServerTransaction) error {
dt, err := s.MatchDialogRequest(req)
if err != nil {
return err
}
return dt.ReadBye(req, tx)
}