-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathdialog_client_session.go
353 lines (297 loc) · 9.75 KB
/
dialog_client_session.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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024, Emir Aganovic
package diago
import (
"context"
"fmt"
"net"
"strings"
"sync/atomic"
"github.com/emiago/diago/media"
"github.com/emiago/sipgo"
"github.com/emiago/sipgo/sip"
"github.com/rs/zerolog/log"
)
// DialogClientSession represents outbound channel
type DialogClientSession struct {
*sipgo.DialogClientSession
DialogMedia
onReferDialog func(referDialog *DialogClientSession)
closed atomic.Uint32
}
func (d *DialogClientSession) Close() {
if !d.closed.CompareAndSwap(0, 1) {
return
}
d.DialogMedia.Close()
d.DialogClientSession.Close()
}
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.lastInvite != nil {
// Invite update can change contact
return d.lastInvite.Contact()
}
return d.InviteResponse.Contact()
}
type InviteClientOptions struct {
Originator DialogSession
OnResponse func(res *sip.Response) error
// OnMediaUpdate called when media is changed. NOTE: you should not block this call
OnMediaUpdate func(d *DialogMedia)
OnRefer func(referDialog *DialogClientSession)
// For digest authentication
Username string
Password string
// Custom headers to pass. DO NOT SET THIS to nil
Headers []sip.Header
}
// Invite sends Invite request and establishes early media.
// NOTE: You must call Ack after to acknowledge session.
// 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
//
// Experimental: Note API may have changes
func (d *DialogClientSession) Invite(ctx context.Context, opts InviteClientOptions) error {
sess := d.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{}
for _, c := range sess.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?
// TODO: Should we honor formats set on this session?
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 fromHDR := inviteReq.From(); fromHDR != nil {
fromHDR.Params["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
d.onMediaUpdate = opts.OnMediaUpdate
// 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
}
return d.waitAnswer(ctx, sipgo.AnswerOptions{
Username: opts.Username,
Password: opts.Password,
OnResponse: opts.OnResponse,
})
}
// InviteLate does not send SDP offer
// NOTE: call AckLate to complete negotiation
// func (d *DialogClientSession) InviteLate(ctx context.Context, opts InviteOptions) error {
// }
func (d *DialogClientSession) waitAnswer(ctx context.Context, opts sipgo.AnswerOptions) error {
sess := d.mediaSession
callID := d.InviteRequest.CallID().Value()
log.Info().Str("call_id", callID).Msg("Waiting answer")
if err := d.WaitAnswer(ctx, opts); err != nil {
return err
}
remoteSDP := d.InviteResponse.Body()
if remoteSDP == nil {
return fmt.Errorf("no SDP in response")
}
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)
d.mu.Lock()
d.initRTPSessionUnsafe(sess, rtpSess)
d.onCloseUnsafe(func() {
if err := rtpSess.Close(); err != nil {
log.Error().Err(err).Msg("Closing session")
}
})
d.mu.Unlock()
log.Debug().Str("laddr", sess.Laddr.String()).Str("raddr", sess.Raddr.String()).Msg("RTP Session setuped")
// Must be called after reader and writer setup due to race
if err := rtpSess.MonitorBackground(); err != nil {
return err
}
return nil
}
// Ack acknowledgeds media
// Before Ack normally you want to setup more stuff like bridging
func (d *DialogClientSession) Ack(ctx context.Context) error {
return d.ack(ctx, 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, body []byte) error {
inviteRequest := d.InviteRequest
recipient := &inviteRequest.Recipient
if contact := d.InviteResponse.Contact(); contact != nil {
recipient = &contact.Address
}
ackRequest := sip.NewRequest(
sip.ACK,
*recipient.Clone(),
)
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() {
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.Do(ctx, req)
if err != nil {
return err
}
if !res.IsSuccess() {
return sipgo.ErrDialogResponse{
Res: res,
}
}
cont := res.Contact()
if cont == nil {
return fmt.Errorf("no contact header present")
}
ack := sip.NewRequest(sip.ACK, cont.Address)
return d.WriteRequest(ack)
}
// Refer tries todo refer (blind transfer) on call
// TODO: not complete
func (d *DialogClientSession) Refer(ctx context.Context, referTo sip.Uri) error {
cont := d.InviteResponse.Contact()
return dialogRefer(ctx, d, cont.Address, referTo)
}
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) readSIPInfoDTMF(req *sip.Request, tx sip.ServerTransaction) error {
return tx.Respond(sip.NewResponseFromRequest(req, sip.StatusNotAcceptable, "Not Acceptable", nil))
}