-
Notifications
You must be signed in to change notification settings - Fork 445
/
SIPUserAgent.cs
1842 lines (1620 loc) · 85.9 KB
/
SIPUserAgent.cs
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
//-----------------------------------------------------------------------------
// Filename: SIPUserAgent.cs
//
// Description: A "full" SIP user agent that encompasses both client and server
// user agents. It is also able to manage in dialog operations after the call
// is established (the client and server user agents don't handle in dialog
// operations).
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 26 Nov 2019 Aaron Clauson Created, Dublin, Ireland.
// rj2: added overload for Answer with customHeader
// 10 May 2020 Aaron Clauson Added handling for REFER requests as per
// https://tools.ietf.org/html/rfc3515
// and https://tools.ietf.org/html/rfc5589.
// 17 May 2020 Aaron Clauson Added exclusive transport option to simplify
// incoming call handling.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SIPSorcery.Net;
using SIPSorcery.Sys;
namespace SIPSorcery.SIP.App
{
/// <summary>
/// A "full" SIP user agent that encompasses both client and server user agents.
/// It is also able to manage in dialog operations after the call is established
/// (the client and server user agents don't handle in dialog operations).
///
/// Unlike other user agents this one also manages its own RTP session object
/// which means it can handle things like call on and off hold, RTP end point
/// changes and sending DTMF events.
/// </summary>
public class SIPUserAgent : IDisposable
{
private static readonly string m_sdpContentType = SDP.SDP_MIME_CONTENTTYPE;
private static readonly string m_sipReferContentType = SIPMIMETypes.REFER_CONTENT_TYPE;
private static int WAIT_ONHOLD_TIMEOUT = SIPTimings.T1;
private static int WAIT_DIALOG_TIMEOUT = SIPTimings.T2;
private static ILogger logger = Log.Logger;
private CancellationTokenSource m_cts = new CancellationTokenSource();
/// <summary>
/// Client user agent for placing calls.
/// </summary>
private SIPClientUserAgent m_uac;
/// <summary>
/// Server user agent for receiving calls.
/// </summary>
private SIPServerUserAgent m_uas;
/// <summary>
/// The SIP transport layer for sending requests and responses.
/// </summary>
private SIPTransport m_transport;
/// <summary>
/// If true indicates the SIP transport instance is specific to this user agent and
/// is not being shared.
/// </summary>
private readonly bool m_isTransportExclusive;
/// <summary>
/// The SIP account used by the server user agent and this user agent
/// for authentication challenges
/// </summary>
private readonly ISIPAccount m_answerSipAccount;
/// <summary>
/// If set all communications are sent to this address irrespective of what the
/// request and response headers indicate.
/// </summary>
private SIPEndPoint m_outboundProxy;
/// <summary>
/// If a call is successfully answered this property will be set with the
/// resultant dialogue.
/// </summary>
private SIPDialogue m_sipDialogue;
/// <summary>
/// Holds the call descriptor for an in progress client (outbound) call.
/// </summary>
private SIPCallDescriptor m_callDescriptor;
/// <summary>
/// Used to keep track of received RTP events. An RTP event will typically span
/// multiple packets but the application only needs to get informed once per event.
/// </summary>
private uint _rtpEventSsrc;
/// <summary>
/// When a blind and attended transfer is in progress the original call will be placed
/// on hold (if not already). To prevent the response from the on hold re-INVITE
/// being applied to the media session while the new transfer call is being made or
/// accepted we don't apply session descriptions on requests or responses with the
/// old (original) call ID.
/// </summary>
private string _oldCallID;
/// <summary>
/// Gets set to true if the SIP user agent has been explicitly closed and is no longer
/// required.
/// </summary>
private bool _isClosed;
/// <summary>
/// This timer is used when an outgoing call is made with a ring timeout specified.
/// If the call is not answered within the timeout it will be cancelled by this agent.
/// </summary>
private Timer _ringTimeout;
/// <summary>
/// The media (RTP) session in use for the current call.
/// </summary>
public IMediaSession MediaSession { get; private set; }
/// <summary>
/// Indicates whether there is an active call or not.
/// </summary>
public bool IsCallActive
{
get
{
return m_sipDialogue?.DialogueState == SIPDialogueStateEnum.Confirmed;
}
}
/// <summary>
/// Indicates whether a call initiated by this user agent is in progress but is yet
/// to get a ring or progress response.
/// </summary>
public bool IsCalling
{
get
{
if (!IsCallActive && m_uac != null && m_uac.ServerTransaction != null)
{
return m_uac.ServerTransaction.TransactionState == SIPTransactionStatesEnum.Calling ||
m_uac.ServerTransaction.TransactionState == SIPTransactionStatesEnum.Trying;
}
else
{
return false;
}
}
}
/// <summary>
/// Indicates whether a call initiated by this user agent has received a ringing or progress response.
/// </summary>
public bool IsRinging
{
get
{
if (!IsCallActive && m_uac != null && m_uac.ServerTransaction != null)
{
return m_uac.ServerTransaction.TransactionState == SIPTransactionStatesEnum.Proceeding;
}
else
{
return false;
}
}
}
/// <summary>
/// Indicates whether the user agent is in the process of hanging up or cancelling a call.
/// </summary>
public bool IsHangingUp
{
get
{
if (m_uac != null && m_uac.m_cancelTransaction != null && m_uac.m_cancelTransaction.DeliveryPending)
{
return true;
}
else if ((m_uac != null && m_uac.IsHangingUp) || (m_uas != null && m_uas.IsHangingUp))
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// True if we've put the remote party on hold.
/// </summary>
public bool IsOnLocalHold { get; private set; }
/// <summary>
/// True if the remote party has put us on hold.
/// </summary>
public bool IsOnRemoteHold { get; private set; }
/// <summary>
/// Once either the client or server call is answered this will hold the SIP
/// dialogue that was created by the call.
/// </summary>
public SIPDialogue Dialogue
{
get { return m_sipDialogue; }
}
/// <summary>
/// For a call initiated by us this is the call descriptor that was used.
/// </summary>
public SIPCallDescriptor CallDescriptor
{
get { return m_callDescriptor; }
}
/// <summary>
/// The default SIP URI that this URI can be contacted on. Depending on the SIP transport
/// being used by the agent there may be multiple ways of contacting it. In that case the
/// first URI found is used.
/// </summary>
public SIPURI ContactURI
{
get
{
if (m_transport.GetSIPChannels().Count > 0)
{
var firstChannel = m_transport.GetSIPChannels()[0];
return firstChannel.GetContactURI(SIPSchemesEnum.sip,
new SIPEndPoint(firstChannel.SIPProtocol, SIPChannel.InternetDefaultAddress, 0));
}
else
{
return null;
}
}
}
/// <summary>
/// The remote party has received our call request and is working on it.
/// </summary>
public event SIPCallResponseDelegate ClientCallTrying;
/// <summary>
/// The remote party has progressed our call request to ringing/in progress.
/// </summary>
public event SIPCallResponseDelegate ClientCallRinging;
/// <summary>
/// The in progress call attempt was answered.
/// </summary>
public event SIPCallResponseDelegate ClientCallAnswered;
/// <summary>
/// The in progress call attempt failed.
/// </summary>
public event SIPCallFailedDelegate ClientCallFailed;
/// <summary>
/// For calls accepted by this user agent this event will be fired if the call
/// is cancelled before it gets answered.
/// </summary>
public event SIPUASDelegate ServerCallCancelled;
/// <summary>
/// For calls accepted by this user agent this event will be fired if the call
/// is answered but the answer response is never confirmed. This can occur if
/// the client does not send the ACK or the ACK does not get through.
/// </summary>
public event SIPUASDelegate ServerCallRingTimeout;
/// <summary>
/// The remote call party has sent us a new re-INVITE request that this
/// class didn't know how to or couldn't handle. Things we can
/// handle are on and off hold. Common examples of what we can't handle
/// are changing RTP end points, changing codecs etc.
/// </summary>
public event Action<UASInviteTransaction> OnReinviteRequest;
/// <summary>
/// Call was hungup by the remote party. Applies to calls initiated by us and calls received
/// by us. An example of when this user agent will initiate a hang up is when a transfer is
/// accepted by the remote calling party.
/// </summary>
public event Action<SIPDialogue> OnCallHungup;
/// <summary>
/// Fires when a NOTIFY request is received that contains an update about the
/// status of a transfer. These events will be received by a user agent acting as the
/// Transferor but only if the Transferee support the transfer subscription.
/// </summary>
public event Action<string> OnTransferNotify;
/// <summary>
/// Fires when a REFER request is received that requests us to place a call to a
/// new destination. The REFER request can be a blind transfer or an attended transfer.
/// The difference is whether the REFER request includes a Replaces parameter. If it does
/// it's used to inform the transfer target (the transfer destination requested) that
/// if they accept our call it should replace an existing one.
/// </summary>
/// <remarks>
/// Parameters for event delegate:
/// bool OnTransferRequested(SIPUserField referTo, string referredBy)
/// SIPUserField: Is the destination that we are being asked to place a call to.
/// string referredBy: The Referred-By header from the REFER request that requested
/// we do the transfer.
/// bool: The boolean result can be returned as false to prevent the transfer. By default
/// if no event handler is hooked up the transfer will be accepted.
/// </remarks>
public event Func<SIPUserField, string, bool> OnTransferRequested;
/// <summary>
/// Fires when the call placed as a result of a transfer request is successfully answered.
/// The SIPUserField contains the destination that was called for the transfer.
/// </summary>
public event Action<SIPUserField> OnTransferToTargetSuccessful;
/// <summary>
/// Fires when the call placed as a result of a transfer request is rejected or fails.
/// The SIPUserField contains the destination that was called for the transfer.
/// </summary>
public event Action<SIPUserField> OnTransferToTargetFailed;
/// <summary>
/// The remote call party has put us on hold.
/// </summary>
public event Action RemotePutOnHold;
/// <summary>
/// The remote call party has taken us off hold.
/// </summary>
public event Action RemoteTookOffHold;
/// <summary>
/// Gets fired when an RTP DTMF event is detected as completed on the remote party's RTP stream.
/// </summary>
public event Action<byte, int> OnDtmfTone;
/// <summary>
/// Gets fired for every RTP event packet received from the remote party. This event allows the
/// application to decipher the vents as it wishes.
/// </summary>
public event Action<RTPEvent, RTPHeader> OnRtpEvent;
/// <summary>
/// Gets fired when a new INVITE request is detected on the SIP transport being used
/// by this user agent.
/// </summary>
public event Action<SIPUserAgent, SIPRequest> OnIncomingCall;
/// <summary>
/// Diagnostic event to allow monitoring of the INVITE transaction state.
/// </summary>
public event SIPTransactionStateChangeDelegate OnTransactionStateChange;
/// <summary>
/// Diagnostic event to receive trace messages related to the INVITE transaction
/// state machine processing.
/// </summary>
public event SIPTransactionTraceMessageDelegate OnTransactionTraceMessage;
/// <summary>
/// Creates a new instance where the user agent has exclusive control of the SIP transport.
/// This is significant for incoming requests. WIth exclusive control the agent knows that
/// any request are for it and can handle accordingly. If the transport needs to be shared
/// amongst multiple user agents use the alternative constructor.
/// </summary>
public SIPUserAgent()
{
m_transport = new SIPTransport();
m_transport.SIPTransportRequestReceived += SIPTransportRequestReceived;
m_isTransportExclusive = true;
}
/// <summary>
/// Creates a new SIP client and server combination user agent with a shared SIP transport instance.
/// With a shared transport outgoing calls and registrations work the same but for incoming calls
/// and requests the destination needs to be coordinated externally.
/// </summary>
/// <param name="transport">The transport layer to use for requests and responses.</param>
/// <param name="outboundProxy">Optional. If set all requests and responses will be forwarded to this
/// end point irrespective of their headers.</param>
/// <param name="isTransportExclusive">True is the SIP transport instance is for the exclusive use of
/// this user agent or false if it's being shared amongst multiple agents.</param>
/// <param name="answerSipAccount">Optional, will ensure that any request that require auth will be able to complete</param>
public SIPUserAgent(SIPTransport transport, SIPEndPoint outboundProxy, bool isTransportExclusive = false, ISIPAccount answerSipAccount = null)
{
m_transport = transport;
m_outboundProxy = outboundProxy;
m_isTransportExclusive = isTransportExclusive;
m_transport.SIPTransportRequestReceived += SIPTransportRequestReceived;
m_answerSipAccount = answerSipAccount;
}
/// <summary>
/// Attempts to place a new outgoing call AND waits for the call to be answered or fail.
/// Use <see cref="InitiateCallAsync(SIPCallDescriptor, IMediaSession)"/> to start a call without
/// waiting for it to complete and monitor <see cref="ClientCallAnsweredHandler"/> and
/// <see cref="ClientCallFailedHandler"/> to detect an answer or failure.
/// </summary>
/// <param name="dst">The destination SIP URI to call.</param>
/// <param name="username">Optional Username if authentication is required.</param>
/// <param name="password">Optional. Password if authentication is required.</param>
/// <param name="mediaSession">The RTP session for the call.</param>
/// <param name="ringTimeout">Optional. If non-zero will be treated as the number of seconds to let the call
/// ring for before giving up and cancelling.</param>
public Task<bool> Call(string dst, string username, string password, IMediaSession mediaSession, int ringTimeout = 0)
{
if (mediaSession == null)
{
throw new ArgumentNullException("mediaSession", "A media session must be supplied when placing a call.");
}
if (!SIPURI.TryParse(dst, out var dstUri))
{
throw new ApplicationException("The destination was not recognised as a valid SIP URI.");
}
string fromHeader = SIPConstants.SIP_DEFAULT_FROMURI;
if (!string.IsNullOrWhiteSpace(username))
{
// If the call needs to be authenticated the From header needs to be set
// with the username and domain to match the credentials.
fromHeader = (new SIPURI(username, dstUri.Host, null, dstUri.Scheme, dstUri.Protocol)).ToParameterlessString();
}
SIPCallDescriptor callDescriptor = new SIPCallDescriptor(
username ?? SIPConstants.SIP_DEFAULT_USERNAME,
password,
dstUri.ToString(),
fromHeader,
dstUri.CanonicalAddress,
null, null, null,
SIPCallDirection.Out,
SDP.SDP_MIME_CONTENTTYPE,
null,
null);
return Call(callDescriptor, mediaSession, ringTimeout);
}
/// <summary>
/// Attempts to place a new outgoing call AND waits for the call to be answered or fail.
/// Use <see cref="InitiateCallAsync(SIPCallDescriptor, IMediaSession)"/> to start a call without
/// waiting for it to complete and monitor <see cref="ClientCallAnsweredHandler"/> and
/// <see cref="ClientCallFailedHandler"/> to detect an answer or failure.
/// </summary>
/// <param name="callDescriptor">The full descriptor for the call destination. Allows customising
/// of additional options above the standard username, password and destination URI.</param>
/// <param name="mediaSession">The RTP session for the call.</param>
/// <param name="ringTimeout">Optional. If non-zero will be treated as the number of seconds to let the call
/// ring for before giving up and cancelling.</param>
public async Task<bool> Call(SIPCallDescriptor callDescriptor, IMediaSession mediaSession, int ringTimeout = 0)
{
TaskCompletionSource<bool> callResult = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
ClientCallAnswered += (uac, resp) => callResult.TrySetResult(true);
ClientCallFailed += (uac, errorMessage, result) => callResult.TrySetResult(false);
await InitiateCallAsync(callDescriptor, mediaSession, ringTimeout).ConfigureAwait(false);
return await callResult.Task.ConfigureAwait(false);
}
/// <summary>
/// Attempts to place a new outgoing call.
/// </summary>
/// <param name="sipCallDescriptor">A call descriptor containing the information about how
/// and where to place the call.</param>
/// <param name="mediaSession">The media session used for this call</param>
/// <param name="ringTimeout">Optional. If non-zero will be treated as the number of seconds to let the call
/// ring for before giving up and cancelling.</param>
public async Task InitiateCallAsync(SIPCallDescriptor sipCallDescriptor, IMediaSession mediaSession, int ringTimeout = 0)
{
m_cts = new CancellationTokenSource();
m_callDescriptor = sipCallDescriptor;
m_uac = new SIPClientUserAgent(m_transport, m_outboundProxy);
m_uac.CallTrying += ClientCallTryingHandler;
m_uac.CallRinging += ClientCallRingingHandler;
m_uac.CallAnswered += ClientCallAnsweredHandler;
m_uac.CallFailed += ClientCallFailedHandler;
// Can be DNS lookups involved in getting the call destination.
SIPEndPoint serverEndPoint = await m_uac.GetCallDestination(sipCallDescriptor).ConfigureAwait(false);
if (serverEndPoint != null)
{
MediaSession = mediaSession;
MediaSession.OnRtpEvent += OnRemoteRtpEvent;
MediaSession.OnTimeout += OnRtpTimeout;
var sdpAnnounceAddress = mediaSession.RtpBindAddress ?? NetServices.GetLocalAddressForRemote(serverEndPoint.Address);
var sdp = mediaSession.CreateOffer(sdpAnnounceAddress);
if (sdp == null)
{
ClientCallFailed?.Invoke(m_uac, $"Could not generate an offer.", null);
CallEnded(m_callDescriptor.CallId);
}
else
{
sipCallDescriptor.Content = sdp.ToString();
if (ringTimeout > 0)
{
logger.LogDebug($"Setting ring timeout of {ringTimeout}s.");
_ringTimeout = new Timer((state) => m_uac?.Cancel(), null, ringTimeout * 1000, Timeout.Infinite);
}
// This initiates the call but does not wait for an answer.
m_uac.Call(sipCallDescriptor, serverEndPoint);
}
}
else
{
ClientCallFailed?.Invoke(m_uac, $"Could not resolve destination when placing call to {sipCallDescriptor.Uri}.", null);
CallEnded(sipCallDescriptor.CallId);
}
}
/// <summary>
/// Cancel our call attempt prior to it being answered.
/// </summary>
public void Cancel()
{
if (m_uac != null)
{
if (m_uac.IsUACAnswered == false)
{
m_uac.Cancel();
}
else
{
m_uac.Hangup();
}
}
if (MediaSession != null)
{
MediaSession.Close("call cancelled");
}
}
/// <summary>
/// Hangup established call
/// </summary>
public void Hangup()
{
if (IsCallActive)
{
m_cts.Cancel();
if (MediaSession != null && !MediaSession.IsClosed)
{
MediaSession?.Close("call hungup");
}
string callID = null;
if (m_uac != null)
{
callID = m_uac.SIPDialogue?.CallId;
m_uac.Hangup();
}
else if (m_uas != null)
{
callID = m_uas.SIPDialogue?.CallId;
m_uas.Hangup(false);
}
IsOnLocalHold = false;
IsOnRemoteHold = false;
CallEnded(callID);
}
}
/// <summary>
/// This method can be used to start the processing of a new incoming call request.
/// The user agent will is acting as a server for this operation and it can be considered
/// the opposite of the Call method. This is only the first step in answering an incoming
/// call. It can still be rejected or answered after this point.
/// </summary>
/// <param name="inviteRequest">The invite request representing the incoming call.</param>
/// <returns>An ID string that needs to be supplied when the call is answered or rejected
/// (used to manage multiple pending incoming calls).</returns>
public SIPServerUserAgent AcceptCall(SIPRequest inviteRequest)
{
UASInviteTransaction uasTransaction = new UASInviteTransaction(m_transport, inviteRequest, m_outboundProxy);
SIPServerUserAgent uas = new SIPServerUserAgent(m_transport, m_outboundProxy, uasTransaction, m_answerSipAccount);
uas.ClientTransaction.TransactionStateChanged += (tx) => OnTransactionStateChange?.Invoke(tx);
uas.ClientTransaction.TransactionTraceMessage += (tx, msg) => OnTransactionTraceMessage?.Invoke(tx, msg);
uas.CallCancelled += (pendingUas) =>
{
CallEnded(inviteRequest.Header.CallId);
ServerCallCancelled?.Invoke(pendingUas);
};
uas.NoRingTimeout += (pendingUas) =>
{
ServerCallRingTimeout?.Invoke(pendingUas);
};
uas.Progress(SIPResponseStatusCodesEnum.Trying, null, null, null, null);
uas.Progress(SIPResponseStatusCodesEnum.Ringing, null, null, null, null);
return uas;
}
/// <summary>
/// Answers the call request contained in the user agent server parameter. Note the
/// <see cref="AcceptCall(SIPRequest)"/> method should be used to create the user agent server.
/// Any existing call will be hungup.
/// </summary>
/// <param name="uas">The user agent server holding the pending call to answer.</param>
/// <param name="mediaSession">The media session used for this call</param>
public Task<bool> Answer(SIPServerUserAgent uas, IMediaSession mediaSession)
{
return Answer(uas, mediaSession, null);
}
/// <summary>
/// Answers the call request contained in the user agent server parameter. Note the
/// <see cref="AcceptCall(SIPRequest)"/> method should be used to create the user agent server.
/// Any existing call will be hungup.
/// </summary>
/// <param name="uas">The user agent server holding the pending call to answer.</param>
/// <param name="mediaSession">The media session used for this call</param>
/// <param name="customHeaders">Custom SIP-Headers to use in Answer.</param>
/// <returns>True if the call was successfully answered or false if there was a problem
/// such as incompatible codecs.</returns>
public async Task<bool> Answer(SIPServerUserAgent uas, IMediaSession mediaSession, string[] customHeaders)
{
if (uas.IsCancelled)
{
logger.LogDebug("The incoming call has been cancelled.");
mediaSession?.Close("call cancelled");
return false;
}
else
{
m_cts = new CancellationTokenSource();
var sipRequest = uas.ClientTransaction.TransactionRequest;
MediaSession = mediaSession;
MediaSession.OnRtpEvent += OnRemoteRtpEvent;
MediaSession.OnTimeout += OnRtpTimeout;
MediaSession.OnRtpClosed += (reason) =>
{
if (MediaSession?.IsClosed == false)
{
logger.LogWarning($"RTP channel was closed with reason {reason}.");
}
};
string sdp = null;
if (!String.IsNullOrEmpty(sipRequest.Body))
{
// The SDP offer was included in the INVITE request.
SDP remoteSdp = SDP.ParseSDPDescription(sipRequest.Body);
var setRemoteResult = MediaSession.SetRemoteDescription(SdpType.offer, remoteSdp);
if (setRemoteResult != SetDescriptionResultEnum.OK)
{
logger.LogWarning($"Error setting remote description from INVITE {setRemoteResult}.");
uas.Reject(SIPResponseStatusCodesEnum.NotAcceptable, setRemoteResult.ToString());
MediaSession.Close("sdp offer not acceptable");
Hangup();
return false;
}
else
{
var sdpAnswer = MediaSession.CreateAnswer(null);
sdp = sdpAnswer.ToString();
}
}
else
{
// No SDP offer was included in the INVITE request need to wait for the ACK.
var sdpAnnounceAddress = MediaSession.RtpBindAddress ?? NetServices.GetLocalAddressForRemote(sipRequest.RemoteSIPEndPoint.GetIPEndPoint().Address);
var sdpOffer = MediaSession.CreateOffer(sdpAnnounceAddress);
sdp = sdpOffer.ToString();
}
m_uas = uas;
// In cases where the initial INVITE did not contain an SDP offer the action sequence is:
// - INVITE with no SDP offer received,
// - Reply with OK and an SDP offer,
// - Wait for ACK with SDP answer.
TaskCompletionSource<SIPDialogue> dialogueCreatedTcs = new TaskCompletionSource<SIPDialogue>(TaskCreationOptions.RunContinuationsAsynchronously);
m_uas.OnDialogueCreated += (dialogue) => dialogueCreatedTcs.TrySetResult(dialogue);
m_uas.Answer(m_sdpContentType, sdp, null, SIPDialogueTransferModesEnum.Default, customHeaders);
await Task.WhenAny(dialogueCreatedTcs.Task, Task.Delay(WAIT_DIALOG_TIMEOUT)).ConfigureAwait(false);
if (m_uas?.SIPDialogue != null)
{
m_sipDialogue = m_uas.SIPDialogue;
if (MediaSession.RemoteDescription == null)
{
// If the initial INVITE did not contain an offer then the remote description will not yet be set.
var remoteSDP = SDP.ParseSDPDescription(m_sipDialogue.RemoteSDP);
var setRemoteResult = MediaSession.SetRemoteDescription(SdpType.offer, remoteSDP);
if (setRemoteResult != SetDescriptionResultEnum.OK)
{
// Failed to set the remote SDP from the ACK request. Only option is to hangup.
logger.LogWarning($"Error setting remote description from ACK {setRemoteResult}.");
MediaSession.Close(setRemoteResult.ToString());
Hangup();
return false;
}
else
{
// SDP from the ACK request was accepted. Start the RTP session.
m_sipDialogue.DialogueState = SIPDialogueStateEnum.Confirmed;
await MediaSession.Start().ConfigureAwait(false);
return true;
}
}
else
{
m_sipDialogue.DialogueState = SIPDialogueStateEnum.Confirmed;
await MediaSession.Start().ConfigureAwait(false);
return true;
}
}
else
{
logger.LogWarning("The attempt to answer a call failed as the dialog was not created. The likely cause is the ACK not being received in time.");
MediaSession.Close("dialog creation failed");
Hangup();
return false;
}
}
}
/// <summary>
/// Initiates a blind transfer by asking the remote call party to call the specified destination.
/// If the transfer is accepted the current call will be hungup.
/// </summary>
/// <param name="destination">The URI to transfer the call to.</param>
/// <param name="timeout">Timeout for the transfer request to get accepted.</param>
/// <param name="ct">Cancellation token. Can be set to cancel the transfer prior to it being
/// accepted or timing out.</param>
/// <param name="customHeaders">Optional. Custom SIP-Headers that will be set in the REFER request sent
/// to the remote party.</param>
/// <returns>True if the transfer was accepted by the Transferee or false if not.</returns>
public Task<bool> BlindTransfer(SIPURI destination, TimeSpan timeout, CancellationToken ct, string[] customHeaders = null)
{
if (m_sipDialogue == null)
{
logger.LogWarning("Blind transfer was called on the SIPUserAgent when no dialogue was available.");
return Task.FromResult(false);
}
else
{
var referRequest = GetReferRequest(destination, customHeaders);
return Transfer(referRequest, timeout, ct);
}
}
/// <summary>
/// Initiates an attended transfer by asking the remote call party to call the specified destination.
/// If the transfer is accepted the current call will be hungup.
/// </summary>
/// <param name="transferee">The dialog that will be replaced on the transfer target call party.</param>
/// <param name="timeout">Timeout for the transfer request to get accepted.</param>
/// <param name="ct">Cancellation token. Can be set to cancel the transfer prior to it being
/// accepted or timing out.</param>
/// <param name="customHeaders">Optional. Custom SIP-Headers that will be set in the REFER request sent
/// to the remote party.</param>
/// <returns>True if the transfer was accepted by the Transferee or false if not.</returns>
public Task<bool> AttendedTransfer(SIPDialogue transferee, TimeSpan timeout, CancellationToken ct, string[] customHeaders = null)
{
if (m_sipDialogue == null || transferee == null)
{
logger.LogWarning("Attended transfer was called on the SIPUserAgent when no dialogue was available.");
return Task.FromResult(false);
}
else
{
var referRequest = GetReferRequest(transferee, customHeaders);
return Transfer(referRequest, timeout, ct);
}
}
/// <summary>
/// Requests the RTP session to transmit a DTMF tone using an RTP event.
/// </summary>
/// <param name="tone">The DTMF tone to transmit.</param>
public Task SendDtmf(byte tone)
{
return MediaSession.SendDtmf(tone, m_cts.Token);
}
/// <summary>
/// Send a re-INVITE request to put the remote call party on hold.
/// </summary>
public void PutOnHold()
{
IsOnLocalHold = true;
// The action we take to put a call on hold is to switch the media status
// to send only and change the audio input from a capture device to on hold
// music.
ApplyHoldAndReinvite();
}
/// <summary>
/// Send a re-INVITE request to take the remote call party on hold.
/// </summary>
public void TakeOffHold()
{
IsOnLocalHold = false;
ApplyHoldAndReinvite();
}
/// <summary>
/// Updates the stream status of the RTP session and sends the re-INVITE request.
/// </summary>
private void ApplyHoldAndReinvite()
{
var streamStatus = GetStreamStatusForOnHoldState();
if (MediaSession.HasAudio)
{
MediaSession.SetMediaStreamStatus(SDPMediaTypesEnum.audio, streamStatus);
}
if (MediaSession.HasVideo)
{
MediaSession.SetMediaStreamStatus(SDPMediaTypesEnum.video, streamStatus);
}
var sdp = MediaSession.CreateOffer(null);
SendReInviteRequest(sdp);
}
/// <summary>
/// Processes a transfer by sending to the remote party once the REFER request has been constructed.
/// </summary>
/// <param name="referRequest">The REFER request for the transfer.</param>
/// <param name="timeout">Timeout for the transfer request to get accepted.</param>
/// <param name="ct">Cancellation token. Can be set to cancel the transfer prior to it being
/// accepted or timing out.</param>
/// <returns>True if the transfer was accepted by the Transferee or false if not.</returns>
private async Task<bool> Transfer(SIPRequest referRequest, TimeSpan timeout, CancellationToken ct)
{
if (m_sipDialogue == null)
{
logger.LogWarning("Transfer was called on the SIPUserAgent when no dialogue was available.");
return false;
}
else
{
TaskCompletionSource<bool> transferAccepted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
SIPNonInviteTransaction referTx = new SIPNonInviteTransaction(m_transport, referRequest, null);
SIPTransactionResponseReceivedDelegate referTxStatusHandler = (localSIPEndPoint, remoteEndPoint, sipTransaction, sipResponse) =>
{
if (sipResponse.Header.CSeqMethod == SIPMethodsEnum.REFER && sipResponse.Status == SIPResponseStatusCodesEnum.Accepted)
{
logger.LogInformation("Call transfer was accepted by remote server.");
transferAccepted.TrySetResult(true);
}
else
{
transferAccepted.TrySetResult(false);
}
return Task.FromResult(SocketError.Success);
};
referTx.NonInviteTransactionFinalResponseReceived += referTxStatusHandler;
referTx.SendRequest();
await Task.WhenAny(transferAccepted.Task, Task.Delay((int)timeout.TotalMilliseconds, ct)).ConfigureAwait(false);
referTx.NonInviteTransactionFinalResponseReceived -= referTxStatusHandler;
if (transferAccepted.Task.IsCompleted)
{
return transferAccepted.Task.Result;
}
else
{
logger.LogWarning($"Call transfer request timed out after {timeout.TotalMilliseconds}ms.");
return false;
}
}
}
/// <summary>
/// Handler for when an in dialog request is received on an established call.
/// Typical types of request will be re-INVITES for things like putting a call on or
/// off hold and REFER requests for transfers. Some in dialog request types, such
/// as re-INVITES have specific events so they can be bubbled up to the
/// application to deal with.
/// </summary>
/// <param name="sipRequest">The in dialog request received.</param>
private async Task DialogRequestReceivedAsync(SIPRequest sipRequest)
{
if (sipRequest.Method == SIPMethodsEnum.BYE)
{
logger.LogInformation($"Remote call party hungup {sipRequest.StatusLine}.");
m_sipDialogue.DialogueState = SIPDialogueStateEnum.Terminated;
SIPNonInviteTransaction byeTx = new SIPNonInviteTransaction(m_transport, sipRequest, null);
byeTx.SendResponse(SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null));
CallEnded(sipRequest.Header.CallId);
}
else if (sipRequest.Method == SIPMethodsEnum.INVITE)
{
logger.LogDebug($"Re-INVITE request received {sipRequest.StatusLine}.");
UASInviteTransaction reInviteTransaction = new UASInviteTransaction(m_transport, sipRequest, m_outboundProxy);
try
{
SDP offer = SDP.ParseSDPDescription(sipRequest.Body);
if (sipRequest.Header.CallId == _oldCallID)
{
// A transfer is in progress and this re-INVITE belongs to the original call. More than likely
// the purpose of the request is to place us on hold. We'll respond with OK but not update any local state.
var answerSdp = MediaSession.CreateAnswer(null);
var okResponse = reInviteTransaction.GetOkResponse(SDP.SDP_MIME_CONTENTTYPE, answerSdp.ToString());
reInviteTransaction.SendFinalResponse(okResponse);
}
else
{
var setRemoteResult = MediaSession.SetRemoteDescription(SdpType.offer, offer);
if (setRemoteResult != SetDescriptionResultEnum.OK)
{
logger.LogWarning($"Unable to set remote description from reINVITE request {setRemoteResult}");
var notAcceptableResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotAcceptable, setRemoteResult.ToString());
reInviteTransaction.SendFinalResponse(notAcceptableResponse);
}
else
{
CheckRemotePartyHoldCondition(MediaSession.RemoteDescription);
if (MediaSession.HasAudio)
{
MediaSession.SetMediaStreamStatus(SDPMediaTypesEnum.audio, GetStreamStatusForOnHoldState());
}
if (MediaSession.HasVideo)
{
MediaSession.SetMediaStreamStatus(SDPMediaTypesEnum.video, GetStreamStatusForOnHoldState());
}
var answerSdp = MediaSession.CreateAnswer(null);
m_sipDialogue.RemoteSDP = sipRequest.Body;
m_sipDialogue.SDP = answerSdp.ToString();
m_sipDialogue.RemoteCSeq = sipRequest.Header.CSeq;
var okResponse = reInviteTransaction.GetOkResponse(SDP.SDP_MIME_CONTENTTYPE, m_sipDialogue.SDP);
reInviteTransaction.SendFinalResponse(okResponse);
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "MediaSession can't process the re-INVITE request.");
if (OnReinviteRequest == null)