-
Notifications
You must be signed in to change notification settings - Fork 522
Expand file tree
/
Copy pathSIPClientUserAgent.cs
More file actions
676 lines (581 loc) · 34.3 KB
/
SIPClientUserAgent.cs
File metadata and controls
676 lines (581 loc) · 34.3 KB
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
//-----------------------------------------------------------------------------
// Filename: SIPClientUserAgent.cs
//
// Description: Implementation of a SIP Client User Agent that can be used to initiate SIP calls.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 22 Feb 2008 Aaron Clauson Created, Hobart, Australia.
// 30 Oct 2019 Aaron Clauson Added support for reliable provisional responses as per RFC3262.
// rj2: use CallID,BranchId from CallDescriptor in Call-method
// rj2: return SIPRequest in Call-method
//
// 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.Tasks;
using Microsoft.Extensions.Logging;
using SIPSorcery.Sys;
namespace SIPSorcery.SIP.App
{
public class SIPClientUserAgent : ISIPClientUserAgent
{
private const char OUTBOUNDPROXY_AS_ROUTESET_CHAR = '<'; // If this character exists in the call descriptor OutboundProxy setting it gets treated as a Route set.
private static ILogger logger = Log.Logger;
private SIPTransport m_sipTransport;
private SIPCallDescriptor m_sipCallDescriptor; // Describes the server leg of the call from the sipswitch.
private UACInviteTransaction m_serverTransaction;
private bool m_callCancelled; // It's possible for the call to be cancelled before the INVITE has been sent. This could occur if a DNS lookup on the server takes a while.
private bool m_hungupOnCancel; // Set to true if a call has been cancelled AND and then an OK response was received AND a BYE has been sent to hang it up. This variable is used to stop another BYE transaction being generated.
private int m_serverAuthAttempts; // Used to determine if credentials for a server leg call fail.
internal SIPNonInviteTransaction m_cancelTransaction; // If the server call is cancelled this transaction contains the CANCEL in case it needs to be resent.
internal SIPNonInviteTransaction m_byeTransaction; // If the server call is hungup this transaction contains the BYE in case it needs to be resent.
private SIPEndPoint m_outboundProxy; // If the system needs to use an outbound proxy for every request this will be set and overrides any user supplied values.
private SIPDialogue m_sipDialogue;
public event SIPCallResponseDelegate CallTrying;
public event SIPCallResponseDelegate CallRinging;
public event SIPCallResponseDelegate CallAnswered;
public event SIPCallFailedDelegate CallFailed;
public Func<SIPRequest, SIPRequest> AdjustInvite;
public UACInviteTransaction ServerTransaction
{
get { return m_serverTransaction; }
}
public bool IsUACAnswered
{
get { return m_serverTransaction.TransactionFinalResponse != null; }
}
public bool IsHangingUp => m_byeTransaction?.DeliveryPending ?? false;
public SIPDialogue SIPDialogue
{
get { return m_sipDialogue; }
}
public SIPCallDescriptor CallDescriptor
{
get { return m_sipCallDescriptor; }
}
/// <summary>
/// Determines whether the agent will operate with support for reliable provisional responses as per RFC3262.
/// If support is not desired it should be set to false before the initial INVITE request is sent.
/// </summary>
public bool PrackSupported { get; set; } = true;
/// <summary>
/// Creates a new SIP user agent client to act as the client on a SIP INVITE transaction.
/// </summary>
/// <param name="sipTransport">The SIP transport this user agent will use for sending and receiving SIP messages.</param>
public SIPClientUserAgent(SIPTransport sipTransport)
{
m_sipTransport = sipTransport;
}
public SIPClientUserAgent(
SIPTransport sipTransport,
SIPEndPoint outboundProxy)
{
m_sipTransport = sipTransport;
m_outboundProxy = outboundProxy?.CopyOf();
}
/// <summary>
/// Gets the destination of the remote SIP end point for this call.
/// </summary>
/// <param name="sipCallDescriptor">The call descriptor containing the settings to use to place the call.</param>
/// <returns>The server end point for the call.</returns>
public async Task<SIPEndPoint> GetCallDestination(SIPCallDescriptor sipCallDescriptor)
{
SIPURI callURI = SIPURI.ParseSIPURI(sipCallDescriptor.Uri);
SIPEndPoint serverEndPoint = null;
// If the outbound proxy is a loopback address, as it will normally be for local deployments, then it cannot be overriden.
if (m_outboundProxy != null && IPAddress.IsLoopback(m_outboundProxy.Address))
{
serverEndPoint = m_outboundProxy;
}
else if (!sipCallDescriptor.ProxySendFrom.IsNullOrBlank())
{
// If the binding has a specific proxy end point sent then the request needs to be forwarded to the proxy's default end point for it to take care of.
//SIPEndPoint outboundProxyEndPoint = SIPEndPoint.ParseSIPEndPoint(sipCallDescriptor.ProxySendFrom);
//m_outboundProxy = new SIPEndPoint(SIPProtocolsEnum.udp, outboundProxyEndPoint.Address, SIPConstants.DEFAULT_SIP_PORT);
//m_serverEndPoint = m_outboundProxy;
m_outboundProxy = SIPEndPoint.ParseSIPEndPoint(sipCallDescriptor.ProxySendFrom);
serverEndPoint = m_outboundProxy;
logger.LogDebug("SIPClientUserAgent Call using alternate outbound proxy of {ServerEndPoint}.", serverEndPoint);
}
else if (m_outboundProxy != null)
{
// Using the system outbound proxy only, no additional user routing requirements.
serverEndPoint = m_outboundProxy;
}
// No outbound proxy, determine the forward destination based on the SIP request.
if (serverEndPoint == null)
{
//SIPDNSLookupResult lookupResult = null;
SIPEndPoint lookupResult = null;
double lookupDurationMilliseconds = 0;
if (sipCallDescriptor.RouteSet != null && sipCallDescriptor.RouteSet.IndexOf(OUTBOUNDPROXY_AS_ROUTESET_CHAR) != -1)
{
var routeSet = new SIPRouteSet();
routeSet.PushRoute(new SIPRoute(sipCallDescriptor.RouteSet, true));
logger.LogDebug("Route set for call {RouteSet}.", routeSet.ToString());
//lookupResult = m_sipTransport.GetURIEndPoint(routeSet.TopRoute.URI, false);
lookupResult = await m_sipTransport.ResolveSIPUriAsync(routeSet.TopRoute.URI).ConfigureAwait(false);
}
else
{
logger.LogDebug("SIPClientUserAgent attempting to resolve {Host}.", callURI.Host);
//lookupResult = m_sipTransport.GetURIEndPoint(callURI, false);
DateTime lookupStartedAt = DateTime.Now;
lookupResult = await m_sipTransport.ResolveSIPUriAsync(callURI).ConfigureAwait(false);
lookupDurationMilliseconds = DateTime.Now.Subtract(lookupStartedAt).TotalMilliseconds;
}
if (lookupResult == null)
{
logger.LogDebug("SIPClientUserAgent DNS failure resolving {Host} in {Duration:0.##}ms. Call cannot proceed.", callURI.Host, lookupDurationMilliseconds);
}
else
{
logger.LogDebug("SIPClientUserAgent resolved {Host} to {Result} in {Duration:0.##}ms.", callURI.Host, lookupResult, lookupDurationMilliseconds);
serverEndPoint = lookupResult;
}
}
return serverEndPoint;
}
public SIPRequest Call(SIPCallDescriptor sipCallDescriptor)
{
return Call(sipCallDescriptor, null);
}
/// <summary>
/// Initiates the call to the remote user agent server.
/// </summary>
/// <param name="sipCallDescriptor">The descriptor for the call that describes how to reach the user agent server and other properties.</param>
/// <param name="serverEndPoint">Optional. If the server end point for the call is known or has been resolved in advance. If
/// not set the SIP transport layer will attempt to resolve the destination at sending time.</param>
public SIPRequest Call(SIPCallDescriptor sipCallDescriptor, SIPEndPoint serverEndPoint)
{
try
{
m_sipCallDescriptor = sipCallDescriptor;
SIPURI callURI = SIPURI.ParseSIPURI(sipCallDescriptor.Uri);
SIPRouteSet routeSet = null;
logger.LogDebug("UAC commencing call to {CanonicalAddress}.", SIPURI.ParseSIPURI(m_sipCallDescriptor.Uri).CanonicalAddress);
// A custom route set may have been specified for the call.
if (m_sipCallDescriptor.RouteSet != null && m_sipCallDescriptor.RouteSet.IndexOf(OUTBOUNDPROXY_AS_ROUTESET_CHAR) != -1)
{
try
{
routeSet = new SIPRouteSet();
routeSet.PushRoute(new SIPRoute(m_sipCallDescriptor.RouteSet, true));
}
catch
{
logger.LogDebug("Error an outbound proxy value was not recognised in SIPClientUserAgent Call. {RouteSet}.", m_sipCallDescriptor.RouteSet);
}
}
string content = sipCallDescriptor.Content;
bool sendOkAckManually = false;
if (content.IsNullOrBlank())
{
logger.LogDebug("Body on UAC call was empty.");
sendOkAckManually = true;
}
if (this.m_sipCallDescriptor.BranchId.IsNullOrBlank())
{
this.m_sipCallDescriptor.BranchId = CallProperties.CreateBranchId();
}
if (this.m_sipCallDescriptor.CallId.IsNullOrBlank())
{
this.m_sipCallDescriptor.CallId = CallProperties.CreateNewCallId();
}
SIPRequest inviteRequest = GetInviteRequest(m_sipCallDescriptor, m_sipCallDescriptor.BranchId, m_sipCallDescriptor.CallId, routeSet, content, sipCallDescriptor.ContentType);
// Now that we have a destination socket create a new UAC transaction for forwarded leg of the call.
m_serverTransaction = new UACInviteTransaction(m_sipTransport, inviteRequest, m_outboundProxy, sendOkAckManually);
m_serverTransaction.UACInviteTransactionInformationResponseReceived += ServerInformationResponseReceived;
m_serverTransaction.UACInviteTransactionFinalResponseReceived += ServerFinalResponseReceived;
m_serverTransaction.UACInviteTransactionFailed += ServerTransactionFailed;
m_serverTransaction.SendInviteRequest();
return inviteRequest;
}
catch (ApplicationException appExcp)
{
m_serverTransaction?.CancelCall(appExcp.Message);
CallFailed?.Invoke(this, appExcp.Message, null);
return null;
}
catch (Exception excp)
{
logger.LogError(excp, "Exception UserAgentClient Call. {ErrorMessage}", excp.Message);
m_serverTransaction?.CancelCall("Unknown exception");
CallFailed?.Invoke(this, excp.Message, null);
return null;
}
}
/// <summary>
/// Cancels an in progress call. This method should be called prior to the remote user agent server answering the call.
/// <param name="reason">The reason for canceling the call.</param>
/// </summary>
public void Cancel(string? reason = null)
{
try
{
m_callCancelled = true;
// Cancel server call.
if (m_serverTransaction == null)
{
logger.LogDebug("Cancelling forwarded call leg {Uri}, server transaction has not been created yet no CANCEL request required.", m_sipCallDescriptor.Uri);
}
else if (m_cancelTransaction != null)
{
if (m_cancelTransaction.TransactionState != SIPTransactionStatesEnum.Completed)
{
logger.LogDebug("Call {Uri} has already been cancelled once, trying again.", m_serverTransaction.TransactionRequest.URI.ToString());
m_cancelTransaction.SendRequest();
}
else
{
logger.LogDebug("Call {Uri} has already responded to CANCEL, probably overlap in messages not re-sending.", m_serverTransaction.TransactionRequest.URI.ToString());
}
}
else //if (m_serverTransaction.TransactionState == SIPTransactionStatesEnum.Proceeding || m_serverTransaction.TransactionState == SIPTransactionStatesEnum.Trying)
{
logger.LogDebug("Cancelling forwarded call leg, sending CANCEL to {URI}.", m_serverTransaction.TransactionRequest.URI.ToString());
// No response has been received from the server so no CANCEL request necessary, stop any retransmits of the INVITE.
m_serverTransaction.CancelCall();
SIPRequest cancelRequest = GetCancelRequest(m_serverTransaction.TransactionRequest);
// If auth header is included inside INVITE request, we re-include them inside CANCEL request
if (m_serverTransaction.TransactionRequest.Header.HasAuthenticationHeader)
{
string username = (m_sipCallDescriptor.AuthUsername == null || m_sipCallDescriptor.AuthUsername.Trim().Length <= 0 ? m_sipCallDescriptor.Username : m_sipCallDescriptor.AuthUsername);
SIPAuthorisationDigest authDigest = m_serverTransaction.TransactionRequest.Header.AuthenticationHeaders.First().SIPDigest;
authDigest.SetCredentials(username, m_sipCallDescriptor.Password, m_sipCallDescriptor.Uri, SIPMethodsEnum.CANCEL.ToString());
var authHeader = new SIPAuthenticationHeader(authDigest);
authHeader.SIPDigest.IncrementNonceCount();
authHeader.SIPDigest.Response = authDigest.GetDigest();
cancelRequest.Header.AuthenticationHeaders.Clear();
cancelRequest.Header.AuthenticationHeaders.Add(authHeader);
if (!string.IsNullOrEmpty(reason))
{
// The REASON header gets pre-appended automatically in the SIPHeader class as "Reason: " when ToString() is called on the SIP Header class.
cancelRequest.Header.Reason = reason;
}
}
m_cancelTransaction = new SIPNonInviteTransaction(m_sipTransport, cancelRequest, m_outboundProxy);
m_cancelTransaction.SendRequest();
}
CallFailed?.Invoke(this, "Call cancelled by user.", null);
}
catch (Exception excp)
{
logger.LogError(excp, "Exception CancelServerCall. {ErrorMessage}", excp.Message);
}
}
/// <summary>
/// Hangs up an answered call. This method should be called after the remote user agent server answered the call.
/// <param name="reason">The reason for hanging up the call.</param>
/// </summary>
public void Hangup(string? reason = null)
{
if (m_sipDialogue == null)
{
return;
}
try
{
//SIPRequest byeRequest = GetByeRequest(m_serverTransaction.TransactionFinalResponse, m_sipDialogue.RemoteTarget);
SIPRequest byeRequest = m_sipDialogue.GetInDialogRequest(SIPMethodsEnum.BYE);
byeRequest.SetSendFromHints(m_serverTransaction.TransactionRequest.LocalSIPEndPoint);
if (!string.IsNullOrEmpty(reason))
{
// The REASON header gets pre-appended automatically in the SIPHeader class as "Reason: " when ToString() is called on the SIP Header class.
byeRequest.Header.Reason = reason;
}
m_byeTransaction = new SIPNonInviteTransaction(m_sipTransport, byeRequest, m_outboundProxy);
m_byeTransaction.NonInviteTransactionFinalResponseReceived += ByeServerFinalResponseReceived;
m_byeTransaction.NonInviteTransactionFailed += (tx, reason) => logger.LogWarning("Bye request for {Uri} failed with {Reason}.", m_sipCallDescriptor.Uri, reason);
m_byeTransaction.SendRequest();
}
catch (Exception excp)
{
logger.LogError(excp, "Exception SIPClientUserAgent Hangup. {ErrorMessage}", excp.Message);
}
}
/// <summary>
/// Sends AckAnswer response.
/// </summary>
/// <param name="sipResponse">SIPResponse to acknowledge</param>
/// <param name="content">The optional content body for the ACK request.</param>
/// <param name="contentType">The optional content type.</param>
public void AckAnswer(SIPResponse sipResponse, string content, string contentType)
{
if (m_sipDialogue == null)
{
return;
}
m_serverTransaction.AckAnswer(sipResponse, content, contentType);
m_sipDialogue.SDP = content;
m_sipDialogue.DialogueState = SIPDialogueStateEnum.Confirmed;
}
private Task<SocketError> ServerFinalResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
{
try
{
logger.LogDebug("Response {StatusCode} {ReasonPhrase} for {URI}.", sipResponse.StatusCode, sipResponse.ReasonPhrase, m_serverTransaction.TransactionRequest.URI);
m_serverTransaction.UACInviteTransactionInformationResponseReceived -= ServerInformationResponseReceived;
m_serverTransaction.UACInviteTransactionFinalResponseReceived -= ServerFinalResponseReceived;
if (m_callCancelled && sipResponse.Status == SIPResponseStatusCodesEnum.RequestTerminated)
{
// No action required. Correctly received request terminated on an INVITE we cancelled.
}
else if (m_callCancelled)
{
#region Call has been cancelled, hangup.
if (m_hungupOnCancel)
{
logger.LogDebug("A cancelled call to {Uri} has been answered AND has already been hungup, no further action being taken.", m_sipCallDescriptor.Uri);
}
else
{
m_hungupOnCancel = true;
logger.LogDebug("A cancelled call to {Uri} has been answered, hanging up.", m_sipCallDescriptor.Uri);
if (sipResponse.Header.Contact != null && sipResponse.Header.Contact.Count > 0)
{
SIPURI byeURI = sipResponse.Header.Contact[0].ContactURI;
SIPRequest byeRequest = GetByeRequest(sipResponse, byeURI);
SIPNonInviteTransaction byeTransaction = new SIPNonInviteTransaction(m_sipTransport, byeRequest, m_outboundProxy);
byeTransaction.SendRequest();
}
else
{
logger.LogDebug("No contact header provided on response for cancelled call to {Uri} no further action.", m_sipCallDescriptor.Uri);
}
}
#endregion
}
else if (sipResponse.Status == SIPResponseStatusCodesEnum.ProxyAuthenticationRequired || sipResponse.Status == SIPResponseStatusCodesEnum.Unauthorised)
{
#region Authenticate client call to third party server.
if (!m_callCancelled)
{
if (m_sipCallDescriptor.Password.IsNullOrBlank())
{
// No point trying to authenticate if there is no password to use.
logger.LogDebug("Forward leg failed, authentication was requested but no credentials were available.");
CallFailed?.Invoke(this, "Authentication requested when no credentials available", sipResponse);
}
else if (m_serverAuthAttempts == 0)
{
m_serverAuthAttempts = 1;
// Resend INVITE with credentials.
string username = (m_sipCallDescriptor.AuthUsername != null && m_sipCallDescriptor.AuthUsername.Trim().Length > 0) ? m_sipCallDescriptor.AuthUsername : m_sipCallDescriptor.Username;
var authRequest = m_serverTransaction.TransactionRequest.DuplicateAndAuthenticate(sipResponse.Header.AuthenticationHeaders,
username, m_sipCallDescriptor.Password);
// Create a new UAC transaction to establish the authenticated server call.
m_serverTransaction = new UACInviteTransaction(m_sipTransport, authRequest, m_outboundProxy);
if (m_serverTransaction.CDR != null)
{
m_serverTransaction.CDR.Updated();
}
m_serverTransaction.UACInviteTransactionInformationResponseReceived += ServerInformationResponseReceived;
m_serverTransaction.UACInviteTransactionFinalResponseReceived += ServerFinalResponseReceived;
m_serverTransaction.UACInviteTransactionFailed += ServerTransactionFailed;
m_serverTransaction.SendInviteRequest();
}
else
{
CallFailed?.Invoke(this, "Authentication with provided credentials failed", sipResponse);
}
}
#endregion
}
else
{
if (sipResponse.StatusCode >= 200 && sipResponse.StatusCode <= 299)
{
m_sipDialogue = new SIPDialogue(m_serverTransaction);
m_sipDialogue.CallDurationLimit = m_sipCallDescriptor.CallDurationLimit;
}
CallAnswered?.Invoke(this, sipResponse);
}
return Task.FromResult(SocketError.Success);
}
catch (Exception excp)
{
logger.LogDebug(excp, "Exception ServerFinalResponseReceived. {ErrorMessage}", excp.Message);
return Task.FromResult(SocketError.Fault);
}
}
private Task<SocketError> ServerInformationResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
{
logger.LogDebug("Information response {StatusCode} {ReasonPhrase} for {URI}.", sipResponse.StatusCode, sipResponse.ReasonPhrase, m_serverTransaction.TransactionRequest.URI.ToString());
if (m_callCancelled)
{
// Call was cancelled in the interim.
Cancel();
}
else
{
if (sipResponse.Status == SIPResponseStatusCodesEnum.Ringing || sipResponse.Status == SIPResponseStatusCodesEnum.SessionProgress)
{
CallRinging?.Invoke(this, sipResponse);
}
else
{
CallTrying?.Invoke(this, sipResponse);
}
}
return Task.FromResult(SocketError.Success);
}
private void ServerTransactionFailed(SIPTransaction sipTransaction, SocketError failureReason)
{
if (!m_callCancelled)
{
CallFailed?.Invoke(this, failureReason.ToString(), null);
}
}
public Task<SocketError> SendNonInviteRequest(SIPRequest sipRequest)
{
try
{
SIPNonInviteTransaction nonInvteTransaction = new SIPNonInviteTransaction(m_sipTransport, sipRequest, m_outboundProxy);
nonInvteTransaction.SendRequest();
return Task.FromResult(SocketError.Success);
}
catch (Exception excp)
{
logger.LogError(excp, "Exception SendNonInviteRequest. {ErrorMessage}", excp.Message);
return Task.FromResult(SocketError.Fault);
}
}
private Task<SocketError> ByeServerFinalResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
{
try
{
logger.LogDebug("Response {StatusCode} {ReasonPhrase} for {URI}.", sipResponse.StatusCode, sipResponse.ReasonPhrase, sipTransaction.TransactionRequest.URI.ToString());
SIPNonInviteTransaction transaction = sipTransaction as SIPNonInviteTransaction;
transaction.NonInviteTransactionFinalResponseReceived -= ByeServerFinalResponseReceived;
if (sipResponse.Status == SIPResponseStatusCodesEnum.ProxyAuthenticationRequired || sipResponse.Status == SIPResponseStatusCodesEnum.Unauthorised)
{
string username = (m_sipCallDescriptor.AuthUsername == null || m_sipCallDescriptor.AuthUsername.Trim().Length <= 0 ? m_sipCallDescriptor.Username : m_sipCallDescriptor.AuthUsername);
var authRequest = transaction.TransactionRequest.DuplicateAndAuthenticate(sipResponse.Header.AuthenticationHeaders,
username, m_sipCallDescriptor.Password);
SIPNonInviteTransaction authByeTransaction = new SIPNonInviteTransaction(m_sipTransport, authRequest, m_outboundProxy);
authByeTransaction.NonInviteTransactionFailed += (tx, reason) => logger.LogWarning("Authenticated Bye request for {Uri} failed with {Reason}.", m_sipCallDescriptor.Uri, reason);
authByeTransaction.SendRequest();
}
return Task.FromResult(SocketError.Success);
}
catch (Exception excp)
{
logger.LogError(excp, "Exception ByServerFinalResponseReceived. {ErrorMessage}", excp.Message);
return Task.FromResult(SocketError.Fault);
}
}
private SIPRequest GetInviteRequest(SIPCallDescriptor sipCallDescriptor, string branchId, string callId, SIPRouteSet routeSet, string content, string contentType)
{
SIPRequest inviteRequest = new SIPRequest(SIPMethodsEnum.INVITE, sipCallDescriptor.Uri);
SIPHeader inviteHeader = new SIPHeader(sipCallDescriptor.GetFromHeader(), SIPToHeader.ParseToHeader(sipCallDescriptor.To), 1, callId);
inviteHeader.From.FromTag = CallProperties.CreateNewTag();
inviteHeader.Contact = new List<SIPContactHeader>() { SIPContactHeader.GetDefaultSIPContactHeader(inviteRequest.URI.Scheme) };
inviteHeader.Contact[0].ContactURI.User = sipCallDescriptor.Username;
inviteHeader.CSeqMethod = SIPMethodsEnum.INVITE;
inviteHeader.UserAgent = SIPConstants.SipUserAgentVersionString;
inviteHeader.Routes = routeSet;
inviteHeader.Supported = SIPExtensionHeaders.REPLACES + ", " + SIPExtensionHeaders.NO_REFER_SUB
+ (PrackSupported ? ", " + SIPExtensionHeaders.PRACK : "");
inviteRequest.Header = inviteHeader;
if (!sipCallDescriptor.ProxySendFrom.IsNullOrBlank())
{
inviteHeader.ProxySendFrom = sipCallDescriptor.ProxySendFrom;
}
SIPViaHeader viaHeader = new SIPViaHeader(new IPEndPoint(IPAddress.Any, 0), branchId);
inviteRequest.Header.Vias.PushViaHeader(viaHeader);
inviteRequest.Body = content;
inviteRequest.Header.ContentLength = (inviteRequest.Body != null) ? inviteRequest.Body.Length : 0;
inviteRequest.Header.ContentType = contentType;
try
{
if (sipCallDescriptor.CustomHeaders != null && sipCallDescriptor.CustomHeaders.Count > 0)
{
foreach (string customHeader in sipCallDescriptor.CustomHeaders)
{
if (customHeader.IsNullOrBlank())
{
continue;
}
else if (customHeader.Trim().StartsWith(SIPHeaders.SIP_HEADER_USERAGENT))
{
inviteRequest.Header.UserAgent = customHeader.Substring(customHeader.IndexOf(":") + 1).Trim();
}
else if (customHeader.Trim().StartsWith(SIPHeaders.SIP_HEADER_TO + ":"))
{
var customToHeader = SIPUserField.ParseSIPUserField(customHeader.Substring(customHeader.IndexOf(":") + 1).Trim());
if (customToHeader != null)
{
inviteRequest.Header.To.ToUserField = customToHeader;
}
}
else
{
inviteRequest.Header.UnknownHeaders.Add(customHeader);
}
}
}
}
catch (Exception excp)
{
logger.LogError("Exception Parsing CustomHeader for GetInviteRequest. {ErrorMessage} {CustomHeaders}", excp.Message, sipCallDescriptor.CustomHeaders);
}
if (AdjustInvite != null)
{
inviteRequest = AdjustInvite(inviteRequest);
}
return inviteRequest;
}
private SIPRequest GetCancelRequest(SIPRequest inviteRequest)
{
SIPRequest cancelRequest = new SIPRequest(SIPMethodsEnum.CANCEL, inviteRequest.URI);
cancelRequest.SetSendFromHints(inviteRequest.LocalSIPEndPoint);
SIPHeader inviteHeader = inviteRequest.Header;
SIPHeader cancelHeader = new SIPHeader(inviteHeader.From, inviteHeader.To, inviteHeader.CSeq, inviteHeader.CallId);
cancelRequest.Header = cancelHeader;
cancelHeader.CSeqMethod = SIPMethodsEnum.CANCEL;
cancelHeader.Routes = inviteHeader.Routes;
cancelHeader.ProxySendFrom = inviteHeader.ProxySendFrom;
cancelHeader.Vias = inviteHeader.Vias;
return cancelRequest;
}
private SIPRequest GetByeRequest(SIPResponse inviteResponse, SIPURI byeURI)
{
SIPRequest byeRequest = new SIPRequest(SIPMethodsEnum.BYE, byeURI);
byeRequest.SetSendFromHints(inviteResponse.LocalSIPEndPoint);
SIPFromHeader byeFromHeader = inviteResponse.Header.From;
SIPToHeader byeToHeader = inviteResponse.Header.To;
int cseq = inviteResponse.Header.CSeq + 1;
SIPHeader byeHeader = new SIPHeader(byeFromHeader, byeToHeader, cseq, inviteResponse.Header.CallId);
byeHeader.CSeqMethod = SIPMethodsEnum.BYE;
byeHeader.ProxySendFrom = m_serverTransaction.TransactionRequest.Header.ProxySendFrom;
byeRequest.Header = byeHeader;
byeRequest.Header.Routes = (inviteResponse.Header.RecordRoutes != null) ? inviteResponse.Header.RecordRoutes.Reversed() : null;
byeRequest.Header.Vias.PushViaHeader(SIPViaHeader.GetDefaultSIPViaHeader());
return byeRequest;
}
private SIPRequest GetUpdateRequest(SIPRequest inviteRequest, CRMHeaders crmHeaders)
{
SIPRequest updateRequest = new SIPRequest(SIPMethodsEnum.UPDATE, inviteRequest.URI);
updateRequest.SetSendFromHints(inviteRequest.LocalSIPEndPoint);
SIPHeader inviteHeader = inviteRequest.Header;
SIPHeader updateHeader = new SIPHeader(inviteHeader.From, inviteHeader.To, inviteHeader.CSeq + 1, inviteHeader.CallId);
inviteRequest.Header.CSeq++;
updateRequest.Header = updateHeader;
updateHeader.CSeqMethod = SIPMethodsEnum.UPDATE;
updateHeader.Routes = inviteHeader.Routes;
updateHeader.ProxySendFrom = inviteHeader.ProxySendFrom;
SIPViaHeader viaHeader = new SIPViaHeader(new IPEndPoint(IPAddress.Any, 0), CallProperties.CreateBranchId());
updateHeader.Vias.PushViaHeader(viaHeader);
return updateRequest;
}
}
}