Ejemplo n.º 1
0
    /// <summary>
    /// Handle client requests and receives
    /// </summary>
    private string Service(ref TcpConnection connection)
    {
        //receives and sends messages
        if (connection.client != null)
        {
            try
            {
                // Get a stream object for reading and writing
                if (connection.client.Connected && connection.stream.DataAvailable)
                {
                    int length;
                    // Buffer for reading data
                    Byte[] bytes = new Byte[64];
                    string data = null;

                    // Loop to receive all the data sent by the client.
                    length = connection.stream.Read(bytes, 0, bytes.Length); //TODO: Find out exactly how many bytes to read per message

                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                    data = data.TrimEnd('\0');
                    return data;
                }
            }
            catch (System.Exception e)
            {
                Debug.Log("Failed in Service() client " + connection.clientID + ", err: " + e.ToString());
            }
        }
        return "-500";
    }
 private void ClientOnConnectionEstablished(TcpConnection tcpConnection)
 {
     _totalReceived[tcpConnection] = 0;
     _totalSent[tcpConnection] = 0;
     tcpConnection.ReceiveAsync(ClientReceiveCallback);
     SendRandomData(tcpConnection, small: false);
 }
Ejemplo n.º 3
0
 public static void Test_GetHashCode_01()
 {
     //packet no 3 192.168.0.1:52581 - 173.194.66.94:443
     //packet no 4 173.194.66.94:443 - 192.168.0.1:52581
     TcpConnection tcpConnection1 = new TcpConnection(new TcpAddress(new MacAddress("00:07:CB:C1:35:5D"), new IpV4Address("192.168.0.1"), 52581),
         new TcpAddress(new MacAddress("48:5B:39:C0:45:48"), new IpV4Address("173.194.66.94"), 443));
     TcpConnection tcpConnection2 = new TcpConnection(new TcpAddress(new MacAddress("48:5B:39:C0:45:48"), new IpV4Address("173.194.66.94"), 443),
         new TcpAddress(new MacAddress("00:07:CB:C1:35:5D"), new IpV4Address("192.168.0.1"), 52581));
 }
Ejemplo n.º 4
0
 public void Add(TcpStreamPacket streamPacket)
 {
     if (_address == null)
         _address = streamPacket.Connection;
     if (streamPacket.Connection.OriginalOrder == _address.OriginalOrder)
         streamPacket.Direction = TcpDirection.SourceToDestination;
     else
         streamPacket.Direction = TcpDirection.DestinationToSource;
     _packets.Add(streamPacket);
     AnalyzePacket(streamPacket);
 }
Ejemplo n.º 5
0
    public HttpResponseInfo(TcpConnection<int, ReplyRFC> AConnection)
	  {
	    _CloseContentStream = true;
			ContentLength = Http.ContentLength;
      RawHeaders.FoldLines = false;
      _Cookies = new ServerCookies();
			ServerSoftware = Http.HttpServer_ServerSoftware;
			ContentType = Http.ContentType;
      _RemoteConnection = AConnection;      
			ResponseNo = Http.ResponseNo;
	  }
        public IEnumerable<int> Execute(BookSearchCriterion criterion)
        {
            using (var connection = new TcpConnection("localhost", 9317))
            {
                var command = new SearchCommand(connection);

                connection.Open();
                command.Execute();

                IEnumerable<int> result = null;

                return result;
            }
        }
Ejemplo n.º 7
0
        public void TestLimitSMTPSessionCount()
        {
            _settings.MaxSMTPConnections = 2;

            using (var conn1 = new TcpConnection())
                using (var conn2 = new TcpConnection())
                    using (var conn3 = new TcpConnection())
                    {
                        CustomAssert.IsTrue(conn1.Connect(25));
                        conn1.Receive();
                        CustomAssert.IsTrue(conn2.Connect(25));
                        conn2.Receive();
                        CustomAssert.IsTrue(conn3.Connect(25));
                        CustomAssert.IsEmpty(conn3.Receive());
                    }

            var log2 = TestSetup.ReadCurrentDefaultLog();

            CustomAssert.IsTrue(log2.Contains("Blocked either by IP range or by connection limit."));
        }
Ejemplo n.º 8
0
        public static async Task <bool> AddFavorite(string uname, string url)
        {
            string        md5 = GetMD5FromUrl(url);
            TcpConnection con = new TcpConnection();
            await con.Connect(ip, port);

            await con.Send(GetAddFavoriteMessage(uname, md5));

            NetMessage mess = await con.ReceiveOnceAsync() as NetMessage;

            con.Close();
            if (mess.Message == MessageType.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 9
0
        public void TestLimitImapSessionCount()
        {
            _settings.MaxIMAPConnections = 2;

            using (var conn1 = new TcpConnection())
                using (var conn2 = new TcpConnection())
                    using (var conn3 = new TcpConnection())
                    {
                        Assert.IsTrue(conn1.Connect(143));
                        conn1.Receive();
                        Assert.IsTrue(conn2.Connect(143));
                        conn2.Receive();
                        Assert.IsTrue(conn3.Connect(143));
                        Assert.IsEmpty(conn3.Receive());
                    }

            var log2 = LogHandler.ReadCurrentDefaultLog();

            Assert.IsTrue(log2.Contains("Blocked either by IP range or by connection limit."));
        }
Ejemplo n.º 10
0
        protected override void HandleNewConnection(TcpConnection newConnection)
        {
            if (newConnection == null)
            {
                throw new ArgumentNullException("newConnection");
            }

            RLoginConnection TypedConnection = new RLoginConnection();

            if (TypedConnection.Open(newConnection.GetSocket()))
            {
                ClientThread NewClientThread = new ClientThread(TypedConnection, _ConnectionType);
                NewClientThread.Start();
            }
            else
            {
                RMLog.Info("Timeout waiting for RLogin header");
                TypedConnection.Close();
            }
        }
Ejemplo n.º 11
0
        public void TestSMTPServerAuthLoginUsernameAsThirdParameter()
        {
            _settings.AllowSMTPAuthPlain = true;

            var sock = new TcpConnection();

            sock.Connect(25);
            Assert.IsTrue(sock.Receive().StartsWith("220"));
            sock.Send("EHLO test.com\r\n");
            Assert.IsTrue(sock.Receive().StartsWith("250"));

            string base64EncodedUsername = EncodeBase64(GetUsername());

            sock.Send("AUTH LOGIN " + base64EncodedUsername + "\r\n");
            Assert.IsTrue(sock.Receive().StartsWith("334"));

            sock.Send(EncodeBase64(GetPassword()) + "\r\n");
            Assert.IsTrue(sock.Receive().StartsWith("535"));
            EnsureNoPassword();
        }
Ejemplo n.º 12
0
 public static bool ConnectToServer(string ip, int port)
 {
     try {
         TcpClient client = new TcpClient(ip, port);
         if (UseSsl)
         {
             Connection = new TcpConnection(client, true, Log, false, true);
         }
         else
         {
             Connection = new TcpConnection(client, true, Log, false);
         }
         Connection.ConnectionEnded += Connection_ConnectionEnded;
         return(true);
     }
     catch (Exception ex) {
         MessageBox.Show("Connection to " + ip + ":" + port + " failed!" + Environment.NewLine + ex.Message, "Connection failed!");
         return(false);
     }
 }
Ejemplo n.º 13
0
        public void StartTlsCommandShouldSwithToTls()
        {
            var smtpClientSimulator = new TcpConnection();

            smtpClientSimulator.Connect(25002);
            var banner        = smtpClientSimulator.Receive();
            var capabilities1 = smtpClientSimulator.SendAndReceive("EHLO example.com\r\n");

            Assert.IsTrue(capabilities1.Contains("STARTTLS"));

            smtpClientSimulator.SendAndReceive("STARTTLS\r\n");
            smtpClientSimulator.HandshakeAsClient();

            // Send a command over TLS.
            var capabilities2 = smtpClientSimulator.SendAndReceive("EHLO example.com\r\n");

            Assert.IsFalse(capabilities2.Contains("STARTTLS"));

            // We're now on SSL.
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Handles when a <see cref="UdpConnection"/> successfully connects to the server.
        /// </summary>
        /// <param name="tcpConnection">The parent <see cref="TcpConnection"/>.</param>
        /// <param name="udpConnection">The connected <see cref="UdpConnection"/>.</param>
        private void udpConnectionReceived(TcpConnection tcpConnection, UdpConnection udpConnection)
        {
            if (!AllowUDPConnections || this[tcpConnection].Count >= UDPConnectionLimit)
            {
                CloseReason closeReason = (this[tcpConnection].Count >= UDPConnectionLimit) ? CloseReason.UdpLimitExceeded : CloseReason.InvalidUdpRequest;
                tcpConnection.Close(closeReason, true);
                return;
            }

            this[tcpConnection].Add(udpConnection);
            udpConnection.NetworkConnectionClosed += connectionClosed;
            KnownTypes.ForEach(udpConnection.AddExternalPackets);

            //Inform all subscribers.
            if (connectionEstablished != null &&
                connectionEstablished.GetInvocationList().Length > 0)
            {
                connectionEstablished(udpConnection, ConnectionType.UDP);
            }
        }
Ejemplo n.º 15
0
        public void TestLimitSMTPSessionCount()
        {
            _settings.MaxSMTPConnections = 2;

            using (var conn1 = new TcpConnection())
                using (var conn2 = new TcpConnection())
                    using (var conn3 = new TcpConnection())
                    {
                        CustomAssert.IsTrue(conn1.Connect(25));
                        string s1 = conn1.Receive();
                        CustomAssert.IsNotEmpty(s1, s1);

                        CustomAssert.IsTrue(conn2.Connect(25));
                        string s2 = conn2.Receive();
                        CustomAssert.IsNotEmpty(s2, s2);
                        CustomAssert.IsTrue(conn3.Connect(25));
                        string s3 = conn3.Receive();
                        CustomAssert.IsEmpty(s3, s3);
                    }
        }
        public void TcpFieldTest()
        {
            NetworkEndPoint ep = new NetworkEndPoint(IPAddress.Loopback, 4296);

            using (TcpConnectionListener listener = new TcpConnectionListener(IPAddress.Any, 4296))
                using (TcpConnection connection = new TcpConnection(ep))
                {
                    listener.Start();

                    connection.Connect();

                    //Connection fields
                    Assert.AreEqual(ep, connection.EndPoint);

                    //TcpConnection fields
                    Assert.AreEqual(new IPEndPoint(IPAddress.Loopback, 4296), connection.RemoteEndPoint);
                    Assert.AreEqual(0, connection.Statistics.DataBytesSent);
                    Assert.AreEqual(0, connection.Statistics.DataBytesReceived);
                }
        }
Ejemplo n.º 17
0
        public void TestTooManyInvalidCommandsHELO()
        {
            Settings settings = _settings;

            settings.DisconnectInvalidClients   = true;
            settings.MaxNumberOfInvalidCommands = 3;

            var sim = new TcpConnection();

            sim.Connect(25);
            sim.Receive(); // banner

            sim.SendAndReceive("HELO\r\n");
            sim.SendAndReceive("HELO\r\n");
            sim.SendAndReceive("HELO\r\n");
            sim.SendAndReceive("HELO\r\n");
            var result = sim.SendAndReceive("HELO\r\n");

            Assert.IsTrue(result.Contains("Too many invalid commands"), result);
        }
Ejemplo n.º 18
0
        public static string LinkPrinter(string printerName, int port)
        {
            try
            {
                string ip = Printer.GetRegistryData(printerName + "\\DsSpooler", "portName");

                if (ip == "" || ip.Split(new char[] { '.' }).Length != 4)
                {
                    throw new ConnectionException("没找到IP");
                }
                foreach (string s in ip.Split(new char[] { '.' }))
                {
                    int.Parse(s);
                }

                Ping      pingSender = new Ping();
                PingReply reply      = pingSender.Send(ip, 1);           //第一个参数为ip地址,第二个参数为ping的时间
                if (reply.Status != IPStatus.Success)
                {
                    throw new ConnectionException("链接失败!");
                }

                TcpConnection connection = new TcpConnection(ip, port);
                connection.Open();
                printer = ZebraPrinterFactory.GetInstance(connection);
            }
            catch (ConnectionException e)
            {
                printer = null;
                FileTools.WriteLineFile(FileTools.exceptionFilePath, DateTime.Now.ToString() + " " + printerName + e.Message);
                return(printerName + e.Message);
            }
            catch (FormatException e)
            {
                printer = null;
                FileTools.WriteLineFile(FileTools.exceptionFilePath, DateTime.Now.ToString() + " " + printerName + "IP地址不正确!");
                return(printerName + "IP地址不正确!");
            }

            return("");
        }
Ejemplo n.º 19
0
        public void TestSendToTooManyRecipients()
        {
            hMailServer.Accounts accounts = _domain.Accounts;
            SingletonProvider <TestSetup> .Instance.AddAccount(accounts, string.Format("*****@*****.**"), "test");

            var sock = new TcpConnection();

            sock.Connect(25);
            sock.ReadUntil("\r\n");
            string result;

            sock.Send("EHLO test.com\r\n");
            result = sock.ReadUntil("\r\n");
            Assert.IsTrue(result.StartsWith("250"));
            sock.Send("MAIL FROM: [email protected]\r\n");
            result = sock.ReadUntil("\r\n");
            Assert.IsTrue(result.StartsWith("250"));

            const int recipientCount = 51000;

            for (int i = 1; i <= recipientCount; i++)
            {
                string address = string.Format("test{0}@gmail.com", i);

                sock.Send(string.Format("RCPT TO: <{0}>\r\n", address));
                result = sock.ReadUntil("\r\n");
                if (i <= 50000)
                {
                    Assert.IsTrue(result.StartsWith("250"));
                }
                else
                {
                    Assert.IsFalse(result.StartsWith("250"));
                }

                if (i % 100 == 0)
                {
                    TestTracer.WriteTraceInfo("{0}/{1}", i, recipientCount);
                }
            }
        }
Ejemplo n.º 20
0
        public static void AssertClamDRunning()
        {
            Process[] processlist = Process.GetProcesses();

            foreach (Process theprocess in processlist)
            {
                if (theprocess.ProcessName == "clamd")
                {
                    return;
                }
            }

            // Check if we can launch it...
            var startInfo = new ProcessStartInfo();

            startInfo.FileName         = @"C:\clamav\clamd.exe";
            startInfo.WorkingDirectory = @"C:\Clamav";
            startInfo.Arguments        = "--daemon";

            try
            {
                Process.Start(startInfo);

                // Wait for clamav to start up.
                for (int i = 0; i < 10; i++)
                {
                    var sock = new TcpConnection();
                    if (sock.Connect(3310))
                    {
                        return;
                    }
                    Thread.Sleep(1000);
                }

                Assert.Fail("ClamD process not starting up.");
            }
            catch (Exception)
            {
                Assert.Inconclusive("Unable to start ClamD process. Is ClamAV installed?");
            }
        }
Ejemplo n.º 21
0
        public static VirtualMachine ConnectInternal(Socket dbg_sock, Socket con_sock, IPEndPoint dbg_ep, IPEndPoint con_ep)
        {
            if (con_sock != null)
            {
                try
                {
                    con_sock.Connect(con_ep);
                }
                catch (Exception)
                {
                    try
                    {
                        dbg_sock.Close();
                    }
                    catch {}
                    throw;
                }
            }

            try
            {
                dbg_sock.Connect(dbg_ep);
            }
            catch (Exception)
            {
                if (con_sock != null)
                {
                    try
                    {
                        con_sock.Close();
                    }
                    catch {}
                }
                throw;
            }

            Connection   transport = new TcpConnection(dbg_sock);
            StreamReader console   = con_sock != null? new StreamReader(new NetworkStream(con_sock)) : null;

            return(Connect(transport, console, null));
        }
Ejemplo n.º 22
0
 protected override void Execute()
 {
     while (!_Stop)
     {
         using (TcpConnection Connection = new TcpConnection()) {
             if (Connection.Listen(_LocalAddress, _LocalPort))
             {
                 while (!_Stop)
                 {
                     // Accept an incoming connection
                     if (Connection.CanAccept(1000)) // 1 second
                     {
                         try {
                             TcpConnection NewConnection = Connection.AcceptTCP();
                             if (NewConnection != null)
                             {
                                 // TODOX Add check for flash socket policy request by doing a peek with a 1 second timeout or something
                                 //       If peeked character is < then peek another character to see if it's the flash request string
                                 HandleNewConnection(NewConnection);
                             }
                         } catch (Exception ex) {
                             RMLog.Exception(ex, "Error in ServerThread::Execute()");
                         }
                     }
                 }
             }
             else
             {
                 RMLog.Error($"{_ConnectionType} Server Thread unable to listen on {_LocalAddress}:{_LocalPort}.  Retry in 15 seconds.");
                 for (int i = 1; i <= 15; i++)
                 {
                     Thread.Sleep(1000);
                     if (_Stop)
                     {
                         break;
                     }
                 }
             }
         }
     }
 }
    static void Main(string[] args)
    {
        using (TcpConnection connection = new TcpConnection())
        {
            ManualResetEvent e = new ManualResetEvent(false);

            //Whenever we receive data print the number of bytes and how it was sent
            connection.DataReceived += (object sender, DataReceivedEventArgs a) =>
                                       Console.WriteLine("Received {0} bytes via {1}!", a.Bytes.Length, a.SendOption);

            //When the end point disconnects from us then release the main thread and exit
            connection.Disconnected += (object sender, DisconnectedEventArgs a) =>
                                       e.Set();

            //Connect to a server
            connection.Connect(new NetworkEndPoint("127.0.0.1", 4296));

            //Wait until the end point disconnects from us
            e.WaitOne();
        }
    }
Ejemplo n.º 24
0
 private void OnSocketAccepted(Socket socket, object userToken)
 {
     Task.Run(() =>
     {
         try
         {
             var connection = new TcpConnection(Name, socket, Setting, _receivedBufferPool, _sendBufferPool, _tcpConnectionServerHandler);
             connection.RegisterConnectionEventListener(_connectionEventListeners);
             if (_connectionDict.TryAdd(connection.Id, connection))
             {
                 Log <ServerSocket> .Info(string.Format("Socket server new client accepted, name: {0}, listeningEndPoint: {1}, remoteEndPoint: {2}", Name, ListeningEndPoint, socket.RemoteEndPoint));
                 connection.Accepted();
             }
         }
         catch (ObjectDisposedException) { }
         catch (Exception ex)
         {
             Log <ServerSocket> .Error(ex, string.Format("Socket server accept new client has unknown exception, name: {0}, listeningEndPoint: {1}", Name, ListeningEndPoint));
         }
     });
 }
Ejemplo n.º 25
0
    public void Connect(string ip, int port)
    {
        Debug.Log("正在连接服务器:" + ip + ":" + port + " ....");
        this.ip   = ip;
        this.port = port;
        TcpConnection conn = new TcpConnection(ip, port, false);

        conn.Connect();

        serverConnectionWorker = new ServerConnectionWorker(conn);
        serverConnectionWorker.Start();

        isConnection = true;
        StartCoroutine(HandleReadPackage());
        //连接成功后缓存当前人物的roleId
        roleId = GetRoleId();
        LinkStatePackage package = PackageFactory.GetPackage(PackageType.LinkState) as LinkStatePackage;

        SendPackage(package);
        AddClientEvents();
    }
Ejemplo n.º 26
0
        public void StartTlsWithTrailingSpaceShouldBeAccepted()
        {
            var smtpClientSimulator = new TcpConnection();

            smtpClientSimulator.Connect(25002);
            var banner        = smtpClientSimulator.Receive();
            var capabilities1 = smtpClientSimulator.SendAndReceive("EHLO example.com\r\n");

            Assert.IsTrue(capabilities1.Contains("STARTTLS"));

            var startTlsResultText = smtpClientSimulator.SendAndReceive("STARTTLS \r\n");

            StringAssert.Contains("220 Ready to start TLS", startTlsResultText);

            smtpClientSimulator.HandshakeAsClient();

            // Send a command over TLS.
            var capabilities2 = smtpClientSimulator.SendAndReceive("EHLO example.com\r\n");

            Assert.IsFalse(capabilities2.Contains("STARTTLS"));
        }
Ejemplo n.º 27
0
        protected override void HandleNewConnection(TcpConnection newConnection)
        {
            if (newConnection == null)
            {
                throw new ArgumentNullException("newConnection");
            }

            WebSocketConnection TypedConnection = new WebSocketConnection();

            if (TypedConnection.Open(newConnection.GetSocket()))
            {
                // TODOX Start a proxy thread instead of a clientthread
                ClientThread NewClientThread = new ClientThread(TypedConnection, _ConnectionType);
                NewClientThread.Start();
            }
            else
            {
                RMLog.Info("No carrier detected (probably a portscanner)");
                TypedConnection.Close();
            }
        }
Ejemplo n.º 28
0
        public void HandshakeCompletionShouldBeLoggedWithCipherDetails()
        {
            var smtpClientSimulator = new TcpConnection();

            smtpClientSimulator.Connect(25002);
            var banner        = smtpClientSimulator.Receive();
            var capabilities1 = smtpClientSimulator.SendAndReceive("EHLO example.com\r\n");

            Assert.IsTrue(capabilities1.Contains("STARTTLS"));

            smtpClientSimulator.SendAndReceive("STARTTLS\r\n");
            smtpClientSimulator.HandshakeAsClient();

            var capabilities2 = smtpClientSimulator.SendAndReceive("EHLO example.com\r\n");

            var default_log = LogHandler.ReadCurrentDefaultLog();

            Assert.IsTrue(default_log.Contains("Version: TLS"));
            Assert.IsTrue(default_log.Contains("Cipher: "));
            Assert.IsTrue(default_log.Contains("Bits: "));
        }
Ejemplo n.º 29
0
        protected override void HandleNewConnection(TcpConnection newConnection)
        {
            if (newConnection == null)
            {
                throw new ArgumentNullException("newConnection");
            }

            TelnetConnection TypedConnection = new TelnetConnection();

            if (TypedConnection.Open(newConnection.GetSocket()))
            {
                ClientThread NewClientThread = new ClientThread(TypedConnection, _ConnectionType);
                NewClientThread.Start();
            }
            else
            {
                // TODOX Duplicated code.  Maybe add method to base class and call it?
                RMLog.Info("No carrier detected (probably a portscanner)");
                TypedConnection.Close();
            }
        }
Ejemplo n.º 30
0
        public void TestLongSMTPCommand()
        {
            var socket = new TcpConnection();

            socket.Connect(25);

            // Build a large string...
            var sb = new StringBuilder();

            sb.Append("A01");
            for (int i = 0; i < 1000000; i++)
            {
                sb.Append("01234567890");
            }

            sb.Append(Environment.NewLine);

            for (int i = 0; i < 100; i++)
            {
                try
                {
                    socket.Send(sb.ToString());
                }
                catch (Exception)
                {
                    return;
                }


                if ((i % 10) == 0)
                {
                    TestTracer.WriteTraceInfo("{0}/{1}", i, 100);
                }
            }

            socket.Send("\r\n");
            socket.Receive();

            socket.Disconnect();
        }
Ejemplo n.º 31
0
        public void TestTooManyInvalidCommandsTempError()
        {
            Account account = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test");

            for (int i = 0; i < 10; i++)
            {
                SingletonProvider <TestSetup> .Instance.AddAccount(_domain, string.Format("test{0}@test.com", i), "test");
            }

            Application application = SingletonProvider <TestSetup> .Instance.GetApp();

            Settings settings = _settings;

            settings.DisconnectInvalidClients   = true;
            settings.MaxNumberOfInvalidCommands = 5;

            settings.AntiSpam.GreyListingEnabled = true;

            var sim = new TcpConnection();

            sim.Connect(25);
            string res = sim.Receive();

            sim.Send("EHLO test.com\r\n");
            res = sim.Receive();
            sim.Send("MAIL FROM: <*****@*****.**>\r\n");
            res = sim.Receive();
            for (int i = 1; i < 10; i++)
            {
                string address = string.Format("test{0}@test.com", i);

                sim.Send("RCPT TO: " + address + "\r\n");

                res = sim.Receive();

                Assert.AreEqual("451 Please try again later.\r\n", res);
            }

            sim.Disconnect();
        }
Ejemplo n.º 32
0
        public void TestMailFromSyntaxValidation()
        {
            Account account1 = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test");

            var smtpClientSimulator = new TcpConnection();

            smtpClientSimulator.Connect(25);

            Assert.IsTrue(smtpClientSimulator.Receive().StartsWith("220"));
            smtpClientSimulator.Send("HELO test\r\n");
            Assert.IsTrue(smtpClientSimulator.Receive().StartsWith("250"));

            // A few tests of invalid syntax.
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM: <[email protected]\r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM: [email protected]>\r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM: <    [email protected]    \r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM: <        \r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM: >        \r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM: <[email protected]\r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM <*****@*****.**>\r\n").StartsWith("250"));
            Assert.IsFalse(smtpClientSimulator.SendAndReceive("MAIL FROM  [email protected]\r\n").StartsWith("250"));

            // Valid syntax, < and >
            Assert.IsTrue(smtpClientSimulator.SendAndReceive("MAIL FROM: <*****@*****.**>\r\n").StartsWith("250"));
            Assert.IsTrue(smtpClientSimulator.SendAndReceive("RSET\r\n").StartsWith("250"));

            Assert.IsTrue(smtpClientSimulator.SendAndReceive("MAIL FROM: [email protected]\r\n").StartsWith("250"));
            Assert.IsTrue(smtpClientSimulator.SendAndReceive("RSET\r\n").StartsWith("250"));

            Assert.IsTrue(smtpClientSimulator.SendAndReceive("MAIL FROM:    [email protected]   \r\n").StartsWith("250"));
            Assert.IsTrue(smtpClientSimulator.SendAndReceive("RSET\r\n").StartsWith("250"));

            Assert.IsTrue(smtpClientSimulator.SendAndReceive("MAIL FROM:[email protected]\r\n").StartsWith("250"));
            Assert.IsTrue(smtpClientSimulator.SendAndReceive("RSET\r\n").StartsWith("250"));

            Assert.IsTrue(smtpClientSimulator.SendAndReceive("MAIL FROM:<*****@*****.**>\r\n").StartsWith("250"));
            Assert.IsTrue(smtpClientSimulator.SendAndReceive("RSET\r\n").StartsWith("250"));

            smtpClientSimulator.Disconnect();
        }
Ejemplo n.º 33
0
        private async Task SocketPingProcess(TcpConnection connection)
        {
            var lastSendPingTime = DateTime.UtcNow;

            try
            {
                while (!connection.Disconnected)
                {
                    await Task.Delay(500);

                    if ((DateTime.UtcNow - SocketStatistic.LastReceiveTime).TotalSeconds > _disconnectInterval)
                    {
                        string disconnectMessage = $"There is no receive activity during {_disconnectInterval} seconds. Disconnecting...";
                        _log?.Warning(
                            message: disconnectMessage,
                            context: new
                        {
                            pingInterval       = _pingInterval,
                            disconnectInterval = _disconnectInterval
                        });
                        _legacyLog?.Add(disconnectMessage);
                        await connection.Disconnect(new Exception(disconnectMessage));
                    }
                    else if ((DateTime.UtcNow - lastSendPingTime).TotalSeconds > _pingInterval)
                    {
                        var pingData = _service.GetPingData();
                        await connection.SendDataToSocket(pingData, CancellationToken.None);

                        lastSendPingTime = DateTime.UtcNow;
                    }
                }
            }
            catch (Exception exception)
            {
                await connection.Disconnect(exception);

                _log?.Error(exception);
                _legacyLog?.Add("Ping Thread Exception: " + exception.Message);
            }
        }
Ejemplo n.º 34
0
        public void TestManyTCPIPConnections()
        {
            LogHandler.DeleteCurrentDefaultLog();

            const int count = 1000;

            List <TcpConnection> sockets = new List <TcpConnection>();

            for (int i = 1; i <= count; i++)
            {
                TcpConnection socket = new TcpConnection();
                Assert.IsTrue(socket.Connect(25));

                if ((i % 10) == 0)
                {
                    TestTracer.WriteTraceInfo("{0}/{1}", i, 1000);
                }

                sockets.Add(socket);
            }

            foreach (TcpConnection socket in sockets)
            {
                socket.Disconnect();
            }

            RetryHelper.TryAction(() =>
            {
                string log = LogHandler.ReadCurrentDefaultLog();

                string connectionCreated = "TCP - 127.0.0.1 connected to 127.0.0.1:25.";
                string connectionEnded   = "Ending session ";

                var created = Regex.Matches(log, connectionCreated);
                var ended   = Regex.Matches(log, connectionEnded);

                Assert.AreEqual(count, created.Count);
                Assert.AreEqual(count, ended.Count);
            }, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30));
        }
Ejemplo n.º 35
0
        public void Data2()
        {
            TcpConnection c  = new TcpConnection(null, "tcp://127.0.0.1:" + port, null);
            MyDataHandler dh = new MyDataHandler(c);

            Assert.IsFalse(c.IsStarted());
            c.Start();
            Assert.IsTrue(c.IsStarted());

            c.WaitUp(TIMEOUT);

            Socket t = lh.accepted.WaitUntilNotEqAndSet(null, TIMEOUT, null);

            AssertWhat(What.UP, dh.what);
            Assert.IsNull(dh.xsender);
            Assert.IsNull(dh.xbuf);

            byte[] buf = { 21, 22, 23 };

            t.Send(buf);
            // t.getOutputStream().flush();

            AssertWhat(What.DATA, dh.what);
            Assert.IsNull(dh.xsender);
            Assert.IsNotNull(dh.xbuf);
            Assert.AreEqual(3, dh.xbuf.Length);
            Assert.AreEqual(( byte )21, dh.xbuf[0]);
            Assert.AreEqual(( byte )22, dh.xbuf[1]);
            Assert.AreEqual(( byte )23, dh.xbuf[2]);

            Assert.IsTrue(c.IsStarted());
            c.Stop();
            Assert.IsFalse(c.IsStarted());

            AssertWhat(What.DOWN, dh.what);
            Assert.IsNull(dh.xsender);
            Assert.IsNull(dh.xbuf);

            t.Close();
        }
Ejemplo n.º 36
0
        //private static void PrintSortedTcpStreamPacket(IndexedTcpConnection tcpConnection, PPacket ppacket)
        private static void PrintSortedTcpStreamPacket(PPacket ppacket)
        {
            TcpConnection tcpConnection = ppacket.GetTcpConnection();
            if (_currentTcpConnection == null || tcpConnection.Index != _currentTcpConnection.Index)
            {
                Trace.WriteLine();
                Trace.WriteLine("group packet    time      source                 dir   destination           protocol flags                data   seq        next seq   ack        window urg       data");
                //_LastStreamNumber = tcpConnection.Index;
                _currentTcpConnection = tcpConnection;
            }
            //TcpDirection direction = TcpDirection.SourceToDestination;
            //string s = GetTcpStreamPacketString1(tcpConnection, ppacket, _currentTcpConnection.GetTcpDirection(tcpConnection), true);
            string s = GetTcpStreamPacketString1(ppacket, _currentTcpConnection.GetTcpDirection(tcpConnection), true);
            //string s2 = null;
            //foreach (Pib.Pcap.Test.TcpPacketError error in streamPacket.Errors)
            //    s2 = s2.zAddValue(streamPacket.GetErrorMessage(error));

            //if (s2 != null)
            //    s2 = " " + s2;
            //Trace.WriteLine("{0,-162}{1}{2}", s, ppacket.GetTcpDescription(), s2);
            Trace.WriteLine(s);
        }
Ejemplo n.º 37
0
        public void TestTooManyInvalidCommandsHELOSuccesfullCommandDoesNotResetCounter()
        {
            Settings settings = _settings;

            settings.DisconnectInvalidClients   = true;
            settings.MaxNumberOfInvalidCommands = 3;

            var sim = new TcpConnection();

            sim.Connect(25);
            sim.Receive(); // banner

            sim.SendAndReceive("HELO\r\n");
            sim.SendAndReceive("HELO\r\n");
            sim.SendAndReceive("HELO\r\n");
            var result = sim.SendAndReceive("HELO test.com\r\n");

            Assert.IsTrue(result.Contains("250 Hello."), result);

            result = sim.SendAndReceive("HELO\r\n");
            Assert.IsTrue(result.Contains("Too many invalid commands"), result);
        }
Ejemplo n.º 38
0
 protected override async Task<ITcpConnection> ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken)
 {
     var tcp = new TcpConnection(useSsl);
     await tcp.ConnectAsync(host, port, cancellationToken);
     return tcp;
 }
Ejemplo n.º 39
0
        private TcpConnection GetConnection(TcpServiceAddress address)
        {
            TcpConnection c;
            lock (connections) {
                // If there isn't, establish a connection,
                if (!connections.TryGetValue(address, out c)) {
                    IPEndPoint endPoint = address.ToEndPoint();
                    Socket socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            #if DEBUG
                    socket.ReceiveTimeout = Int32.MaxValue;
            #else
                    socket.ReceiveTimeout = 8 * 1000;  // 8 second timeout,
            #endif
                    socket.NoDelay = true;

                    int curSendBufSize = socket.SendBufferSize;
                    if (curSendBufSize < 256 * 1024)
                        socket.SendBufferSize = 256 * 1024;

                    int curReceiveBufSize = socket.ReceiveBufferSize;
                    if (curReceiveBufSize < 256 * 1024)
                        socket.ReceiveBufferSize = 256 * 1024;

                    socket.Connect(endPoint);
                    c = new TcpConnection(socket);
                    c.Connect(password);
                    connections.Add(address, c);
                } else {
                    c.AddLock();
                }
            }
            return c;
        }
Ejemplo n.º 40
0
 public TcpStreamPacket(PPacket ppacket)
 {
     _direction = TcpDirection.SourceToDestination;
     //_connection = new TcpConnection(packet.Packet);
     _connection = ppacket.GetTcpConnection();
     _ppacket = ppacket;
     _packet = ppacket.Packet;
 }
Ejemplo n.º 41
0
 private void ReleaseConnection(TcpConnection c)
 {
     lock (connections) {
         c.RemoveLock();
     }
 }
Ejemplo n.º 42
0
 public TcpStream(TcpConnection tcpConnection)
 {
     _tcpConnection = tcpConnection;
     _streamSourceToDestination = new TcpMonoStream();
     _streamSourceToDestination.WriteData = WriteDataSourceToDestination;
     _streamDestinationToSource = new TcpMonoStream();
     _streamDestinationToSource.WriteData = WriteDataDestinationToSource;
 }
Ejemplo n.º 43
0
 public Connection Connect()
 {
     try
     {
         var socket = new System.Net.Sockets.TcpClient(host, port);
         Connection connection = new TcpConnection(socket);
         return connection;
     }
     catch (System.IO.IOException e)
     {
         throw new FastConnectionException(e);
     }
     catch (System.Exception e)
     {
         throw new FastConnectionException(e);
     }
 }
Ejemplo n.º 44
0
    void OnConnectRequest(IAsyncResult result)
    {
        try
        {
            Socket sock = (Socket)result.AsyncState;

            TcpConnection newConn = new TcpConnection(sock.EndAccept(result));
            newConn.ReceivedMessage += new EventHandler<MessageEventArgs>(newConn_ReceivedMessage);
            newConn.Disconnected += new EventHandler<ConnectionEventArgs>(newConn_Disconnected);
            sock.BeginAccept(this.OnConnectRequest, sock);
        }
        catch
        {
        }
    }
Ejemplo n.º 45
0
 private void removeConnection(TcpConnection connection)
 {
     lock (_tcpConnections)
     {
         try
         {
             if (connection.Connected())
             {
                 Log("Closing connection from " + connection.getRemoteEndpoint() + ".");
             }
             connection.Close();
             _tcpConnections.Remove(connection);
         }
         catch (Exception ex)
         {
             Log("Error removing TcpConnection: " + ex);
         }
     }
 }
 public NewPatientForm(TcpConnection tcpConnections)
 {
     InitializeComponent();
     connection = tcpConnections;
 }
 private void ClientOnConnectionFailed(TcpConnection tcpConnection, SocketError socketError)
 {
     Debug.Fail("Cannot establish connection: " + socketError);
 }
 private void ServerListenCallback(TcpConnection tcpConnection)
 {
     _totalReceived[tcpConnection] = 0;
     _totalSent[tcpConnection] = 0;
     tcpConnection.ReceiveAsync(ServerReceiveCallback);
     SendRandomData(tcpConnection, small: false);
     //StartPing(tcpConnection);
 }
Ejemplo n.º 49
0
 public TcpStreamReassembledPacket(TcpStream tcpStream)
 {
     _tcpConnection = tcpStream.TcpConnection;
     tcpStream.WriteData += WriteData;
 }
Ejemplo n.º 50
0
 //private static void PrintIpAdressList(Packet packet)
 private static void PrintIpAdressList(PPacket ppacket)
 {
     Packet packet = ppacket.Packet;
     //if (packet.Ethernet == null)
     //    return;
     //IpV4Datagram ip = packet.Ethernet.IpV4;
     IpV4Datagram ip = ppacket.Ipv4;
     if (ip == null)
         return;
     uint ipAdress = ip.Source.ToValue();
     if (!_ipAdressList.ContainsKey(ipAdress))
     {
         _ipAdressList.Add(ipAdress, null);
         Trace.WriteLine("new ip adress {0}", ip.Source.ToString());
     }
     ipAdress = ip.Destination.ToValue();
     if (!_ipAdressList.ContainsKey(ipAdress))
     {
         _ipAdressList.Add(ipAdress, null);
         Trace.WriteLine("new ip adress {0}", ip.Destination.ToString());
     }
     //TcpDatagram tcp = ip.Tcp;
     TcpDatagram tcp = ppacket.Tcp;
     if (tcp == null)
         return;
     TcpConnection tcpConnection = new TcpConnection(packet);
     if (!_tcpStreamList.ContainsKey(tcpConnection))
     {
         _tcpStreamList.Add(tcpConnection, null);
         //_tr.WriteLine("new tcp stream {0}:{1} {2}:{3}", tcpConnection.Source.IpAddress, tcpConnection.Source.Port,
         //    tcpConnection.Destination.IpAddress, tcpConnection.Destination.Port);
         Trace.WriteLine("new tcp stream {0}", tcpConnection.GetConnectionName());
     }
 }
Ejemplo n.º 51
0
        private void Poll()
        {
            try {
                Logger.Info("Node started on " + Address);

                while (polling) {
                    if (!listener.Pending()) {
                        Thread.Sleep(500);
                        continue;
                    }

                    Socket s;
                    try {
                        // The socket to run the service,
                        s = listener.AcceptSocket();
                        s.NoDelay = true;
                        int cur_send_buf_size = s.SendBufferSize;
                        if (cur_send_buf_size < 256 * 1024) {
                            s.SendBufferSize = 256 * 1024;
                        }

                        // Make sure this ip address is allowed,
                        IPAddress ipAddress = ((IPEndPoint)s.RemoteEndPoint).Address;

                        Logger.Info("Connection from " + ipAddress);

                        bool authorized = IPAddress.IsLoopback(ipAddress) ||
                                          IsAddressAllowed(ipAddress.ToString());

                        if (OnClientConnect(ipAddress.ToString(), authorized)) {
                            // Dispatch the connection to the thread pool,
                            TcpConnection c = new TcpConnection(this, s);
                            if (connections == null)
                                connections = new List<TcpConnection>();
                            connections.Add(c);
                            ThreadPool.QueueUserWorkItem(c.Work, null);
                        } else {
                            Logger.Error("Connection refused from " + ipAddress + ": not allowed");
                        }

                    } catch (SocketException e) {
                        Logger.Warning("Socket Errot while processing a connection.", e);
                    }
                }
            } catch(Exception e) {
                Logger.Error("Error while polling.", e);
            }
        }
Ejemplo n.º 52
0
 /**
  * 切断した
  */
 private void OnDisconnected(TcpConnection conn, Result result)
 {
     result.Log();
     Debug.Log("切断した");
 }
 private void StartPing(TcpConnection tcpConnection)
 {
     WaitCallback callBack = null;
     callBack = state =>
                    {
                       //var outData = new List<ArraySegment<byte>>();
                        //outData.Add(new ArraySegment<byte>(_data, 0, 4));
                        //Interlocked.Add(ref _sent, 4);
                        //tcpConnection.TotalSent += 4;
                        //tcpConnection.EnqueueSend(outData);
                        Thread.Sleep(2000);
                        ThreadPool.QueueUserWorkItem(callBack);
                    };
     ThreadPool.QueueUserWorkItem(callBack);
 }
Ejemplo n.º 54
0
 public GameSession(TcpConnection c)
 {
     _connection = c;
 }
Ejemplo n.º 55
0
        private TcpConnection GetConnection(TcpServiceAddress address)
        {
            TcpConnection c;
            lock (connectionPool) {
                // If there isn't, establish a connection,
                if (!connectionPool.TryGetValue(address, out c)) {
                    Socket socket = new Socket(address.IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
                                               SocketType.Stream, ProtocolType.IP);
                    socket.Connect(address.ToIPAddress(), address.Port);
                    socket.ReceiveTimeout = (30*1000); // 30 second timeout,
                    socket.NoDelay = true;
                    int curSendBufSize = socket.SendBufferSize;
                    if (curSendBufSize < 256*1024)
                        socket.SendBufferSize = 256*1024;

                    int curReceiveBufSize = socket.ReceiveBufferSize;
                    if (curReceiveBufSize < 256*1024)
                        socket.ReceiveBufferSize = 256*1024;

                    c = new TcpConnection(this, socket);
                    c.Connect();
                    connectionPool[address] = c;
                } else {
                    c.AddLock();
                }
            }
            return c;
        }
        internal IInnerConnection CreateInnerConnection (ConnectionOptions options, bool enlist)
        {
            Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoConnection.CreateInnerConnection()");

            IInnerConnection conn;
#if UNMANAGED_ODBC
            if (options.UseOdbc)
                conn = new OdbcConnection ();
            else
#endif
                conn = new TcpConnection ();

            conn.OuterConnectionWeakRef = new WeakReference (this);

            conn.Open (options);
#if MTS 
			if (enlist && options.Enlist && ContextUtil.IsInTransaction)
			 	EnlistInnerConnection (conn);
#endif			

            return conn;
        }
Ejemplo n.º 57
0
 public TcpStreamPacket(Packet packet)
 {
     _direction = TcpDirection.SourceToDestination;
     _connection = new TcpConnection(packet);
     _packet = packet;
 }
Ejemplo n.º 58
0
        private void Poll()
        {
            polling = true;

            try {
                //TODO: INFO log ...

                while (polling) {
                    Socket s;
                    try {
                        // The socket to run the service,
                        s = listener.AcceptSocket();
                        s.NoDelay = true;
                        int cur_send_buf_size = s.SendBufferSize;
                        if (cur_send_buf_size < 256 * 1024) {
                            s.SendBufferSize = 256 * 1024;
                        }

                        //TODO: INFO log ...

                        TcpConnection c = new TcpConnection(this);
                        ThreadPool.QueueUserWorkItem(c.Work, s);
                    } catch (IOException) {
                        //TODO: WARN log ...
                    }
                }
            } catch(Exception) {
                //TODO: WARN log ...
            }
        }
Ejemplo n.º 59
0
 public TcpConnection GetTcpConnection()
 {
     if (_tcpConnection == null && _tcp != null)
         _tcpConnection = new TcpConnection(_packet);
     return _tcpConnection;
 }
Ejemplo n.º 60
0
 /**
  * 接続失敗した
  */
 private void OnConnectFailed(TcpConnection conn, Result result)
 {
     result.Log();
     Debug.Log("接続失敗した");
 }