public ManualResetEvent DelayMRE; // If the call needs to be delayed DelaySeconds this MRE will be used. /// <summary> /// /// </summary> /// <param name="toSIPAccount"></param> /// <param name="uri">The uri can be different to the to SIP account if a dotted notation is used. For /// example [email protected].</param> /// <param name="fromHeader"></param> /// <param name="contentType"></param> /// <param name="content"></param> public SIPCallDescriptor(SIPAccount toSIPAccount, string uri, string fromHeader, string contentType, string content) { ToSIPAccount = toSIPAccount; Uri = uri ?? toSIPAccount.SIPUsername + "@" + toSIPAccount.SIPDomain; From = fromHeader; ContentType = contentType; Content = content; }
public bool LoadSIPAccountForIncomingCall() { try { bool loaded = false; if (GetSIPAccount_External == null) { // No point trying to authenticate if we haven't been given a delegate to load the SIP account. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else { m_sipAccount = GetSIPAccount_External(m_sipUsername, m_sipDomain); if (m_sipAccount == null) { // A full lookup failed. Now try a partial lookup if the incoming username is in a dotted domain name format. if (m_sipUsername.Contains(".")) { string sipUsernameSuffix = m_sipUsername.Substring(m_sipUsername.LastIndexOf(".") + 1); m_sipAccount = GetSIPAccount_External(sipUsernameSuffix, m_sipDomain); } if (m_sipAccount == null) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Rejecting public call for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found.", null)); Reject(SIPResponseStatusCodesEnum.NotFound, null, null); } else { loaded = true; } } else { loaded = true; } } if (loaded) { SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId); } return(loaded); } catch (Exception excp) { logger.LogError("Exception LoadSIPAccountForIncomingCall. " + excp.Message); Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); return(false); } }
/// <summary></summary> /// <param name="uacRecvdEndPoint">If this is non-null it indicates the contact header should be mangled based on the public socket the register request was demmed /// to have originated from rather then relying on the contact value recieved from the uac.</param> public SIPRegistrarBinding( SIPAccount sipAccount, SIPURI bindingURI, string callId, int cseq, string userAgent, SIPEndPoint remoteSIPEndPoint, SIPEndPoint proxySIPEndPoint, SIPEndPoint registrarSIPEndPoint, int expiry) { Id = Guid.NewGuid(); LastUpdate = DateTime.UtcNow; SIPAccountId = sipAccount.Id; SIPAccountName = sipAccount.SIPUsername + "@" + sipAccount.SIPDomain; Owner = sipAccount.Owner; AdminMemberId = sipAccount.AdminMemberId; m_contactURI = bindingURI.CopyOf(); m_mangledContactURI = m_contactURI.CopyOf(); CallId = callId; CSeq = cseq; UserAgent = userAgent; RemoteSIPEndPoint = remoteSIPEndPoint; m_proxySIPEndPoint = proxySIPEndPoint; m_registrarSIPEndPoint = registrarSIPEndPoint; //if (SIPTransport.IsPrivateAddress(sipRequest.Header.Contact[0].ContactURI.Host) && m_mangleUACContact) if (!sipAccount.DontMangleEnabled && Regex.Match(m_mangledContactURI.Host, @"(\d+\.){3}\d+").Success) { // The Contact URI Host is used by registrars as the contact socket for the user so it needs to be changed to reflect the socket // the intial request was received on in order to work around NAT. It's no good just relying on private addresses as a lot of User Agents // determine their public IP but NOT their public port so they send the wrong port in the Contact header. //logger.Debug("Mangling contact header from " + m_mangledContactURI.Host + " to " + IPSocket.GetSocketString(uacRecvdEndPoint) + "."); m_mangledContactURI.Host = remoteSIPEndPoint.GetIPEndPoint().ToString(); } m_expiry = expiry; }
public SIPAccountDetailsControl( DetailsControlModesEnum mode, SIPAccount sipAccount, string owner, SIPAccountUpdateDelegate add, SIPAccountUpdateDelegate update, ControlClosedDelegate closed, GetDialPlanNamesDelegate getDialPlanNames, GetSIPDomainsDelegate getSIPDomains) { InitializeComponent(); m_detailsMode = mode; m_owner = owner; m_sipAccount = sipAccount; AddSIPAccount_External = add; UpdateSIPAccount_External = update; Closed_External = closed; GetDialPlanNames_External = getDialPlanNames; GetSIPDomains_External = getSIPDomains; if (m_detailsMode == DetailsControlModesEnum.Edit) { PopulateDataFields(m_sipAccount); } else { m_sipAccountUpdateButton.Content = "Add"; m_sipAccountIdCanvas.Visibility = Visibility.Collapsed; m_statusDisabledRadio.Visibility = Visibility.Collapsed; m_statusAdminDisabledRadio.Visibility = Visibility.Collapsed; UIHelper.SetText(m_sipAccountOwner, m_owner); SetDomainNames(null); SetDialPlanNames(null); } }
public override void DeleteSIPAccount(SIPAccount sipAccount) { m_provisioningServiceProxy.DeleteSIPAccountAsync(sipAccount); }
public abstract void DeleteSIPAccount(SIPAccount sipAccount);
private void AddNATKeepAliveJob(SIPAccount sipAccount, SIPEndPoint remoteSIPEndPoint, SIPEndPoint proxySIPEndPoint, SIPRegistrarBinding binding, int bindingExpiry) { try { lock (m_natKeepAliveJobs) { if (m_natKeepAliveJobs.ContainsKey(binding.RemoteSIPSocket)) { //logger.Debug("Updating NAT keep-alive job for binding socket " + binding.RemoteSIPSocket + "."); m_natKeepAliveJobs[binding.RemoteSIPSocket].Update(proxySIPEndPoint, DateTime.Now.AddSeconds(bindingExpiry)); } else { //logger.Debug("Adding NAT keep-alive job for binding socket " + binding.RemoteSIPSocket + "."); m_natKeepAliveJobs.Add(binding.RemoteSIPSocket, new NATKeepAliveJob(proxySIPEndPoint, remoteSIPEndPoint, DateTime.Now.AddSeconds(bindingExpiry), sipAccount.Owner)); } } } catch (Exception natAddExcp) { logger.Error("Exception AddNATKeepAliveJob for SIP account " + sipAccount.SIPUsername + ". " + natAddExcp.Message); } }
public static string ValidateAndClean(SIPAccount sipAccount) { if (sipAccount.Owner.IsNullOrBlank()) { return "The owner must be specified when creating a new SIP account."; } if (sipAccount.SIPUsername.IsNullOrBlank()) { return "The username must be specified when creating a new SIP account."; } if (sipAccount.SIPDomain.IsNullOrBlank()) { return "The domain must be specified when creating a new SIP account."; } else if (sipAccount.SIPUsername.Length < USERNAME_MIN_LENGTH) { return "The username must be at least " + USERNAME_MIN_LENGTH + " characters long."; } else if (Regex.Match(sipAccount.SIPUsername, BANNED_SIPACCOUNT_NAMES).Success) { return "The username you have requested is not permitted."; } else if (Regex.Match(sipAccount.SIPUsername, "[^" + USERNAME_ALLOWED_CHARS + "]").Success) { return "The username had an invalid character, characters permitted are alpha-numeric and .-_."; } else if (sipAccount.SIPUsername.Contains(".") && (sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim().Length >= USERNAME_MIN_LENGTH && sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() != sipAccount.Owner)) { return "You are not permitted to create this username. Only user " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() + " can create SIP accounts ending in " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".")).Trim() + "."; } else if (!sipAccount.IsIncomingOnly || !sipAccount.SIPPassword.IsNullOrBlank()) { if (sipAccount.SIPPassword.IsNullOrBlank()) { return "A password must be specified."; } else if (sipAccount.SIPPassword.Length < PASSWORD_MIN_LENGTH || sipAccount.SIPPassword.Length > PASSWORD_MAX_LENGTH) { return "The password field must be at least " + PASSWORD_MIN_LENGTH + " characters and no more than " + PASSWORD_MAX_LENGTH + " characters."; } else { #region Check the password illegal characters. char[] passwordChars = sipAccount.SIPPassword.ToCharArray(); bool illegalCharFound = false; char illegalChar = ' '; foreach (char passwordChar in passwordChars) { if (Regex.Match(passwordChar.ToString(), "[a-zA-Z0-9]").Success) { continue; } else { bool validChar = false; foreach (char allowedChar in NONAPLPHANUM_ALLOWED_PASSWORD_CHARS) { if (allowedChar == passwordChar) { validChar = true; break; } } if (validChar) { continue; } else { illegalCharFound = true; illegalChar = passwordChar; break; } } } #endregion if (illegalCharFound) { return "Your password has an invalid character " + illegalChar + " it can only contain a to Z, 0 to 9 and characters in this set " + SafeXML.MakeSafeXML(new String(NONAPLPHANUM_ALLOWED_PASSWORD_CHARS)) + "."; } } } sipAccount.Owner = sipAccount.Owner.Trim(); sipAccount.SIPUsername = sipAccount.SIPUsername.Trim(); sipAccount.SIPPassword = (sipAccount.SIPPassword.IsNullOrBlank()) ? null : sipAccount.SIPPassword.Trim(); sipAccount.SIPDomain = sipAccount.SIPDomain.Trim(); return null; }
/// <summary> /// Authenticates a SIP request. /// </summary> public static SIPRequestAuthenticationResult AuthenticateSIPRequest(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest, SIPAccount sipAccount, SIPMonitorLogDelegate logSIPMonitorEvent) { try { if (sipAccount == null) { return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null); } else if (sipAccount.IsDisabled) { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " is disabled for " + sipRequest.Method + ".", sipAccount.Owner)); } return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null); } else { SIPAuthenticationHeader reqAuthHeader = sipRequest.Header.AuthenticationHeader; if (reqAuthHeader == null) { // Check for IP address authentication. if (!sipAccount.IPAddressACL.IsNullOrBlank()) { SIPEndPoint uaEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : remoteEndPoint; if (Regex.Match(uaEndPoint.GetIPEndPoint().ToString(), sipAccount.IPAddressACL).Success) { // Successfully authenticated return new SIPRequestAuthenticationResult(true, true); } } SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce()); return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader); } else { // Check for IP address authentication. if (!sipAccount.IPAddressACL.IsNullOrBlank()) { SIPEndPoint uaEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : remoteEndPoint; if (Regex.Match(uaEndPoint.GetIPEndPoint().ToString(), sipAccount.IPAddressACL).Success) { // Successfully authenticated return new SIPRequestAuthenticationResult(true, true); } } string requestNonce = reqAuthHeader.SIPDigest.Nonce; string uri = reqAuthHeader.SIPDigest.URI; string response = reqAuthHeader.SIPDigest.Response; // Check for stale nonces. if (IsNonceStale(requestNonce)) { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Warn, "Authentication failed stale nonce for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".", null)); } SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce()); return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader); } else { SIPAuthorisationDigest checkAuthReq = reqAuthHeader.SIPDigest; checkAuthReq.SetCredentials(sipAccount.SIPUsername, sipAccount.SIPPassword, uri, sipRequest.Method.ToString()); string digest = checkAuthReq.Digest; if (digest == response) { // Successfully authenticated return new SIPRequestAuthenticationResult(true, false); } else { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Warn, "Authentication token check failed for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".", sipAccount.Owner)); } SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce()); return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader); } } } } } catch (Exception excp) { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Error, "Exception AuthoriseSIPRequest. " + excp.Message, null)); } return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.InternalServerError, null); } }
/// <summary> /// Authenticates a SIP request. /// </summary> public static SIPRequestAuthenticationResult AuthenticateSIPRequest(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest, SIPAccount sipAccount, SIPMonitorLogDelegate logSIPMonitorEvent) { try { if (sipAccount == null) { return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null)); } else if (sipAccount.IsDisabled) { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " is disabled for " + sipRequest.Method + ".", sipAccount.Owner)); } return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null)); } else { SIPAuthenticationHeader reqAuthHeader = sipRequest.Header.AuthenticationHeader; if (reqAuthHeader == null) { // Check for IP address authentication. if (!sipAccount.IPAddressACL.IsNullOrBlank()) { SIPEndPoint uaEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : remoteEndPoint; if (Regex.Match(uaEndPoint.GetIPEndPoint().ToString(), sipAccount.IPAddressACL).Success) { // Successfully authenticated return(new SIPRequestAuthenticationResult(true, true)); } } SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce()); return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader)); } else { // Check for IP address authentication. if (!sipAccount.IPAddressACL.IsNullOrBlank()) { SIPEndPoint uaEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : remoteEndPoint; if (Regex.Match(uaEndPoint.GetIPEndPoint().ToString(), sipAccount.IPAddressACL).Success) { // Successfully authenticated return(new SIPRequestAuthenticationResult(true, true)); } } string requestNonce = reqAuthHeader.SIPDigest.Nonce; string uri = reqAuthHeader.SIPDigest.URI; string response = reqAuthHeader.SIPDigest.Response; // Check for stale nonces. if (IsNonceStale(requestNonce)) { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Warn, "Authentication failed stale nonce for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".", null)); } SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce()); return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader)); } else { SIPAuthorisationDigest checkAuthReq = reqAuthHeader.SIPDigest; checkAuthReq.SetCredentials(sipAccount.SIPUsername, sipAccount.SIPPassword, uri, sipRequest.Method.ToString()); string digest = checkAuthReq.Digest; if (digest == response) { // Successfully authenticated return(new SIPRequestAuthenticationResult(true, false)); } else { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Warn, "Authentication token check failed for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".", sipAccount.Owner)); } SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce()); return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader)); } } } } } catch (Exception excp) { if (logSIPMonitorEvent != null) { logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Error, "Exception AuthoriseSIPRequest. " + excp.Message, null)); } return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.InternalServerError, null)); } }
public SIPAccount DeleteSIPAccount(SIPAccount sipAccount) { Customer customer = AuthoriseRequest(); if (customer.AdminId != Customer.TOPLEVEL_ADMIN_ID && sipAccount.Owner != customer.CustomerUsername) { throw new ApplicationException("You are not authorised to delete the SIP Account."); } SIPAccountPersistor.Delete(sipAccount); // Enables the caller to see which SIP account has been deleted. return sipAccount; }
private void SIPAccountsAssetViewer_Add() { m_selectedSIPAccount = null; m_addControl = new SIPAccountDetailsControl(DetailsControlModesEnum.Add, null, m_owner, SIPAccountAdd, null, DetailsControlClosed, GetDialPlanNames_External, GetSIPDomains); m_sipAccountsPanel.SetDetailsElement(m_addControl); }
private void SIPAccountUpdate(SIPAccount sipAccount) { //LogActivityMessage_External(MessageLevelsEnum.Info, "Attempting to update " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + "."); m_persistor.UpdateSIPAccount(sipAccount); }
private void SIPAccountAdd(SIPAccount sipAccount) { m_persistor.AddSIPAccountAsync(sipAccount); }
public ManualResetEvent DelayMRE; // If the call needs to be delayed DelaySeconds this MRE will be used. /// <summary> /// /// </summary> /// <param name="toSIPAccount"></param> /// <param name="uri">The uri can be different to the to SIP account if a dotted notation is used. For /// example [email protected].</param> /// <param name="fromHeader"></param> /// <param name="contentType"></param> /// <param name="content"></param> public SIPCallDescriptor(SIPAccount toSIPAccount, string uri, string fromHeader, string contentType, string content) { ToSIPAccount = toSIPAccount; Uri = uri ?? toSIPAccount.SIPUsername + "@" + toSIPAccount.SIPDomain; From = fromHeader; ContentType = contentType; Content = content; }
private void PopulateDataFields(SIPAccount sipAccount) { m_outDialPlan.Visibility = Visibility.Collapsed; m_inDialPlan.Visibility = Visibility.Collapsed; m_domainNames.Visibility = Visibility.Collapsed; m_sipAccountUsername.Visibility = Visibility.Collapsed; if (sipAccount.IsAdminDisabled) { WriteStatusMessage(MessageLevelsEnum.Warn, "SIP Account has been disabled by administrator. " + sipAccount.AdminDisabledReason); m_sipAccountPassword.IsEnabled = false; m_keepAlivesCheckBox.IsEnabled = false; m_statusAdminDisabledRadio.IsEnabled = true; m_statusAdminDisabledRadio.IsChecked = true; m_statusAdminDisabledRadio.IsEnabled = false; m_statusStandardRadio.IsEnabled = false; m_statusIncomingOnlyRadio.IsEnabled = false; m_statusDisabledRadio.IsEnabled = false; m_outDialPlan.IsEnabled = false; m_inDialPlan.IsEnabled = false; m_sipAccountUpdateButton.IsEnabled = false; m_sipAccountOutDialPlanStatus.Text = (m_sipAccount.OutDialPlanName != null) ? m_sipAccount.OutDialPlanName : "-"; m_sipAccountInDialPlanStatus.Text = (m_sipAccount.InDialPlanName != null) ? m_sipAccount.InDialPlanName : "-"; m_sipAccountNetworkId.IsEnabled = false; m_sipAccountIPAddressACL.IsEnabled = false; m_isSwitchboardEnabledCheckBox.IsEnabled = false; } else { if (sipAccount.Owner == m_owner) { //ThreadPool.QueueUserWorkItem(new WaitCallback(SetDialPlanNames), null); SetDialPlanNames(null); } else { // Don't have a list of dial plan names for non-owned SIP accounts so just display the dial plan names. m_sipAccountOutDialPlanStatus.Text = (m_sipAccount.OutDialPlanName != null) ? m_sipAccount.OutDialPlanName : "-"; m_sipAccountInDialPlanStatus.Text = (m_sipAccount.InDialPlanName != null) ? m_sipAccount.InDialPlanName : "-"; } if (sipAccount.IsDisabled) { m_statusDisabledRadio.IsChecked = true; } else if (sipAccount.IsIncomingOnly) { m_statusIncomingOnlyRadio.IsChecked = true; } } m_sipAccountId.Text = sipAccount.Id.ToString(); m_sipAccountOwner.Text = sipAccount.Owner; m_sipAccountUsernameText.Text = sipAccount.SIPUsername; m_sipAccountPassword.Text = sipAccount.SIPPassword; m_sipAccountDomain.Text = sipAccount.SIPDomain; m_keepAlivesCheckBox.IsChecked = sipAccount.SendNATKeepAlives; m_sipAccountNetworkId.Text = (sipAccount.NetworkId != null) ? sipAccount.NetworkId : String.Empty; m_sipAccountIPAddressACL.Text = (sipAccount.IPAddressACL != null) ? sipAccount.IPAddressACL : String.Empty; m_isSwitchboardEnabledCheckBox.IsChecked = sipAccount.IsSwitchboardEnabled; }
private void Add() { try { string username = m_sipAccountUsername.Text.Trim(); string password = m_sipAccountPassword.Text.Trim(); string domain = m_domainNames.SelectedItem as string; string outDialPlan = m_outDialPlan.SelectedItem as string; string inDialPlan = (m_inDialPlan.SelectedIndex != -1) ? m_inDialPlan.SelectedItem as string : null; string networkId = m_sipAccountNetworkId.Text.Trim(); string ipAddressACL = m_sipAccountIPAddressACL.Text.Trim(); bool sendKeepAlives = m_keepAlivesCheckBox.IsChecked.Value; bool isIncomingOnly = m_statusIncomingOnlyRadio.IsChecked.Value; bool isSwitchboardEnabled = m_isSwitchboardEnabledCheckBox.IsChecked.Value; SIPAccount sipAccount = new SIPAccount(m_owner, domain, username, password, outDialPlan); sipAccount.InDialPlanName = inDialPlan; sipAccount.SendNATKeepAlives = sendKeepAlives; sipAccount.IsIncomingOnly = isIncomingOnly; sipAccount.NetworkId = networkId; sipAccount.IPAddressACL = ipAddressACL; sipAccount.Inserted = DateTime.UtcNow; string validationError = SIPAccount.ValidateAndClean(sipAccount); if (validationError != null) { WriteStatusMessage(MessageLevelsEnum.Warn, validationError); } else { WriteStatusMessage(MessageLevelsEnum.Info, "Adding SIP Account please wait..."); AddSIPAccount_External(sipAccount); } } catch (Exception excp) { WriteStatusMessage(MessageLevelsEnum.Error, "Add SIPAccount Exception. " + excp.Message); } }
public SIPAccount AddSIPAccount(SIPAccount sipAccount) { Customer customer = AuthoriseRequest(); sipAccount.Owner = customer.CustomerUsername; string validationError = SIPAccount.ValidateAndClean(sipAccount); if (validationError != null) { logger.Warn("Validation error in AddSIPAccount for customer " + customer.CustomerUsername + ". " + validationError); throw new ApplicationException(validationError); } else { return SIPAccountPersistor.Add(sipAccount); } }
private void SIPAccountsDataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { try { if (m_initialLoadComplete && !m_sipAccountLoadInProgress && m_sipAccounts.Count > 0) { DataGrid dataGrid = (DataGrid)sender; if (dataGrid.CurrentColumn.Header as string != "Delete") { SIPAccount sipAccount = (SIPAccount)m_sipAccountsDataGrid.SelectedItem; if (m_selectedSIPAccount == null || m_selectedSIPAccount != sipAccount) { m_selectedSIPAccount = sipAccount; m_editControl = new SIPAccountDetailsControl(DetailsControlModesEnum.Edit, sipAccount, m_owner, null, SIPAccountUpdate, DetailsControlClosed, GetDialPlanNames_External, GetSIPDomains); m_sipAccountsPanel.SetDetailsElement(m_editControl); } } } } catch (Exception excp) { LogActivityMessage_External(MessageLevelsEnum.Error, "Exception showing SIP account details. " + excp.Message); m_selectedSIPAccount = null; } }
public void CreateCustomer(Customer customer) { try { // Check whether the number of customers is within the allowed limit. if (m_newCustomersAllowedLimit != 0 && CRMCustomerPersistor.Count(null) >= m_newCustomersAllowedLimit) { throw new ApplicationException("Sorry new account creations are currently disabled. Please monitor sipsorcery.wordpress.com for updates."); } else { // Check whether the username is already taken. customer.CustomerUsername = customer.CustomerUsername.ToLower(); Customer existingCustomer = CRMCustomerPersistor.Get(c => c.CustomerUsername == customer.CustomerUsername); if (existingCustomer != null) { throw new ApplicationException("The requested username is already in use please try a different one."); } // Check whether the email address is already taken. customer.EmailAddress = customer.EmailAddress.ToLower(); existingCustomer = CRMCustomerPersistor.Get(c => c.EmailAddress == customer.EmailAddress); if (existingCustomer != null) { throw new ApplicationException("The email address is already associated with an account."); } string validationError = Customer.ValidateAndClean(customer); if (validationError != null) { throw new ApplicationException(validationError); } customer.MaxExecutionCount = Customer.DEFAULT_MAXIMUM_EXECUTION_COUNT; CRMCustomerPersistor.Add(customer); logger.Debug("New customer record added for " + customer.CustomerUsername + "."); // Create a default dialplan. SIPDialPlan defaultDialPlan = new SIPDialPlan(customer.CustomerUsername, "default", null, "sys.Log(\"hello world\")\n", SIPDialPlanScriptTypesEnum.Ruby); DialPlanPersistor.Add(defaultDialPlan); logger.Debug("Default dialplan added for " + customer.CustomerUsername + "."); // Get default domain name. string defaultDomain = SIPDomainManager.GetDomain("local", true); // Create SIP account. if (SIPAccountPersistor.Get(s => s.SIPUsername == customer.CustomerUsername && s.SIPDomain == defaultDomain) == null) { SIPAccount sipAccount = new SIPAccount(customer.CustomerUsername, defaultDomain, customer.CustomerUsername, customer.CustomerPassword, "default"); SIPAccountPersistor.Add(sipAccount); logger.Debug("SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " added for " + sipAccount.Owner + "."); } else { int attempts = 0; while (attempts < 10) { string testUsername = customer.CustomerUsername + Crypto.GetRandomString(4); if (SIPAccountPersistor.Get(s => s.SIPUsername == testUsername && s.SIPDomain == defaultDomain) == null) { SIPAccount sipAccount = new SIPAccount(customer.CustomerUsername, defaultDomain, testUsername, customer.CustomerPassword, "default"); SIPAccountPersistor.Add(sipAccount); logger.Debug("SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " added for " + sipAccount.Owner + "."); break; } else { attempts++; } } } logger.Debug("Sending new account confirmation email to " + customer.EmailAddress + "."); Email.SendEmail(customer.EmailAddress, NEW_ACCOUNT_EMAIL_FROM_ADDRESS, NEW_ACCOUNT_EMAIL_SUBJECT, String.Format(NEW_ACCOUNT_EMAIL_BODY, customer.FirstName, customer.Id)); } } catch (Exception excp) { logger.Error("Exception CreateNewCustomer. " + excp.Message); throw; } }
private void DetailsControlClosed() { m_selectedSIPAccount = null; m_sipAccountsPanel.CloseDetailsPane(); }
public SIPAccount UpdateSIPAccount(SIPAccount sipAccount) { Customer customer = AuthoriseRequest(); if (customer.AdminId != Customer.TOPLEVEL_ADMIN_ID && sipAccount.Owner != customer.CustomerUsername) { logger.Debug("Unauthorised attempt to update SIP account by user="******", on account owned by=" + sipAccount.Owner + "."); throw new ApplicationException("You are not authorised to update the SIP Account."); } string validationError = SIPAccount.ValidateAndClean(sipAccount); if (validationError != null) { logger.Warn("Validation error in UpdateSIPAccount for customer " + customer.CustomerUsername + ". " + validationError); throw new ApplicationException(validationError); } else { return SIPAccountPersistor.Update(sipAccount); } }
/// <summary> /// Handler for processing incoming SIP requests. /// </summary> /// <param name="localSIPEndPoint">The end point the request was received on.</param> /// <param name="remoteEndPoint">The end point the request came from.</param> /// <param name="sipRequest">The SIP request received.</param> private static void SIPTransportRequestReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) { try { if (sipRequest.Method == SIPMethodsEnum.BYE) { throw new NotImplementedException(); } else if (sipRequest.Method == SIPMethodsEnum.CANCEL) { throw new NotImplementedException(); } else if (sipRequest.Method == SIPMethodsEnum.INVITE) { throw new NotImplementedException(); } else if (sipRequest.Method == SIPMethodsEnum.OPTIONS) { SIPNonInviteTransaction optionsTransaction = _sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null); SIPResponse optionsResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); optionsTransaction.SendFinalResponse(optionsResponse); } else if (sipRequest.Method == SIPMethodsEnum.REGISTER) { SIPResponseStatusCodesEnum registerResponse = SIPResponseStatusCodesEnum.Ok; if (sipRequest.Header.Contact != null && sipRequest.Header.Contact.Count > 0) { int expiry = sipRequest.Header.Contact[0].Expires > 0 ? sipRequest.Header.Contact[0].Expires : sipRequest.Header.Expires; var sipAccount = new SIPAccount(null, sipRequest.Header.From.FromURI.Host, sipRequest.Header.From.FromURI.User, null, null); SIPRegistrarBinding binding = new SIPRegistrarBinding(sipAccount, sipRequest.Header.Contact[0].ContactURI, null, 0, null, remoteEndPoint, localSIPEndPoint, null, expiry); if (_sipRegistrations.ContainsKey(sipAccount.SIPUsername)) { _sipRegistrations.Remove(sipAccount.SIPUsername); } _sipRegistrations.Add(sipAccount.SIPUsername, binding); logger.Debug("Registered contact for " + sipAccount.SIPUsername + " as " + binding.ToContactString() + "."); } else { registerResponse = SIPResponseStatusCodesEnum.BadRequest; } SIPNonInviteTransaction registerTransaction = _sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null); SIPResponse okResponse = SIPTransport.GetResponse(sipRequest, registerResponse, null); registerTransaction.SendFinalResponse(okResponse); } else { logger.Debug("SIP " + sipRequest.Method + " request received but no processing has been set up for it, rejecting."); } } catch (NotImplementedException) { logger.Debug(sipRequest.Method + " request processing not implemented for " + sipRequest.URI.ToParameterlessString() + " from " + remoteEndPoint + "."); SIPNonInviteTransaction notImplTransaction = _sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null); SIPResponse notImplResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotImplemented, null); notImplTransaction.SendFinalResponse(notImplResponse); } }
public static string ValidateAndClean(SIPAccount sipAccount) { if (sipAccount.Owner.IsNullOrBlank()) { return("The owner must be specified when creating a new SIP account."); } if (sipAccount.SIPUsername.IsNullOrBlank()) { return("The username must be specified when creating a new SIP account."); } if (sipAccount.SIPDomain.IsNullOrBlank()) { return("The domain must be specified when creating a new SIP account."); } else if (sipAccount.SIPUsername.Length < USERNAME_MIN_LENGTH) { return("The username must be at least " + USERNAME_MIN_LENGTH + " characters long."); } else if (Regex.Match(sipAccount.SIPUsername, BANNED_SIPACCOUNT_NAMES).Success) { return("The username you have requested is not permitted."); } else if (Regex.Match(sipAccount.SIPUsername, "[^" + USERNAME_ALLOWED_CHARS + "]").Success) { return("The username had an invalid character, characters permitted are alpha-numeric and .-_."); } else if (sipAccount.SIPUsername.Contains(".") && (sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim().Length >= USERNAME_MIN_LENGTH && sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() != sipAccount.Owner)) { return("You are not permitted to create this username. Only user " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() + " can create SIP accounts ending in " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".")).Trim() + "."); } else if (!sipAccount.IsIncomingOnly || !sipAccount.SIPPassword.IsNullOrBlank()) { if (sipAccount.SIPPassword.IsNullOrBlank()) { return("A password must be specified."); } else if (sipAccount.SIPPassword.Length < PASSWORD_MIN_LENGTH || sipAccount.SIPPassword.Length > PASSWORD_MAX_LENGTH) { return("The password field must be at least " + PASSWORD_MIN_LENGTH + " characters and no more than " + PASSWORD_MAX_LENGTH + " characters."); } else { #region Check the password illegal characters. char[] passwordChars = sipAccount.SIPPassword.ToCharArray(); bool illegalCharFound = false; char illegalChar = ' '; foreach (char passwordChar in passwordChars) { if (Regex.Match(passwordChar.ToString(), "[a-zA-Z0-9]").Success) { continue; } else { bool validChar = false; foreach (char allowedChar in NONAPLPHANUM_ALLOWED_PASSWORD_CHARS) { if (allowedChar == passwordChar) { validChar = true; break; } } if (validChar) { continue; } else { illegalCharFound = true; illegalChar = passwordChar; break; } } } #endregion if (illegalCharFound) { return("Your password has an invalid character " + illegalChar + " it can only contain a to Z, 0 to 9 and characters in this set " + SafeXML.MakeSafeXML(new String(NONAPLPHANUM_ALLOWED_PASSWORD_CHARS)) + "."); } } } sipAccount.Owner = sipAccount.Owner.Trim(); sipAccount.SIPUsername = sipAccount.SIPUsername.Trim(); sipAccount.SIPPassword = (sipAccount.SIPPassword.IsNullOrBlank()) ? null : sipAccount.SIPPassword.Trim(); sipAccount.SIPDomain = sipAccount.SIPDomain.Trim(); return(null); }
/// <summary></summary> /// <param name="uacRecvdEndPoint">If this is non-null it indicates the contact header should be mangled based on the public socket the register request was demmed /// to have originated from rather then relying on the contact value recieved from the uac.</param> public SIPRegistrarBinding( SIPAccount sipAccount, SIPURI bindingURI, string callId, int cseq, string userAgent, SIPEndPoint remoteSIPEndPoint, SIPEndPoint proxySIPEndPoint, SIPEndPoint registrarSIPEndPoint, int expiry) { Id = Guid.NewGuid(); LastUpdate = DateTime.UtcNow; SIPAccountId = sipAccount.Id; SIPAccountName = sipAccount.SIPUsername + "@" + sipAccount.SIPDomain; Owner = sipAccount.Owner; AdminMemberId = sipAccount.AdminMemberId; m_contactURI = bindingURI.CopyOf(); m_mangledContactURI = m_contactURI.CopyOf(); CallId = callId; CSeq = cseq; UserAgent = userAgent; RemoteSIPEndPoint = remoteSIPEndPoint; m_proxySIPEndPoint = proxySIPEndPoint; m_registrarSIPEndPoint = registrarSIPEndPoint; //if (SIPTransport.IsPrivateAddress(sipRequest.Header.Contact[0].ContactURI.Host) && m_mangleUACContact) if (!sipAccount.DontMangleEnabled && Regex.Match(m_mangledContactURI.Host, @"(\d+\.){3}\d+").Success) { // The Contact URI Host is used by registrars as the contact socket for the user so it needs to be changed to reflect the socket // the intial request was received on in order to work around NAT. It's no good just relying on private addresses as a lot of User Agents // determine their public IP but NOT their public port so they send the wrong port in the Contact header. //logger.Debug("Mangling contact header from " + m_mangledContactURI.Host + " to " + IPSocket.GetSocketString(uacRecvdEndPoint) + "."); m_mangledContactURI.Host = remoteSIPEndPoint.GetIPEndPoint().ToString(); } m_expiry = expiry; }
public abstract void AddSIPAccountAsync(SIPAccount sipAccount);
public override void AddSIPAccountAsync(SIPAccount sipAccount) { if (AddSIPAccountComplete != null) { AddSIPAccountComplete(new AddSIPAccountCompletedEventArgs(new object[] { sipAccount }, null, false, null)); } }
/// <summary> /// Updates the bindings list for a registrar's address-of-records. /// </summary> /// <param name="proxyEndPoint">If the request arrived at this registrar via a proxy then this will contain the end point of the proxy.</param> /// <param name="uacRecvdEndPoint">The public end point the UAC REGISTER request was deemded to have originated from.</param> /// <param name="registrarEndPoint">The registrar end point the registration request was received on.</param> /// <param name="maxAllowedExpiry">The maximum allowed expiry that can be granted to this binding request.</param> /// <returns>If the binding update was successful the expiry time for it is returned otherwise 0.</returns> public List<SIPRegistrarBinding> UpdateBindings( SIPAccount sipAccount, SIPEndPoint proxySIPEndPoint, SIPEndPoint remoteSIPEndPoint, SIPEndPoint registrarSIPEndPoint, List<SIPContactHeader> contactHeaders, string callId, int cseq, //int contactHeaderExpiresValue, int expiresHeaderValue, string userAgent, out SIPResponseStatusCodesEnum responseStatus, out string responseMessage) { //logger.Debug("UpdateBinding " + bindingURI.ToString() + "."); int maxAllowedExpiry = m_userAgentConfigs.GetMaxAllowedExpiry(userAgent); responseMessage = null; string sipAccountAOR = sipAccount.SIPUsername + "@" + sipAccount.SIPDomain; responseStatus = SIPResponseStatusCodesEnum.Ok; try { userAgent = (userAgent != null && userAgent.Length > MAX_USERAGENT_LENGTH) ? userAgent.Substring(0, MAX_USERAGENT_LENGTH) : userAgent; List<SIPRegistrarBinding> bindings = m_bindingsPersistor.Get(b => b.SIPAccountId == sipAccount.Id, null, 0, Int32.MaxValue); foreach (SIPContactHeader contactHeader in contactHeaders) { SIPURI bindingURI = contactHeader.ContactURI.CopyOf(); int contactHeaderExpiresValue = contactHeader.Expires; int bindingExpiry = 0; if (bindingURI.Host == m_sipRegisterRemoveAll) { if (contactHeaders.Count > 1) { // If a register request specifies remove all it cannot contain any other binding requests. FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.BindingRemoval, "Remove all bindings requested for " + sipAccountAOR + " but mutliple bindings specified, rejecting as a bad request.", sipAccount.SIPUsername)); responseStatus = SIPResponseStatusCodesEnum.BadRequest; break; } #region Process remove all bindings. if (expiresHeaderValue == 0) { // Removing all bindings for user. FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.BindingRemoval, "Remove all bindings requested for " + sipAccountAOR + ".", sipAccount.SIPUsername)); // Mark all the current bindings as expired. if (bindings != null && bindings.Count > 0) { for (int index = 0; index < bindings.Count; index++) { bindings[index].RemovalReason = SIPBindingRemovalReason.ClientExpiredAll; bindings[index].Expiry = 0; m_bindingsPersistor.Update(bindings[index]); // Remove the NAT keep-alive job if present. if (m_natKeepAliveJobs.ContainsKey(bindings[index].RemoteSIPSocket)) { m_natKeepAliveJobs[bindings[index].RemoteSIPSocket].CancelJob(); } } } FireSIPMonitorLogEvent(new SIPMonitorMachineEvent(SIPMonitorMachineEventTypesEnum.SIPRegistrarBindingRemoval, sipAccount.Owner, sipAccount.Id.ToString(), SIPURI.ParseSIPURIRelaxed(sipAccountAOR))); responseStatus = SIPResponseStatusCodesEnum.Ok; } else { // Remove all header cannot be present with other headers and must have an Expiry equal to 0. responseStatus = SIPResponseStatusCodesEnum.BadRequest; } #endregion } else { int requestedExpiry = (contactHeaderExpiresValue != -1) ? contactHeaderExpiresValue : expiresHeaderValue; requestedExpiry = (requestedExpiry == -1) ? maxAllowedExpiry : requestedExpiry; // This will happen if the Expires header and the Expiry on the Contact are both missing. bindingExpiry = (requestedExpiry > maxAllowedExpiry) ? maxAllowedExpiry : requestedExpiry; bindingExpiry = (bindingExpiry < MINIMUM_EXPIRY_SECONDS) ? MINIMUM_EXPIRY_SECONDS : bindingExpiry; bindingURI.Parameters.Remove(m_sipExpiresParameterKey); SIPRegistrarBinding binding = GetBindingForContactURI(bindings, bindingURI.ToString()); if (binding != null) { if (requestedExpiry <= 0) { FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.BindingExpired, "Binding expired by client for " + sipAccountAOR + " from " + remoteSIPEndPoint.ToString() + ".", sipAccount.SIPUsername)); bindings.Remove(binding); m_bindingsPersistor.Delete(binding); bindingExpiry = 0; FireSIPMonitorLogEvent(new SIPMonitorMachineEvent(SIPMonitorMachineEventTypesEnum.SIPRegistrarBindingRemoval, sipAccount.Owner, sipAccount.Id.ToString(), SIPURI.ParseSIPURIRelaxed(sipAccountAOR))); // Remove the NAT keep-alive job if present. if (m_natKeepAliveJobs.ContainsKey(binding.RemoteSIPSocket)) { m_natKeepAliveJobs[binding.RemoteSIPSocket].CancelJob(); } } else { FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.Registrar, "Binding update request for " + sipAccountAOR + " from " + remoteSIPEndPoint.ToString() + ", expiry requested " + requestedExpiry + "s granted " + bindingExpiry + "s.", sipAccount.Owner)); binding.RefreshBinding(bindingExpiry, remoteSIPEndPoint, proxySIPEndPoint, registrarSIPEndPoint, sipAccount.DontMangleEnabled); DateTime startTime = DateTime.Now; m_bindingsPersistor.Update(binding); TimeSpan duration = DateTime.Now.Subtract(startTime); //FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.RegistrarTiming, "Binding database update time for " + sipAccountAOR + " took " + duration.TotalMilliseconds + "ms.", null)); FireSIPMonitorLogEvent(new SIPMonitorMachineEvent(SIPMonitorMachineEventTypesEnum.SIPRegistrarBindingUpdate, sipAccount.Owner, sipAccount.Id.ToString(), SIPURI.ParseSIPURIRelaxed(sipAccountAOR))); // Add a NAT keep-alive job if required. if (sipAccount.SendNATKeepAlives && proxySIPEndPoint != null) { AddNATKeepAliveJob(sipAccount, remoteSIPEndPoint, proxySIPEndPoint, binding, bindingExpiry); } } } else { if (requestedExpiry > 0) { FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.BindingInProgress, "New binding request for " + sipAccountAOR + " from " + remoteSIPEndPoint.ToString() + ", expiry requested " + requestedExpiry + "s granted " + bindingExpiry + "s.", sipAccount.Owner)); if (bindings.Count >= m_maxBindingsPerAccount) { // Need to remove the oldest binding to stay within limit. //SIPRegistrarBinding oldestBinding = m_bindingsPersistor.Get(b => b.SIPAccountId == sipAccount.Id, null, 0, Int32.MaxValue).OrderBy(x => x.LastUpdateUTC).Last(); SIPRegistrarBinding oldestBinding = bindings.OrderBy(x => x.LastUpdate).Last(); FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.BindingInProgress, "Binding limit exceeded for " + sipAccountAOR + " from " + remoteSIPEndPoint.ToString() + " removing oldest binding to stay within limit of " + m_maxBindingsPerAccount + ".", sipAccount.Owner)); m_bindingsPersistor.Delete(oldestBinding); if (m_natKeepAliveJobs.ContainsKey(binding.RemoteSIPSocket)) { m_natKeepAliveJobs[binding.RemoteSIPSocket].CancelJob(); } } SIPRegistrarBinding newBinding = new SIPRegistrarBinding(sipAccount, bindingURI, callId, cseq, userAgent, remoteSIPEndPoint, proxySIPEndPoint, registrarSIPEndPoint, bindingExpiry); DateTime startTime = DateTime.Now; bindings.Add(newBinding); m_bindingsPersistor.Add(newBinding); TimeSpan duration = DateTime.Now.Subtract(startTime); //FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.RegistrarTiming, "Binding database add time for " + sipAccountAOR + " took " + duration.TotalMilliseconds + "ms.", null)); // Add a NAT keep-alive job if required. if (sipAccount.SendNATKeepAlives && proxySIPEndPoint != null) { AddNATKeepAliveJob(sipAccount, remoteSIPEndPoint, proxySIPEndPoint, newBinding, bindingExpiry); } FireSIPMonitorLogEvent(new SIPMonitorMachineEvent(SIPMonitorMachineEventTypesEnum.SIPRegistrarBindingUpdate, sipAccount.Owner, sipAccount.Id.ToString(), SIPURI.ParseSIPURIRelaxed(sipAccountAOR))); } else { FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.BindingFailed, "New binding received for " + sipAccountAOR + " with expired contact," + bindingURI.ToString() + " no update.", sipAccount.Owner)); bindingExpiry = 0; } } responseStatus = SIPResponseStatusCodesEnum.Ok; } } return bindings; } catch (Exception excp) { logger.Error("Exception UpdateBinding. " + excp.Message); FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Registrar, SIPMonitorEventTypesEnum.Error, "Registrar error updating binding: " + excp.Message + " Binding not updated.", sipAccount.SIPUsername)); responseStatus = SIPResponseStatusCodesEnum.InternalServerError; return null; } }
public bool AuthenticateCall() { m_isAuthenticated = false; try { if (SIPAuthenticateRequest_External == null) { // No point trying to authenticate if we haven't been given an authentication delegate. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else if (GetSIPAccount_External == null) { // No point trying to authenticate if we haven't been given a delegate to load the SIP account. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else { m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == m_sipUsername && s.SIPDomain == m_sipDomain); if (m_sipAccount == null) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Rejecting authentication required call for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found.", null)); Reject(SIPResponseStatusCodesEnum.Forbidden, null, null); } else { SIPRequest sipRequest = m_uasTransaction.TransactionRequest; SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn) : sipRequest.LocalSIPEndPoint; SIPEndPoint remoteEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : sipRequest.RemoteSIPEndPoint; SIPRequestAuthenticationResult authenticationResult = SIPAuthenticateRequest_External(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount, Log_External); if (authenticationResult.Authenticated) { if (authenticationResult.WasAuthenticatedByIP) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "New call from " + remoteEndPoint.ToString() + " successfully authenticated by IP address.", m_sipAccount.Owner)); } else { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "New call from " + remoteEndPoint.ToString() + " successfully authenticated by digest.", m_sipAccount.Owner)); } SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId); m_isAuthenticated = true; } else { // Send authorisation failure or required response SIPResponse authReqdResponse = SIPTransport.GetResponse(sipRequest, authenticationResult.ErrorResponse, null); authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader; Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call not authenticated for " + m_sipUsername + "@" + m_sipDomain + ", responding with " + authenticationResult.ErrorResponse + ".", null)); m_uasTransaction.SendFinalResponse(authReqdResponse); } } } } catch (Exception excp) { logger.Error("Exception SIPServerUserAgent AuthenticateCall. " + excp.Message); Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } return m_isAuthenticated; }
public bool AuthenticateCall() { m_isAuthenticated = false; try { if (SIPAuthenticateRequest_External == null) { // No point trying to authenticate if we haven't been given an authentication delegate. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else if (GetSIPAccount_External == null) { // No point trying to authenticate if we haven't been given a delegate to load the SIP account. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else { m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == m_sipUsername && s.SIPDomain == m_sipDomain); if (m_sipAccount == null) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Rejecting authentication required " + m_transaction.TransactionRequest.Method + " for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found.", null)); Reject(SIPResponseStatusCodesEnum.Forbidden, null, null); } else { SIPRequest sipRequest = m_transaction.TransactionRequest; SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn) : sipRequest.LocalSIPEndPoint; SIPEndPoint remoteEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : sipRequest.RemoteSIPEndPoint; SIPRequestAuthenticationResult authenticationResult = SIPAuthenticateRequest_External(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount, Log_External); if (authenticationResult.Authenticated) { if (authenticationResult.WasAuthenticatedByIP) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, m_transaction.TransactionRequest.Method + " request from " + remoteEndPoint.ToString() + " successfully authenticated by IP address.", m_sipAccount.Owner)); } else { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, m_transaction.TransactionRequest.Method + " request from " + remoteEndPoint.ToString() + " successfully authenticated by digest.", m_sipAccount.Owner)); } SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId); m_isAuthenticated = true; } else { // Send authorisation failure or required response SIPResponse authReqdResponse = SIPTransport.GetResponse(sipRequest, authenticationResult.ErrorResponse, null); authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader; Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, m_transaction.TransactionRequest.Method + " request not authenticated for " + m_sipUsername + "@" + m_sipDomain + ", responding with " + authenticationResult.ErrorResponse + ".", null)); m_transaction.SendFinalResponse(authReqdResponse); } } } } catch (Exception excp) { logger.Error("Exception SIPNonInviteUserAgent AuthenticateCall. " + excp.Message); Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } return(m_isAuthenticated); }
public abstract void UpdateSIPAccount(SIPAccount sipAccount);
public bool AuthenticateCall() { m_isAuthenticated = false; try { if (SIPAuthenticateRequest_External == null) { // No point trying to authenticate if we haven't been given an authentication delegate. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else if (GetSIPAccount_External == null) { // No point trying to authenticate if we haven't been given a delegate to load the SIP account. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else { m_sipAccount = GetSIPAccount_External(m_sipUsername, m_sipDomain); if (m_sipAccount == null) { logger.LogWarning("Rejecting authentication required call for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found."); Reject(SIPResponseStatusCodesEnum.Forbidden, null, null); } else { SIPRequest sipRequest = m_uasTransaction.TransactionRequest; SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn) : sipRequest.LocalSIPEndPoint; SIPEndPoint remoteEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : sipRequest.RemoteSIPEndPoint; SIPRequestAuthenticationResult authenticationResult = SIPAuthenticateRequest_External(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount); if (authenticationResult.Authenticated) { if (authenticationResult.WasAuthenticatedByIP) { logger.LogDebug("New call from " + remoteEndPoint.ToString() + " successfully authenticated by IP address."); } else { logger.LogDebug("New call from " + remoteEndPoint.ToString() + " successfully authenticated by digest."); } SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId); m_isAuthenticated = true; } else { // Send authorisation failure or required response SIPResponse authReqdResponse = SIPResponse.GetResponse(sipRequest, authenticationResult.ErrorResponse, null); authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader; logger.LogWarning("Call not authenticated for " + m_sipUsername + "@" + m_sipDomain + ", responding with " + authenticationResult.ErrorResponse + "."); m_uasTransaction.SendFinalResponse(authReqdResponse); } } } } catch (Exception excp) { logger.LogError("Exception SIPServerUserAgent AuthenticateCall. " + excp.Message); Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } return(m_isAuthenticated); }
public static IPAddress PublicIPAddress; // If the app server is behind a NAT then it can set this address to be used in mangled SDP. /// <summary> /// /// </summary> /// <param name="sipTransport"></param> /// <param name="owner"></param> /// <param name="sipAccount">The SIP account that was called and resulted in the dialplan executing. Will be null if the /// execution was not initated by a call to a SIP account call such as if a web callback occurs.</param> /// <param name="sipProviders"></param> /// <param name="getSIPAccount"></param> /// <param name="getRegistrarBindings"></param> /// <param name="getCanonicalDomainDelegate"></param> /// <param name="logDelegate"></param> /// <param name="dialplanName">Used to ensure that a call leg cannot create a B2B call that loops into the same dial plan.</param> public DialStringParser( SIPTransport sipTransport, string owner, SIPAccount sipAccount, List<SIPProvider> sipProviders, SIPAssetGetDelegate<SIPAccount> getSIPAccount, SIPAssetGetListDelegate<SIPRegistrarBinding> getRegistrarBindings, GetCanonicalDomainDelegate getCanonicalDomainDelegate, SIPMonitorLogDelegate logDelegate, string dialplanName) { m_sipTransport = sipTransport; m_username = owner; m_sipAccount = sipAccount; m_sipProviders = sipProviders; GetSIPAccount_External = getSIPAccount; GetRegistrarBindings_External = getRegistrarBindings; GetCanonicalDomain_External = getCanonicalDomainDelegate; Log_External = logDelegate; m_dialPlanName = dialplanName; }
public override void DeleteSIPAccount(SIPAccount sipAccount) { if (DeleteSIPAccountComplete != null) { DeleteSIPAccountComplete(new DeleteSIPAccountCompletedEventArgs(new object[] { sipAccount }, null, false, null)); } }
/// <summary> /// Creates a list of calls based on the registered contacts for a user registration. /// </summary> /// <param name="user"></param> /// <param name="domain"></param> /// <param name="from">The From header that will be set on the forwarded call leg.</param> /// <returns></returns> public List<SIPCallDescriptor> GetForwardsForLocalLeg( SIPRequest sipRequest, SIPAccount sipAccount, List<string> customHeaders, string customContentType, string customContent, string options, string callersNetworkId, string fromDisplayName, string fromUsername, string fromHost, CRMHeaders contact) { List<SIPCallDescriptor> localUserSwitchCalls = new List<SIPCallDescriptor>(); try { if (sipAccount == null) { throw new ApplicationException("Cannot lookup forwards for a null SIP account."); } List<SIPRegistrarBinding> bindings = GetRegistrarBindings_External(b => b.SIPAccountId == sipAccount.Id, null, 0, Int32.MaxValue); if (bindings != null) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, bindings.Count + " found for " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + ".", m_username)); // Build list of registered contacts. for (int index = 0; index < bindings.Count; index++) { SIPRegistrarBinding binding = bindings[index]; SIPURI contactURI = binding.MangledContactSIPURI; // Determine the content based on a custom request, caller's network id and whether mangling is required. string contentType = (sipRequest != null) ? sipRequest.Header.ContentType : null; string content = (sipRequest != null) ? sipRequest.Body : null; if (!customContentType.IsNullOrBlank()) { contentType = customContentType; } if (!customContent.IsNullOrBlank()) { content = customContent; } IPAddress publicSDPAddress = PublicIPAddress; if (publicSDPAddress == null && sipRequest != null) { publicSDPAddress = SIPPacketMangler.GetRequestIPAddress(sipRequest); } string fromHeader = (sipRequest != null) ? sipRequest.Header.From.ToString() : m_anonymousFromURI; SIPCallDescriptor switchCall = new SIPCallDescriptor( null, null, contactURI.ToString(), fromHeader, new SIPToHeader(null, SIPURI.ParseSIPURIRelaxed(sipAccount.SIPUsername + "@" + sipAccount.SIPDomain), null).ToString(), null, customHeaders, null, SIPCallDirection.In, contentType, content, publicSDPAddress); switchCall.CRMHeaders = contact; // If the binding for the call is a switchboard add the custom switchboard headers. if (!sipRequest.Header.SwitchboardFrom.IsNullOrBlank()) { switchCall.SwitchboardHeaders.SwitchboardFrom = sipRequest.Header.SwitchboardFrom; } // If the binding has a proxy socket defined set the header to ask the upstream proxy to use it. if (binding.ProxySIPEndPoint != null) { switchCall.ProxySendFrom = binding.ProxySIPEndPoint.ToString(); } switchCall.ParseCallOptions(options); if (sipAccount != null && !sipAccount.NetworkId.IsNullOrBlank() && sipAccount.NetworkId == callersNetworkId) { switchCall.MangleResponseSDP = false; } switchCall.SetGeneralFromHeaderFields(fromDisplayName, fromUsername, fromHost); localUserSwitchCalls.Add(switchCall); } } else { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "No current bindings found for local SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + ".", m_username)); } return localUserSwitchCalls; } catch (Exception excp) { logger.Error("Exception GetForwardsForLocalLeg. " + excp); return localUserSwitchCalls; } }
public bool LoadSIPAccountForIncomingCall() { try { bool loaded = false; if (GetSIPAccount_External == null) { // No point trying to authenticate if we haven't been given a delegate to load the SIP account. Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); } else { m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == m_sipUsername && s.SIPDomain == m_sipDomain); if (m_sipAccount == null) { // A full lookup failed. Now try a partial lookup if the incoming username is in a dotted domain name format. if (m_sipUsername.Contains(".")) { string sipUsernameSuffix = m_sipUsername.Substring(m_sipUsername.LastIndexOf(".") + 1); m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == sipUsernameSuffix && s.SIPDomain == m_sipDomain); } if (m_sipAccount == null) { Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Rejecting public call for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found.", null)); Reject(SIPResponseStatusCodesEnum.NotFound, null, null); } else { loaded = true; } } else { loaded = true; } } if (loaded) { SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId); } return loaded; } catch (Exception excp) { logger.Error("Exception LoadSIPAccountForIncomingCall. " + excp.Message); Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null); return false; } }
public override void AddSIPAccountAsync(SIPAccount sipAccount) { m_provisioningServiceProxy.AddSIPAccountAsync(sipAccount); }