-
Notifications
You must be signed in to change notification settings - Fork 9
/
phone.go
1312 lines (1113 loc) · 32.9 KB
/
phone.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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sipgox
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/emiago/media"
"github.com/emiago/media/sdp"
"github.com/emiago/sipgo"
"github.com/emiago/sipgo/sip"
"github.com/icholy/digest"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// Phone is easy wrapper for creating phone like functionaliy
// but actions are creating clients and servers on a fly so
// it is not designed for long running apps
var (
// Value must be zerolog.Logger
ContextLoggerKey = "logger"
)
type Phone struct {
UA *sipgo.UserAgent
// listenAddrs is map of transport:addr which will phone use to listen incoming requests
listenAddrs []ListenAddr
log zerolog.Logger
// Custom client or server
// By default they are created
client *sipgo.Client
server *sipgo.Server
}
type ListenAddr struct {
Network string
Addr string
TLSConf *tls.Config
}
type Listener struct {
ListenAddr
io.Closer
Listen func() error
}
type PhoneOption func(p *Phone)
// WithPhoneListenAddrs
// NOT TLS supported
func WithPhoneListenAddr(addr ListenAddr) PhoneOption {
return func(p *Phone) {
p.listenAddrs = append(p.listenAddrs, addr)
}
}
func WithPhoneLogger(l zerolog.Logger) PhoneOption {
return func(p *Phone) {
p.log = l
}
}
// func WithPhoneClient(c *sipgo.Client) PhoneOption {
// return func(p *Phone) {
// p.client = c
// }
// }
// func WithPhoneServer(s *sipgo.Server) PhoneOption {
// return func(p *Phone) {
// p.server = s
// }
// }
func NewPhone(ua *sipgo.UserAgent, options ...PhoneOption) *Phone {
p := &Phone{
UA: ua,
// c: client,
listenAddrs: []ListenAddr{},
log: log.Logger,
}
for _, o := range options {
o(p)
}
if len(p.listenAddrs) == 0 {
// WithPhoneListenAddr(ListenAddr{"udp", "127.0.0.1:5060"})(p)
// WithPhoneListenAddr(ListenAddr{"tcp", "0.0.0.0:5060"})(p)
}
// In case ws we want to run http
return p
}
func (p *Phone) Close() {
}
// func (p *Phone) getOrCreateClient(opts ...sipgo.ClientOption) (*sipgo.Client, error) {
// if p.client != nil {
// return p.client, nil
// }
// return sipgo.NewClient(p.ua, opts...)
// }
// func (p *Phone) getOrCreateServer(opts ...sipgo.ServerOption) (*sipgo.Server, error) {
// if p.server != nil {
// return p.server, nil
// }
// return sipgo.NewServer(p.ua, opts...)
// }
func (p *Phone) getLoggerCtx(ctx context.Context, caller string) zerolog.Logger {
l := ctx.Value(ContextLoggerKey)
if l != nil {
log, ok := l.(zerolog.Logger)
if ok {
return log
}
}
return p.log.With().Str("caller", caller).Logger()
}
func (p *Phone) getInterfaceAddr(network string, targetAddr string) (addr string, err error) {
host, port, err := p.getInterfaceHostPort(network, targetAddr)
if err != nil {
return "", err
}
return net.JoinHostPort(host, strconv.Itoa(port)), nil
}
func (p *Phone) createServerListener(s *sipgo.Server, a ListenAddr) (*Listener, error) {
network, addr := a.Network, a.Addr
switch network {
case "udp":
// resolve local UDP endpoint
laddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, fmt.Errorf("fail to resolve address. err=%w", err)
}
udpConn, err := net.ListenUDP("udp", laddr)
if err != nil {
return nil, fmt.Errorf("listen udp error. err=%w", err)
}
// Port can be dynamic
a.Addr = udpConn.LocalAddr().String()
return &Listener{
a,
udpConn,
func() error { return s.ServeUDP(udpConn) },
}, nil
case "ws", "tcp":
laddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return nil, fmt.Errorf("fail to resolve address. err=%w", err)
}
conn, err := net.ListenTCP("tcp", laddr)
if err != nil {
return nil, fmt.Errorf("listen tcp error. err=%w", err)
}
a.Addr = conn.Addr().String()
// and uses listener to buffer
if network == "ws" {
return &Listener{
a,
conn,
func() error { return s.ServeWS(conn) },
}, nil
}
return &Listener{
a,
conn,
func() error { return s.ServeTCP(conn) },
}, nil
}
return nil, fmt.Errorf("unsuported protocol")
}
func (p *Phone) createServerListeners(s *sipgo.Server) (listeners []*Listener, e error) {
newListener := func(a ListenAddr) error {
l, err := p.createServerListener(s, a)
if err != nil {
return err
}
listeners = append(listeners, l)
return nil
}
if len(p.listenAddrs) == 0 {
addr, err := p.getInterfaceAddr("udp", "")
if err != nil {
return listeners, err
}
err = newListener(ListenAddr{Network: "udp", Addr: addr})
// ip, err := resolveHostIPWithTarget("udp", "")
// if err != nil {
// return listeners, err
// }
// err = newListener(ListenAddr{Network: "udp", Addr: ip.String() + ":0"})
return listeners, err
}
for _, a := range p.listenAddrs {
err := newListener(a)
if err != nil {
return nil, err
}
}
return listeners, nil
}
func (p *Phone) getInterfaceHostPort(network string, targetAddr string) (host string, port int, err error) {
for _, a := range p.listenAddrs {
if a.Network == network {
host, port, err = sip.ParseAddr(a.Addr)
if err != nil {
return
}
// What is with port
// If user provides this 127.0.0.1:0 -> then this tell us to use random port
// If user provides this non IP then port will stay empty
if port != 0 {
return
}
ip := net.ParseIP(host)
if ip != nil {
port, err = findFreePort(network, ip)
return
}
// port = sip.DefaultPort(network)
return
}
}
ip, port, err := FindFreeInterfaceHostPort(network, targetAddr)
if err != nil {
return "", 0, err
}
return ip.String(), port, nil
}
var (
ErrRegisterFail = fmt.Errorf("register failed")
ErrRegisterUnathorized = fmt.Errorf("register unathorized")
)
type RegisterResponseError struct {
RegisterReq *sip.Request
RegisterRes *sip.Response
Msg string
}
func (e *RegisterResponseError) StatusCode() sip.StatusCode {
return e.RegisterRes.StatusCode
}
func (e RegisterResponseError) Error() string {
return e.Msg
}
// Register the phone by sip uri. Pass username and password via opts
// NOTE: this will block and keep periodic registration. Use context to cancel
type RegisterOptions struct {
Username string
Password string
Expiry int
AllowHeaders []string
UnregisterAll bool
}
func (p *Phone) Register(ctx context.Context, recipient sip.Uri, opts RegisterOptions) error {
log := p.getLoggerCtx(ctx, "Register")
// Make our client reuse address
network := recipient.Headers["transport"]
if network == "" {
network = "udp"
}
lhost, lport, _ := p.getInterfaceHostPort(network, recipient.HostPort())
// addr := net.JoinHostPort(lhost, strconv.Itoa(lport))
// Run server on UA just to handle OPTIONS
// We do not need to create listener as client will create underneath connections and point contact header
server, err := sipgo.NewServer(p.UA)
if err != nil {
return err
}
defer server.Close()
server.OnOptions(func(req *sip.Request, tx sip.ServerTransaction) {
res := sip.NewResponseFromRequest(req, sip.StatusOK, "OK", nil)
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("OPTIONS 200 failed to respond")
}
})
client, err := sipgo.NewClient(p.UA,
sipgo.WithClientHostname(lhost),
sipgo.WithClientPort(lport),
sipgo.WithClientNAT(), // add rport support
)
defer client.Close()
contactHdr := sip.ContactHeader{
Address: sip.Uri{
User: p.UA.Name(),
Host: lhost,
Port: lport,
Headers: sip.HeaderParams{"transport": network},
UriParams: sip.NewParams(),
},
Params: sip.NewParams(),
}
t, err := p.register(ctx, client, recipient, contactHdr, opts)
if err != nil {
return err
}
// Unregister
defer func() {
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
err := t.Unregister(ctx)
if err != nil {
log.Error().Err(err).Msg("Fail to unregister")
}
}()
return t.QualifyLoop(ctx)
}
func (p *Phone) register(ctx context.Context, client *sipgo.Client, recipient sip.Uri, contact sip.ContactHeader, opts RegisterOptions) (*RegisterTransaction, error) {
t := NewRegisterTransaction(p.getLoggerCtx(ctx, "Register"), client, recipient, contact, opts)
if opts.UnregisterAll {
if err := t.Unregister(ctx); err != nil {
return nil, ErrRegisterFail
}
}
err := t.Register(ctx)
if err != nil {
return nil, err
}
return t, nil
}
type DialResponseError struct {
InviteReq *sip.Request
InviteResp *sip.Response
Msg string
}
func (e *DialResponseError) StatusCode() sip.StatusCode {
return e.InviteResp.StatusCode
}
func (e DialResponseError) Error() string {
return e.Msg
}
type DialOptions struct {
// Authentication via digest challenge
Username string
Password string
// Custom headers passed on INVITE
SipHeaders []sip.Header
// SDP Formats to customize. NOTE: Only ulaw and alaw are fully supported
Formats sdp.Formats
// OnResponse is just callback called after INVITE is sent and all responses before final one
// Useful for tracking call state
OnResponse func(inviteResp *sip.Response)
// OnRefer is called 2 times.
// 1st with state NONE and dialog=nil. This is to have caller prepared
// 2nd with state Established or Ended with dialog
OnRefer func(state DialogReferState)
// Experimental
//
// OnMedia handles INVITE updates and passes new MediaSession with new propertie
OnMedia func(sess *media.MediaSession)
}
type DialogReferState struct {
// Updates current transfer progress with state
State sip.DialogState
// Dialog present when state is answered (Confirmed dialog state)
Dialog *DialogClientSession
}
// Dial creates dialog with recipient
//
// return DialResponseError in case non 200 responses
func (p *Phone) Dial(dialCtx context.Context, recipient sip.Uri, o DialOptions) (*DialogClientSession, error) {
log := p.getLoggerCtx(dialCtx, "Dial")
ctx, _ := context.WithCancel(dialCtx)
// defer cancel()
network := "udp"
if recipient.UriParams != nil {
if t := recipient.UriParams["transport"]; t != "" {
network = t
}
}
// Remove password from uri.
recipient.Password = ""
server, err := sipgo.NewServer(p.UA)
if err != nil {
return nil, err
}
// We need to listen as long our answer context is running
// Listener needs to be alive even after we have created dialog
// listeners, err := p.createServerListeners(server)
// if err != nil {
// return nil, err
// }
// host, listenPort, _ := sip.ParseAddr(listeners[0].Addr)
// NOTE: this can return empty port, in this case we probably have hostname
host, port, err := p.getInterfaceHostPort(network, recipient.HostPort())
if err != nil {
return nil, err
}
contactHDR := sip.ContactHeader{
Address: sip.Uri{User: p.UA.Name(), Host: host, Port: port},
Params: sip.HeaderParams{"transport": network},
}
// We will force client to use same interface and port as defined for contact header
// The problem could be if this is required to be different, but for now keeping phone simple
client, err := sipgo.NewClient(p.UA,
sipgo.WithClientHostname(host),
sipgo.WithClientPort(port),
)
if err != nil {
return nil, err
}
// Setup dialog client
dc := sipgo.NewDialogClient(client, contactHDR)
server.OnBye(func(req *sip.Request, tx sip.ServerTransaction) {
if err := dc.ReadBye(req, tx); err != nil {
if errors.Is(err, sipgo.ErrDialogDoesNotExists) {
log.Info().Msg("Received BYE but dialog was already closed")
return
}
log.Error().Err(err).Msg("Dialog reading BYE failed")
return
}
log.Debug().Msg("Received BYE")
})
server.OnRefer(func(req *sip.Request, tx sip.ServerTransaction) {
if o.OnRefer == nil {
log.Warn().Str("req", req.StartLine()).Msg("Refer is not handled. Missing OnRefer")
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusMethodNotAllowed, "Method not allowed", nil))
return
}
var dialog *sipgo.DialogClientSession
var newDialog *DialogClientSession
var err error
// TODO refactor this
refer := func() error {
referUri := sip.Uri{}
dialog, err = dc.ReadRefer(req, tx, &referUri)
if err != nil {
return err
}
// Setup session
rtpIp := p.UA.GetIP()
if lip := net.ParseIP(host); lip != nil && !lip.IsUnspecified() {
rtpIp = lip
}
msess, err := media.NewMediaSession(&net.UDPAddr{IP: rtpIp, Port: 0})
if err != nil {
return err
}
notifyAccepted := true
{
// Do Notify
log.Info().Msg("Sending NOTIFY")
notify := sip.NewRequest(sip.NOTIFY, req.Contact().Address)
notify.AppendHeader(sip.NewHeader("Content-Type", "message/sipfrag;version=2.0"))
notify.SetBody([]byte("SIP/2.0 100 Trying"))
cliTx, err := dialog.TransactionRequest(dialog.Context(), notify)
if err != nil {
return err
}
defer cliTx.Terminate()
select {
case <-cliTx.Done():
case res := <-cliTx.Responses():
notifyAccepted = res.StatusCode == sip.StatusOK
}
}
invite := sip.NewRequest(sip.INVITE, referUri)
invite.SetTransport(network)
invite.AppendHeader(sip.NewHeader("Content-Type", "application/sdp"))
invite.SetBody(msess.LocalSDP())
newDialog, err = p.dial(context.TODO(), dc, invite, msess, o)
if err != nil {
return err
}
if notifyAccepted {
notify := sip.NewRequest(sip.NOTIFY, req.Contact().Address)
notify.AppendHeader(sip.NewHeader("Content-Type", "message/sipfrag;version=2.0"))
notify.SetBody([]byte("SIP/2.0 200 OK"))
cliTx, err := dialog.TransactionRequest(dialog.Context(), notify)
if err != nil {
return err
}
defer cliTx.Terminate()
}
return nil
}
// Refer can happen and due to new dialog creation current one could be terminated.
// Caller would not be able to get control of new dialog until it is answered
// This way we say to caller to wait transfer completition, and current dialog can be terminated
o.OnRefer(DialogReferState{State: 0})
if err := refer(); err != nil {
log.Error().Err(err).Msg("Fail to dial REFER")
// Handle better this errors
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusInternalServerError, err.Error(), nil))
o.OnRefer(DialogReferState{State: sip.DialogStateEnded})
return
}
// Let caller decide will it close current dialog or continue with transfer
// defer dialog.Close()
// defer dialog.Bye(context.TODO())
o.OnRefer(DialogReferState{State: sip.DialogStateConfirmed, Dialog: newDialog})
})
var dialogRef *DialogClientSession
// waitingAck := atomic.
server.OnInvite(func(req *sip.Request, tx sip.ServerTransaction) {
id, err := sip.UACReadRequestDialogID(req)
if err != nil {
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusBadRequest, "Bad Request", nil))
return
}
if dialogRef.ID != id {
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusNotFound, "Dialog does not exist", nil))
return
}
// Forking current dialog session and applying new SDP
msess := dialogRef.MediaSession.Fork()
if err := msess.RemoteSDP(req.Body()); err != nil {
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusBadRequest, "SDP applying failed", nil))
return
}
log.Info().
Str("formats", logFormats(msess.Formats)).
Str("localAddr", msess.Laddr.String()).
Str("remoteAddr", msess.Raddr.String()).
Msg("Media/RTP session updated")
if o.OnMedia != nil {
o.OnMedia(msess)
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusOK, "OK", nil))
return
}
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusMethodNotAllowed, "Method not allowed", nil))
})
server.OnAck(func(req *sip.Request, tx sip.ServerTransaction) {
// This gets received when we send 200 on INVITE media update
id, err := sip.UACReadRequestDialogID(req)
if err != nil {
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusBadRequest, "Bad Request", nil))
return
}
if dialogRef.ID != id {
tx.Respond(sip.NewResponseFromRequest(req, sip.StatusNotFound, "Dialog does not exist", nil))
return
}
})
// Start server
// for _, l := range listeners {
// log.Info().Str("network", l.Network).Str("addr", l.Addr).Msg("Listening on")
// go l.Listen()
// }
// Setup session
rtpIp := p.UA.GetIP()
if lip := net.ParseIP(host); lip != nil && !lip.IsUnspecified() {
rtpIp = lip
}
msess, err := media.NewMediaSession(&net.UDPAddr{IP: rtpIp, Port: 0})
if err != nil {
return nil, err
}
// Create Generic SDP
if len(o.Formats) > 0 {
msess.Formats = o.Formats
}
sdpSend := msess.LocalSDP()
// Creating INVITE
req := sip.NewRequest(sip.INVITE, recipient)
req.SetTransport(network)
req.AppendHeader(sip.NewHeader("Content-Type", "application/sdp"))
req.SetBody(sdpSend)
// Add custom headers
for _, h := range o.SipHeaders {
log.Info().Str(h.Name(), h.Value()).Msg("Adding SIP header")
req.AppendHeader(h)
}
dialog, err := p.dial(ctx, dc, req, msess, o)
if err != nil {
return nil, err
}
dialogRef = dialog
return dialog, nil
}
func (p *Phone) dial(ctx context.Context, dc *sipgo.DialogClient, invite *sip.Request, msess *media.MediaSession, o DialOptions) (*DialogClientSession, error) {
log := p.getLoggerCtx(ctx, "Dial")
dialog, err := dc.WriteInvite(ctx, invite)
if err != nil {
return nil, err
}
p.logSipRequest(&log, invite)
return p.dialWaitAnswer(ctx, dialog, msess, o)
}
func (p *Phone) dialWaitAnswer(ctx context.Context, dialog *sipgo.DialogClientSession, msess *media.MediaSession, o DialOptions) (*DialogClientSession, error) {
log := p.getLoggerCtx(ctx, "Dial")
invite := dialog.InviteRequest
// Wait 200
waitStart := time.Now()
err := dialog.WaitAnswer(ctx, sipgo.AnswerOptions{
OnResponse: func(res *sip.Response) error {
p.logSipResponse(&log, res)
if o.OnResponse != nil {
o.OnResponse(res)
}
return nil
},
Username: o.Username,
Password: o.Password,
})
var rerr *sipgo.ErrDialogResponse
if errors.As(err, &rerr) {
return nil, &DialResponseError{
InviteReq: invite,
InviteResp: rerr.Res,
Msg: fmt.Sprintf("Call not answered: %s", rerr.Res.StartLine()),
}
}
if err != nil {
return nil, err
}
r := dialog.InviteResponse
log.Info().
Int("code", int(r.StatusCode)).
// Str("reason", r.Reason).
Str("duration", time.Since(waitStart).String()).
Msg("Call answered")
// Setup media
err = msess.RemoteSDP(r.Body())
// TODO handle bad SDP
if err != nil {
return nil, err
}
log.Info().
Str("formats", logFormats(msess.Formats)).
Str("localAddr", msess.Laddr.String()).
Str("remoteAddr", msess.Raddr.String()).
Msg("Media/RTP session created")
// Send ACK
if err := dialog.Ack(ctx); err != nil {
return nil, fmt.Errorf("fail to send ACK: %w", err)
}
return &DialogClientSession{
MediaSession: msess,
DialogClientSession: dialog,
}, nil
}
var (
// You can use this key with AnswerReadyCtxValue to get signal when
// Answer is ready to receive traffic
AnswerReadyCtxKey = "AnswerReadyCtxKey"
)
type AnswerReadyCtxValue chan struct{}
type AnswerOptions struct {
Ringtime time.Duration
SipHeaders []sip.Header
// For authorizing INVITE unless RegisterAddr is defined
Username string
Password string
Realm string //default sipgo
RegisterAddr string //If defined it will keep registration in background
// For SDP codec manipulating
Formats sdp.Formats
// OnCall is just INVITE request handler that you can use to notify about incoming call
// After this dialog should be created and you can watch your changes with dialog.State
// -1 == Cancel
// 0 == continue
// >0 different response
OnCall func(inviteRequest *sip.Request) int
// Default is 200 (answer a call)
AnswerCode sip.StatusCode
AnswerReason string
}
// Answer will answer call
// Closing ansCtx will close listeners or it will be closed on BYE
// TODO: reusing listener
func (p *Phone) Answer(ansCtx context.Context, opts AnswerOptions) (*DialogServerSession, error) {
dialog, err := p.answer(ansCtx, opts)
if err != nil {
return nil, err
}
log.Debug().Msg("Dialog answer created")
if !dialog.InviteResponse.IsSuccess() {
// Return closed/terminated dialog
return dialog, dialog.Close()
}
return dialog, nil
}
func (p *Phone) answer(ansCtx context.Context, opts AnswerOptions) (*DialogServerSession, error) {
log := p.getLoggerCtx(ansCtx, "Answer")
ringtime := opts.Ringtime
waitDialog := make(chan *DialogServerSession)
var d *DialogServerSession
// TODO reuse server and listener
server, err := sipgo.NewServer(p.UA)
if err != nil {
return nil, err
}
// We need to listen as long our answer context is running
// Listener needs to be alive even after we have created dialog
listeners, err := p.createServerListeners(server)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(ansCtx)
var exitErr error
stopAnswer := sync.OnceFunc(func() {
cancel() // Cancel context
for _, l := range listeners {
log.Debug().Str("addr", l.Addr).Msg("Closing listener")
l.Close()
}
})
exitError := func(err error) {
exitErr = err
}
lhost, lport, _ := sip.ParseAddr(listeners[0].Addr)
contactHdr := sip.ContactHeader{
Address: sip.Uri{
User: p.UA.Name(),
Host: lhost,
Port: lport,
Headers: sip.HeaderParams{"transport": listeners[0].Network},
UriParams: sip.NewParams(),
},
Params: sip.NewParams(),
}
// Create client handle for responding
client, err := sipgo.NewClient(p.UA,
sipgo.WithClientNAT(), // needed for registration
sipgo.WithClientHostname(lhost),
// Do not use with ClientPort as we want always this to be a seperate connection
)
if err != nil {
return nil, err
}
if opts.RegisterAddr != "" {
// We will use registration to resolve NAT
// so WithClientNAT must be present
// Keep registration
rhost, rport, _ := sip.ParseAddr(opts.RegisterAddr)
registerURI := sip.Uri{
Host: rhost,
Port: rport,
User: p.UA.Name(),
}
regTr, err := p.register(ctx, client, registerURI, contactHdr, RegisterOptions{
Username: opts.Username,
Password: opts.Password,
Expiry: 30,
// UnregisterAll: true,
// AllowHeaders: server.RegisteredMethods(),
})
if err != nil {
return nil, err
}
// In case our register changed contact due to NAT detection via rport, lets update
contact := regTr.Origin.Contact()
contactHdr = *contact.Clone()
origStopAnswer := stopAnswer
// Override stopAnswer with unregister
stopAnswer = sync.OnceFunc(func() {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := regTr.Unregister(ctx)
if err != nil {
log.Error().Err(err).Msg("Fail to unregister")
}
regTr = nil
origStopAnswer()
})
go func(ctx context.Context) {
err := regTr.QualifyLoop(ctx)
exitError(err)
stopAnswer()
}(ctx)
}
ds := sipgo.NewDialogServer(client, contactHdr)
var chal *digest.Challenge
server.OnInvite(func(req *sip.Request, tx sip.ServerTransaction) {
if d != nil {
didAnswered, _ := sip.MakeDialogIDFromResponse(d.InviteResponse)
did, _ := sip.MakeDialogIDFromRequest(req)
if did == didAnswered {
// We received INVITE for update
if err := d.MediaSession.RemoteSDP(req.Body()); err != nil {
res := sip.NewResponseFromRequest(req, 400, err.Error(), nil)
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("Fail to send 400")
return
}
return
}
res := sip.NewResponseFromRequest(req, 200, "OK", nil)
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("Fail to send 200")
return
}
return
}
log.Error().Msg("Received second INVITE is not yet supported: 486 busy here")
res := sip.NewResponseFromRequest(req, 486, "busy here", nil)
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("Fail to send 486")
return
}
return
}
// We authorize request if password provided and no register addr defined
// Use cases:
// 1. INVITE auth like registrar before processing INVITE
// 2. Auto answering client which keeps registration and accepts calls
if opts.Password != "" && opts.RegisterAddr == "" {
// https://www.rfc-editor.org/rfc/rfc2617#page-6
h := req.GetHeader("Authorization")
if h == nil {
if chal != nil {
// If challenge is created next is forbidden
res := sip.NewResponseFromRequest(req, 403, "Forbidden", nil)
tx.Respond(res)
return
}
if opts.Realm == "" {
opts.Realm = "sipgo"
}
chal = &digest.Challenge{
Realm: opts.Realm,
Nonce: fmt.Sprintf("%d", time.Now().UnixMicro()),
// Opaque: "sipgo",
Algorithm: "MD5",
}
res := sip.NewResponseFromRequest(req, 401, "Unathorized", nil)
res.AppendHeader(sip.NewHeader("WWW-Authenticate", chal.String()))
tx.Respond(res)
return
}
cred, err := digest.ParseCredentials(h.Value())
if err != nil {
log.Error().Err(err).Msg("parsing creds failed")
tx.Respond(sip.NewResponseFromRequest(req, 401, "Bad credentials", nil))
return
}
// Make digest and compare response
digCred, err := digest.Digest(chal, digest.Options{
Method: "INVITE",
URI: cred.URI,
Username: opts.Username,
Password: opts.Password,
})
if err != nil {
log.Error().Err(err).Msg("Calc digest failed")
tx.Respond(sip.NewResponseFromRequest(req, 401, "Bad credentials", nil))
return
}
if cred.Response != digCred.Response {
tx.Respond(sip.NewResponseFromRequest(req, 401, "Unathorized", nil))
return
}
log.Info().Str("username", cred.Username).Str("source", req.Source()).Msg("INVITE authorized")
}
p.logSipRequest(&log, req)
dialog, err := ds.ReadInvite(req, tx)
if err != nil {
res := sip.NewResponseFromRequest(req, 400, err.Error(), nil)
if err := tx.Respond(res); err != nil {
log.Error().Err(err).Msg("Failed to send 400 response")
}
exitError(err)