Esempio n. 1
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void EnsureOpen(int timeout)
        {
            _closeTimeout = 0;
            if (SoTimeout != 0)
            {
                _closeTimeout = Math.Max(SoTimeout, timeout);
            }
            // If socket is still good, the new closeTimeout will
            // be ignored; see tryClose comment.
            if (_socket == null)
            {
                _socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                //IPAddress.`Address` property deleted
                //_socket.Bind(new IPEndPoint(laddr.Address, _lport));
                _socket.Bind(new IPEndPoint(laddr, _lport));

                if (_waitResponse)
                {
                    _thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient");
                    _thread.SetDaemon(true);
                    _thread.Start();
                }
            }
        }
Esempio n. 2
0
        internal FtpResponseReader(SocketEx s, Encoding en, int maxLineLength)
        {
            if (null == s)
            {
                throw new ArgumentNullException("s", "FtpResponseReader requires non null socket.");
            }

            if (null == en)
            {
                throw new ArgumentNullException("en", "FtpResponseReader requires non null encoding.");
            }

            //maxLineLength = 10;

            _socket       = s;
            _recvBuffer   = new byte[maxLineLength * 2];
            _linesBuilder = new LinesBuilder(maxLineLength);

            //---------------------------------------
            // single line mode is enabled
            // because sometimes few responses (150, 200)
            // may came in the single packet
            // and we should read only first one
            _linesBuilder.SingleLineMode = true;
            _encoding = en;
        }
Esempio n. 3
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, BindInfo 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++;
                  *         }
                  *     }
                  *
                  *     // Maximum allowed exceeded
                  *     if(nSessions >= m_MaxConnectionsPerIP){
                  *         socket.Send(System.Text.Encoding.ASCII.GetBytes("-ERR 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;
            }
            HTTP_Session session = new HTTP_Session(sessionID, socketEx, bindInfo, this);
        }
Esempio n. 4
0
        private async void Connect(IPAddress ip)
        {
            if (connection?.Connected ?? false)
            {
                var result = MessageBox.Show("이미 서버에 연결되어 있습니다.");
                return;
            }

            IPEndPoint remoteEp = new IPEndPoint(ip, 52217);

            try
            {
                Socket server = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                await server.ConnectAsync(remoteEp);

                connection = new SocketEx(server);
                await connection.SendMessageAsync(new CS_Login
                {
                    UserName = "******"
                });

                await HandleReceiveAsync();

                user = new User("yhj");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"서버 연결에 실패하였습니다. {ex.Message}");
                connection?.Close();
                connection = null;
            }
        }
Esempio n. 5
0
        /// <exception cref="System.IO.IOException"></exception>
        protected internal override void DoDisconnect(bool hard)
        {
            try
            {
                if (Sessions != null)
                {
                    foreach (var ssn in Sessions)
                    {
                        ssn?.Logoff(hard);
                    }
                }

                Out?.Close();
                In?.Close();

                //Socket.`Close` method deleted
                //Socket.Close();
                Socket?.Shutdown(SocketShutdown.Both);
                Socket?.Dispose();
            }
            finally
            {
                Digest       = null;
                Socket       = null;
                TconHostName = null;
            }
        }
Esempio n. 6
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,BindInfo 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++;
                            }
                        }

                        // Maximum allowed exceeded
                        if(nSessions >= m_MaxConnectionsPerIP){
                            socket.Send(System.Text.Encoding.ASCII.GetBytes("-ERR 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;
            }
			HTTP_Session session = new HTTP_Session(sessionID,socketEx,bindInfo,this);
		}
Esempio n. 7
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();
        }
Esempio n. 8
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();
        }
Esempio n. 9
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>
        public SocketServerSession(string sessionID, SocketEx socket, IPBindInfo bindInfo, SocketServer server)
        {
            m_SessionID = sessionID;
            m_pSocket   = socket;
            m_pBindInfo = bindInfo;
            m_pServer   = server;

            m_SessionStartTime = DateTime.Now;
        }
Esempio n. 10
0
        private void btnRequest_Click(object sender, System.EventArgs e)
        {
            SocketEx sock = null;

            try
            {
                Uri reqUri = new Uri(txtURL.Text);

                string host = reqUri.Host;
                int    port = reqUri.Port;
                string path = reqUri.PathAndQuery;

                sock = new SocketEx(_proxyType, _proxyServer, _proxyPort,
                                    _proxyUser, _proxyPwd);

                //configure preauthenticate
                sock.PreAuthenticate = _preAuthenticate;


                sock.Connect(host, port);
                string cmd = "GET " + path + " HTTP/1.0\r\n" +
                             "Host: " + host + "\r\n\r\n";
                sock.Send(_usedEnc.GetBytes(cmd));


                //simple reading loop
                //read while have the data
                try
                {
                    byte[] data = new byte[32 * 1024];
                    while (true)
                    {
                        int dataLen = sock.Receive(data);
                        if (0 == dataLen)
                        {
                            break;
                        }
                        txtRes.Text += _usedEnc.GetString(data, 0, dataLen);
                    }
                }
                catch (Exception ex)
                {
                    txtRes.Text += Environment.NewLine + ex.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught!");
            }

            if (null != sock)
            {
                sock.Close();
            }
        }
Esempio n. 11
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)
        {
            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);
        }
Esempio n. 12
0
        internal FtpControlConnection(FtpClient ftp, Encoding en, int maxLineLength)
        {
            if (null == en)
            {
                throw new ArgumentNullException("en", "FtpControlConnection requires non null encoding.");
            }

            _encoding = en;
            _socket   = ftp.GetSocket();
            _reader   = new FtpResponseReader(_socket, _encoding, maxLineLength);
            _client   = ftp;
        }
Esempio n. 13
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void EnsureOpen(int timeout)
        {
            //Log.Out($"NameServiceClient.EnsureOpen");

            _closeTimeout = 0;
            if (SoTimeout != 0)
            {
                _closeTimeout = Math.Max(SoTimeout, timeout);
            }

            var localPort = (SmbConstants.Lport == 0) ? _lport : SmbConstants.Lport;

            // If socket is still good, the new closeTimeout will
            // be ignored; see tryClose comment.
            if (
                _socketSender == null ||
                _socketSender.LocalEndPoint == null ||
                _socketSender.GetLocalPort() != localPort ||
                !IPAddress.Any.Equals(_socketSender.GetLocalInetAddress())
                )
            {
                if (_socketSender != null)
                {
                    _socketSender.Dispose();
                    _socketSender = null;
                }

                _socketSender = new SocketEx(AddressFamily.InterNetwork,
                                             SocketType.Dgram,
                                             ProtocolType.Udp);

                _socketSender.Bind(new IPEndPoint(IPAddress.Any, localPort));


                if (_waitResponse)
                {
                    if (_thread != null)
                    {
                        _thread.Cancel(true);
                        _thread.Dispose();
                    }

                    _thread = new Thread(this);
                    _thread.SetDaemon(true);
                    _thread.Start(true);
                }
            }
        }
Esempio n. 14
0
        public async Task HandlePacketAsync(SocketEx clientSocket, JObject packetObj)
        {
            var packetType = Enum.Parse <PacketType>(packetObj.Value <string>("Type"));
            var userData   = clients.FirstOrDefault(x => x.Socket == clientSocket);

            if (packetType == PacketType.CS_Login)
            {
                var packet = packetObj.ToObject <CS_Login>();
                await Handle_CS_Login(clientSocket, packet);
            }
            else if (packetType == PacketType.CS_Message)
            {
                var packet = packetObj.ToObject <CS_Message>();
                await Handle_CS_Message(userData, packet);
            }
        }
Esempio n. 15
0
 override internal IAsyncResult BeginPrepare(int timeout, SocketEx ccSocket,
                                             AsyncCallback callback,
                                             object state)
 {
     CheckDisposed();
     try
     {
         Prepare_SO stateObj = new Prepare_SO(callback, state);
         stateObj.SetCompleted();
         return(stateObj);
     }
     catch
     {
         CheckDisposed();
         throw;
     }
 }
Esempio n. 16
0
        private async Task Handle_CS_Login(SocketEx clientSocket, CS_Login packet)
        {
            clients.Add(new UserSocketData(packet.UserName, clientSocket));

            await clientSocket.SendMessageAsync(new SC_LoginAllow
            {
                Allow = true,
            });

            await clients.Where(x => x.Socket.Connected)
            .ForEachParallelAsync(async x =>
            {
                await x.Socket.SendMessageAsync(new SC_System
                {
                    Data = $"{packet.UserName}님이 로그인했습니다.",
                });
            });
        }
Esempio n. 17
0
 public void AcceptConnection()
 {
     try
     {
         AcceptSockets.Add(MainSocket.Accept());
         StatusReport    = "Client " + AcceptSockets.Count + " Connected !!";
         ClientConnected = true;
         Send            = true;
         StatusReport.SerializePacket();
         TotalNumberOfConnectedClients = AcceptSockets.Count;
     }
     catch (SocketException SocketEx)
     {
         if (SocketEx.SocketErrorCode != SocketError.WouldBlock)
         {
             StatusReport = SocketEx.ToString();
         }
     }
 }
Esempio n. 18
0
 internal override void EndEstablish(IAsyncResult ar)
 {
     try
     {
         _socket = _listenSocket.EndAccept(ar);
         _stream = new NetworkStreamEx(_socket);
     }
     catch (SocketException e)
     {
         CheckDisposed();
         CheckTimeoutException(e);
         throw;
     }
     catch
     {
         CheckDisposed();
         throw;
     }
 }
Esempio n. 19
0
        private async void Connect(IPAddress ip) // 이 작업 끝나기 전까지는 다른 작업 안함.
        {
            if (connection?.Connected ?? false)
            {
                var result = MessageBox.Show("Already connected. Reconnect?", "", MessageBoxButtons.YesNo);// 재 연결 하시겠습니까?
                if (result == DialogResult.No)
                {
                    return;
                }

                connection.Disconnect(false);
                connection.Close();
                connection = null;
            }
            //IPAddress ipAddress = IPAddress.Parse("221.143.21.37");
            IPEndPoint remoteEP = new IPEndPoint(ip, 52217);

            // Create a TCP/IP socket.
            try
            {
                Socket server = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                await server.ConnectAsync(remoteEP);

                //richTextBox1.Text += $"Connected: {server.Connected} \n";

                connection = new SocketEx(server);

                await connection.SendMessageAsync(new CS_Login
                {
                    UserName = "******",
                });

                await HandleReceiveAsync();
            }
            catch (Exception ex)
            {
                richTextBox1.Text += "Error: " + ex.Message;
                connection?.Close();
                connection = null;
            }
        }
Esempio n. 20
0
        /// <exception cref="System.IO.IOException"></exception>
        protected internal override void DoDisconnect(bool hard)
        {
            try
            {
                foreach (var ssn in Sessions)
                {
                    ssn.Logoff(hard);
                }

                Out.Close();
                In.Close();
                Socket.Dispose();
            }
            finally
            {
                Digest       = null;
                Socket       = null;
                TconHostName = null;
            }
        }
Esempio n. 21
0
        private async void HandleConnection(SocketEx client)
        {
            IServerApi api = new ServerApi(_lobby, client);

            try
            {
                while (true)
                {
                    var(receiveCount, receiveText) = await client.ReceiveMessageAsync();

                    if (receiveCount == 0)
                    {
                        Console.WriteLine("receive 0.");

                        await api.ConnectionClosed();

                        return;
                    }

                    var obj = JObject.Parse(receiveText);
                    if (!obj.ContainsKey("Type"))
                    {
                        //await client.SendMessageAsync(new SC_System
                        //{
                        //    Data = "올바르지 않은 패킷입니다.",
                        //});
                    }

                    await api.HandlePacketAsync(obj);
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Esempio n. 22
0
 override internal void Prepare(int timeout, SocketEx ccSocket)
 {
     CheckDisposed();
     try
     {
         _listenSocket.ConnectTimeout = timeout;                 //Bind used ConnectTimeout value
         _listenSocket.Bind(ccSocket);
         _listenSocket.Listen(1);
     }
     catch (SocketException e)
     {
         CheckDisposed();
         CheckTimeoutException(e);
         throw;
     }
     catch
     {
         CheckDisposed();
         throw;
     }
 }
Esempio n. 23
0
 internal override void Establish(int timeout)
 {
     CheckDisposed();
     try
     {
         _listenSocket.AcceptTimeout = timeout;
         _socket = _listenSocket.Accept();
         _stream = new NetworkStreamEx(_socket);
     }
     catch (SocketException e)
     {
         CheckDisposed();
         CheckTimeoutException(e);
         throw;
     }
     catch
     {
         CheckDisposed();
         throw;
     }
 }
Esempio n. 24
0
        internal virtual void TryClose()
        {
            lock (_lock)
            {
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }
                _thread = null;

                if (_waitResponse)
                {
                    _responseTable.Clear();
                }
                else
                {
                    _autoResetWaitReceive.Set();
                }
            }
        }
        /// <summary>
        /// Converts socket local or remote end point to SIP_EndPointInfo.
        /// </summary>
        /// <param name="socket">Socket to use.</param>
        /// <param name="local_remote">Specifies if loacl or remote end point of socket is used.</param>
        /// <returns>Returns SIP end point info.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> is null.</exception>
        public static SIP_EndPointInfo ToEndPointInfo(SocketEx socket,bool local_remote)
        {
            if(socket == null){
                throw new ArgumentNullException("socket");
            }

            IPEndPoint ep = null;
            if(local_remote){
                ep = (IPEndPoint)socket.LocalEndPoint;
            }
            else{
                ep = (IPEndPoint)socket.RemoteEndPoint;
            }

            if(socket.RawSocket.ProtocolType == System.Net.Sockets.ProtocolType.Udp){
                return new SIP_EndPointInfo(SIP_Transport.UDP,ep);
            }
            else{
                return new SIP_EndPointInfo(SIP_Transport.TCP,ep);
            }
        }
Esempio n. 26
0
        public void TestFlushAfterGatheredFlush()
        {
            var      group  = new MultithreadEventLoopGroup(1);
            var      socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            IChannel sc     = null;

            try
            {
                ServerBootstrap sb = new ServerBootstrap();
                sb.Group(group)
                .Channel <TcpServerSocketChannel>()
                .ChildHandler(new ChannelInboundHandlerAdapter0());

                sc = sb.BindAsync(new IPEndPoint(IPAddress.Loopback, 0)).GetAwaiter().GetResult();
                socket.ConnectAsync(sc.LocalAddress).GetAwaiter().GetResult();
                byte[]      tempArea   = new byte[3];
                Span <byte> buf        = tempArea;
                var         totalCount = 0;
                do
                {
                    var byteCount = socket.Receive(buf);
                    if (byteCount < 0)
                    {
                        break;
                    }
                    totalCount += byteCount;
                    if (totalCount < 3)
                    {
                        buf = buf.Slice(totalCount);
                    }
                } while (totalCount < 3);
                Assert.Equal("abc", Encoding.ASCII.GetString(tempArea));
            }
            finally
            {
                sc?.CloseAsync().GetAwaiter().GetResult();
                SocketEx.SafeClose(socket);
                group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)).GetAwaiter().GetResult();
            }
        }
Esempio n. 27
0
        private async void Connect(IPAddress ip)
        {
            if (connection?.Connected ?? false)
            {
                var result = MessageBox.Show("Already connected. Reconnect?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.No)
                {
                    return;
                }
                connection.Disconnect(false);
                connection.Close();
                connection = null;
            }

            IPEndPoint remoteEP = new IPEndPoint(ip, 52217);

            // Create a TCP/IP socket.
            try
            {
                Socket server = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                await server.ConnectAsync(remoteEP);

                connection = new SocketEx(server);

                await connection.SendMessageAsync(new CS_Login
                {
                    UserName = "******",
                });

                await HandleReceiveAsync();
            }
            catch (Exception ex)
            {
                ChattingListTextBox.Text += "Error: " + ex.Message;
                connection?.Close();
                connection = null;
            }
        }
Esempio n. 28
0
 override internal IAsyncResult BeginPrepare(int timeout,
                                             SocketEx ccSocket,
                                             AsyncCallback callback,
                                             object state)
 {
     CheckDisposed();
     try
     {
         _listenSocket.ConnectTimeout = timeout;                 //Bind used ConnectTimeout value
         return(_listenSocket.BeginBind(ccSocket, callback, state));
     }
     catch (SocketException e)
     {
         CheckDisposed();
         CheckTimeoutException(e);
         throw;
     }
     catch
     {
         CheckDisposed();
         throw;
     }
 }
Esempio n. 29
0
        internal virtual void TryClose()
        {
            //Log.Out("NameSerciceClient.TryClose");

            if (this._isActive)
            {
                //Log.Out("NameSerciceClient.TryClose - Now in Processing... Exit.");
                return;
            }

            lock (_lock)
            {
                if (_socketSender != null)
                {
                    _socketSender.Dispose();
                    _socketSender = null;
                    //Log.Out("NameSerciceClient.TryClose - _socketSender.Disposed");
                }

                if (_thread != null)
                {
                    _thread.Cancel(true);
                    _thread.Dispose();
                    _thread = null;
                    //Log.Out("NameSerciceClient.TryClose - _thread.Aborted");
                }

                if (_waitResponse)
                {
                    _responseTable.Clear();
                }
                else
                {
                    _autoResetWaitReceive.Set();
                }
            }
        }
Esempio n. 30
0
        private async void HandleConnection(SocketEx client)
        {
            try
            {
                while (true)
                {
                    var(receiveCount, receiveText) = await client.ReceiveMessageAsync();

                    if (receiveCount == 0)
                    {
                        Console.WriteLine("receive 0.");

                        await _chattingServer.DisconnectAsync(client);

                        return;
                    }

                    var obj = JObject.Parse(receiveText);
                    if (!obj.ContainsKey("Type"))
                    {
                        await client.SendMessageAsync(new SC_System
                        {
                            Data = "올바르지 않은 패킷입니다.",
                        });
                    }

                    await _chattingServer.HandlePacketAsync(client, obj);
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch
            {
            }
        }
Esempio n. 31
0
        void Connect()
        {
            while (!MainSocket.Connected)
            {
                Thread.Sleep(100);

                try
                {
                    MainSocket.Connect(ServerIPEndPoint);
                }
                catch (SocketException SocketEx)
                {
                    if (SocketEx.SocketErrorCode != SocketError.WouldBlock)
                    {
                        StatusReport = SocketEx.ToString();
                    }
                }

                if (MainSocket.Connected)
                {
                    StatusReport = "Game Client Connected to " + ServerIPEndPoint.ToString();
                }
            }
        }
Esempio n. 32
0
        void ProcessAccept(SocketAsyncEventArgs e)
        {
            if (Server == null || Server.Stopped.IsTrue())
            {
                return;
            }

            Socket socket = null;

            if (e.SocketError != SocketError.Success)
            {
                if (SocketEx.IsIgnorableError(e.SocketError) == false)
                {
                    Logger.Error(string.Format("ProcessAccept:{0}", e.SocketError));
                }

                Task.Run(() => { e.AcceptSocket.CloseEx(); });

                e.AcceptSocket = null;
                Server.m_AcceptSAEAPool.Push(e);
                StartAccept();
                return;
            }

            socket = e.AcceptSocket;

            StartAccept();

            e.AcceptSocket = null;
            Server.m_AcceptSAEAPool.Push(e);

            if (socket != null)
            {
                OnAccepted(socket);
            }
        }
        /// <summary>
        /// Connects to specified NNTP server.
        /// </summary>
        /// <param name="server">NNTP server.</param>
        /// <param name="port">NNTP server port. Defualt NNTP port is 119.</param>
        public void Connect(string server,int port)
        {
            if(m_Connected){
                throw new Exception("NNTP client is already connected, Disconnect first before calling Connect !");
            }

            m_pSocket = new SocketEx();
            m_pSocket.Connect(server,port);
            /*
            if(m_LogCmds && SessionLog != null){
                m_pLogger = new SocketLogger(s,SessionLog);
                m_pLogger.SessionID = Guid.NewGuid().ToString();
                m_pSocket.Logger = m_pLogger;
            }*/

            // Set connected flag
            m_Connected = true;

            // Read server response
            string responseLine = m_pSocket.ReadLine(1000);
            if(!responseLine.StartsWith("200")){
                throw new Exception(responseLine);
            }
        }
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                if(m_Disposed){
                    return;
                }
                m_Disposed = true;

                if(m_pSocket != null){
                    try{
                        m_pSocket.Dispose();
                    }
                    catch{
                    }
                    m_pSocket = null;
                }

                // Remove from active pipes.
                if(m_pTLayer != null){
                    m_pTLayer.m_pTcpReceiviePipes.Remove(this);
                }
            }
 /// <summary>
 /// Sends response to request maker.
 /// </summary>
 /// <param name="socket">Socket which to use to send response.</param>
 /// <param name="response">Response to send.</param>
 public void SendResponse(SocketEx socket,SIP_Response response)
 {
     SendResponse(socket,null,response);
 }
        /// <summary>
        /// Sends response to request maker.
        /// </summary>
        /// <param name="socket">Socket which to use to send response.</param>
        /// <param name="remoteEndPoint">Remote end point where to send response. 
        /// If this value is null, Via header is used to get remote end point.
        /// </param>
        /// <param name="response">Response to send.</param>
        public void SendResponse(SocketEx socket,IPEndPoint remoteEndPoint,SIP_Response response)
        {
            /* RFC 3581 4.  Server Behavior.
                When a server attempts to send a response, it examines the topmost
                Via header field value of that response.  If the "sent-protocol"
                component indicates an unreliable unicast transport protocol, such as
                UDP, and there is no "maddr" parameter, but there is both a
                "received" parameter and an "rport" parameter, the response MUST be
                sent to the IP address listed in the "received" parameter, and the
                port in the "rport" parameter.  The response MUST be sent from the
                same address and port that the corresponding request was received on
                in order to traverse symmetric NATs.

            */

            /* RFC 3261 18.2.2 Sending Responses.
                The server transport uses the value of the top Via header field in
                order to determine where to send a response.  It MUST follow the
                following process:

                  o  If the "sent-protocol" is a reliable transport protocol such as
                     TCP or SCTP, or TLS over those, the response MUST be sent using
                     the existing connection to the source of the original request
                     that created the transaction, if that connection is still open.
                     This requires the server transport to maintain an association
                     between server transactions and transport connections.  If that
                     connection is no longer open, the server SHOULD open a
                     connection to the IP address in the "received" parameter, if
                     present, using the port in the "sent-by" value, or the default
                     port for that transport, if no port is specified.  If that
                     connection attempt fails, the server SHOULD use the procedures
                     in [4] for servers in order to determine the IP address and
                     port to open the connection and send the response to.

                  o  Otherwise, if the Via header field value contains a "maddr"
                     parameter, the response MUST be forwarded to the address listed
                     there, using the port indicated in "sent-by", or port 5060 if
                     none is present.  If the address is a multicast address, the
                     response SHOULD be sent using the TTL indicated in the "ttl"
                     parameter, or with a TTL of 1 if that parameter is not present.

                  o  Otherwise (for unreliable unicast transports), if the top Via
                     has a "received" parameter, the response MUST be sent to the
                     address in the "received" parameter, using the port indicated
                     in the "sent-by" value, or using port 5060 if none is specified
                     explicitly.  If this fails, for example, elicits an ICMP "port
                     unreachable" response, the procedures of Section 5 of [4]
                     SHOULD be used to determine where to send the response.

                  o  Otherwise, if it is not receiver-tagged, the response MUST be
                     sent to the address indicated by the "sent-by" value, using the
                     procedures in Section 5 of [4].
            */

            // TODO: Probably we can use local endpoint instead of socket. Because then we can
            //       Search right UDP connection or TCP/TLS connection.

            try{
                SIP_t_ViaParm via = response.Via.GetTopMostValue();

                // End point not specified, get it from Via.
                if(remoteEndPoint == null){
                    string host = null;
                    int    port = 5060;

                    // Use received host.
                    if(via.Received != null){
                        host = via.Received;
                    }
                    // Get sent-by host
                    else{
                        host = via.SentBy.Split(':')[0];
                    }

                    // Use rport if recevived is specified too
                    if(via.Received != null && via.RPort > 0){
                        port = via.RPort;
                    }
                    // Get port from sent-by
                    else{
                        string[] host_port = via.SentBy.Split(':');
                        if(host_port.Length == 2){
                            port = Convert.ToInt32(host_port[1]);
                        }
                    }

                    remoteEndPoint = new IPEndPoint(System.Net.Dns.GetHostAddresses(host)[0],port);
                }

                byte[] data = response.ToByteData();

                // Log
                m_pSipStack.Logger.AddWrite(data.Length,"Sending (" + data.Length + " bytes): " + socket.LocalEndPoint.ToString() + " -> " + remoteEndPoint.ToString() + "\r\n<begin>\r\n" + System.Text.Encoding.UTF8.GetString(data) + "<end>\r\n");

                // We don't have any more that socket what accepted request which response it is.
                // There are 2 known cases when no socket:
                //   1) Stateless proxy.
                //   2) Statefull proxy, but response didn't match any transaction.
                if(socket == null){
                    // UDP Multicast
                    if(via.ProtocolTransport.ToUpper() == SIP_Transport.UDP && via.Maddr != null){
                        throw new SIP_TransportException("UDP Multicast not implemented !");
                    }
                    // UDP
                    else if(via.ProtocolTransport.ToUpper() == SIP_Transport.UDP){
                        foreach(SipListeningPoint listeningPoint in m_pListeningPoints){
                            if(listeningPoint.Protocol == BindInfoProtocol.UDP){
                                listeningPoint.Socket.SendTo(data,remoteEndPoint);
                                return;
                            }
                        }

                        throw new SIP_TransportException("No UDP transport available, this never should happen !");
                    }
                    // TCP
                    else if(via.ProtocolTransport.ToUpper() == SIP_Transport.TCP){
                        SipTcpPipe pipe = GetTcpPipe(SIP_Transport.TCP,remoteEndPoint);
                        // Not existing connection, create it.
                        if(pipe == null){
                            pipe = new SipTcpPipe(this,remoteEndPoint,true);
                        }
                        pipe.SendMessage(data);
                    }
                    // TCP TLS
                    else if(via.ProtocolTransport.ToUpper() == SIP_Transport.TLS){
                        SipTcpPipe pipe = GetTcpPipe(SIP_Transport.TLS,remoteEndPoint);
                        // Not existing connection, create it.
                        if(pipe == null){
                            pipe = new SipTcpPipe(this,remoteEndPoint,true);
                        }
                        pipe.SendMessage(data);
                    }
                }
                // We have existing socket, use it.
                else{
                    if(via.ProtocolTransport.ToUpper() == SIP_Transport.UDP){
                        socket.SendTo(data,remoteEndPoint);
                    }
                    else{
                        socket.Write(data);
                    }
                }
            }
            catch(Exception x){
                throw new SIP_TransportException(x.Message);
            }
        }
Esempio n. 37
0
        /// <exception cref="System.IO.IOException"></exception>
        private void Negotiate(int port, ServerMessageBlock resp)
        {
            lock (Sbuf)
            {
                if (port == 139)
                {
                    Ssn139();
                }
                else
                {
                    if (port == -1)
                    {
                        port = SmbConstants.DefaultPort;
                    }
                    // 445
                    Socket = new SocketEx(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);

                    //TCPローカルポートは、毎回空いているものを使う。
                    //https://blogs.msdn.microsoft.com/dgorti/2005/09/18/only-one-usage-of-each-socket-address-protocolnetwork-addressport-is-normally-permitted/
                    Socket.Bind(new IPEndPoint(LocalAddr, 0));

                    Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()),
                                                  port), // <- 445
                                   SmbConstants.ConnTimeout);

                    Socket.SoTimeOut = SmbConstants.SoTimeout;
                    Out = Socket.GetOutputStream();
                    In  = Socket.GetInputStream();
                }
                if (++Mid == 32000)
                {
                    Mid = 1;
                }
                NegotiateRequest.Mid = Mid;
                int n = NegotiateRequest.Encode(Sbuf, 4);
                Encdec.Enc_uint32be(n & 0xFFFF, Sbuf, 0);
                if (Log.Level >= 4)
                {
                    Log.WriteLine(NegotiateRequest);
                    if (Log.Level >= 6)
                    {
                        Hexdump.ToHexdump(Log, Sbuf, 4, n);
                    }
                }
                Out.Write(Sbuf, 0, 4 + n);
                Out.Flush();
                if (PeekKey() == null)
                {
                    throw new IOException("transport closed in negotiate");
                }
                int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
                if (size < 33 || (4 + size) > Sbuf.Length)
                {
                    throw new IOException("Invalid payload size: " + size);
                }
                Readn(In, Sbuf, 4 + 32, size - 32);
                resp.Decode(Sbuf, 4);
                if (Log.Level >= 4)
                {
                    Log.WriteLine(resp);
                    if (Log.Level >= 6)
                    {
                        Hexdump.ToHexdump(Log, Sbuf, 4, n);
                    }
                }
            }
        }
        /// <summary>
        /// Processes SIP data (request or response).
        /// </summary>
        /// <param name="socket">Socket what accepted specified SIP message.</param>
        /// <param name="data">SIP message or may be junk data too.</param>
        /// <param name="remoteEndPoint">Remote IP end point what sent SIP message.</param>
        /// <param name="transport">SIP transport what received message.</param>
        private void Process(string transport,SocketEx socket,byte[] data,IPEndPoint remoteEndPoint)
        {
            try{
                // Log
                m_pSipStack.Logger.AddRead(data.Length,"Received (" + data.Length + " bytes): " + socket.LocalEndPoint.ToString() + " <- " + remoteEndPoint.ToString() + "\r\n" + System.Text.Encoding.UTF8.GetString(data) + "\r\n");

                // Bad request or response.
                if(data.Length < 10){
                    return;
                }

                // TODO: Check that advertised transport matches actual received transport.

                // Dedect if sip request or reponse.
                // Response
                if(System.Text.Encoding.UTF8.GetString(data,0,10).ToUpper().StartsWith("SIP")){
                    try{
                        SIP_Response response = SIP_Response.Parse(data);
                        response.Validate();

                        ProcessResponse(response);
                    }
                    catch(Exception x){
                        // We have bad response, just skip it.

                        // Log
                        if(m_pSipStack.Logger != null){
                            m_pSipStack.Logger.AddDebug("Skipping message, parse error: " + x.Message);
                        }
                    }
                }
                // Request
                else{
                    SIP_Request request = null;
                    try{
                        request = SIP_Request.Parse(data);
                        try{
                            request.Validate();
                        }
                        catch(Exception x){
                            // Log
                            if(m_pSipStack.Logger != null){
                                m_pSipStack.Logger.AddDebug("Invalid request: " + x.Message);
                            }

                            // Bad request, send error to request maker.
                            SendResponse(socket,request.CreateResponse(SIP_ResponseCodes.x400_Bad_Request + ". " + x.Message));
                            return;
                        }
                    }
                    catch(Exception x){
                        // Log
                        if(m_pSipStack.Logger != null){
                            m_pSipStack.Logger.AddDebug("Invalid request: " + x.Message);
                        }

                        // We have bad request, try to send bad request error to request maker.
                        SIP_Response badRequestResponse = new SIP_Response();
                        badRequestResponse.StatusCode_ReasonPhrase = SIP_ResponseCodes.x400_Bad_Request;
                        socket.SendTo(badRequestResponse.ToByteData(),remoteEndPoint);
                        return;
                    }

                    SIP_ValidateRequestEventArgs eArgs = m_pSipStack.OnValidateRequest(request,remoteEndPoint);
                    // Request validated, allow transport layer to handle it.
                    if(eArgs.ResponseCode == null){
                        ProcessRequest(request,socket,remoteEndPoint);
                    }
                    // Request rejected, return response.
                    else{
                        SendResponse(socket,request.CreateResponse(eArgs.ResponseCode));
                    }
                }
            }
            catch(SocketException s){
                // Skip all socket errors here
                string dummy = s.Message;
            }
            catch(Exception x){
                m_pSipStack.OnError(x);
            }
        }
        /// <summary>
        /// Processes incoming SIP UDP messages or incoming new SIP connections.
        /// </summary>
        private void ProcessIncomingData()
        {
            try{
                // If no binds, wait some to be created.
                while(m_pSipStack.BindInfo.Length == 0 && m_IsRunning){
                    System.Threading.Thread.Sleep(100);
                }

                //--- Create listening sockets --------------------------------------------------------------
                foreach(BindInfo bindInfo in m_pSipStack.BindInfo){
                    // TCP
                    if(bindInfo.Protocol == BindInfoProtocol.TCP){
                        Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                        s.Bind(new IPEndPoint(bindInfo.IP,bindInfo.Port));
                        s.Listen(500);

                        m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,bindInfo.SSL,bindInfo.SSL_Certificate));
                    }
                    // UDP
                    else if(bindInfo.Protocol == BindInfoProtocol.UDP){
                        // If any IP, replicate socket for each IP, other can't get LocalEndpoint for UDP socket.
                        if(bindInfo.IP.Equals(IPAddress.Any)){
                            IPAddress[] addresses = System.Net.Dns.GetHostAddresses("");
                            foreach(IPAddress address in addresses){
                                // IPv4
                                if(address.AddressFamily == AddressFamily.InterNetwork){
                                    Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
                                    s.Bind(new IPEndPoint(address,bindInfo.Port));

                                    m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,false,null));
                                }
                                // IPv6
                                /*
                                else{
                                    Socket s = new Socket(AddressFamily.InterNetworkV6,SocketType.Dgram,ProtocolType.Udp);
                                    s.Bind(new IPEndPoint(address,bindInfo.Port));

                                    m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,false,null));
                                }*/
                            }
                        }
                        else{
                            Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
                            s.Bind(new IPEndPoint(bindInfo.IP,bindInfo.Port));

                            m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,false,null));
                        }
                    }
                }

                CircleCollection<SipListeningPoint> binds = new CircleCollection<SipListeningPoint>();
                binds.Add(m_pListeningPoints.ToArray());
                //-------------------------------------------------------------------------------------------

                // Accept incoming connections and datagrams.
                while(m_IsRunning){
                    try{
                        // Check that maximum allowed connections not exceeded.
                        if(m_pSipStack.MaximumConnections > 0 && m_pTcpReceiviePipes.Count > m_pSipStack.MaximumConnections){
                            // Sleep here or CPU used 100%
                            Thread.Sleep(1);

                            // Step to next while loop.
                            continue;
                        }

                        // Check next listening point and queue it up when Socket has data or connection attampt.
                        SipListeningPoint listeningPoint = binds.Next();
                        if(listeningPoint.Socket.Poll(0,SelectMode.SelectRead)){
                            Socket socket = listeningPoint.Socket;

                            // TCP, TLS
                            if(listeningPoint.Protocol == BindInfoProtocol.TCP){
                                // Accept incoming connection.
                                SocketEx clientSocket = new SocketEx(socket.Accept());

                                // SSL
                                if(listeningPoint.SSL){
                                    clientSocket.SwitchToSSL(listeningPoint.Certificate);
                                }

                                // Queue for futher processing.
                                m_pTcpReceiviePipes.Add(new SipTcpPipe(this,clientSocket));
                            }
                            // UDP
                            else if(listeningPoint.Protocol == BindInfoProtocol.UDP){
                                // Receive data packet.
                                byte[] dataBuffer = new byte[32000];
                                EndPoint remoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any,0);
                                int size = socket.ReceiveFrom(dataBuffer,ref remoteEndPoint);

                                // Copy received data to new buffer what is exactly received size.
                                byte[] data = new byte[size];
                                Array.Copy(dataBuffer,data,size);

                                // Queue UDP datagram for processing.
                                ThreadPool.QueueUserWorkItem(
                                    new WaitCallback(this.Process),
                                    new SIP_Packet(socket,(IPEndPoint)remoteEndPoint,data)
                                );
                            }
                        }

                        // Sleep here or CPU used 100%
                        Thread.Sleep(1);
                    }
                    catch(SocketException x){
                        // Just skip recieve errors.

                        /* WSAETIMEDOUT 10060 Connection timed out.
                            A connection attempt failed because the connected party did not properly respond
                            after a period of time, or the established connection failed because the connected
                            host has failed to respond.
                        */
                        if(x.ErrorCode == 10060){
                            // Skip
                        }
                        /* WSAECONNRESET 10054 Connection reset by peer.
                            An existing connection was forcibly closed by the remote host. This normally results
                            if the peer application on the remote host is suddenly stopped, the host is rebooted,
                           the host or remote network interface is disabled, or the remote host uses a hard close.
                        */
                        else if(x.ErrorCode == 10054){
                            // Skip
                        }
                        else{
                            m_pSipStack.OnError(x);
                        }
                    }
                    catch(Exception x){
                        m_pSipStack.OnError(x);
                    }
                }
            }
            catch(Exception x){
                m_pSipStack.OnError(x);
            }
        }
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner SIP_TransportLayer.</param>
            /// <param name="remoteEP">Remote end point.</param>
            /// <param name="ssl">Specifies if SSL pipe.</param>
            public SipTcpPipe(SIP_TransportLayer owner,IPEndPoint remoteEP,bool ssl)
            {
                m_pTLayer = owner;

                m_pSocket = new SocketEx();
                m_pSocket.Connect(remoteEP,true);
                if(ssl){
                    m_Transport = SIP_Transport.TLS;
                    m_pSocket.SwitchToSSL_AsClient();
                }
                else{
                    m_Transport = SIP_Transport.TLS;
                }

                // Add this to TCP pipes collection.
                m_pTLayer.m_pTcpReceiviePipes.Add(this);

                Start();
            }
        /// <summary>
        /// Disconnects from NNTP server, trys to send QUIT command before.
        /// </summary>
        public void Disconnect()
        {
            try{
                if(m_Connected){
                    m_pSocket.WriteLine("QUIT");
                    m_pSocket.Shutdown(SocketShutdown.Both);
                }
            }
            catch{
            }

            m_Connected = false;
            m_pSocket = null;
        }
Esempio n. 42
0
        /// <summary>
        /// Connects to sepcified host.
        /// </summary>
        /// <param name="localEndpoint">Sets local endpoint. Pass null, to use default.</param>
        /// <param name="host">Host name or IP address.</param>
        /// <param name="port">Port where to connect.</param>
        /// <param name="ssl">Specifies if to connected via SSL. Default SMTP port is 25 and SSL port is 465.</param>
        public void Connect(IPEndPoint localEndpoint, string host, int port, bool ssl)
        {
            m_pSocket = new SocketEx();
            if (localEndpoint != null)
            {
                m_pSocket.Bind(localEndpoint);
            }

            // Create logger
            if (SessionLog != null)
            {
                m_pLogger = new SocketLogger(m_pSocket.RawSocket, SessionLog);
                m_pLogger.SessionID = Guid.NewGuid().ToString();
                m_pSocket.Logger = m_pLogger;
            }

            if (host.IndexOf("@") == -1)
            {
                m_pSocket.Connect(host, port, ssl);
            }
            else
            {
                //---- Parse e-domain -------------------------------//
                string domain = host;

                // eg. Ivx <*****@*****.**>
                if (domain.IndexOf("<") > -1 && domain.IndexOf(">") > -1)
                {
                    domain = domain.Substring(domain.IndexOf("<") + 1,
                                              domain.IndexOf(">") - domain.IndexOf("<") - 1);
                }

                if (domain.IndexOf("@") > -1)
                {
                    domain = domain.Substring(domain.LastIndexOf("@") + 1);
                }

                if (domain.Trim().Length == 0)
                {
                    if (m_pLogger != null)
                    {
                        m_pLogger.AddTextEntry("Destination address '" + host + "' is invalid, aborting !");
                    }
                    throw new Exception("Destination address '" + host + "' is invalid, aborting !");
                }

                //--- Get MX record -------------------------------------------//
                Dns_Client dns = new Dns_Client();
                Dns_Client.DnsServers = m_pDnsServers;
                DnsServerResponse dnsResponse = dns.Query(domain, QTYPE.MX);

                bool connected = false;
                switch (dnsResponse.ResponseCode)
                {
                    case RCODE.NO_ERROR:
                        DNS_rr_MX[] mxRecords = dnsResponse.GetMXRecords();

                        // Try all available hosts by MX preference order, if can't connect specified host.
                        foreach (DNS_rr_MX mx in mxRecords)
                        {
                            try
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Connecting with mx record to: " + mx.Host);
                                }
                                m_pSocket.Connect(mx.Host, port, ssl);
                                connected = true;
                                break;
                            }
                            catch (Exception x)
                            {
                                // Just skip and let for to try next host.									
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Failed connect to: " + mx.Host + " error:" +
                                                           x.Message);
                                }
                            }
                        }

                        // None of MX didn't connect
                        if (mxRecords.Length > 0 && !connected)
                        {
                            throw new Exception("Destination email server is down");
                        }

                        /* Rfc 2821 5
						 If no MX records are found, but an A RR is found, the A RR is treated as
						 if it was associated with an implicit MX RR, with a preference of 0,
						 pointing to that host.
						*/
                        if (!connected)
                        {
                            // Try to connect with A record
                            IPAddress[] ipEntry = null;
                            try
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("No mx record, trying to get A record for: " +
                                                           domain);
                                }
                                ipEntry = Dns_Client.Resolve(domain);
                            }
                            catch
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Invalid domain,no MX or A record: " + domain);
                                }
                                throw new Exception("Invalid domain,no MX or A record: " + domain);
                            }

                            try
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Connecting with A record to:" + domain);
                                }
                                m_pSocket.Connect(domain, port, ssl);
                            }
                            catch
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Failed connect to:" + domain);
                                }
                                throw new Exception("Destination email server is down");
                            }
                        }
                        break;

                    case RCODE.NAME_ERROR:
                        if (m_pLogger != null)
                        {
                            m_pLogger.AddTextEntry("Invalid domain,no MX or A record: " + domain);
                        }
                        throw new Exception("Invalid domain,no MX or A record: " + domain);

                    case RCODE.SERVER_FAILURE:
                        if (m_pLogger != null)
                        {
                            m_pLogger.AddTextEntry("Dns server unvailable.");
                        }
                        throw new Exception("Dns server unvailable.");
                }
            }

            /*
			 * Notes: Greeting may be single or multiline response.
			 *		
			 * Examples:
			 *		220<SP>SMTP server ready<CRLF> 
			 * 
			 *		220-SMTP server ready<CRLF>
			 *		220-Addtitional text<CRLF>
			 *		220<SP>final row<CRLF>
			 * 
			*/

            // Read server response
            string responseLine = m_pSocket.ReadLine(1000);
            while (!responseLine.StartsWith("220 "))
            {
                // If lisne won't start with 220, then its error response
                if (!responseLine.StartsWith("220"))
                {
                    throw new Exception(responseLine);
                }

                responseLine = m_pSocket.ReadLine(1000);
            }

            m_Connected = true;
        }
Esempio n. 43
0
        /*		/// <summary>
		/// Starts disconnecting SMTP client.
		/// </summary>
		public void BeginDisconnect()
		{
			if(!m_Connected){
				throw new Exception("You must connect first");
			}
		}*/

        /// <summary>
        /// Disconnects smtp client from server.
        /// </summary>
        public void Disconnect()
        {
            try
            {
                if (m_pSocket != null && m_pSocket.Connected)
                {
                    m_pSocket.WriteLine("QUIT");

                    m_pSocket.Shutdown(SocketShutdown.Both);
                }
            }
            catch {}

            m_pSocket = null;
            m_Connected = false;
            m_Supports_Size = false;
            m_Supports_Bdat = false;
            m_Supports_Login = false;
            m_Supports_CramMd5 = false;

            if (m_pLogger != null)
            {
                m_pLogger.Flush();
                m_pLogger = null;
            }
        }
        /// <summary>
        /// Processes incoming request.
        /// </summary>
        /// <param name="request">SIP request.</param>
        /// <param name="socket">Socket which made request.</param>
        /// <param name="remoteEndPoint">Remote end point what created request.</param>
        private void ProcessRequest(SIP_Request request,SocketEx socket,IPEndPoint remoteEndPoint)
        {
            /* RFC 3581 4. Server Behavior.
                When a server compliant to this specification (which can be a proxy
                or UAS) receives a request, it examines the topmost Via header field
                value.  If this Via header field value contains an "rport" parameter
                with no value, it MUST set the value of the parameter to the source
                port of the request.  This is analogous to the way in which a server
                will insert the "received" parameter into the topmost Via header
                field value.  In fact, the server MUST insert a "received" parameter
                containing the source IP address that the request came from, even if
                it is identical to the value of the "sent-by" component.
            */

             /* RFC 3261 18.2.1 Receiving Requests.
                 Next, the server transport attempts to match the request to a server
                 transaction.  It does so using the matching rules described in
                 Section 17.2.3.  If a matching server transaction is found, the
                 request is passed to that transaction for processing.  If no match is
                 found, the request is passed to the core, which may decide to
                 construct a new server transaction for that request.  Note that when
                 a UAS core sends a 2xx response to INVITE, the server transaction is
                 destroyed.  This means that when the ACK arrives, there will be no
                 matching server transaction, and based on this rule, the ACK is
                 passed to the UAS core, where it is processed.
            */

            // Store request socket.
            request.Socket = socket;
            request.RemoteEndPoint = remoteEndPoint;

            // Add received to via and rport if empty value specified in header.
            SIP_t_ViaParm via = request.Via.GetTopMostValue();
            // RFC 3581 4. say add always, this causes troubles with some routers, so add if needed.
            if(via.SentBy.Split(':')[0] != remoteEndPoint.Address.ToString()){
                via.Received = remoteEndPoint.Address.ToString();
            }
            // *** If via host LAN IP, always add rport. Thats not defined in RFC.
            if(via.RPort == 0/* || Core.IsPrivateIP(via.Host.Split(':')[0])*/){
                via.RPort = remoteEndPoint.Port;
            }

            /* Try to match BYE to dialog. If match found pass to daialog for processing.
               There we bend RFC, rfc says that TU must handle BYE. We just hide BYE from end user and
               process it in dialog as needed. When somebody know why we may not do so, let me know.
            */
            if(request.Method == "BYE"){
                SIP_Dialog dialog = m_pSipStack.TransactionLayer.MatchDialog(request);
                if(dialog != null){
                    dialog.ProcessRequest(request);
                }
                // Pass request to core.
                else{
                    m_pSipStack.SipCore.OnRequestReceived(new SIP_RequestReceivedEventArgs(m_pSipStack,request));
                }
            }
            else{
                SIP_ServerTransaction transaction = m_pSipStack.TransactionLayer.MatchServerTransaction(request);
                // Pass to matched server transaction.
                if(transaction != null){
                    transaction.ProcessRequest(request);
                }
                // Pass request to core.
                else{
                    m_pSipStack.SipCore.OnRequestReceived(new SIP_RequestReceivedEventArgs(m_pSipStack,request));
                }
            }
        }
Esempio n. 45
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 HTTP_Session(string sessionID,SocketEx socket,BindInfo bindInfo,HTTP_Server server) : base(sessionID,socket,bindInfo,server)
        {
            m_pServer = server;

            StartSession();
        }
Esempio n. 46
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)
 {
     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>
        /// Connects to specified host.
        /// </summary>
        /// <param name="host">Host name.</param>
        /// <param name="port">Port.</param>
        public void Connect(string host,int port)
        {
            m_pSocket = new SocketEx();
            m_pSocket.Connect(host,port);

            string reply = m_pSocket.ReadLine();
            while(!reply.StartsWith("220 ")){
                reply = m_pSocket.ReadLine();
            }

            m_Connected = true;
        }
        /// <summary>
        /// Disconnects from active host.
        /// </summary>
        public void Disconnect()
        {
            if(m_pSocket != null){
                if(m_pSocket.Connected){
                    // Send QUIT
                    m_pSocket.WriteLine("QUIT");
                }

                m_pSocket = null;
            }

            m_Connected     = false;
            m_Authenticated = false;
        }
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner SIP_TransportLayer.</param>
            /// <param name="socket">Connected socket.</param>
            public SipTcpPipe(SIP_TransportLayer owner,SocketEx socket)
            {
                m_pTLayer = owner;
                m_pSocket = socket;

                if(socket.SSL){
                    m_Transport = SIP_Transport.TLS;
                }
                else{
                    m_Transport = SIP_Transport.TCP;
                }

                Start();
            }
        /// <summary>
        /// Connects to IMAP server.
        /// </summary>		
        /// <param name="host">Host name.</param>
        /// <param name="port">Port number. Default IMAP port is 143 and SSL port is 993.</param>
        /// <param name="ssl">Specifies if to connected via SSL.</param>
        public void Connect(string host,int port,bool ssl)
        {
            if(!m_Connected){
                m_pSocket = new SocketEx();
                m_pSocket.Connect(host,port,ssl);

                string reply = m_pSocket.ReadLine();
                reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag

                if(!reply.ToUpper().StartsWith("OK")){
                    m_pSocket.Disconnect();
                    m_pSocket = null;
                    throw new Exception("Server returned:" + reply);
                }

                m_Connected = true;
                // Clear path separator, so next access will get it.
                m_PathSeparator  = '\0';
            }
        }