forked from emiago/sipgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
276 lines (236 loc) · 6.78 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
package sipgo
import (
"fmt"
"log/slog"
"net"
"github.com/google/uuid"
"github.com/livekit/sipgo/sip"
"github.com/livekit/sipgo/transport"
)
func Init() {
uuid.EnableRandPool()
}
type Client struct {
*UserAgent
host string
port int
log *slog.Logger
}
type ClientOption func(c *Client) error
// WithClientLogger allows customizing client logger
func WithClientLogger(logger *slog.Logger) ClientOption {
return func(s *Client) error {
s.log = logger
return nil
}
}
// WithClientHost allows setting default route host
// default it will be used user agent IP
func WithClientHostname(hostname string) ClientOption {
return func(s *Client) error {
s.host = hostname
return nil
}
}
// WithClientPort allows setting default route port
func WithClientPort(port int) ClientOption {
return func(s *Client) error {
s.port = port
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,
host: ua.GetIP().String(),
log: slog.With("caller", "Client"),
}
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
}
func (c *Client) GetHostname() string {
return c.host
}
// TransactionRequest uses transaction layer to send request and returns transaction
// NOTE: 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 you have request fully built
// This is useful when using client handle in proxy building as request are already parsed
func (c *Client) TransactionRequest(req *sip.Request, options ...ClientRequestOption) (sip.ClientTransaction, error) {
if len(options) == 0 {
clientRequestBuildReq(c, req)
return c.tx.Request(req)
}
for _, o := range options {
if err := o(c, req); err != nil {
return nil, err
}
}
return c.tx.Request(req)
}
// 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
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;
if req.Via() == nil {
// Multi VIA value must be manually added
ClientRequestAddVia(c, req)
}
// From and To headers should not contain Port numbers, headers, uri params
if req.From() == nil {
from := sip.FromHeader{
DisplayName: c.name,
Address: sip.Uri{
User: c.name,
Host: c.host,
UriParams: sip.NewParams(),
Headers: sip.NewParams(),
},
Params: sip.NewParams(),
}
from.Params.Add("tag", sip.GenerateTagN(16))
req.AppendHeader(&from)
}
if req.To() == 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(),
}
req.AppendHeader(&to)
}
if req.CallID() == nil {
uuid, err := uuid.NewRandom()
if err != nil {
return err
}
callid := sip.CallIDHeader(uuid.String())
req.AppendHeader(&callid)
}
if req.CSeq() == nil {
// TODO consider atomic increase cseq within Dialog
cseq := sip.CSeqHeader{
SeqNo: 1,
MethodName: req.Method,
}
req.AppendHeader(&cseq)
}
if req.MaxForwards() == nil {
maxfwd := sip.MaxForwardsHeader(70)
req.AppendHeader(&maxfwd)
}
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 {
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 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)
}
}
r.PrependHeader(newvia)
return nil
}
// 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(transport.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": transport.NetworkToLower(r.Transport()),
"lr": "",
},
},
}
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
}