Example #1
0
        public SIPEndPoint(SIPURI sipURI)
        {
            Protocol = sipURI.Protocol;
            IPEndPoint endPoint = IPSocket.ParseSocketString(sipURI.Host);

            Address = endPoint.Address;
            Port    = (endPoint.Port == 0) ? (Protocol == SIPProtocolsEnum.tls) ? m_defaultSIPTLSPort : m_defaultSIPPort : endPoint.Port;
        }
Example #2
0
        /// <summary>
        /// This constructor is used by client user agents or SIP elements acting in a client user agent role. When
        /// acting as a client user agent the local fields are contained in the From header and the remote fields are
        /// in the To header.
        /// </summary>
        public SIPDialogue(
            UACInviteTransaction uacInviteTransaction,
            string owner,
            string adminMemberId)
        {
            Id = Guid.NewGuid();

            CallId   = uacInviteTransaction.TransactionRequest.Header.CallId;
            RouteSet =
                (uacInviteTransaction.TransactionFinalResponse != null &&
                 uacInviteTransaction.TransactionFinalResponse.Header.RecordRoutes != null)
                    ? uacInviteTransaction.TransactionFinalResponse.Header.RecordRoutes.Reversed()
                    : null;
            LocalUserField  = uacInviteTransaction.TransactionFinalResponse.Header.From.FromUserField;
            LocalTag        = uacInviteTransaction.TransactionFinalResponse.Header.From.FromTag;
            RemoteUserField = uacInviteTransaction.TransactionFinalResponse.Header.To.ToUserField;
            RemoteTag       = uacInviteTransaction.TransactionFinalResponse.Header.To.ToTag;
            CSeq            = uacInviteTransaction.TransactionRequest.Header.CSeq;
            CDRId           = (uacInviteTransaction.CDR != null) ? uacInviteTransaction.CDR.CDRId : Guid.Empty;
            Owner           = owner;
            AdminMemberId   = adminMemberId;
            ContentType     = uacInviteTransaction.TransactionRequest.Header.ContentType;
            SDP             = uacInviteTransaction.TransactionRequest.Body;
            RemoteSDP       = uacInviteTransaction.TransactionFinalResponse.Body;
            Inserted        = DateTimeOffset.UtcNow;
            Direction       = SIPCallDirection.Out;

            // Set the dialogue remote target and take care of mangling if an upstream proxy has indicated it's required.
            if (uacInviteTransaction.TransactionFinalResponse != null)
            {
                RemoteTarget = new SIPURI(uacInviteTransaction.TransactionRequest.URI.Scheme,
                                          uacInviteTransaction.TransactionFinalResponse.RemoteSIPEndPoint.CopyOf());
            }
            else
            {
                RemoteTarget = new SIPURI(uacInviteTransaction.TransactionRequest.URI.Scheme,
                                          uacInviteTransaction.TransactionRequest.RemoteSIPEndPoint.CopyOf());
            }

            ProxySendFrom = uacInviteTransaction.TransactionFinalResponse.Header.ProxyReceivedOn;
            if (uacInviteTransaction.TransactionFinalResponse.Header.Contact != null &&
                uacInviteTransaction.TransactionFinalResponse.Header.Contact.Count > 0)
            {
                RemoteTarget = uacInviteTransaction.TransactionFinalResponse.Header.Contact[0].ContactURI.CopyOf();
                if (!uacInviteTransaction.TransactionFinalResponse.Header.ProxyReceivedFrom.IsNullOrBlank())
                {
                    // Setting the Proxy-ReceivedOn header is how an upstream proxy will let an agent know it should mangle the contact.
                    // Don't mangle private contacts if there is a Record-Route header. If a proxy is putting private IP's in a Record-Route header that's its problem.
                    if (RouteSet == null && IPSocket.IsPrivateAddress(RemoteTarget.Host))
                    {
                        SIPEndPoint remoteUASSIPEndPoint =
                            SIPEndPoint.ParseSIPEndPoint(uacInviteTransaction.TransactionFinalResponse.Header
                                                         .ProxyReceivedFrom);
                        RemoteTarget.Host = remoteUASSIPEndPoint.GetIPEndPoint().ToString();
                    }
                }
            }
        }
Example #3
0
        public void ParsePortFromSocketTest()
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);

            int port = IPSocket.ParsePortFromSocket("localhost:5060");

            Console.WriteLine("port=" + port);
            Assert.IsTrue(port == 5060, "The port was not parsed correctly.");
        }
Example #4
0
        public void ParseHostFromSocketTest()
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);

            string host = IPSocket.ParseHostFromSocket("localhost:5060");

            Console.WriteLine("host=" + host);
            Assert.IsTrue(host == "localhost", "The host was not parsed correctly.");
        }
Example #5
0
        public void Test172IPRangeIsPrivate()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            Assert.IsFalse(IPSocket.IsPrivateAddress("172.15.1.1"), "Public IP address was mistakenly identified as private.");
            Assert.IsTrue(IPSocket.IsPrivateAddress("172.16.1.1"), "Private IP address was not correctly identified.");

            Console.WriteLine("-----------------------------------------");
        }
Example #6
0
        /// <summary>
        /// Initiate a new abstract ATCPConnection using the given TcpClient class
        /// </summary>
        public ATCPConnection(TcpClient TCPClientConnection)
        {
            this.TCPClientConnection = TCPClientConnection;
            var _IPEndPoint          = this.TCPClientConnection.Client.RemoteEndPoint as IPEndPoint;
            RemoteSocket             = new IPSocket(new IPv4Address(_IPEndPoint.Address), new IPPort((UInt16) _IPEndPoint.Port));

            if (RemoteSocket == null)
                throw new ArgumentNullException("The RemoteEndPoint is invalid!");
        }
Example #7
0
        protected void SendTCPSocketDetached(DateTime Timestamp, IPSocket TCPSocket, String Message = null)
        {
            var OnTCPSocketDetachedLocal = OnTCPSocketDetached;

            if (OnTCPSocketDetachedLocal != null)
            {
                OnTCPSocketDetachedLocal(this, Timestamp, TCPSocket, Message);
            }
        }
Example #8
0
        /// <summary>
        /// Reverses ToString().
        /// </summary>
        /// <param name="serialisedSIPEndPoint">The serialised SIP end point MUST be in the form protocol:socket and protocol must
        /// be exactly 3 characters. Valid examples are udp:10.0.0.1:5060, invalid example is 10.0.0.1:5060.</param>
        private static SIPEndPoint ParseSerialisedSIPEndPoint(string serialisedSIPEndPoint)
        {
            if (!IPSocket.TryParseIPEndPoint(serialisedSIPEndPoint.Substring(4), out var endPoint))
            {
                throw new ApplicationException($"Could not parse SIPURI host {serialisedSIPEndPoint.Substring(4)} as an IP end point.");
            }

            return(new SIPEndPoint(SIPProtocolsType.GetProtocolType(serialisedSIPEndPoint.Substring(0, 3)), endPoint));
        }
Example #9
0
        static SIPRegistrarState()
        {
            try
            {
                #region Configure logging.

                try
                {
                    log4net.Config.XmlConfigurator.Configure();
                    logger = log4net.LogManager.GetLogger(LOGGER_NAME);
                }
                catch (Exception logExcp)
                {
                    Console.WriteLine("Exception SIPRegistrarState Configure Logging. " + logExcp.Message);
                }

                #endregion

                if (AppState.GetSection(SIPREGISTRAR_CONFIGNODE_NAME) != null)
                {
                    m_sipRegistrarNode = (XmlNode)AppState.GetSection(SIPREGISTRAR_CONFIGNODE_NAME);
                }

                if (m_sipRegistrarNode == null)
                {
                    //throw new ApplicationException("The SIP Registrar could not be started, no " + SIPREGISTRAR_CONFIGNODE_NAME + " config node available.");
                    logger.Warn("The SIP Registrar " + SIPREGISTRAR_CONFIGNODE_NAME + " config node was not available, the agent will not be able to start.");
                }
                else
                {
                    SIPRegistrarSocketsNode = m_sipRegistrarNode.SelectSingleNode(SIPSOCKETS_CONFIGNODE_NAME);
                    if (SIPRegistrarSocketsNode == null)
                    {
                        throw new ApplicationException("The SIP Registrar could not be started, no " + SIPSOCKETS_CONFIGNODE_NAME + " node could be found.");
                    }

                    UserAgentsConfigNode = m_sipRegistrarNode.SelectSingleNode(USERAGENTS_CONFIGNODE_NAME);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, MONITOR_LOOPBACK_PORT_KEY), out MonitorLoopbackPort);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, MAXIMUM_ACCOUNT_BINDINGS_KEY), out MaximumAccountBindings);
                    if (!AppState.GetConfigNodeValue(m_sipRegistrarNode, NATKEEPALIVE_RELAY_SOCKET).IsNullOrBlank())
                    {
                        NATKeepAliveRelaySocket = IPSocket.ParseSocketString(AppState.GetConfigNodeValue(m_sipRegistrarNode, NATKEEPALIVE_RELAY_SOCKET));
                    }
                    //SwitchboardCertificateName = AppState.GetConfigNodeValue(m_sipRegistrarNode, SWITCHBOARD_CERTIFICATE_NAME_KEY);
                    SwitchboardUserAgentPrefix = AppState.GetConfigNodeValue(m_sipRegistrarNode, SWITCHBOARD_USERAGNET_PREFIX_KEY);
                    if (!AppState.GetConfigNodeValue(m_sipRegistrarNode, THREAD_COUNT_KEY).IsNullOrBlank())
                    {
                        Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, THREAD_COUNT_KEY), out ThreadCount);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPRegistrarState. " + excp.Message);
                throw;
            }
        }
Example #10
0
        public SIPMonitorUDPSink(string udpSocket)
        {
            logger.Debug("Request to create SIPMonitorUDPSink on " + udpSocket + ".");

            m_monitorProxyManager   = new MonitorProxyManager();
            m_eventReceiverEndPoint = IPSocket.ParseSocketString(udpSocket);

            ThreadPool.QueueUserWorkItem(delegate { Listen(); });
        }
Example #11
0
 /// <summary>
 /// Create a new e-mail envelop based on the given sender
 /// and receiver addresses and the e-mail builder data.
 /// </summary>
 /// <param name="MailFrom">The sender(s) of the e-mail.</param>
 /// <param name="RcptTo">The receiver(s) of the e-mail.</param>
 /// <param name="EMail">An e-mail.</param>
 /// <param name="RemoteSocket">The remote socket of the incoming SMTP connection.</param>
 public EMailEnvelop(EMailAddressList MailFrom,
                     EMailAddressList RcptTo,
                     EMail EMail,
                     IPSocket RemoteSocket = null)
 {
     this._MailFrom     = MailFrom;
     this._RcptTo       = RcptTo;
     this._Mail         = EMail;
     this._RemoteSocket = RemoteSocket;
 }
Example #12
0
 /// <summary>
 /// Create a new e-mail envelop based on the given sender
 /// and receiver addresses and the e-mail builder data.
 /// </summary>
 /// <param name="MailFrom">The sender(s) of the e-mail.</param>
 /// <param name="RcptTo">The receiver(s) of the e-mail.</param>
 /// <param name="EMail">An e-mail.</param>
 /// <param name="RemoteSocket">The remote socket of the incoming SMTP connection.</param>
 public EMailEnvelop(EMailAddressList  MailFrom,
                     EMailAddressList  RcptTo,
                     EMail             EMail,
                     IPSocket          RemoteSocket  = null)
 {
     this._MailFrom      = MailFrom;
     this._RcptTo        = RcptTo;
     this._Mail          = EMail;
     this._RemoteSocket  = RemoteSocket;
 }
Example #13
0
 /// <summary>
 /// Create a new HTTPClient using the given optional parameters.
 /// </summary>
 /// <param name="RemoteSocket">The remote IP socket to connect to.</param>
 /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
 /// <param name="ClientCert">The TLS client certificate to use.</param>
 /// <param name="DNSClient">An optional DNS client.</param>
 public HTTPSClient(IPSocket                             RemoteSocket,
                    RemoteCertificateValidationCallback  RemoteCertificateValidator,
                    X509Certificate                      ClientCert  = null,
                    DNSClient                            DNSClient   = null)
     : base(RemoteSocket,
            RemoteCertificateValidator,
            ClientCert,
            DNSClient)
 {
 }
Example #14
0
 /// <summary>
 /// Create a new e-mail envelop based on the given sender
 /// and receiver addresses and the e-mail builder data.
 /// </summary>
 /// <param name="MailFrom">The sender(s) of the e-mail.</param>
 /// <param name="RcptTo">The receiver(s) of the e-mail.</param>
 /// <param name="MailBuilder">An e-mail builder.</param>
 /// <param name="RemoteSocket">The remote socket of the incoming SMTP connection.</param>
 public EMailEnvelop(EMailAddressList MailFrom,
                     EMailAddressList RcptTo,
                     AbstractEMailBuilder MailBuilder,
                     IPSocket RemoteSocket = null)
 {
     this._RemoteSocket = RemoteSocket;
     this._MailFrom     = MailFrom;
     this._RcptTo       = RcptTo;
     this._Mail         = new EMail(MailBuilder);
 }
        public void Test172IPRangeIsPrivate()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            Assert.False(IPSocket.IsPrivateAddress("172.15.1.1"), "Public IP address was mistakenly identified as private.");
            Assert.True(IPSocket.IsPrivateAddress("172.16.1.1"), "Private IP address was not correctly identified.");

            logger.LogDebug("-----------------------------------------");
        }
        public void ParseHostFromSocketTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            string host = IPSocket.ParseHostFromSocket("localhost:5060");

            logger.LogDebug("host=" + host);
            Assert.True(host == "localhost", "The host was not parsed correctly.");
        }
        public void ParsePortFromSocketTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            int port = IPSocket.ParsePortFromSocket("localhost:5060");

            logger.LogDebug("port=" + port);
            Assert.True(port == 5060, "The port was not parsed correctly.");
        }
Example #18
0
        private void UACInviteTransaction_TransactionFinalResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
        {
            try
            {
                // BranchId for 2xx responses needs to be a new one, non-2xx final responses use same one as original request.
                SIPRequest ackRequest = null;
                if (sipResponse.StatusCode >= 200 && sipResponse.StatusCode < 299)
                {
                    if (sipResponse.Header.To != null)
                    {
                        m_remoteTag = sipResponse.Header.To.ToTag;
                    }

                    SIPURI ackURI = m_transactionRequest.URI;
                    if (sipResponse.Header.Contact != null && sipResponse.Header.Contact.Count > 0)
                    {
                        ackURI = sipResponse.Header.Contact[0].ContactURI;
                        // Don't mangle private contacts if there is a Record-Route header. If a proxy is putting private IP's in a Record-Route header that's its problem.
                        if ((sipResponse.Header.RecordRoutes == null || sipResponse.Header.RecordRoutes.Length == 0) &&
                            IPSocket.IsPrivateAddress(ackURI.Host) && !sipResponse.Header.ProxyReceivedFrom.IsNullOrBlank())
                        {
                            // Setting the Proxy-ReceivedOn header is how an upstream proxy will let an agent know it should mangle the contact.
                            SIPEndPoint remoteUASSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(sipResponse.Header.ProxyReceivedFrom);
                            ackURI.Host = remoteUASSIPEndPoint.GetIPEndPoint().ToString();
                        }
                    }

                    // ACK for 2xx response needs to be a new transaction and gets routed based on SIP request fields.
                    ackRequest = GetNewTransactionACKRequest(sipResponse, ackURI, LocalSIPEndPoint);
                    base.SendRequest(ackRequest);
                }
                else
                {
                    // ACK for non 2xx response is part of the INVITE transaction and gets routed to the same endpoint as the INVITE.
                    ackRequest = GetInTransactionACKRequest(sipResponse, m_transactionRequest.URI, LocalSIPEndPoint);
                    base.SendRequest(RemoteEndPoint, ackRequest);
                }

                if (UACInviteTransactionFinalResponseReceived != null)
                {
                    UACInviteTransactionFinalResponseReceived(localSIPEndPoint, remoteEndPoint, sipTransaction, sipResponse);
                }

                if (CDR != null)
                {
                    SIPEndPoint localEP  = SIPEndPoint.TryParse(sipResponse.Header.ProxyReceivedOn) ?? localSIPEndPoint;
                    SIPEndPoint remoteEP = SIPEndPoint.TryParse(sipResponse.Header.ProxyReceivedFrom) ?? remoteEndPoint;
                    CDR.Answered(sipResponse.StatusCode, sipResponse.Status, sipResponse.ReasonPhrase, localEP, remoteEP);
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception UACInviteTransaction_TransactionFinalResponseReceived. " + excp.Message);
            }
        }
Example #19
0
 public static Task <SIPEndPoint> ResolveSIPUri(SIPURI uri, bool preferIPv6)
 {
     if (IPSocket.TryParseIPEndPoint(uri.Host, out var ipEndPoint))
     {
         return(Task.FromResult(new SIPEndPoint(uri.Protocol, ipEndPoint)));
     }
     else
     {
         return(Task.FromResult <SIPEndPoint>(null));
     }
 }
Example #20
0
        /// <summary>
        /// Creates a new HTTP header.
        /// </summary>
        /// <param name="RemoteSocket">The remote TCP/IP socket.</param>
        /// <param name="LocalSocket">The local TCP/IP socket.</param>
        /// <param name="HTTPHeader">A valid string representation of a http request header.</param>
        /// <param name="HTTPBody">The HTTP body as an array of bytes.</param>
        /// <param name="HTTPBodyStream">The HTTP body as an stream of bytes.</param>
        /// <param name="CancellationToken">A token to cancel the HTTP request processing.</param>
        /// <param name="EventTrackingId">An unique event tracking identification for correlating this request with other events.</param>
        public AHTTPPDU(IPSocket RemoteSocket,
                        IPSocket LocalSocket,
                        String HTTPHeader,
                        Byte[]              HTTPBody        = null,
                        Stream HTTPBodyStream               = null,
                        CancellationToken?CancellationToken = null,
                        EventTracking_Id EventTrackingId    = null)

            : this()

        {
            this.Timestamp         = DateTime.Now;
            this.RemoteSocket      = RemoteSocket;
            this._LocalSocket      = LocalSocket;
            this.RawHTTPHeader     = HTTPHeader.Trim();
            this._HTTPBody         = HTTPBody;
            this._HTTPBodyStream   = HTTPBodyStream;
            this.CancellationToken = CancellationToken.HasValue ? CancellationToken.Value : new CancellationTokenSource().Token;
            this.EventTrackingId   = EventTrackingId;

            #region Process first line...

            var AllLines = HTTPHeader.Trim().Split(_LineSeparator, StringSplitOptions.RemoveEmptyEntries);

            FirstPDULine = AllLines.FirstOrDefault();
            if (FirstPDULine == null)
            {
                throw new Exception("Bad request");
            }

            #endregion

            #region ...process all other header lines

            String[] KeyValuePair = null;

            foreach (var Line in AllLines.Skip(1))
            {
                KeyValuePair = Line.Split(_ColonSeparator, 2, StringSplitOptions.RemoveEmptyEntries);

                // Not valid for every HTTP header... but at least for most...
                if (KeyValuePair.Length == 1)
                {
                    _HeaderFields.Add(KeyValuePair[0].Trim(), String.Empty);
                }

                else // KeyValuePair.Length == 2
                {
                    _HeaderFields.Add(KeyValuePair[0].Trim(), KeyValuePair[1].Trim());
                }
            }

            #endregion
        }
Example #21
0
 protected internal void SendNewConnection(DateTime ServerTimestamp,
                                           IPSocket RemoteSocket,
                                           String ConnectionId,
                                           TCPConnection TCPConnection)
 {
     OnNewConnection?.Invoke(this,
                             ServerTimestamp,
                             RemoteSocket,
                             ConnectionId,
                             TCPConnection);
 }
Example #22
0
 protected internal void SendConnectionClosed(DateTime ServerTimestamp,
                                              IPSocket RemoteSocket,
                                              String ConnectionId,
                                              ConnectionClosedBy ClosedBy)
 {
     OnConnectionClosed?.Invoke(this,
                                ServerTimestamp,
                                RemoteSocket,
                                ConnectionId,
                                ClosedBy);
 }
Example #23
0
        public SIPEndPoint(SIPURI sipURI)
        {
            Protocol = sipURI.Protocol;

            if (!IPSocket.TryParseIPEndPoint(sipURI.Host, out var endPoint))
            {
                throw new ApplicationException($"Could not parse SIPURI host {sipURI.Host} as an IP end point.");
            }

            Address = endPoint.Address;
            Port    = (endPoint.Port == 0) ? SIPConstants.GetDefaultPort(Protocol) : endPoint.Port;
        }
 private void SendMonitorEventViaUDP(SIPMonitorEvent monitorEvent, string destinationSocket)
 {
     try
     {
         byte[] monitorEventBytes = Encoding.UTF8.GetBytes(monitorEvent.ToCSV());
         m_udpEventSender.Send(monitorEventBytes, monitorEventBytes.Length, IPSocket.ParseSocketString(destinationSocket));
     }
     catch (Exception excp)
     {
         logger.Error("Exception SendMonitorEventViaUDP. " + excp.Message);
     }
 }
        public void NoMangleIPv6UnitTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI uri     = SIPURI.ParseSIPURI("sip:user@[2001:730:3ec2::10]:5060?Replaces=xyz");
            SIPURI mangled = SIPURI.Mangle(uri, IPSocket.Parse("67.222.131.147:5060"));

            Assert.Null(mangled);

            logger.LogDebug("-----------------------------------------");
        }
Example #26
0
        /// <summary>
        /// Send data to device and read data from device
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="MaxReceive"></param>
        /// <param name="TermChars"></param>
        /// <param name="ReturnTerm"></param>
        /// <returns></returns>
        public string SendAndReceive(string Message, int MaxReceive, string TermChars, bool ReturnTerm)
        {
            if (((Message.Length == 0) || (MaxReceive <= 0)) || !IsConnected)
            {
                return("");
            }
            Flush();

            StringBuilder builder   = new StringBuilder();
            int           termIndex = 0;

            if (IPSocket.WriteSocket(Message) && ReturnsStatus)
            {
                isWriteSocket = true;
                System.Threading.Thread.Sleep(50);

                bool flag2 = false;
                while (!flag2)
                {
                    if (IPSocket.WaitForSocketData())
                    {
                        builder.Append(IPSocket.GetReceiveBuffer().Replace("\0", ""));
                        IPSocket.ClearReceiveBuffer();

                        termIndex = builder.ToString().IndexOf(TermChars);
                        if (termIndex > 0)
                        {
                            flag2 = true;
                        }
                    }
                    else
                    {
                        break;
                    }

                    if (TermChars.Length == 0 && builder.Length >= MaxReceive)
                    {
                        break;
                    }
                }
            }

            if (TermChars.Length == 0 &&
                MaxReceive > 1 &&
                builder.Length > MaxReceive)
            {
                return(builder.ToString().Substring(0, MaxReceive - 1));
            }
            else
            {
                return(termIndex > 0 ? builder.ToString().Substring(0, termIndex - TermChars.Length) : builder.ToString());
            }
        }
Example #27
0
        private AppTimeMetric ProcessJob(object job)
        {
            Socket fastAGISocket = null;

            try
            {
                fastAGISocket = (Socket)job;
                fastAGISocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

                logger.Debug("fastagi connection from " + IPSocket.GetSocketString((IPEndPoint)fastAGISocket.RemoteEndPoint) + "(" + Thread.CurrentThread.Name + " " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + ")");

                byte[] buffer    = new byte[2048];
                int    bytesRead = 1;

                // Caution - it could take the Asterisk server more than one socket send to get the all the request parameters sent.
                StringBuilder request = new StringBuilder();
                while (bytesRead > 0)
                {
                    bytesRead = fastAGISocket.Receive(buffer, 0, 2048, SocketFlags.None);
                    request.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
                    logger.Debug(Encoding.ASCII.GetString(buffer, 0, bytesRead));

                    if (request.ToString() != null && (Regex.Match(request.ToString(), @"\n\n", RegexOptions.Singleline).Success || Regex.Match(request.ToString(), @"\r\n\r\n", RegexOptions.Singleline).Success))
                    {
                        break;
                    }
                }

                FastAGIRequest fastAGIRequest = new FastAGIRequest();
                return(fastAGIRequest.Run(fastAGISocket, request.ToString()));
            }
            catch (Exception excp)
            {
                logger.Error("Exception FastAGIWorker ProcessJobEvent. " + excp.Message);
                ExceptionAlert(excp.Message);
                return(new AppTimeMetric());
            }
            finally
            {
                if (fastAGISocket != null)
                {
                    try
                    {
                        logger.Debug("connection closed.");
                        fastAGISocket.Close();
                    }
                    catch (Exception sockCkoseExcp)
                    {
                        logger.Error("Exception FastAGIQueueDaemon ProceesJob (closing AGI socket). " + sockCkoseExcp);
                    }
                }
            }
        }
Example #28
0
        /// <summary>
        /// Create a new UDP packet.
        /// </summary>
        /// <param name="ServerTimestamp">The timestamp of the packet arrival  at the UDP receiver.</param>
        /// <param name="LocalSocket">The local/receiving IP socket of the UDP packet.</param>
        /// <param name="RemoteSocket">The remote  IP socket of the UDP packet.</param>
        /// <param name="Payload">The message/payload of the UDP packet.</param>
        public UDPPacket(UDPReceiver <TData> UDPReceiver,
                         DateTime ServerTimestamp,
                         IPSocket LocalSocket,
                         IPSocket RemoteSocket,
                         TData Payload)

            : base(LocalSocket, RemoteSocket)

        {
            this._ServerTimestamp = ServerTimestamp;
            this._Payload         = Payload;
        }
        public void NoMangleSameAddressUnitTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI uri     = SIPURI.ParseSIPURI("sip:[email protected]:5060?Replaces=xyz");
            SIPURI mangled = SIPURI.Mangle(uri, IPSocket.Parse("192.168.0.50:5060"));

            Assert.Null(mangled);

            logger.LogDebug("-----------------------------------------");
        }
Example #30
0
        public SIPEndPoint(SIPURI sipURI)
        {
            Protocol = sipURI.Protocol;

            if (!IPSocket.TryParseIPEndPoint(sipURI.Host, out var endPoint))
            {
                throw new ApplicationException($"Could not parse SIPURI host {sipURI.Host} as an IP end point.");
            }

            Address = endPoint.Address;
            Port    = (endPoint.Port == 0) ? (Protocol == SIPProtocolsEnum.tls) ? m_defaultSIPTLSPort : m_defaultSIPPort : endPoint.Port;
        }
Example #31
0
        public STUNServer(IPEndPoint primaryEndPoint, STUNSendMessageDelegate primarySend, IPEndPoint secondaryEndPoint, STUNSendMessageDelegate secondarySend)
        {
            m_primaryEndPoint   = primaryEndPoint;
            m_primarySend       = primarySend;
            m_secondaryEndPoint = secondaryEndPoint;
            m_secondarySend     = secondarySend;

            m_primaryDiffPortSocket   = NetServices.CreateRandomUDPListener(m_primaryEndPoint.Address, out m_primaryDiffPortEndPoint);
            m_secondaryDiffPortSocket = NetServices.CreateRandomUDPListener(m_secondaryEndPoint.Address, out m_secondaryDiffPortEndPoint);

            logger.LogDebug("STUN Server additional sockets, primary=" + IPSocket.GetSocketString(m_primaryDiffPortEndPoint) + ", secondary=" + IPSocket.GetSocketString(m_secondaryDiffPortEndPoint) + ".");
        }
Example #32
0
 protected void SendNewConnection(TCPServer TCPServer,
                                  DateTime Timestamp,
                                  IPSocket RemoteSocket,
                                  String ConnectionId,
                                  TCPConnection TCPConnection)
 {
     OnNewConnection?.Invoke(TCPServer,
                             Timestamp,
                             RemoteSocket,
                             ConnectionId,
                             TCPConnection);
 }
Example #33
0
        /// <summary>
        /// Create a new HTTPClient using the given optional parameters.
        /// </summary>
        /// <param name="RemoteSocket">The remote IP socket to connect to.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCert">The TLS client certificate to use.</param>
        /// <param name="DNSClient">An optional DNS client.</param>
        public HTTPSClient(IPSocket RemoteSocket,
                           RemoteCertificateValidationCallback RemoteCertificateValidator,
                           X509Certificate ClientCert = null,
                           DNSClient DNSClient        = null)

            : base(RemoteSocket,
                   RemoteCertificateValidator,
                   ClientCert,
                   DNSClient)

        {
        }
Example #34
0
        public DNSInfo(IPSocket                         Origin,
                       Int32                            QueryId,
                       Boolean                          IsAuthorativeAnswer,
                       Boolean                          IsTruncated,
                       Boolean                          RecursionDesired,
                       Boolean                          RecursionAvailable,
                       DNSResponseCodes                 ResponseCode,
                       IEnumerable<ADNSResourceRecord>  Answers,
                       IEnumerable<ADNSResourceRecord>  Authorities,
                       IEnumerable<ADNSResourceRecord>  AdditionalRecords)
        {
            this._Origin              = Origin;
            this._QueryId             = QueryId;
            this._AuthorativeAnswer   = IsAuthorativeAnswer;
            this._IsTruncated         = IsTruncated;
            this._RecursionDesired    = RecursionDesired;
            this._RecursionAvailable  = RecursionAvailable;
            this._ResponseCode        = ResponseCode;

            this._Answers             = new List<ADNSResourceRecord>(Answers);
            this._Authorities         = new List<ADNSResourceRecord>(Authorities);
            this._AdditionalRecords   = new List<ADNSResourceRecord>(AdditionalRecords);
        }
Example #35
0
        /// <summary>
        /// Add the given DNS resource record to the DNS cache.
        /// </summary>
        /// <param name="Domainname">The domain name.</param>
        /// <param name="Origin">The origin of the DNS resource record.</param>
        /// <param name="ResourceRecord">The DNS resource record to add.</param>
        public DNSCache Add(String              Domainname,
                            IPSocket            Origin,
                            ADNSResourceRecord  ResourceRecord)
        {
            lock (_DNSCache)
            {

                DNSCacheEntry CacheEntry = null;

                //Debug.WriteLine("[" + DateTime.Now + "] Adding '" + Domainname + "' to the DNS cache!");

                if (!_DNSCache.TryGetValue(Domainname, out CacheEntry))
                    _DNSCache.Add(Domainname, new DNSCacheEntry(
                                                         DateTime.Now + TimeSpan.FromSeconds(ResourceRecord.TimeToLive.TotalSeconds / 2),
                                                         DateTime.Now + ResourceRecord.TimeToLive,
                                                         new DNSInfo(Origin:               Origin,
                                                                     QueryId:              new Random().Next(),
                                                                     IsAuthorativeAnswer:  false,
                                                                     IsTruncated:          false,
                                                                     RecursionDesired:     false,
                                                                     RecursionAvailable:   false,
                                                                     ResponseCode:         DNSResponseCodes.NoError,
                                                                     Answers:              new ADNSResourceRecord[1] { ResourceRecord },
                                                                     Authorities:          new ADNSResourceRecord[0],
                                                                     AdditionalRecords:    new ADNSResourceRecord[0])));

                else
                {

                    // ToDo: Merge of DNS responses!
                    Debug.WriteLine("[" + DateTime.Now + "] Resource record for '" + Domainname + "' already exists within the DNS cache!");

                }

                return this;

            }
        }
Example #36
0
 /// <summary>
 /// Create a new HTTPClient using the given optional parameters.
 /// </summary>
 /// <param name="RemoteSocket">The IP socket to connect to.</param>
 public HTTPClient(IPSocket RemoteSocket)
 {
     this.RemoteIPAddress = RemoteSocket.IPAddress;
     this.RemotePort      = RemoteSocket.Port;
 }
Example #37
0
        /// <summary>
        /// Create a new HTTPClient using the given optional parameters.
        /// </summary>
        /// <param name="RemoteSocket">The remote IP socket to connect to.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCert">The TLS client certificate to use.</param>
        /// <param name="DNSClient">An optional DNS client.</param>
        public HTTPClient(IPSocket                             RemoteSocket,
                          RemoteCertificateValidationCallback  RemoteCertificateValidator  = null,
                          X509Certificate                      ClientCert                  = null,
                          DNSClient                            DNSClient                   = null)

            : this(RemoteSocket.IPAddress,
                   RemoteSocket.Port,
                   RemoteCertificateValidator,
                   ClientCert,
                   DNSClient)

        { }
Example #38
0
        public TCPConnectResult Connect()
        {
            // if already connected => return!

            if (RemoteHost == null &&
                RemoteHost == String.Empty)
                return TCPConnectResult.InvalidDomainName;

            var retry = 0;

            do
            {

                if (OrderedDNS == null)
                    QueryDNS();

                if (OrderedDNS.Count == 0)
                    return TCPConnectResult.NoIPAddressFound;

                // Get next IP socket in ordered list...
                while (OrderedDNSEnumerator.MoveNext())
                {

                    CurrentIPSocket = OrderedDNSEnumerator.Current;

                    if (Reconnect())
                        return TCPConnectResult.Ok;

                }

                OrderedDNS = null;
                retry++;

            } while (retry < 2);

            return TCPConnectResult.UnknownError;
        }
Example #39
0
 /// <summary>
 /// Start a new TCP/HTTP/REST based graph server.
 /// </summary>
 /// <param name="Graph">A graph.</param>
 /// <param name="IPSocket">The listening IPSocket.</param>
 /// <param name="Autostart">Autostart the server.</param>
 public static IBifrostHTTPServer StartHTTPServer(this IGenericPropertyGraph<String, Int64, String, String, Object,
                                                                       String, Int64, String, String, Object,
                                                                       String, Int64, String, String, Object,
                                                                       String, Int64, String, String, Object> Graph,
                                            IPSocket IPSocket,
                                            Boolean Autostart = false)
 {
     var Server = new BifrostHTTPServer(IPSocket, Autostart);
     Server.AddGraph(Graph);
     return Server;
 }
Example #40
0
 /// <summary>
 /// Create a new UDP packet.
 /// </summary>
 /// <param name="UDPPacketData">The UDP packet data.</param>
 /// <param name="LocalSocket">The local socket of this UDP packet.</param>
 /// <param name="RemoteSocket">The remote socket of this UDP packet.</param>
 public UDPPacket(Byte[] UDPPacketData, IPSocket LocalSocket, IPSocket RemoteSocket)
     : base(UDPPacketData, LocalSocket, RemoteSocket)
 {
     Data = UDPPacketData;
 }
 /// <summary>
 /// Create a new abstract local/remote socket combination.
 /// </summary>
 /// <param name="LocalSocket">The local socket.</param>
 /// <param name="RemoteSocket">The remote socket.</param>
 public AReadOnlyLocalRemoteSockets(IPSocket LocalSocket, IPSocket RemoteSocket)
 {
     this._LocalSocket   = LocalSocket;
     this._RemoteSocket  = RemoteSocket;
 }
Example #42
0
 /// <summary>
 /// Create a new abstract AUDPPacket.
 /// </summary>
 /// <param name="UDPPacketData">The UDP packet data.</param>
 /// <param name="LocalSocket">The local socket of this UDP packet.</param>
 /// <param name="RemoteSocket">The remote socket of this UDP packet.</param>
 public AUDPPacket(Byte[] UDPPacketData, IPSocket LocalSocket, IPSocket RemoteSocket)
     : base(LocalSocket, RemoteSocket)
 {
     this.PacketData   = UDPPacketData;
 }
Example #43
0
 /// <summary>
 /// Create a new abstract ALocalRemoteSockets.
 /// </summary>
 /// <param name="LocalSocket">The local socket of this UDP packet.</param>
 /// <param name="RemoteSocket">The remote socket of this UDP packet.</param>
 public ALocalRemoteSockets(IPSocket LocalSocket, IPSocket RemoteSocket)
 {
     this.LocalSocket  = LocalSocket;
     this.RemoteSocket = RemoteSocket;
 }
Example #44
0
 /// <summary>
 /// Create a new e-mail envelop based on the given sender
 /// and receiver addresses and the e-mail builder data.
 /// </summary>
 /// <param name="MailFrom">The sender(s) of the e-mail.</param>
 /// <param name="RcptTo">The receiver(s) of the e-mail.</param>
 /// <param name="MailBuilder">An e-mail builder.</param>
 /// <param name="RemoteSocket">The remote socket of the incoming SMTP connection.</param>
 public EMailEnvelop(EMailAddressList      MailFrom,
                     EMailAddressList      RcptTo,
                     AbstractEMailBuilder  MailBuilder,
                     IPSocket              RemoteSocket  = null)
 {
     this._RemoteSocket  = RemoteSocket;
     this._MailFrom      = MailFrom;
     this._RcptTo        = RcptTo;
     this._Mail          = new EMail(MailBuilder);
 }