-
-
Notifications
You must be signed in to change notification settings - Fork 79
/
client.go
478 lines (404 loc) · 13.2 KB
/
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
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
package sipgo
import (
"context"
"fmt"
"net"
"github.com/emiago/sipgo/sip"
"github.com/google/uuid"
"github.com/icholy/digest"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func Init() {
uuid.EnableRandPool()
}
type ClientTransactionRequester interface {
Request(ctx context.Context, req *sip.Request) (sip.ClientTransaction, error)
}
type Client struct {
*UserAgent
host string
port int
rport bool
log zerolog.Logger
// TxRequester allows you to use your transaction requester instead default from transaction layer
// Useful only for testing
//
// Experimental
TxRequester ClientTransactionRequester
}
type ClientOption func(c *Client) error
// WithClientLogger allows customizing client logger
func WithClientLogger(logger zerolog.Logger) ClientOption {
return func(s *Client) error {
s.log = logger
return nil
}
}
// WithClientHost allows setting default route host or IP on Via
// in case of IP it will enforce transport layer to create/reuse connection with this IP
// This is useful when you need to act as client first and avoid creating server handle listeners.
// NOTE: From header hostname is WithUserAgentHostname option on UA or modify request manually
func WithClientHostname(hostname string) ClientOption {
return func(s *Client) error {
s.host = hostname
return nil
}
}
// WithClientPort allows setting default route Via port
// it will enforce transport layer to create connection with this port if does NOT exist
// transport layer will choose existing connection by default unless
// TransportLayer.ConnectionReuse is set to false
// default: ephemeral port
func WithClientPort(port int) ClientOption {
return func(s *Client) error {
s.port = port
return nil
}
}
// WithClientNAT makes client aware that is behind NAT.
func WithClientNAT() ClientOption {
return func(s *Client) error {
s.rport = true
return nil
}
}
// WithClientAddr is merge of WithClientHostname and WithClientPort
// addr is format <host>:<port>
func WithClientAddr(addr string) ClientOption {
return func(s *Client) error {
host, port, err := sip.ParseAddr(addr)
if err != nil {
return err
}
WithClientHostname(host)(s)
WithClientPort(port)(s)
return nil
}
}
// NewClient creates client handle for user agent
func NewClient(ua *UserAgent, options ...ClientOption) (*Client, error) {
c := &Client{
UserAgent: ua,
log: log.Logger.With().Str("caller", "Client").Logger(),
}
for _, o := range options {
if err := o(c); err != nil {
return nil, err
}
}
return c, nil
}
// Close client handle. UserAgent must be closed for full transaction and transport layer closing.
func (c *Client) Close() error {
return nil
}
// Hostname returns default hostname or what is set WithHostname option
func (c *Client) Hostname() string {
return c.host
}
// TransactionRequest uses transaction layer to send request and returns transaction
// For more correct behavior use client.Do instead which acts same like HTTP req/response
//
// By default request will not be cloned and it will populate request with missing headers unless options are used
// In most cases you want this as you will retry with additional headers
//
// Following header fields will be added if not exist to have correct SIP request:
// To, From, CSeq, Call-ID, Max-Forwards, Via
// Passing options will override this behavior, that is, it is expected that your request is already prebuild
// This is mostly the case when creating proxy
func (c *Client) TransactionRequest(ctx context.Context, req *sip.Request, options ...ClientRequestOption) (sip.ClientTransaction, error) {
if req.IsAck() {
return nil, fmt.Errorf("ACK request must be sent directly through transport. Use WriteRequest")
}
if len(options) == 0 {
if cseq := req.CSeq(); cseq != nil {
// Increase cseq if this is existing transaction
// WriteRequest for ex ACK will not increase and this is wanted behavior
// This will be a problem if we allow ACK to be passed as transaction request
cseq.SeqNo++
cseq.MethodName = req.Method
}
clientRequestBuildReq(c, req)
return c.requestTransaction(ctx, req)
}
for _, o := range options {
if err := o(c, req); err != nil {
return nil, err
}
}
return c.requestTransaction(ctx, req)
}
func (c *Client) requestTransaction(ctx context.Context, req *sip.Request) (sip.ClientTransaction, error) {
if c.TxRequester != nil {
return c.TxRequester.Request(ctx, req)
}
return c.tx.Request(ctx, req)
}
// Do request is HTTP client like Do request/response.
// It returns on final response.
// NOTE: Canceling ctx WILL not send Cancel Request which is needed for INVITE. Use dialog API for dealing with dialogs
// For more lower API use TransactionRequest directly
func (c *Client) Do(ctx context.Context, req *sip.Request) (*sip.Response, error) {
tx, err := c.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()
}
}
}
type DigestAuth struct {
Username string
Password string
}
// DoDigestAuth will apply digest authentication if initial request is chalenged by 401 or 407.
// It returns new transaction that is created for this request
func (c *Client) DoDigestAuth(ctx context.Context, req *sip.Request, res *sip.Response, auth DigestAuth) (sip.ClientTransaction, error) {
if res.StatusCode == sip.StatusProxyAuthRequired {
return digestProxyAuthRequest(ctx, c, req, res, digest.Options{
Method: req.Method.String(),
URI: req.Recipient.Addr(),
Username: auth.Username,
Password: auth.Password,
})
}
return c.digestTransactionRequest(ctx, req, res, digest.Options{
Method: req.Method.String(),
URI: req.Recipient.Addr(),
Username: auth.Username,
Password: auth.Password,
})
}
// digestTransactionRequest does basic digest auth
func (c *Client) digestTransactionRequest(ctx context.Context, req *sip.Request, res *sip.Response, opts digest.Options) (sip.ClientTransaction, error) {
if err := digestAuthApply(req, res, opts); err != nil {
return nil, err
}
cseq := req.CSeq()
cseq.SeqNo++
req.RemoveHeader("Via")
tx, err := c.TransactionRequest(ctx, req, ClientRequestAddVia)
return tx, err
}
// WriteRequest sends request directly to transport layer
// Behavior is same as TransactionRequest
// Non-transaction ACK request should be passed like this
func (c *Client) WriteRequest(req *sip.Request, options ...ClientRequestOption) error {
if len(options) == 0 {
clientRequestBuildReq(c, req)
return c.tp.WriteMsg(req)
}
for _, o := range options {
if err := o(c, req); err != nil {
return err
}
}
return c.tp.WriteMsg(req)
}
type ClientRequestOption func(c *Client, req *sip.Request) error
// ClientRequestBuild will build missing fields in request
// This is by default but can be used to combine with other ClientRequestOptions
func ClientRequestBuild(c *Client, r *sip.Request) error {
return clientRequestBuildReq(c, r)
}
func clientRequestBuildReq(c *Client, req *sip.Request) error {
// https://www.rfc-editor.org/rfc/rfc3261#section-8.1.1
// A valid SIP request formulated by a UAC MUST, at a minimum, contain
// the following header fields: To, From, CSeq, Call-ID, Max-Forwards,
// and Via;
mustHeader := make([]sip.Header, 0, 6)
if v := req.Via(); v == nil {
// Multi VIA value must be manually added
via := clientRequestCreateVia(c, req)
mustHeader = append(mustHeader, via)
}
// From and To headers should not contain Port numbers, headers, uri params
if v := req.From(); v == nil {
from := sip.FromHeader{
DisplayName: c.UserAgent.name,
Address: sip.Uri{
Scheme: req.Recipient.Scheme,
User: c.UserAgent.name,
Host: c.UserAgent.hostname,
UriParams: sip.NewParams(),
Headers: sip.NewParams(),
},
Params: sip.NewParams(),
}
if from.Address.Host == "" {
// In case we have no UA hostname set use whatever is our routing host
from.Address.Host = c.host
}
from.Params.Add("tag", sip.GenerateTagN(16))
mustHeader = append(mustHeader, &from)
}
if v := req.To(); v == nil {
to := sip.ToHeader{
Address: sip.Uri{
Scheme: req.Recipient.Scheme,
User: req.Recipient.User,
Host: req.Recipient.Host,
UriParams: sip.NewParams(),
Headers: sip.NewParams(),
},
Params: sip.NewParams(),
}
mustHeader = append(mustHeader, &to)
}
if v := req.CallID(); v == nil {
uuid, err := uuid.NewRandom()
if err != nil {
return err
}
callid := sip.CallIDHeader(uuid.String())
mustHeader = append(mustHeader, &callid)
}
if v := req.CSeq(); v == nil {
cseq := sip.CSeqHeader{
SeqNo: 1,
MethodName: req.Method,
}
mustHeader = append(mustHeader, &cseq)
}
if v := req.MaxForwards(); v == nil {
maxfwd := sip.MaxForwardsHeader(70)
mustHeader = append(mustHeader, &maxfwd)
}
req.PrependHeader(mustHeader...)
if req.Body() == nil {
req.SetBody(nil)
}
return nil
}
// ClientRequestAddVia is option for adding via header
// Based on proxy setup https://www.rfc-editor.org/rfc/rfc3261.html#section-16.6
func ClientRequestAddVia(c *Client, r *sip.Request) error {
via := clientRequestCreateVia(c, r)
r.PrependHeader(via)
return nil
}
func clientRequestCreateVia(c *Client, r *sip.Request) *sip.ViaHeader {
// TODO
// A client that sends a request to a multicast address MUST add the
// "maddr" parameter to its Via header field value containing the
// destination multicast address
newvia := &sip.ViaHeader{
ProtocolName: "SIP",
ProtocolVersion: "2.0",
Transport: r.Transport(),
Host: c.host, // This can be rewritten by transport layer
Port: c.port, // This can be rewritten by transport layer
Params: sip.NewParams(),
}
// NOTE: Consider lenght of branch configurable
newvia.Params.Add("branch", sip.GenerateBranchN(16))
if c.rport {
newvia.Params.Add("rport", "")
}
if via := r.Via(); via != nil {
// https://datatracker.ietf.org/doc/html/rfc3581#section-6
// As proxy rport and received must be fullfiled
if via.Params.Has("rport") {
h, p, _ := net.SplitHostPort(r.Source())
via.Params.Add("rport", p)
via.Params.Add("received", h)
}
}
return newvia
}
// ClientRequestAddRecordRoute is option for adding record route header
// Based on proxy setup https://www.rfc-editor.org/rfc/rfc3261#section-16
func ClientRequestAddRecordRoute(c *Client, r *sip.Request) error {
// We will try to use our listen port. Host must be set to some none NAT IP
port := c.tp.GetListenPort(sip.NetworkToLower(r.Transport()))
rr := &sip.RecordRouteHeader{
Address: sip.Uri{
Host: c.host,
Port: port, // This must be listen port
UriParams: sip.HeaderParams{
// Transport must be provided as wesll
// https://datatracker.ietf.org/doc/html/rfc5658
"transport": sip.NetworkToLower(r.Transport()),
"lr": "",
},
Headers: sip.NewParams(),
},
}
r.PrependHeader(rr)
return nil
}
// Based on proxy setup https://www.rfc-editor.org/rfc/rfc3261#section-16
// ClientRequestDecreaseMaxForward should be used when forwarding request. It decreases max forward
// in case of 0 it returnes error
func ClientRequestDecreaseMaxForward(c *Client, r *sip.Request) error {
maxfwd := r.MaxForwards()
if maxfwd == nil {
// TODO, should we return error here
return nil
}
maxfwd.Dec()
if maxfwd.Val() <= 0 {
return fmt.Errorf("max forwards reached")
}
return nil
}
func digestProxyAuthApply(req *sip.Request, res *sip.Response, opts digest.Options) error {
authHeader := res.GetHeader("Proxy-Authenticate")
chal, err := digest.ParseChallenge(authHeader.Value())
if err != nil {
return fmt.Errorf("fail to parse challenge authHeader=%q: %w", authHeader.Value(), err)
}
// Fix lower case algorithm although not supported by rfc
chal.Algorithm = sip.ASCIIToUpper(chal.Algorithm)
// Reply with digest
cred, err := digest.Digest(chal, opts)
if err != nil {
return fmt.Errorf("fail to build digest: %w", err)
}
req.RemoveHeader("Proxy-Authorization")
req.AppendHeader(sip.NewHeader("Proxy-Authorization", cred.String()))
return nil
}
func digestAuthApply(req *sip.Request, res *sip.Response, opts digest.Options) error {
wwwAuth := res.GetHeader("WWW-Authenticate")
if wwwAuth == nil {
return fmt.Errorf("No WWW-Authenticate header present")
}
chal, err := digest.ParseChallenge(wwwAuth.Value())
if err != nil {
return fmt.Errorf("fail to parse chalenge wwwauth=%q: %w", wwwAuth.Value(), err)
}
// Fix lower case algorithm although not supported by rfc
chal.Algorithm = sip.ASCIIToUpper(chal.Algorithm)
// Reply with digest
cred, err := digest.Digest(chal, opts)
if err != nil {
return fmt.Errorf("fail to build digest: %w", err)
}
req.RemoveHeader("Authorization")
req.AppendHeader(sip.NewHeader("Authorization", cred.String()))
return nil
}
// digestProxyAuthRequest does basic digest auth with proxy header
func digestProxyAuthRequest(ctx context.Context, client *Client, req *sip.Request, res *sip.Response, opts digest.Options) (sip.ClientTransaction, error) {
if err := digestProxyAuthApply(req, res, opts); err != nil {
return nil, err
}
cseq := req.CSeq()
cseq.SeqNo++
req.RemoveHeader("Via")
tx, err := client.TransactionRequest(ctx, req, ClientRequestAddVia)
return tx, err
}