forked from emiago/sipgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
301 lines (250 loc) · 8.12 KB
/
main.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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"net/http"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"strconv"
"time"
"github.com/arl/statsviz"
"github.com/emiago/sipgo/sip"
_ "net/http/pprof"
"github.com/emiago/sipgo"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
// _ "go.uber.org/automaxprocs"
)
var ()
func main() {
defer pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
debflag := flag.Bool("debug", false, "")
pprof := flag.Bool("pprof", false, "Full profile")
extIP := flag.String("ip", "127.0.0.1:5060", "My exernal ip")
dst := flag.String("dst", "", "Destination pbx, sip server")
transportType := flag.String("t", "udp", "Transport, default will be determined by request")
flag.Parse()
sip.UDPMTUSize = 10000
if *pprof {
runtime.SetBlockProfileRate(1)
runtime.SetMutexProfileFraction(1)
runtime.MemProfileRate = 64
}
lev := zerolog.InfoLevel
debuglev := os.Getenv("LOGDEBUG")
if *debflag || debuglev != "" {
lev = zerolog.DebugLevel
sip.SIPDebug = true
}
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro
log.Logger = zerolog.New(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: time.StampMicro,
}).With().Timestamp().Logger().Level(lev)
log.Info().Int("cpus", runtime.NumCPU()).Msg("Runtime")
log.Info().Msg("Server routes setuped")
go httpServer(":8080")
srv := setupSipProxy(*dst, *extIP)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
if err := srv.ListenAndServe(ctx, *transportType, *extIP); err != nil {
log.Error().Err(err).Msg("Fail to start sip server")
return
}
}
func httpServer(address string) {
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("Alive"))
})
http.HandleFunc("/mem", func(w http.ResponseWriter, r *http.Request) {
runtime.GC()
stats := &runtime.MemStats{}
runtime.ReadMemStats(stats)
data, _ := json.MarshalIndent(stats, "", " ")
w.WriteHeader(200)
w.Write(data)
})
statsviz.Register(http.DefaultServeMux)
log.Info().Msgf("Http server started address=%s", address)
http.ListenAndServe(address, nil)
}
func setupSipProxy(proxydst string, ip string) *sipgo.Server {
// Prepare all variables we need for our service
host, port, _ := sip.ParseAddr(ip)
ua, err := sipgo.NewUA()
if err != nil {
log.Fatal().Err(err).Msg("Fail to setup user agent")
}
srv, err := sipgo.NewServer(ua)
if err != nil {
log.Fatal().Err(err).Msg("Fail to setup server handle")
}
client, err := sipgo.NewClient(ua, sipgo.WithClientAddr(
ip,
))
if err != nil {
log.Fatal().Err(err).Msg("Fail to setup client handle")
}
registry := NewRegistry()
var getDestination = func(req *sip.Request) string {
tohead := req.To()
dst := registry.Get(tohead.Address.User)
if dst == "" {
return proxydst
}
return dst
}
var reply = func(tx sip.ServerTransaction, req *sip.Request, code sip.StatusCode, reason string) {
resp := sip.NewResponseFromRequest(req, code, reason, nil)
resp.SetDestination(req.Source()) //This is optional, but can make sure not wrong via is read
if err := tx.Respond(resp); err != nil {
log.Error().Err(err).Msg("Fail to respond on transaction")
}
}
var route = func(req *sip.Request, tx sip.ServerTransaction) {
// If we are proxying to asterisk or other proxy -dst must be set
// Otherwise we will look on our registration entries
dst := getDestination(req)
if dst == "" {
reply(tx, req, 404, "Not found")
return
}
ctx := context.Background()
req.SetDestination(dst)
// Start client transaction and relay our request
clTx, err := client.TransactionRequest(ctx, req, sipgo.ClientRequestAddVia, sipgo.ClientRequestAddRecordRoute)
if err != nil {
log.Error().Err(err).Msg("RequestWithContext failed")
reply(tx, req, 500, "")
return
}
defer clTx.Terminate()
// Keep monitoring transactions, and proxy client responses to server transaction
log.Debug().Str("req", req.Method.String()).Msg("Starting transaction")
for {
select {
case res, more := <-clTx.Responses():
if !more {
return
}
res.SetDestination(req.Source())
// https://datatracker.ietf.org/doc/html/rfc3261#section-16.7
// Based on section removing via. Topmost via should be removed and check that exist
// Removes top most header
res.RemoveHeader("Via")
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("ResponseHandler transaction respond failed")
}
// Early terminate
// if req.Method == sip.BYE {
// // We will call client Terminate
// return
// }
case <-clTx.Done():
if err := tx.Err(); err != nil {
log.Error().Err(err).Str("req", req.Method.String()).Msg("Client Transaction done with error")
}
return
case m := <-tx.Acks():
// Acks can not be send directly trough destination
log.Info().Str("m", m.StartLine()).Str("dst", dst).Msg("Proxing ACK")
m.SetDestination(dst)
client.WriteRequest(m)
case <-tx.Done():
if err := tx.Err(); err != nil {
if errors.Is(err, sip.ErrTransactionCanceled) {
// Cancel other side. This is only on INVITE needed
// We need now new transaction
if req.IsInvite() {
r := newCancelRequest(req)
res, err := client.Do(ctx, r)
if err != nil {
log.Error().Err(err).Str("req", req.Method.String()).Msg("Canceling transaction failed")
return
}
if res.StatusCode != 200 {
log.Error().Err(err).Str("req", req.Method.String()).Msg("Canceling transaction failed with non 200 code")
return
}
return
}
}
log.Error().Err(err).Str("req", req.Method.String()).Msg("Transaction done with error")
return
}
log.Debug().Str("req", req.Method.String()).Msg("Transaction done")
return
}
}
}
var registerHandler = func(req *sip.Request, tx sip.ServerTransaction) {
// https://www.rfc-editor.org/rfc/rfc3261#section-10.3
cont := req.Contact()
if cont == nil {
reply(tx, req, 404, "Missing address of record")
return
}
// We have a list of uris
uri := cont.Address
if uri.Host == host && uri.Port == port {
reply(tx, req, 401, "Contact address not provided")
return
}
addr := uri.Host + ":" + strconv.Itoa(uri.Port)
registry.Add(uri.User, addr)
log.Debug().Msgf("Contact added %s -> %s", uri.User, addr)
res := sip.NewResponseFromRequest(req, 200, "OK", nil)
// log.Debug().Msgf("Sending response: \n%s", res.String())
// URI params must be reset or this should be regenetad
cont.Address.UriParams = sip.NewParams()
cont.Address.UriParams.Add("transport", req.Transport())
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("Sending REGISTER OK failed")
return
}
}
var inviteHandler = func(req *sip.Request, tx sip.ServerTransaction) {
route(req, tx)
}
var ackHandler = func(req *sip.Request, tx sip.ServerTransaction) {
dst := getDestination(req)
if dst == "" {
return
}
req.SetDestination(dst)
if err := client.WriteRequest(req, sipgo.ClientRequestAddVia); err != nil {
log.Error().Err(err).Msg("Send failed")
reply(tx, req, 500, "")
}
}
var cancelHandler = func(req *sip.Request, tx sip.ServerTransaction) {
route(req, tx)
}
var byeHandler = func(req *sip.Request, tx sip.ServerTransaction) {
route(req, tx)
}
srv.OnRegister(registerHandler)
srv.OnInvite(inviteHandler)
srv.OnAck(ackHandler)
srv.OnCancel(cancelHandler)
srv.OnBye(byeHandler)
return srv
}
func newCancelRequest(inviteRequest *sip.Request) *sip.Request {
cancelReq := sip.NewRequest(sip.CANCEL, inviteRequest.Recipient)
cancelReq.AppendHeader(sip.HeaderClone(inviteRequest.Via())) // Cancel request must match invite TOP via and only have that Via
cancelReq.AppendHeader(sip.HeaderClone(inviteRequest.From()))
cancelReq.AppendHeader(sip.HeaderClone(inviteRequest.To()))
cancelReq.AppendHeader(sip.HeaderClone(inviteRequest.CallID()))
sip.CopyHeaders("Route", inviteRequest, cancelReq)
cancelReq.SetSource(inviteRequest.Source())
cancelReq.SetDestination(inviteRequest.Destination())
return cancelReq
}