/// <summary>
        /// Dns relay session constructor.
        /// </summary>
        /// <param name="server">Owner relay server.</param>
        /// <param name="localBindInfo">Local bind info.</param>
        /// <param name="realyItem">Relay item.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>localBindInfo</b> or <b>realyItem</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        internal Relay_Session(Relay_Server server, IPBindInfo localBindInfo, Relay_QueueItem realyItem)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (localBindInfo == null)
            {
                throw new ArgumentNullException("localBindInfo");
            }
            if (realyItem == null)
            {
                throw new ArgumentNullException("realyItem");
            }

            m_pServer        = server;
            m_pLocalBindInfo = localBindInfo;
            m_pRelayItem     = realyItem;

            m_SessionID         = Guid.NewGuid().ToString();
            m_SessionCreateTime = DateTime.Now;
            m_pTargets          = new List <Relay_Target>();
            m_pSmtpClient       = new SMTP_Client();

            m_pSmtpClient.BdatEnabled = false;
        }
        /// <summary>
        /// Smart host relay session constructor.
        /// </summary>
        /// <param name="server">Owner relay server.</param>
        /// <param name="localBindInfo">Local bind info.</param>
        /// <param name="realyItem">Relay item.</param>
        /// <param name="smartHosts">Smart hosts.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>localBindInfo</b>,<b>realyItem</b> or <b>smartHosts</b>is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        internal Relay_Session(Relay_Server server,
                               IPBindInfo localBindInfo,
                               Relay_QueueItem realyItem,
                               Relay_SmartHost[] smartHosts)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (localBindInfo == null)
            {
                throw new ArgumentNullException("localBindInfo");
            }
            if (realyItem == null)
            {
                throw new ArgumentNullException("realyItem");
            }
            if (smartHosts == null)
            {
                throw new ArgumentNullException("smartHosts");
            }

            m_pServer        = server;
            m_pLocalBindInfo = localBindInfo;
            m_pRelayItem     = realyItem;
            m_pSmartHosts    = smartHosts;

            m_RelayMode         = Relay_Mode.SmartHost;
            m_SessionID         = Guid.NewGuid().ToString();
            m_SessionCreateTime = DateTime.Now;
            m_pTargets          = new List <Relay_Target>();
        }
Exemple #3
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="sessionID">Session ID.</param>
        /// <param name="socket">Server connected socket.</param>
        /// <param name="bindInfo">BindInfo what accepted socket.</param>
        /// <param name="server">Reference to server.</param>
        internal FTP_Session(string sessionID, SocketEx socket, IPBindInfo bindInfo, FTP_Server server) : base(sessionID, socket, bindInfo, server)
        {
            m_pServer = server;

            // Start session proccessing
            StartSession();
        }
        public void Start()
        {
            if (!_started)
            {
                _localIP = IPAddressHelper.GetLocalIp();
                Gateway gw = InfoService.Instance.CurrentGateway; //当前网关配置。
                _localAOR = $"{gw.SipNumber}@{_localIP}";

                //m_stack = new SIP_Stack();
                //m_stack.Realm = "seecool"; //本地域,当需要验证远程注册用户的时候,发送此域。
                //m_stack.UserAgent = "NetGateway www.seecool.cc";//必须设置。
                //m_stack.Error += M_stack_Error;
                //m_stack.RequestReceived += M_stack_RequestReceived;
                //m_stack.ResponseReceived += M_stack_ResponseReceived;
                //m_stack.Logger.WriteLog += Logger_WriteLog;

                //用户注册授权凭证,向远程服务器注册本机时需要。
                //m_stack.Credentials.Add(new NetworkCredential("admin", "admin", "seecool"));

                //添加本地端口绑定
                IPBindInfo[] bindInfo = new IPBindInfo[] {
                    new IPBindInfo(_localIP, BindInfoProtocol.UDP, IPAddress.Parse(_localIP), gw.Port),
                    new IPBindInfo(_localIP, BindInfoProtocol.TCP, IPAddress.Parse(_localIP), gw.Port)
                };

                Stack.BindInfo = bindInfo;
                Stack.Start();
                addVirtualServer();
                _deviceMgr.Start();
                _started = true;
            }
        }
Exemple #5
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="socket">Listening socket.</param>
            /// <param name="bindInfo">Bind info what acceped socket.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> or <b>bind</b> is null.</exception>
            public ListeningPoint(Socket socket, IPBindInfo bindInfo)
            {
                AssertUtil.ArgumentNotNull(socket, nameof(socket));
                AssertUtil.ArgumentNotNull(bindInfo, nameof(bindInfo));

                this.Socket   = socket;
                this.BindInfo = bindInfo;
            }
Exemple #6
0
        public void LoadTcpSettings(QueueHost host)
        {
            IPBindInfo bindinfo = new IPBindInfo(host.HostAddress, NetworkProtocol.Tcp, IPAddress.Any, host.Port);

            MaxConnections      = 0;
            MaxConnectionsPerIP = 0;
            TaskIdleTimeout     = 0;
        }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="sessionID">Session ID.</param>
        /// <param name="socket">Server connected socket.</param>
        /// <param name="bindInfo">BindInfo what accepted socket.</param>
        /// <param name="server">Reference to server.</param>
        internal FTP_Session(string sessionID, SocketEx socket, IPBindInfo bindInfo, FTP_Server server)
            : base(sessionID, socket, bindInfo, server)
        {
            m_pServer = server;

            // Start session proccessing
            StartSession();
        }
Exemple #8
0
 private void LoadData()
 {
     try
     {
         SipSettings sIP = this.m_pVirtualServer.SystemSettings.SIP;
         this.m_pTabGeneral_Enabled.Checked = sIP.Enabled;
         if ((sIP.ProxyMode & SIP_ProxyMode.B2BUA) != (SIP_ProxyMode)0)
         {
             this.m_pTabGeneral_ProxyType.SelectedIndex = 0;
         }
         else
         {
             this.m_pTabGeneral_ProxyType.SelectedIndex = 1;
         }
         this.m_pTabGeneral_MinExpires.Value = Convert.ToDecimal(sIP.MinimumExpires);
         IPBindInfo[] binds = sIP.Binds;
         for (int i = 0; i < binds.Length; i++)
         {
             IPBindInfo   iPBindInfo   = binds[i];
             ListViewItem listViewItem = new ListViewItem();
             listViewItem.Text = iPBindInfo.HostName;
             if (iPBindInfo.IP.ToString() == "0.0.0.0")
             {
                 listViewItem.SubItems.Add("Any IPv4");
             }
             else if (iPBindInfo.IP.ToString() == "0:0:0:0:0:0:0:0")
             {
                 listViewItem.SubItems.Add("Any IPv6");
             }
             else
             {
                 listViewItem.SubItems.Add(iPBindInfo.IP.ToString());
             }
             listViewItem.SubItems.Add(iPBindInfo.Protocol.ToString());
             listViewItem.SubItems.Add(iPBindInfo.Port.ToString());
             listViewItem.SubItems.Add(iPBindInfo.SslMode.ToString());
             listViewItem.SubItems.Add(Convert.ToString(iPBindInfo.Certificate != null));
             listViewItem.Tag = iPBindInfo;
             this.m_pTabGeneral_Bindings.Items.Add(listViewItem);
         }
         foreach (SipGateway sipGateway in this.m_pVirtualServer.SystemSettings.SIP.Gateways)
         {
             ListViewItem listViewItem2 = new ListViewItem(sipGateway.UriScheme);
             listViewItem2.SubItems.Add(sipGateway.Transport);
             listViewItem2.SubItems.Add(sipGateway.Host);
             listViewItem2.SubItems.Add(sipGateway.Port.ToString());
             listViewItem2.Tag = sipGateway;
             this.m_pTabGateways_Gateways.Items.Add(listViewItem2);
         }
         this.m_pTabGateways_Gateways_SelectedIndexChanged(null, null);
     }
     catch (Exception x)
     {
         ErrorForm errorForm = new ErrorForm(x, new StackTrace());
         errorForm.ShowDialog(this);
     }
 }
Exemple #9
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="socket">Socket.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> is null reference.</exception>
            public TCP_Acceptor(Socket socket, IPBindInfo bindInfo)
            {
                if (socket == null)
                {
                    throw new ArgumentNullException("socket");
                }

                m_pSocket = socket;

                m_pBindInfo = bindInfo;
            }
        /// <summary>
        /// Initialize and start new session here. Session isn't added to session list automatically,
        /// session must add itself to server session list by calling AddSession().
        /// </summary>
        /// <param name="socket">Connected client socket.</param>
        /// <param name="bindInfo">BindInfo what accepted socket.</param>
        protected override void InitNewSession(Socket socket, IPBindInfo bindInfo)
        {
            string   sessionID = Guid.NewGuid().ToString();
            SocketEx socketEx  = new SocketEx(socket);

            if (LogCommands)
            {
                socketEx.Logger           = new SocketLogger(socket, SessionLog);
                socketEx.Logger.SessionID = sessionID;
            }
            FTP_Session session = new FTP_Session(sessionID, socketEx, bindInfo, this);
        }
        /// <summary>
        /// Processes specified connection.
        /// </summary>
        /// <param name="socket">Accpeted socket.</param>
        /// <param name="bindInfo">Local bind info what accpeted connection.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> or <b>bindInfo</b> is null reference.</exception>
        private void ProcessConnection(Socket socket, IPBindInfo bindInfo)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }
            if (bindInfo == null)
            {
                throw new ArgumentNullException("bindInfo");
            }

            m_ConnectionsProcessed++;

            try
            {
                T session = new T();
                session.Init(this,
                             socket,
                             bindInfo.HostName,
                             bindInfo.SslMode == SslMode.SSL,
                             bindInfo.Certificate);

                // Maximum allowed connections exceeded, reject connection.
                if (m_MaxConnections != 0 && m_pSessions.Count > m_MaxConnections)
                {
                    OnMaxConnectionsExceeded(session);
                    session.Dispose();
                }
                // Maximum allowed connections per IP exceeded, reject connection.
                else if (m_MaxConnectionsPerIP != 0)
                {
                    OnMaxConnectionsPerIPExceeded(session);
                    session.Dispose();
                }
                // Start processing new session.
                else
                {
                    session.Disonnected +=
                        delegate(object sender, EventArgs e) { m_pSessions.Remove((T)sender); };
                    m_pSessions.Add(session);

                    OnSessionCreated(session);

                    session.Start();
                }
            }
            catch (Exception x)
            {
                OnError(x);
            }
        }
Exemple #12
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="socket">Listening socket.</param>
            /// <param name="bind">Bind info what acceped socket.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> or <b>bind</b> is null reference.</exception>
            public ListeningPoint(Socket socket, IPBindInfo bind)
            {
                if (socket == null)
                {
                    throw new ArgumentNullException("socket");
                }
                if (bind == null)
                {
                    throw new ArgumentNullException("socket");
                }

                m_pSocket   = socket;
                m_pBindInfo = bind;
            }
Exemple #13
0
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                if (m_IsDisposed)
                {
                    return;
                }
                m_IsDisposed = true;

                m_pSocket     = null;
                m_pSocketArgs = null;
                m_pBindInfo   = null;

                this.ConnectionAccepted = null;
                this.Error = null;
            }
Exemple #14
0
 private void LoadData()
 {
     try
     {
         SmtpSettings sMTP = this.m_pVirtualServer.SystemSettings.SMTP;
         this.m_pEnabled.Checked       = sMTP.Enabled;
         this.m_pGreetingText.Text     = sMTP.GreetingText;
         this.m_pDefaultDomain.Text    = sMTP.DefaultDomain;
         this.m_pSessionTimeout.Value  = sMTP.SessionIdleTimeOut;
         this.m_pMaxConnections.Value  = sMTP.MaximumConnections;
         this.m_pMaxConnsPerIP.Value   = sMTP.MaximumConnectionsPerIP;
         this.m_pMaxBadCommands.Value  = sMTP.MaximumBadCommands;
         this.m_pMaxMessageSize.Value  = sMTP.MaximumMessageSize;
         this.m_pMaxRecipients.Value   = sMTP.MaximumRecipientsPerMessage;
         this.m_pMaxTransactions.Value = sMTP.MaximumTransactions;
         this.m_pRequireAuth.Checked   = sMTP.RequireAuthentication;
         IPBindInfo[] binds = sMTP.Binds;
         for (int i = 0; i < binds.Length; i++)
         {
             IPBindInfo   iPBindInfo   = binds[i];
             ListViewItem listViewItem = new ListViewItem();
             listViewItem.Text = iPBindInfo.HostName;
             if (iPBindInfo.IP.ToString() == "0.0.0.0")
             {
                 listViewItem.SubItems.Add("Any IPv4");
             }
             else if (iPBindInfo.IP.ToString() == "0:0:0:0:0:0:0:0")
             {
                 listViewItem.SubItems.Add("Any IPv6");
             }
             else
             {
                 listViewItem.SubItems.Add(iPBindInfo.IP.ToString());
             }
             listViewItem.SubItems.Add(iPBindInfo.Port.ToString());
             listViewItem.SubItems.Add(iPBindInfo.SslMode.ToString());
             listViewItem.SubItems.Add(Convert.ToString(iPBindInfo.Certificate != null));
             listViewItem.Tag = iPBindInfo;
             this.m_pTabGeneral_Bindings.Items.Add(listViewItem);
         }
         this.m_pTabGeneral_Bindings_SelectedIndexChanged(this, new EventArgs());
     }
     catch (Exception x)
     {
         ErrorForm errorForm = new ErrorForm(x, new StackTrace());
         errorForm.ShowDialog(this);
     }
 }
Exemple #15
0
        /// <summary>
        /// Completes relay session and does clean up. This method is thread-safe.
        /// </summary>
        /// <param name="exception">Exception happened or null if relay completed successfully.</param>
        public void Dispose(Exception exception)
        {
            try
            {
                lock (this)
                {
                    if (m_IsDisposed)
                    {
                        return;
                    }
                    try
                    {
                        m_pServer.OnSessionCompleted(this, exception);
                    }
                    catch
                    {
                    }
                    m_pServer.Sessions.Remove(this);
                    m_IsDisposed = true;

                    m_pLocalBindInfo = null;
                    m_pRelayItem     = null;
                    m_pSmartHosts    = null;
                    if (m_pSmtpClient != null)
                    {
                        m_pSmtpClient.Dispose();
                        m_pSmtpClient = null;
                    }
                    m_pTargets = null;
                    if (m_pActiveTarget != null)
                    {
                        m_pServer.RemoveIpUsage(m_pActiveTarget.Target.Address);
                        m_pActiveTarget = null;
                    }
                    m_pServer = null;
                }
            }
            catch (Exception x)
            {
                if (m_pServer != null)
                {
                    m_pServer.OnError(x);
                }
            }
        }
Exemple #16
0
        //void Load()
        //{
        //    this.LoadSettings(HostAddressTypes.tcp);
        //    if (Adapters.Count > 0)
        //    {
        //        List<IPBindInfo> binds = new List<IPBindInfo>();

        //        foreach (var adapter in Adapters)
        //        {
        //            IPBindInfo bindinfo = new IPBindInfo(adapter.Source.OriginalHostAddress, NetworkProtocol.Tcp, IPAddress.Any, adapter.Source.Port);
        //            binds.Add(bindinfo);
        //        }
        //        var first = Adapters[0];
        //        Bindings = binds.ToArray();
        //        MaxConnections = first.WorkerCount;
        //        MaxConnectionsPerIP = first.MaxItemsPerSession;
        //        TaskIdleTimeout = first.ConnectTimeout;
        //    }
        //}

        internal void Load(AdapterProperties[] adapters)
        {
            if (adapters != null && adapters.Length > 0)
            {
                List <IPBindInfo> binds = new List <IPBindInfo>();

                foreach (var adapter in Adapters)
                {
                    IPBindInfo bindinfo = new IPBindInfo(adapter.Source.HostAddress, NetworkProtocol.Tcp, IPAddress.Any, adapter.Source.Port);
                    binds.Add(bindinfo);
                }
                var first = Adapters[0];
                Bindings            = binds.ToArray();
                MaxConnections      = first.WorkerCount;
                MaxConnectionsPerIP = first.MaxItemsPerSession;
                TaskIdleTimeout     = first.ConnectTimeout;
            }
        }
        /// <summary>
        /// Starts accepting connection(s).
        /// </summary>
        /// <param name="socketArgs">AcceptAsync method data.</param>
        /// <param name="listeningSocket">Local listening socket.</param>
        /// <param name="bindInfo">Local listening socket bind info.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>socketArgs</b>,<b>listeningSocket</b> or <b>bindInfo</b> is null reference.</exception>
        private void IOCompletionBeginAccept(SocketAsyncEventArgs socketArgs,
                                             Socket listeningSocket,
                                             IPBindInfo bindInfo)
        {
            if (socketArgs == null)
            {
                throw new ArgumentNullException("socketArgs");
            }
            if (listeningSocket == null)
            {
                throw new ArgumentNullException("listeningSocket");
            }
            if (bindInfo == null)
            {
                throw new ArgumentNullException("bindInfo");
            }

            try
            {
                // We need to clear it, before reuse.
                socketArgs.AcceptSocket = null;

                // Use active worker thread as long as AcceptAsync completes synchronously.
                // (With this approeach we don't have thread context switches while AcceptAsync completes synchronously)
                while (m_IsRunning && !listeningSocket.AcceptAsync(socketArgs))
                {
                    // Operation completed synchronously.

                    if (socketArgs.SocketError == SocketError.Success)
                    {
                        ProcessConnection(socketArgs.AcceptSocket, bindInfo);
                    }

                    // We need to clear it, before reuse.
                    socketArgs.AcceptSocket = null;
                }
            }
            catch (ObjectDisposedException x)
            {
                string dummy = x.Message;
                // Listening socket closed, so skip that error.
            }
        }
Exemple #18
0
        /// <summary>
        /// Processes specified connection.
        /// </summary>
        /// <param name="socket">Accpeted socket.</param>
        /// <param name="bindInfo">Local bind info what accpeted connection.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> or <b>bindInfo</b> is null reference.</exception>
        private void ProcessConnection(Socket socket, IPBindInfo bindInfo)
        {
            AssertUtil.ArgumentNotNull(socket, nameof(socket));
            AssertUtil.ArgumentNotNull(bindInfo, nameof(bindInfo));

            m_ConnectionsProcessed++;

            try
            {
                T session = new T();
                session.Init(this, socket, bindInfo.HostName, bindInfo.SslMode == SslMode.SSL, bindInfo.Certificate);

                // Maximum allowed connections exceeded, reject connection.
                if (m_MaxConnections > 0 && m_pSessions.Count > m_MaxConnections)
                {
                    OnMaxConnectionsExceeded(session);
                    session.Dispose();
                }
                // Maximum allowed connections per IP exceeded, reject connection.
                else if (m_MaxConnectionsPerIP > 0 &&
                         m_pSessions.GetConnectionsPerIP(session.RemoteEndPoint.Address) > m_MaxConnectionsPerIP)
                {
                    OnMaxConnectionsPerIPExceeded(session);
                    session.Dispose();
                }
                // Start processing new session.
                else
                {
                    session.Disonnected += (sender, e) =>
                    {
                        m_pSessions.Remove((TCP_ServerSession)sender);
                    };

                    m_pSessions.Add(session);
                    OnSessionCreated(session);

                    session.Start();
                }
            }
            catch (Exception ex)
            { OnError(ex); }
        }
Exemple #19
0
        /// <summary>
        /// Initialize and start new session here. Session isn't added to session list automatically,
        /// session must add itself to server session list by calling AddSession().
        /// </summary>
        /// <param name="socket">Connected client socket.</param>
        /// <param name="bindInfo">BindInfo what accepted socket.</param>
        protected override void InitNewSession(Socket socket, IPBindInfo bindInfo)
        {
            // Check maximum conncurent connections from 1 IP.
            if (m_MaxConnectionsPerIP > 0)
            {
                lock (this.Sessions){
                    int nSessions = 0;
                    foreach (SocketServerSession s in this.Sessions)
                    {
                        IPEndPoint ipEndpoint = s.RemoteEndPoint;
                        if (ipEndpoint != null)
                        {
                            if (ipEndpoint.Address.Equals(((IPEndPoint)socket.RemoteEndPoint).Address))
                            {
                                nSessions++;
                            }
                        }

                        // Maimum allowed exceeded
                        if (nSessions >= m_MaxConnectionsPerIP)
                        {
                            socket.Send(System.Text.Encoding.ASCII.GetBytes("421 Maximum connections from your IP address is exceeded, try again later !\r\n"));
                            socket.Shutdown(SocketShutdown.Both);
                            socket.Close();
                            return;
                        }
                    }
                }
            }

            string   sessionID = Guid.NewGuid().ToString();
            SocketEx socketEx  = new SocketEx(socket);

            if (LogCommands)
            {
                socketEx.Logger           = new SocketLogger(socket, this.SessionLog);
                socketEx.Logger.SessionID = sessionID;
            }
            SMTP_Session session = new SMTP_Session(sessionID, socketEx, bindInfo, this);
        }
        /// <summary>
        /// Dns relay session constructor.
        /// </summary>
        /// <param name="server">Owner relay server.</param>
        /// <param name="localBindInfo">Local bind info.</param>
        /// <param name="realyItem">Relay item.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>localBindInfo</b> or <b>realyItem</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        internal Relay_Session(Relay_Server server, IPBindInfo localBindInfo, Relay_QueueItem realyItem)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (localBindInfo == null)
            {
                throw new ArgumentNullException("localBindInfo");
            }
            if (realyItem == null)
            {
                throw new ArgumentNullException("realyItem");
            }

            m_pServer = server;
            m_pLocalBindInfo = localBindInfo;
            m_pRelayItem = realyItem;

            m_SessionID = Guid.NewGuid().ToString();
            m_SessionCreateTime = DateTime.Now;
            m_pTargets = new List<Relay_Target>();
        }
Exemple #21
0
        /// <summary>
        /// Processes relay queue.
        /// </summary>
        private void Run()
        {
            while (m_IsRunning)
            {
                try
                {
                    // Bind info has changed, create new local end points.
                    if (m_HasBindingsChanged)
                    {
                        m_pLocalEndPoints.Clear();

                        foreach (IPBindInfo binding in m_pBindings)
                        {
                            if (binding.IP == IPAddress.Any)
                            {
                                foreach (IPAddress ip in Dns.GetHostAddresses(""))
                                {
                                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        IPBindInfo b = new IPBindInfo(binding.HostName,
                                                                      binding.Protocol,
                                                                      ip,
                                                                      25);
                                        if (!m_pLocalEndPoints.Contains(b))
                                        {
                                            m_pLocalEndPoints.Add(b);
                                        }
                                    }
                                }
                            }
                            else if (binding.IP == IPAddress.IPv6Any)
                            {
                                foreach (IPAddress ip in Dns.GetHostAddresses(""))
                                {
                                    if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                                    {
                                        IPBindInfo b = new IPBindInfo(binding.HostName,
                                                                      binding.Protocol,
                                                                      ip,
                                                                      25);
                                        if (!m_pLocalEndPoints.Contains(b))
                                        {
                                            m_pLocalEndPoints.Add(b);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                IPBindInfo b = new IPBindInfo(binding.HostName,
                                                              binding.Protocol,
                                                              binding.IP,
                                                              25);
                                if (!m_pLocalEndPoints.Contains(b))
                                {
                                    m_pLocalEndPoints.Add(b);
                                }
                            }
                        }

                        m_HasBindingsChanged = false;
                    }

                    // There are no local end points specified.
                    if (m_pLocalEndPoints.Count == 0)
                    {
                        Thread.Sleep(10);
                    }
                    // Maximum allowed relay sessions exceeded, skip adding new ones.
                    else if (m_MaxConnections != 0 && m_pSessions.Count >= m_MaxConnections)
                    {
                        Thread.Sleep(10);
                    }
                    else
                    {
                        Relay_QueueItem item = null;

                        // Get next queued message from highest possible priority queue.
                        foreach (Relay_Queue queue in m_pQueues)
                        {
                            item = queue.DequeueMessage();
                            // There is queued message.
                            if (item != null)
                            {
                                break;
                            }
                            // No messages in this queue, see next lower priority queue.
                        }

                        // There are no messages in any queue.
                        if (item == null)
                        {
                            Thread.Sleep(10);
                        }
                        // Create new session for queued relay item.
                        else
                        {
                            // Get round-robin local end point for that session.
                            // This ensures if multiple network connections, all will be load balanced.
                            IPBindInfo localBindInfo = m_pLocalEndPoints.Next();

                            if (m_RelayMode == Relay_Mode.Dns)
                            {
                                Relay_Session session = new Relay_Session(this, localBindInfo, item);
                                m_pSessions.Add(session);
                                ThreadPool.QueueUserWorkItem(session.Start);
                            }
                            else if (m_RelayMode == Relay_Mode.SmartHost)
                            {
                                // Get smart hosts in balance mode order.
                                Relay_SmartHost[] smartHosts = null;
                                if (m_SmartHostsBalanceMode == BalanceMode.FailOver)
                                {
                                    smartHosts = m_pSmartHosts.ToArray();
                                }
                                else
                                {
                                    smartHosts = m_pSmartHosts.ToCurrentOrderArray();
                                }

                                Relay_Session session = new Relay_Session(this,
                                                                          localBindInfo,
                                                                          item,
                                                                          smartHosts);
                                m_pSessions.Add(session);
                                ThreadPool.QueueUserWorkItem(session.Start);
                            }
                        }
                    }
                }
                catch (Exception x)
                {
                    OnError(x);
                }
            }
        }
Exemple #22
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="server">Reference to server.</param>
 /// <param name="allowUDP">Specifies if UDP protocol is enabled.</param>
 /// <param name="defaultPort">Specifies default port.</param>
 /// <param name="defaultSSLPort">Specifies default SSL port.</param>
 /// <param name="bindInfo">Bind info.</param>
 public wfrm_sys_BindInfo(Server server, bool allowUDP, int defaultPort, int defaultSSLPort, IPBindInfo bindInfo) : this(server, allowUDP, true, true, defaultPort, defaultSSLPort, bindInfo)
 {
 }
        /// <summary>
        /// Completes relay session and does clean up. This method is thread-safe.
        /// </summary>
        /// <param name="exception">Exception happened or null if relay completed successfully.</param>
        public void Dispose(Exception exception)
        {
            try
            {
                lock (this)
                {
                    if (m_IsDisposed)
                    {
                        return;
                    }
                    try
                    {
                        m_pServer.OnSessionCompleted(this, exception);
                    }
                    catch {}
                    m_pServer.Sessions.Remove(this);
                    m_IsDisposed = true;

                    m_pLocalBindInfo = null;
                    m_pRelayItem = null;
                    m_pSmartHosts = null;
                    if (m_pSmtpClient != null)
                    {
                        m_pSmtpClient.Dispose();
                        m_pSmtpClient = null;
                    }
                    m_pTargets = null;
                    if (m_pActiveTarget != null)
                    {
                        m_pServer.RemoveIpUsage(m_pActiveTarget.Target.Address);
                        m_pActiveTarget = null;
                    }
                    m_pServer = null;
                }
            }
            catch (Exception x)
            {
                if (m_pServer != null)
                {
                    m_pServer.OnError(x);
                }
            }
        }
Exemple #24
0
 public AddEditBindInfoForm(Server server, bool allowUDP, int defaultPort, int defaultSSLPort, IPBindInfo bindInfo) : this(server, allowUDP, true, true, defaultPort, defaultSSLPort, bindInfo)
 {
 }
Exemple #25
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="server">Reference to server.</param>
        /// <param name="allowUDP">Specifies if UDP protocol is enabled.</param>
        /// <param name="allowSSL">Specifies if SSL is enabled.</param>
        /// <param name="allowChangePort">Specifies if port can be changed.</param>
        /// <param name="defaultPort">Specifies default port.</param>
        /// <param name="defaultSSLPort">Specifies default SSL port.</param>
        /// <param name="bindInfo">Bind info.</param>
        public wfrm_sys_BindInfo(Server server, bool allowUDP, bool allowSSL, bool allowChangePort, int defaultPort, int defaultSSLPort, IPBindInfo bindInfo)
        {
            m_SslEnabled     = allowSSL;
            m_DefaultPort    = defaultPort;
            m_DefaultSSLPort = defaultSSLPort;

            InitUI();

            m_pSslMode.SelectedIndex = 0;
            if (!allowSSL)
            {
                m_pSslMode.Enabled = false;
            }
            if (!allowChangePort)
            {
                m_pPort.Enabled = false;
            }

            if (bindInfo != null)
            {
                m_pHostName.Text = bindInfo.HostName;
            }

            m_pProtocol.Items.Add("TCP");
            if (allowUDP)
            {
                m_pProtocol.Items.Add("UDP");
            }
            if (bindInfo == null)
            {
                m_pProtocol.SelectedIndex = 0;
            }
            else
            {
                m_pProtocol.Text = bindInfo.Protocol.ToString();
            }

            foreach (IPAddress ip in server.IPAddresses)
            {
                m_pIP.Items.Add(new WComboBoxItem(IpToString(ip), ip));
            }

            if (bindInfo == null)
            {
                m_pIP.SelectedIndex = 0;
                m_pPort.Value       = defaultPort;
            }
            else
            {
                m_pCert = bindInfo.Certificate;

                m_pIP.Text      = IpToString(bindInfo.IP);
                m_pPort.Value   = bindInfo.Port;
                m_pSslMode.Text = bindInfo.SslMode.ToString();
            }

            UpdateCertStatus();
        }
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="socket">Listening socket.</param>
 /// <param name="bind">Bind info what acceped socket.</param>
 public ListeningPoint(Socket socket, IPBindInfo bind)
 {
     m_pSocket   = socket;
     m_pBindInfo = bind;
 }
Exemple #27
0
 public AddEditBindInfoForm(Server server, bool allowUDP, bool allowSSL, bool allowChangePort, int defaultPort, int defaultSSLPort, IPBindInfo bindInfo)
 {
     this.m_SslEnabled     = allowSSL;
     this.m_DefaultPort    = defaultPort;
     this.m_DefaultSSLPort = defaultSSLPort;
     this.InitializeComponent();
     this.m_pSslMode.SelectedIndex = 0;
     if (!allowSSL)
     {
         this.m_pSslMode.Enabled = false;
     }
     if (!allowChangePort)
     {
         this.m_pPort.Enabled = false;
     }
     if (bindInfo != null)
     {
         this.m_pHostName.Text = bindInfo.HostName;
     }
     this.m_pProtocol.Items.Add("TCP");
     if (allowUDP)
     {
         this.m_pProtocol.Items.Add("UDP");
     }
     if (bindInfo == null)
     {
         this.m_pProtocol.SelectedIndex = 0;
     }
     else
     {
         this.m_pProtocol.Text = bindInfo.Protocol.ToString();
     }
     IPAddress[] iPAddresses = server.IPAddresses;
     for (int i = 0; i < iPAddresses.Length; i++)
     {
         IPAddress iPAddress = iPAddresses[i];
         this.m_pIP.Items.Add(new WComboBoxItem(this.IpToString(iPAddress), iPAddress));
     }
     if (bindInfo == null)
     {
         this.m_pIP.SelectedIndex = 0;
         this.m_pPort.Value       = defaultPort;
     }
     else
     {
         this.m_pCert         = bindInfo.Certificate;
         this.m_pIP.Text      = this.IpToString(bindInfo.IP);
         this.m_pPort.Value   = bindInfo.Port;
         this.m_pSslMode.Text = bindInfo.SslMode.ToString();
     }
     this.UpdateCertStatus();
 }
        /// <summary>
        /// Processes relay queue.
        /// </summary>
        private void Run()
        {
            while (m_IsRunning)
            {
                try
                {
                    // Bind info has changed, create new local end points.
                    if (m_HasBindingsChanged)
                    {
                        m_pLocalEndPoints.Clear();

                        foreach (IPBindInfo binding in m_pBindings)
                        {
                            if (binding.IP == IPAddress.Any)
                            {
                                foreach (IPAddress ip in Dns.GetHostAddresses(""))
                                {
                                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        IPBindInfo b = new IPBindInfo(binding.HostName,
                                                                      binding.Protocol,
                                                                      ip,
                                                                      25);
                                        if (!m_pLocalEndPoints.Contains(b))
                                        {
                                            m_pLocalEndPoints.Add(b);
                                        }
                                    }
                                }
                            }
                            else if (binding.IP == IPAddress.IPv6Any)
                            {
                                foreach (IPAddress ip in Dns.GetHostAddresses(""))
                                {
                                    if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                                    {
                                        IPBindInfo b = new IPBindInfo(binding.HostName,
                                                                      binding.Protocol,
                                                                      ip,
                                                                      25);
                                        if (!m_pLocalEndPoints.Contains(b))
                                        {
                                            m_pLocalEndPoints.Add(b);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                IPBindInfo b = new IPBindInfo(binding.HostName,
                                                              binding.Protocol,
                                                              binding.IP,
                                                              25);
                                if (!m_pLocalEndPoints.Contains(b))
                                {
                                    m_pLocalEndPoints.Add(b);
                                }
                            }
                        }

                        m_HasBindingsChanged = false;
                    }

                    // There are no local end points specified.
                    if (m_pLocalEndPoints.Count == 0)
                    {
                        Thread.Sleep(10);
                    }
                        // Maximum allowed relay sessions exceeded, skip adding new ones.
                    else if (m_MaxConnections != 0 && m_pSessions.Count >= m_MaxConnections)
                    {
                        Thread.Sleep(10);
                    }
                    else
                    {
                        Relay_QueueItem item = null;

                        // Get next queued message from highest possible priority queue.
                        foreach (Relay_Queue queue in m_pQueues)
                        {
                            item = queue.DequeueMessage();
                            // There is queued message.
                            if (item != null)
                            {
                                break;
                            }
                            // No messages in this queue, see next lower priority queue.
                        }

                        // There are no messages in any queue.
                        if (item == null)
                        {
                            Thread.Sleep(10);
                        }
                            // Create new session for queued relay item.
                        else
                        {
                            // Get round-robin local end point for that session.
                            // This ensures if multiple network connections, all will be load balanced.
                            IPBindInfo localBindInfo = m_pLocalEndPoints.Next();

                            if (m_RelayMode == Relay_Mode.Dns)
                            {
                                Relay_Session session = new Relay_Session(this, localBindInfo, item);
                                m_pSessions.Add(session);
                                ThreadPool.QueueUserWorkItem(session.Start);
                            }
                            else if (m_RelayMode == Relay_Mode.SmartHost)
                            {
                                // Get smart hosts in balance mode order.
                                Relay_SmartHost[] smartHosts = null;
                                if (m_SmartHostsBalanceMode == BalanceMode.FailOver)
                                {
                                    smartHosts = m_pSmartHosts.ToArray();
                                }
                                else
                                {
                                    smartHosts = m_pSmartHosts.ToCurrentOrderArray();
                                }

                                Relay_Session session = new Relay_Session(this,
                                                                          localBindInfo,
                                                                          item,
                                                                          smartHosts);
                                m_pSessions.Add(session);
                                ThreadPool.QueueUserWorkItem(session.Start);
                            }
                        }
                    }
                }
                catch (Exception x)
                {
                    OnError(x);
                }
            }
        }
 /// <summary>
 /// Initialize and start new session here. Session isn't added to session list automatically, 
 /// session must add itself to server session list by calling AddSession().
 /// </summary>
 /// <param name="socket">Connected client socket.</param>
 /// <param name="bindInfo">BindInfo what accepted socket.</param>
 protected override void InitNewSession(Socket socket, IPBindInfo bindInfo)
 {
     string sessionID = Guid.NewGuid().ToString();
     SocketEx socketEx = new SocketEx(socket);
     if (LogCommands)
     {
         socketEx.Logger = new SocketLogger(socket, SessionLog);
         socketEx.Logger.SessionID = sessionID;
     }
     FTP_Session session = new FTP_Session(sessionID, socketEx, bindInfo, this);
 }
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="socket">Socket.</param>
 /// <param name="bindInfo">Bind info.</param>
 public QueuedConnection(Socket socket,IPBindInfo bindInfo)
 {
     m_pSocket   = socket;
     m_pBindInfo = bindInfo;
 }
 private void LoadData()
 {
     try
     {
         Relay_Settings relay = this.m_pVirtualServer.SystemSettings.Relay;
         if (relay.RelayMode == Relay_Mode.SmartHost)
         {
             this.m_pTabGeneral_SendSmartHost.Checked = true;
         }
         else
         {
             this.m_pTabGeneral_SendDns.Checked = true;
         }
         if (relay.SmartHostsBalanceMode == BalanceMode.LoadBalance)
         {
             this.m_pTabGeneral_SmartHostsBalanceMode.SelectedIndex = 0;
         }
         else
         {
             this.m_pTabGeneral_SmartHostsBalanceMode.SelectedIndex = 1;
         }
         this.m_pTabGeneral_SessionTimeout.Value         = relay.SessionIdleTimeOut;
         this.m_pTabGeneral_MaxConnections.Value         = relay.MaximumConnections;
         this.m_pTabGeneral_MaxConnsPerIP.Value          = relay.MaximumConnectionsPerIP;
         this.m_pTabGeneral_RelayInterval.Value          = relay.RelayInterval;
         this.m_pTabGeneral_RelayRetryInterval.Value     = relay.RelayRetryInterval;
         this.m_pTabGeneral_SendUndelWarning.Value       = relay.SendUndeliveredWarningAfter;
         this.m_pTabGeneral_SendUndelivered.Value        = relay.SendUndeliveredAfter;
         this.m_pTabGeneral_StoreUndeliveredMsgs.Checked = relay.StoreUndeliveredMessages;
         this.m_pTabGeneral_UseTlsIfPossible.Checked     = relay.UseTlsIfPossible;
         Relay_SmartHost[] smartHosts = relay.SmartHosts;
         for (int i = 0; i < smartHosts.Length; i++)
         {
             Relay_SmartHost relay_SmartHost = smartHosts[i];
             ListViewItem    listViewItem    = new ListViewItem();
             listViewItem.Text = relay_SmartHost.Host;
             listViewItem.SubItems.Add(relay_SmartHost.Port.ToString());
             listViewItem.SubItems.Add(relay_SmartHost.SslMode.ToString());
             listViewItem.SubItems.Add(relay_SmartHost.UserName);
             listViewItem.Tag = relay_SmartHost;
             this.m_pTabGeneral_SmartHosts.Items.Add(listViewItem);
         }
         IPBindInfo[] binds = relay.Binds;
         for (int j = 0; j < binds.Length; j++)
         {
             IPBindInfo   iPBindInfo    = binds[j];
             ListViewItem listViewItem2 = new ListViewItem();
             listViewItem2.Text = iPBindInfo.HostName;
             if (iPBindInfo.IP.ToString() == "0.0.0.0")
             {
                 listViewItem2.SubItems.Add("Any IPv4");
             }
             else if (iPBindInfo.IP.ToString() == "0:0:0:0:0:0:0:0")
             {
                 listViewItem2.SubItems.Add("Any IPv6");
             }
             else
             {
                 listViewItem2.SubItems.Add(iPBindInfo.IP.ToString());
             }
             listViewItem2.SubItems.Add(iPBindInfo.Port.ToString());
             listViewItem2.SubItems.Add(iPBindInfo.SslMode.ToString());
             listViewItem2.SubItems.Add(Convert.ToString(iPBindInfo.Certificate != null));
             listViewItem2.Tag = iPBindInfo;
             this.m_pTabBindings_Bindings.Items.Add(listViewItem2);
         }
         this.AddNotifications();
     }
     catch (Exception x)
     {
         ErrorForm errorForm = new ErrorForm(x, new StackTrace());
         errorForm.ShowDialog(this);
     }
 }
        /// <summary>
        /// Starts connecting to best target.
        /// </summary>
        private void BeginConnect()
        {
            // No tagets, abort relay.
            if (m_pTargets.Count == 0)
            {
                LogText("No relay target(s) for '" + m_pRelayItem.To + "', aborting.");
                Dispose(new Exception("No relay target(s) for '" + m_pRelayItem.To + "', aborting."));

                return;
            }

            // Maximum connections per IP limited.
            if (m_pServer.MaxConnectionsPerIP > 0)
            {
                // For DNS or load-balnced smart host relay, search free target if any.
                if (m_pServer.RelayMode == Relay_Mode.Dns || m_pServer.SmartHostsBalanceMode == BalanceMode.LoadBalance)
                {
                    foreach (Relay_Target t in m_pTargets)
                    {
                        // Get local IP binding for remote IP.
                        m_pLocalBindInfo = m_pServer.GetLocalBinding(t.Target.Address);

                        // We have suitable local IP binding for the target.
                        if (m_pLocalBindInfo != null)
                        {
                            // We found free target, stop searching.
                            if (m_pServer.TryAddIpUsage(t.Target.Address))
                            {
                                m_pActiveTarget = t;
                                m_pTargets.Remove(t);

                                break;
                            }
                            // Connection per IP limit reached.
                            else
                            {
                                LogText("Skipping relay target (" + t.HostName + "->" + t.Target.Address + "), maximum connections to the specified IP has reached.");
                            }
                        }
                        // No suitable local IP binding, try next target.
                        else
                        {
                            LogText("Skipping relay target (" + t.HostName + "->" + t.Target.Address + "), no suitable local IPv4/IPv6 binding.");
                        }
                    }
                }
                // Smart host fail-over mode, just check if it's free.
                else
                {
                    // Get local IP binding for remote IP.
                    m_pLocalBindInfo = m_pServer.GetLocalBinding(m_pTargets[0].Target.Address);

                    // We have suitable local IP binding for the target.
                    if (m_pLocalBindInfo != null)
                    {
                        // Smart host IP limit not reached.
                        if (m_pServer.TryAddIpUsage(m_pTargets[0].Target.Address))
                        {
                            m_pActiveTarget = m_pTargets[0];
                            m_pTargets.RemoveAt(0);
                        }
                        // Connection per IP limit reached.
                        else
                        {
                            LogText("Skipping relay target (" + m_pTargets[0].HostName + "->" + m_pTargets[0].Target.Address + "), maximum connections to the specified IP has reached.");
                        }
                    }
                    // No suitable local IP binding, try next target.
                    else
                    {
                        LogText("Skipping relay target (" + m_pTargets[0].HostName + "->" + m_pTargets[0].Target.Address + "), no suitable local IPv4/IPv6 binding.");
                    }
                }
            }
            // Just get first target.
            else
            {
                // Get local IP binding for remote IP.
                m_pLocalBindInfo = m_pServer.GetLocalBinding(m_pTargets[0].Target.Address);

                // We have suitable local IP binding for the target.
                if (m_pLocalBindInfo != null)
                {
                    m_pActiveTarget = m_pTargets[0];
                    m_pTargets.RemoveAt(0);
                }
                // No suitable local IP binding, try next target.
                else
                {
                    LogText("Skipping relay target (" + m_pTargets[0].HostName + "->" + m_pTargets[0].Target.Address + "), no suitable local IPv4/IPv6 binding.");
                }
            }

            // We don't have suitable local IP end point for relay target.
            // This may heppen for example: if remote server supports only IPv6 and we don't have local IPv6 local end point.
            if (m_pLocalBindInfo == null)
            {
                LogText("No suitable IPv4/IPv6 local IP endpoint for relay target.");
                Dispose(new Exception("No suitable IPv4/IPv6 local IP endpoint for relay target."));

                return;
            }

            // If all targets has exeeded maximum allowed connection per IP address, end relay session,
            // next relay cycle will try to relay again.
            if (m_pActiveTarget == null)
            {
                LogText("All targets has exeeded maximum allowed connection per IP address, skip relay.");
                Dispose(new Exception("All targets has exeeded maximum allowed connection per IP address, skip relay."));

                return;
            }

            // Set SMTP host name.
            m_pSmtpClient.LocalHostName = m_pLocalBindInfo.HostName;

            // Start connecting to remote end point.
            TCP_Client.ConnectAsyncOP connectOP = new TCP_Client.ConnectAsyncOP(new IPEndPoint(m_pLocalBindInfo.IP, 0), m_pActiveTarget.Target, false, null);
            connectOP.CompletedAsync += delegate(object s, EventArgs <TCP_Client.ConnectAsyncOP> e){
                ConnectCompleted(connectOP);
            };
            if (!m_pSmtpClient.ConnectAsync(connectOP))
            {
                ConnectCompleted(connectOP);
            }
        }