-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathdialog_client_session.go
More file actions
662 lines (556 loc) · 18.6 KB
/
dialog_client_session.go
File metadata and controls
662 lines (556 loc) · 18.6 KB
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024, Emir Aganovic
package diago
import (
"context"
"errors"
"fmt"
mrand "math/rand/v2"
"net"
"strings"
"sync/atomic"
"time"
"github.com/emiago/diago/media"
"github.com/emiago/diago/media/sdp"
"github.com/emiago/sipgo"
"github.com/emiago/sipgo/sip"
)
var (
ErrClientEarlyMedia = errors.New("Early media detected")
)
// DialogClientSession represents outbound channel
type DialogClientSession struct {
*sipgo.DialogClientSession
DialogMedia
onReferDialog OnReferDialogFunc
mediaConfig MediaConfig
closed atomic.Uint32
}
func (d *DialogClientSession) Close() error {
if !d.closed.CompareAndSwap(0, 1) {
return nil
}
e1 := d.DialogMedia.Close()
e2 := d.DialogClientSession.Close()
return errors.Join(e1, e2)
}
func (d *DialogClientSession) Id() string {
return d.ID
}
func (d *DialogClientSession) Hangup(ctx context.Context) error {
return d.Bye(ctx)
}
func (d *DialogClientSession) FromUser() string {
return d.InviteRequest.From().Address.User
}
func (d *DialogClientSession) ToUser() string {
return d.InviteRequest.To().Address.User
}
func (d *DialogClientSession) DialogSIP() *sipgo.Dialog {
return &d.Dialog
}
func (d *DialogClientSession) RemoteContact() *sip.ContactHeader {
d.mu.Lock()
defer d.mu.Unlock()
return d.remoteContactUnsafe()
}
func (d *DialogClientSession) remoteContactUnsafe() *sip.ContactHeader {
if d.remoteContactTarget != nil {
// Invite update can change contact
return d.remoteContactTarget
}
return d.InviteResponse.Contact()
}
// InviteClientOptions is passed on dialog client Invite with extra control over dialog
type InviteClientOptions struct {
Originator DialogSession
OnResponse func(res *sip.Response) error
// OnMediaUpdate called when media is changed.
// NOTE: you should not block this call as it blocks response processing.
OnMediaUpdate func(d *DialogMedia)
// OnRefer is called on successfull REFER handling
//
// It creates new dialog (NewDialog) on which you need to call Invite() and Ack()
// Any error from invite, ack or other processing should be returned for correct Notify handling
//
// NOTE: IT is SCOPED to handler and exiting handler will Close/Terminate this dialog!
OnRefer OnReferDialogFunc
// For digest authentication
Username string
Password string
// Custom headers to pass. DO NOT SET THIS to nil
Headers []sip.Header
// Stop on early media. ErrClientEarlyMedia will be returned
EarlyMediaDetect bool
}
// WithAnonymousCaller sets from user Anonymous per RFC
func (o *InviteClientOptions) WithAnonymousCaller() {
o.Headers = append(o.Headers, &sip.FromHeader{
DisplayName: "Anonymous",
Address: sip.Uri{User: "anonymous", Host: "anonymous.invalid"},
Params: sip.NewParams(),
})
}
// WithCaller allows simpler way modifying caller
func (o *InviteClientOptions) WithCaller(displayName string, callerID string, host string) {
o.Headers = append(o.Headers, &sip.FromHeader{
DisplayName: displayName,
Address: sip.Uri{User: callerID, Host: host},
Params: sip.NewParams(),
})
}
// Invite sends Invite request and establishes [early] media. Normally you need to call Ack after.
//
// Normal Answer with 200 OK (SDP)
// - You MUST call Ack() after to acknowledge session.
//
// Early Media Detect:
// - EarlyMediaDetect=true must be set as part of options otherwise it ignores early media
// - It RETURNS ErrClientEarlyMedia if remote answers with 183 Session in Progress
// - Media is negotiated and setuped
// - You need to call WaitAnswer() if you want to proceed with answering call
//
// Errors:
// - sipgo.ErrDialogResponse
// - ErrClientEarlyMedia
//
// NOTE: It updates internal invite request so NOT THREAD SAFE.
// If you pass originator it will use originator to set correct from header and avoid media transcoding
func (d *DialogClientSession) Invite(ctx context.Context, opts InviteClientOptions) error {
if err := d.initMediaSessionFromConf(d.mediaConfig); err != nil {
return err
}
return d.invite(ctx, &d.DialogMedia, opts)
}
func (d *DialogClientSession) invite(ctx context.Context, med *DialogMedia, opts InviteClientOptions) error {
sess := med.mediaSession
inviteReq := d.InviteRequest
originator := opts.Originator
for _, h := range opts.Headers {
inviteReq.AppendHeader(h)
}
if originator != nil {
// In case originator then:
// - check do we support this media formats by conf
// - if we do, then filter and pass to dial endpoint filtered
origInvite := originator.DialogSIP().InviteRequest
if fromHDR := inviteReq.From(); fromHDR == nil {
// From header should be preserved from originator
fromHDROrig := origInvite.From()
f := sip.FromHeader{
DisplayName: fromHDROrig.DisplayName,
Address: *fromHDROrig.Address.Clone(),
Params: fromHDROrig.Params.Clone(),
}
inviteReq.AppendHeader(&f)
}
// Avoid transcoding if originator present
// Check ContentType and body present
contType := origInvite.ContentType()
if body := origInvite.Body(); body != nil && (contType != nil && contType.Value() == "application/sdp") {
// apply remote SDP
if err := sess.RemoteSDP(body); err != nil {
return fmt.Errorf("failed to apply originator sdp: %w", err)
}
// We do not want originator to be remote side, but we want to apply codec filtering
sess.SetRemoteAddr(&net.UDPAddr{})
// Now to totally remove transcoding a chance. Leave only one codec of different types
audioCodec := media.Codec{}
telEventCodec := media.Codec{}
codecs := sess.CommonCodecs()
if len(codecs) == 0 { // No negotiation yet happened
codecs = sess.Codecs
}
for _, c := range codecs {
// TODO refactor this
if strings.HasPrefix(c.Name, "telephone-event") {
if telEventCodec.SampleRate == 0 {
telEventCodec = c
}
continue
}
if audioCodec.SampleRate == 0 {
audioCodec = c
}
}
// TODO: DO we need to be thread safe here?
// In this case we want to rewrite what should be Offered in our SDP
// NOTE: Generally this would require Session Fork, but for now we avoid this extra step.
sessCodecs := sess.Codecs[:0]
if audioCodec.SampleRate != 0 {
sessCodecs = append(sessCodecs, audioCodec)
}
// TODO: should we only match telephone event with same sampling rate?
if telEventCodec.SampleRate != 0 {
sessCodecs = append(sessCodecs, telEventCodec)
}
if len(sessCodecs) == 0 {
return fmt.Errorf("no codecs support found from originator")
}
sess.Codecs = sessCodecs
}
}
dialogCli := d.UA
inviteReq.AppendHeader(&dialogCli.ContactHDR)
inviteReq.AppendHeader(sip.NewHeader("Content-Type", "application/sdp"))
inviteReq.SetBody(sess.LocalSDP())
// We allow changing full from header, but we need to make sure it is correctly set
// If users specify 'tag' parameter it is assumed that they know what they do
if fromHDR := inviteReq.From(); fromHDR != nil && !fromHDR.Params.Has("tag") {
fromHDR.Params.Add("tag", sip.GenerateTagN(16))
}
// Build here request
client := d.UA.Client
if err := sipgo.ClientRequestBuild(client, inviteReq); err != nil {
return err
}
// This only gets called after session established
med.onMediaUpdate = opts.OnMediaUpdate
d.onReferDialog = opts.OnRefer
// reuse UDP listener
// Problem if listener is unspecified IP sipgo will not map this to listener
// Code below only works if our bind host is specified
// For now let SIPgo create 1 UDP connection and it will reuse it
// via := inviteReq.Via()
// if via.Host == "" {
// }
err := d.DialogClientSession.Invite(ctx, func(c *sipgo.Client, req *sip.Request) error {
// Do nothing
return nil
})
if err != nil {
// sess.Close()
return err
}
ansOpts := sipgo.AnswerOptions{
Username: opts.Username,
Password: opts.Password,
OnResponse: opts.OnResponse,
}
if opts.EarlyMediaDetect {
return d.waitAnswerEarly(ctx, &d.DialogMedia, ansOpts)
}
return d.waitAnswer(ctx, &d.DialogMedia, ansOpts)
}
// WaitAnswer waits dialog on answer. It should only be used if you have error Invite but still want to continue
// ex. ErrClientEarlyMedia was returned but you want to proceed with answering
func (d *DialogClientSession) WaitAnswer(ctx context.Context, opts sipgo.AnswerOptions) error {
return d.waitAnswer(ctx, &d.DialogMedia, opts)
}
func (d *DialogClientSession) waitAnswerEarly(ctx context.Context, med *DialogMedia, opts sipgo.AnswerOptions) error {
sess := med.mediaSession
onResps := opts.OnResponse
// Add early media check
opts.OnResponse = func(res *sip.Response) error {
// https://datatracker.ietf.org/doc/html/rfc3261#section-8.1.3.2
// UAC MUST treat any provisional response different than 100 that it
// does not recognize as 183 (Session Progress).
// Check any existing
if onResps != nil {
if err := onResps(res); err != nil {
return err
}
}
// handle 183 Session Progress early media
if res.StatusCode != sip.StatusSessionInProgress {
return nil
}
if cont := res.ContentType(); cont == nil || cont.Value() != "application/sdp" {
return nil
}
remoteSDP := res.Body()
if remoteSDP == nil {
return nil
}
if err := sess.RemoteSDP(remoteSDP); err != nil {
return err
}
if err := sess.Finalize(); err != nil {
return err
}
rtpSess := media.NewRTPSession(sess)
med.mu.Lock()
med.initRTPSessionUnsafe(sess, rtpSess)
med.onCloseUnsafe(func() error {
return rtpSess.Close()
})
med.mu.Unlock()
// Must be called after reader and writer setup due to race
if err := rtpSess.MonitorBackground(); err != nil {
return err
}
return ErrClientEarlyMedia
}
return d.waitAnswer(ctx, med, opts)
}
func (d *DialogClientSession) waitAnswer(ctx context.Context, med *DialogMedia, opts sipgo.AnswerOptions) error {
if err := d.DialogClientSession.WaitAnswer(ctx, opts); err != nil {
return err
}
remoteSDP := d.InviteResponse.Body()
if remoteSDP == nil {
return fmt.Errorf("no SDP in response")
}
if err := d.applyRemoteSDP(med, remoteSDP); err != nil {
// Terminate call. Call must be ACK before doing BYE
if err := d.Ack(ctx); err != nil {
return errors.Join(err, d.Ack(ctx))
}
return errors.Join(err, d.Bye(ctx))
}
return nil
}
func (d *DialogClientSession) applyRemoteSDP(med *DialogMedia, remoteSDP []byte) error {
sess := med.mediaSession
// Apply SDP on existing (Early) media if it exists
if err := med.checkEarlyMedia(remoteSDP); err != errNoRTPSession {
return err
}
if err := sess.RemoteSDP(remoteSDP); err != nil {
return err
}
// Create RTP session. After this no media session configuration should be changed
rtpSess := media.NewRTPSession(sess)
med.mu.Lock()
med.initRTPSessionUnsafe(sess, rtpSess)
// d.onCloseUnsafe(func() error {
// return rtpSess.Close()
// })
med.mu.Unlock()
// Must be called after reader and writer setup due to race
return rtpSess.MonitorBackground()
}
// Ack acknowledgeds media
// Before Ack normally you want to setup more stuff like bridging
func (d *DialogClientSession) Ack(ctx context.Context) error {
inviteRequest := d.InviteRequest
recipient := inviteRequest.Recipient
if contact := d.InviteResponse.Contact(); contact != nil {
recipient = contact.Address
}
if err := d.ack(ctx, recipient, nil); err != nil {
return err
}
// NOTE it generally advisable todo this after successfull ACK:
// Server may not even listen yet as it is waiting for ACK
if d.mediaSession != nil {
if err := d.mediaSession.Finalize(); err != nil {
return err
}
}
return nil
}
// AckLate sends ACK with media. Use this in combination with late(delay) offer
// func (d *DialogClientSession) AckLate(ctx context.Context) error {
// return d.ack(ctx, d.mediaSession.LocalSDP())
// }
func (d *DialogClientSession) ack(ctx context.Context, remoteTarget sip.Uri, body []byte) error {
// inviteRequest := d.InviteRequest
// recipient := &inviteRequest.Recipient
// if contact := d.InviteResponse.Contact(); contact != nil {
// recipient = &contact.Address
// }
ackRequest := sip.NewRequest(
sip.ACK,
remoteTarget,
)
if body != nil {
// This is delayed offer
ackRequest.AppendHeader(sip.NewHeader("Content-Type", "application/sdp"))
ackRequest.SetBody(body)
}
if err := d.DialogClientSession.WriteAck(ctx, ackRequest); err != nil {
return err
}
// Now dialog is established and can be add into store
// if err := DialogsClientCache.DialogStore(ctx, d.ID, d); err != nil {
// return err
// }
// d.OnClose(func() error {
// return DialogsClientCache.DialogDelete(context.Background(), d.ID)
// })
return nil
}
// ReInvite sends new invite based on current media session
func (d *DialogClientSession) ReInvite(ctx context.Context) error {
d.mu.Lock()
sdp := d.mediaSession.LocalSDP()
contact := d.remoteContactUnsafe()
d.mu.Unlock()
req := sip.NewRequest(sip.INVITE, contact.Address)
req.AppendHeader(d.InviteRequest.Contact())
req.AppendHeader(sip.NewHeader("Content-Type", "application/sdp"))
req.SetBody(sdp)
res, err := d.reInviteDo(ctx, req)
if err != nil {
return err
}
cont := res.Contact()
if cont == nil {
return fmt.Errorf("no contact header present")
}
ack := sip.NewRequest(sip.ACK, cont.Address)
return d.WriteRequest(ack)
}
func (d *DialogClientSession) reInviteDo(ctx context.Context, req *sip.Request) (*sip.Response, error) {
for {
res, err := d.Do(ctx, req.Clone())
if err != nil {
return nil, err
}
if !res.IsSuccess() {
// https://datatracker.ietf.org/doc/html/rfc3261#section-14.1
// If a UAC receives a 491 response to a re-INVITE, it SHOULD start a
// timer with a value T chosen as follows:
// 1. If the UAC is the owner of the Call-ID of the dialog ID
// (meaning it generated the value), T has a randomly chosen value
// between 2.1 and 4 seconds in units of 10 ms.
// 2. If the UAC is not the owner of the Call-ID of the dialog ID, T
// has a randomly chosen value of between 0 and 2 seconds in units
// of 10 ms.
if res.StatusCode == sip.StatusRequestPending {
select {
case <-time.After(time.Duration(2000+mrand.IntN(200)*10) * time.Millisecond):
continue
case <-ctx.Done():
return nil, ctx.Err()
}
}
return nil, sipgo.ErrDialogResponse{
Res: res,
}
}
// Now do ACK on new Contact
if err := d.ack(ctx, res.Contact().Address, nil); err != nil {
return res, err
}
return res, nil
}
}
// reInviteMediaSession updates with full new media session
// media MUST BE Forked
func (d *DialogClientSession) reInviteMediaSession(ctx context.Context, ms *media.MediaSession) error {
sdp := ms.LocalSDP()
// NOTE: we do not change original invite request
d.mu.Lock()
contact := d.remoteContactUnsafe()
d.mu.Unlock()
req := sip.NewRequest(sip.INVITE, contact.Address)
req.AppendHeader(d.InviteRequest.Contact())
req.AppendHeader(sip.NewHeader("Content-Type", "application/sdp"))
req.SetBody(sdp)
res, err := d.reInviteDo(ctx, req)
if err != nil {
return err
}
// Save new remote target contact and update media
return func() error {
d.mu.Lock()
defer d.mu.Unlock()
d.remoteContactTarget = res.Contact()
remoteSDP := res.Body()
if err := ms.RemoteSDP(remoteSDP); err != nil {
return fmt.Errorf("sdp update media remote SDP applying failed: %w", err)
}
return d.mediaUpdateUnsafe(ms)
}()
}
// reInvites withs empty SDP are way to keep alive or do some post media update after receiving offer on 2xx
func (d *DialogClientSession) reInviteKeepAlive(ctx context.Context) error {
// NOTE: we do not change original invite request
d.mu.Lock()
contact := d.remoteContactUnsafe()
d.mu.Unlock()
req := sip.NewRequest(sip.INVITE, contact.Address)
req.AppendHeader(d.InviteRequest.Contact())
res, err := d.reInviteDo(ctx, req)
if err != nil {
return err
}
// Save new remote target contact
d.mu.Lock()
d.remoteContactTarget = res.Contact()
d.mu.Unlock()
return nil
}
// Refer tries todo refer (blind transfer) on call. For more control use ReferOptions
//
// NOTE: It is expected that after calling this you are hanguping call to send BYE
func (d *DialogClientSession) Refer(ctx context.Context, referTo sip.Uri, headers ...sip.Header) error {
// cont := d.InviteRequest.Contact()
// return dialogRefer(ctx, d, cont.Address, referTo, headers...)
return d.ReferOptions(ctx, referTo, ReferClientOptions{
Headers: headers,
})
}
type ReferClientOptions struct {
Headers []sip.Header
// OnNotify sends notify status code.
// If implemented you need to react on different status code.
OnNotify func(statusCode int)
}
func (d *DialogClientSession) ReferOptions(ctx context.Context, referTo sip.Uri, opts ReferClientOptions) error {
d.mu.Lock()
cont := d.remoteContactUnsafe()
if opts.OnNotify != nil {
d.onReferNotify = opts.OnNotify
}
d.mu.Unlock()
return dialogRefer(ctx, d, cont.Address, referTo, d.InviteResponse.Contact().Address, opts.Headers...)
}
func (d *DialogClientSession) handleReferNotify(req *sip.Request, tx sip.ServerTransaction) {
dialogHandleReferNotify(d, req, tx)
}
func (d *DialogClientSession) handleRefer(dg *Diago, req *sip.Request, tx sip.ServerTransaction) {
d.mu.Lock()
onRefDialog := d.onReferDialog
d.mu.Unlock()
if onRefDialog == nil {
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusNotAcceptable, "Not Acceptable", nil))
return
}
dialogHandleRefer(d, dg, req, tx, onRefDialog)
}
func (d *DialogClientSession) handleReInvite(req *sip.Request, tx sip.ServerTransaction) error {
if err := d.ReadRequest(req, tx); err != nil {
return tx.Respond(sip.NewResponseFromRequest(req, sip.StatusBadRequest, "Bad Request - "+err.Error(), nil))
}
return d.handleMediaUpdate(req, tx, d.InviteRequest.Contact())
}
func (d *DialogClientSession) handleReInviteACK(req *sip.Request, tx sip.ServerTransaction) error {
// Check do we need to handle Late Offer from ACK and update media
body := req.Body()
if body != nil {
// Update media session state under lock, but invoke the app callback after unlock to avoid deadlocks.
d.mu.Lock()
err := d.sdpUpdateUnsafe(body)
onMediaUpdate := d.onMediaUpdate
d.mu.Unlock()
if err != nil {
return err
}
if onMediaUpdate != nil {
onMediaUpdate(d.Media())
}
}
return d.mediaSession.Finalize()
}
func (d *DialogClientSession) readSIPInfoDTMF(req *sip.Request, tx sip.ServerTransaction) error {
return tx.Respond(sip.NewResponseFromRequest(req, sip.StatusNotAcceptable, "Not Acceptable", nil))
}
func (d *DialogClientSession) Hold(ctx context.Context) error {
m := d.MediaSession().Fork()
m.Mode = sdp.ModeSendonly
if err := d.reInviteMediaSession(ctx, m); err != nil {
return err
}
return nil
}
func (d *DialogClientSession) Unhold(ctx context.Context) error {
m := d.MediaSession().Fork()
m.Mode = sdp.ModeSendrecv
if err := d.reInviteMediaSession(ctx, m); err != nil {
return err
}
return nil
}