Beispiel #1
0
            protected override IEnumerable <DataFrame> GetFrames()
            {
                ProxyConnection conn = _conns.Dequeue();

                while (conn != null)
                {
                    bool receivedFinal = false;

                    foreach (HttpResponseDataChunk chunk in conn.ResponseReader)
                    {
                        receivedFinal = chunk.FinalChunk;
                        yield return(chunk.ToDataFrame());
                    }

                    // If we didn't receive final chunk we have an error, start shutdown
                    if (!receivedFinal)
                    {
                        _conns.Stop();
                        break;
                    }

                    conn = _conns.Dequeue();
                }

                lock (_graphs)
                {
                    foreach (NetGraph graph in _graphs)
                    {
                        _service.CloseConnection(graph);
                    }
                }
            }
Beispiel #2
0
        public static ProxyConnection CreateProxy(int serverID, byte[] connectMsg)
        {
            ProxyConnection conn = null;

            try
            {
                //DebugWriteLine($"Attempting to create proxy for ServerID {serverID}...");
                conn = new ProxyConnection(serverID, connectMsg, OnProxyClose);
                //DebugWriteLine($"Created proxy connection for ServerID {serverID}!");
            }
            catch (SocksException ex)
            {
                //DebugWriteLine($"Failed to create ProxyConnection for ServerID {serverID}. Reason: {ex.Message} ({ex.ErrorCode})");
                switch (ex.ErrorCode)
                {
                case SocksError.Disconnected:
                    new Thread(() => SendDisconnect(serverID)).Start();
                    break;

                case SocksError.InvalidDatagram:
                    new Thread(() => SendDisconnect(serverID)).Start();
                    break;

                default:
                    new Thread(() => SendError(serverID, ex.ErrorCode)).Start();
                    break;
                }
            }
            catch (Exception ex)
            {
                //DebugWriteLine($"Unhandled exception while creating new proxy connection to ServerID {serverID}: {ex.Message}");
                new Thread(() => SendDisconnect(serverID));
            }
            return(conn);
        }
Beispiel #3
0
        private static void DispatchDatagram(object dg)
        {
            SocksDatagram curMsg = (SocksDatagram)dg;

            byte[] data;
            try
            {
                data = Convert.FromBase64String(curMsg.data);
            }
            catch (Exception ex)
            {
                //DebugWriteLine($"Error decoding data: {ex.Message}");
                return;
            }
            ProxyConnection conn = GetProxyConnection(curMsg.server_id);

            if (conn == null)
            {
                if (curMsg.data != "LTE=")
                {
                    CreateNewProxyConnection(curMsg.server_id, data);
                }
            }
            else
            {
                conn.EnqueueRequestData(data);
            }
        }
Beispiel #4
0
        private static void ProcessConnectionEvent(ConnectionTable connectionTable, ProxyConnection connection, string eventMessage)
        {
            var connections = connectionTable.ConnectionIndecies.Count;
            var endPoint    = (IPEndPoint)connection.Socket.RemoteEndPoint;
            var target      = connection.IsClient ? "client" : "telegram";

            Log($"{endPoint.Address}:{endPoint.Port} ({target}) {eventMessage} ({connections} connections)");
        }
 public TcpConnectionHandler(Socket client)
 {
     Console.WriteLine("TcpHandlerConnection thread->" + Thread.CurrentThread.ManagedThreadId);
     this.sObject = new StateObject(size: 512, client.RemoteEndPoint);
     this.client  = client;
     proxy        = new ProxyConnection(this);
     BeginReceive();
 }
Beispiel #6
0
        public void TunnelTest()
        {
            var clientTcp  = new TestTcpClient();
            var connection = new ProxyConnection(clientTcp)
            {
                CreateTcpClientForServer = (host, port) => new TestTcpClient(host, port)
            };
            var exceptions = new List <Exception>();

            connection.FatalException += (_, e) => exceptions.Add(e);

            connection.StartReceiving();

            var tcsSession = new TaskCompletionSource <IReadOnlySession>();

            connection.HttpResponseSent += result => tcsSession.TrySetResult(result);

            var request =
                @"CONNECT www.example.com:443 HTTP/1.1
Host: www.example.com:443
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36

";

            clientTcp.WriteToInput(request);

            var session = tcsSession.GetResult();

            session.Request.ToString().Is(request);

            var expectedResponse =
                @"HTTP/1.1 200 Connection Established
Date: Mon, 01 Jan 2018 01:00:00 GMT

";

            session.Response.ToString().Is(expectedResponse);

            connection.serverConnection.client.AsTest().Host.Is("www.example.com");
            connection.serverConnection.client.AsTest().Port.Is(443);
            connection.serverConnection.IsTunnelMode.IsTrue();
            connection.clientConnection.IsTunnelMode.IsTrue();

            var expectedString = "hogehoge\r\n";

            clientTcp.WriteToInput(expectedString);

            // HTTP と解釈できないので例外が発生するが、データは送信されている。
            var serverTcp = connection.serverConnection.client.AsTest();

            serverTcp.GetStream().AsTest().OutputStream.Is(expectedString);

            exceptions.Count.Is(1);

            connection.Dispose();
        }
Beispiel #7
0
        public void Session302Test()
        {
            var clientTcp  = new TestTcpClient();
            var connection = new ProxyConnection(clientTcp)
            {
                CreateTcpClientForServer = (host, port) => new TestTcpClient(host, port)
            };

            connection.StartReceiving();

            var tcsRequest = new TaskCompletionSource <IReadOnlyHttpRequest>();

            connection.HttpRequestSent += result => tcsRequest.TrySetResult(result);

            var tcsSession = new TaskCompletionSource <IReadOnlySession>();

            connection.HttpResponseSent += result => tcsSession.TrySetResult(result);

            var tcsClose = new TaskCompletionSource <ProxyConnection>();

            connection.Disposing += result => tcsClose.TrySetResult(result);

            var request =
                @"GET http://www.example.com/netgame/social/-/gadgets/=/app_id=854854/ HTTP/1.1
Host: www.example.com
Proxy-Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

";

            clientTcp.WriteToInput(request);

            var requestResult = tcsRequest.GetResult();

            connection.serverConnection.client.AsTest().WriteFileToInput("TestData/Response302");

            var sessionResult = tcsSession.GetResult();

            sessionResult.Request.ToString().Is(request);

            var response = sessionResult.Response as HttpResponse;

            response.GetBodyAsString().Is("");

            connection.serverConnection.client.AsTest().Close();    // サーバーから閉じる
            //clientTcp.Close();  // クライアントから閉じる

            tcsClose.GetResult().Is(connection);

            connection.Dispose();
        }
Beispiel #8
0
        private async Task ListenToConnection()
        {
            while (_isRunning)
            {
                var client = await _listener.AcceptTcpClientAsync();

                var connection = new ProxyConnection(this, client, _to);
                _connections.Add(connection);
                connection.Transfer();
            }
        }
Beispiel #9
0
 public static void AddProxy(ProxyConnection conn)
 {
     if (conn == null)
     {
         return;
     }
     //proxyConnectionMapMtx.WaitOne();
     proxyConnectionMap[conn.ServerID] = conn;
     //DebugWriteLine($"ProxyConnectionMap Count: {proxyConnectionMap.Count}");
     //proxyConnectionMapMtx.ReleaseMutex();
 }
Beispiel #10
0
        //public static void AwaitConnectionDisconnect(ProxyConnection conn)
        //{
        //    if (conn == null)
        //        return;
        //    conn.ExitEvent.WaitOne();
        //    var msg = new SocksDatagram()
        //    {
        //        server_id = conn.ServerID,
        //        data = Convert.ToBase64String(DisconnectMessageBytes)
        //    };
        //    AddMythicMessageToQueue(msg);
        //}

        //public static void AwaitRemoveConnection(ProxyConnection conn)
        //{
        //    if (conn == null)
        //        return;
        //    conn.ExitEvent.WaitOne();
        //    //DebugWriteLine("Attempting to remove proxy!");
        //    RemoveProxyConnection(conn.ServerID);
        //}

        public static void CreateNewProxyConnection(int serverID, byte[] dg)
        {
            ProxyConnection conn = CreateProxy(serverID, dg);

            if (conn != null)
            {
                AddProxy(conn);
                conn.StartRelay();
                var msgToSend = CreateFormattedMessageWithLength(SocksError.SuccessReply, conn);
                AddMythicMessageToQueue(msgToSend);
            }
        }
Beispiel #11
0
        public void PerformTest()
        {
            Mock <EventInfo>       mockEventInfo       = new Mock <EventInfo>();
            Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());

            EventInfo       eventInfo       = mockEventInfo.Object;
            ProxyConnection proxyConnection = mockProxyConnection.Object;

            var testCases = new[]
            {
                new
                {
                    EventType            = EventType.Connected,
                    SendDataCalled       = false,
                    ExpectedThenResponse = ThenResponse.Continue
                },
                new
                {
                    EventType            = EventType.Disconnected,
                    SendDataCalled       = false,
                    ExpectedThenResponse = ThenResponse.Continue
                },
                new
                {
                    EventType            = EventType.Message,
                    SendDataCalled       = true,
                    ExpectedThenResponse = ThenResponse.Continue
                }
            };

            foreach (var testCase in testCases)
            {
                ThenSendData then = new ThenSendData();

                mockEventInfo.Reset();
                mockProxyConnection.Reset();

                mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
                mockEventInfo.Setup(mock => mock.Type).Returns(testCase.EventType);

                Assert.AreEqual(testCase.ExpectedThenResponse, then.Perform(eventInfo));

                if (testCase.SendDataCalled)
                {
                    mockProxyConnection.Verify(mock => mock.SendData(eventInfo), Times.Once);
                }
                else
                {
                    mockProxyConnection.Verify(mock => mock.SendData(It.IsAny <EventInfo>()), Times.Never);
                }
            }
        }
Beispiel #12
0
        public void SessionNoBodyTest()
        {
            var clientTcp  = new TestTcpClient();
            var connection = new ProxyConnection(clientTcp)
            {
                CreateTcpClientForServer = (host, port) => new TestTcpClient(host, port)
            };

            connection.StartReceiving();

            var tcsRequest = new TaskCompletionSource <IReadOnlyHttpRequest>();

            connection.HttpRequestSent += result => tcsRequest.TrySetResult(result);

            var tcsSession = new TaskCompletionSource <IReadOnlySession>();

            connection.HttpResponseSent += result => tcsSession.TrySetResult(result);

            var tcsClose = new TaskCompletionSource <ProxyConnection>();

            connection.Disposing += result => tcsClose.TrySetResult(result);

            var request =
                @"GET http://203.104.209.71/kcs2/resources/voice/titlecall_1/005.mp3 HTTP/1.1
Host: 203.104.209.71

";

            clientTcp.WriteToInput(request);

            var requestResult = tcsRequest.GetResult();

            connection.serverConnection.client.AsTest().WriteFileToInput("TestData/ResponseNoBody");

            var sessionResult = tcsSession.GetResult();

            sessionResult.Request.ToString().Is(request);

            var response = sessionResult.Response as HttpResponse;

            response.GetBodyAsString().Is("");

            connection.serverConnection.client.AsTest().Close();    // サーバーから閉じる
            //clientTcp.Close();  // クライアントから閉じる

            tcsClose.GetResult().Is(connection);

            connection.Dispose();
        }
Beispiel #13
0
        public Entity.ProxyConnection GetOneConnection(Guid id)
        {
            CacheHelper.ClearCache();
            ProxyConnection conn = null;

            //using (Xrm.XrmServiceContext context = new Xrm.XrmServiceContext("Xrm"))
            //{
            Xrm.Connection c = this.xrm.ConnectionSet.Where(i => i.Id == id).FirstOrDefault();
            if (c != null)
            {
                conn = ObjectConverter.SingleConvertToProxyConnection(c, this.xrm);
            }
            //}
            return(conn);
        }
Beispiel #14
0
        public static ProxyConnection GetProxyConnection(int channelID)
        {
            ProxyConnection result = null;

            ////DebugWriteLine("Requesting proxyConnectionMapMtx.");
            //proxyConnectionMapMtx.WaitOne();
            //DebugWriteLine($"Attempting to fetch connection with Channel ID: {channelID}...");
            if (proxyConnectionMap.TryGetValue(channelID, out result))
            {
                //DebugWriteLine($"Fetched connection with Channel ID: {channelID}!");
                return(result);
            }
            else
            {
                //DebugWriteLine($"Failed fetch connection with Channel ID: {channelID}.");
                return(null);
            }
        }
        private void Poll()
        {
            while (polling)
            {
                try {
                    if (!listener.Pending())
                    {
                        Thread.Sleep(500);
                        continue;
                    }

                    Socket          socket = listener.AcceptSocket();
                    ProxyConnection conn   = new ProxyConnection(this);
                    ThreadPool.QueueUserWorkItem(conn.Process, socket);
                } catch (Exception e) {
                    Logger.Warning("Socket Error while processing a proxy connection.", e);
                }
            }
        }
Beispiel #16
0
        public void WhenHasEntity_IsMatch_AlwaysTrue()
        {
            List <MessageValue> alwaysTrueMessageValues = new List <MessageValue>()
            {
                MessageValue.DataDirection,
                MessageValue.LocalAddress,
                MessageValue.LocalPort,
                MessageValue.Protocol,
                MessageValue.SourceRemoteAddress,
                MessageValue.SourceRemotePort
            };
            IEnumerable <MessageValue> notAlwaysTrueMessageValues = Enum.GetValues(typeof(MessageValue)).Cast <MessageValue>().Except(alwaysTrueMessageValues);

            Mock <EventInfo>       mockEventInfo       = new Mock <EventInfo>();
            Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
            Mock <ProxyInfo>       mockProxyInfo       = new Mock <ProxyInfo>();

            EventInfo       eventInfo       = mockEventInfo.Object;
            ProxyConnection proxyConnection = mockProxyConnection.Object;
            ProxyInfo       proxyInfo       = mockProxyInfo.Object;

            mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
            mockProxyConnection.Setup(mock => mock.ProxyInfo).Returns(proxyInfo);

            WhenHasEntity when = new WhenHasEntity();

            foreach (MessageValue value in alwaysTrueMessageValues)
            {
                when.MessageValue = value;
                Assert.IsTrue(when.IsMatch(eventInfo));
            }

            foreach (MessageValue value in notAlwaysTrueMessageValues)
            {
                when.MessageValue = value;
                Assert.IsFalse(when.IsMatch(eventInfo));
            }
        }
        private void OnConnected(IAsyncResult result)
        {
            try
            {
                TelegramSocket.EndConnect(result);
                if (!TelegramSocket.Connected)
                {
                    Connection.Close();
                    return;
                }
                TelegramSocket.Blocking = false;

                var telegramConnection = new ProxyConnection(TelegramSocket, Connection);

                var encryptor = new Cryptography.MTProtoCryptor(Buffer, false);
                var decryptor = new Cryptography.MTProtoCryptor(Buffer, true);

                var tmp = new byte[Buffer.Length];
                encryptor.Transform(Buffer, 0, Buffer.Length, tmp, 0);
                for (var i = 0; i < 56; i++)
                {
                    tmp[i] = Buffer[i];
                }
                telegramConnection.Send(tmp, 0, tmp.Length);

                telegramConnection.Encryptor = encryptor;
                telegramConnection.Decryptor = decryptor;

                Connection.ReverseConnection = telegramConnection;
                Connection.DataHandler       = new ProxyHandler(Connection);
                Connection.AssignedTabled.Register(telegramConnection);
            }
            catch
            {
                Connection.Close();
            }
        }
Beispiel #18
0
        public void WhenHasEntity_IsMatch_DestinationRemotePortTest()
        {
            WhenHasEntity when = new WhenHasEntity()
            {
                MessageValue = MessageValue.DestinationRemotePort
            };

            Mock <EventInfo>       mockEventInfo       = new Mock <EventInfo>();
            Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());

            EventInfo       eventInfo       = mockEventInfo.Object;
            ProxyConnection proxyConnection = mockProxyConnection.Object;

            mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
            mockProxyConnection.Setup(mock => mock.HasTargetConnection).Returns(true);

            Assert.IsTrue(when.IsMatch(eventInfo));

            mockProxyConnection.Reset();

            mockProxyConnection.Setup(mock => mock.HasTargetConnection).Returns(false);

            Assert.IsFalse(when.IsMatch(eventInfo));
        }
 public CryptoSetupHandler(ProxyConnection connection)
 {
     Connection = connection;
 }
Beispiel #20
0
 public virtual EventInfo Clone(RulesEngine engine = null, EventType?type = null, DataDirection?direction = null, Message message = null, ProxyConnection proxyConnection = null, Variables variables = null)
 {
     return(new EventInfo()
     {
         Engine = engine ?? Engine,
         Type = type ?? Type,
         Direction = direction ?? Direction,
         Message = message ?? Message,
         ProxyConnection = proxyConnection ?? ProxyConnection,
         Variables = variables ?? Variables
     });
 }
Beispiel #21
0
 public void UpdateOneConnection(ProxyConnection c)
 {
 }
Beispiel #22
0
        public void ThenAddMessage_PerformTest()
        {
            string    messageText       = "blah blah blah";
            Variables toTargetVariables = new Variables();
            Variables toOriginVariables = new Variables();

            Mock <EventInfo> mockEventInfo = new Mock <EventInfo>()
            {
                CallBase = true
            };
            Mock <ProxyConnection> mockProxyConnection   = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
            Mock <VariableString>  mockMessageTextString = new Mock <VariableString>(It.IsAny <string>(), null);
            Mock <RulesEngine>     mockRulesEngine       = new Mock <RulesEngine>()
            {
                CallBase = true
            };
            Mock <MessageQueue <EventInfo> > mockMessageQueue = new Mock <MessageQueue <EventInfo> >();

            EventInfo                eventInfo         = mockEventInfo.Object;
            VariableString           messageTextString = mockMessageTextString.Object;
            RulesEngine              rulesEngine       = mockRulesEngine.Object;
            MessageQueue <EventInfo> messageQueue      = mockMessageQueue.Object;
            ProxyConnection          proxyConnection   = mockProxyConnection.Object;

            mockMessageTextString.Setup(mock => mock.GetText(It.IsAny <Variables>())).Returns(messageText);
            mockProxyConnection.Setup(mock => mock.ToTargetConnectionVariables).Returns(toTargetVariables);
            mockProxyConnection.Setup(mock => mock.ToOriginConnectionVariables).Returns(toOriginVariables);
            mockRulesEngine.Setup(mock => mock.Queue).Returns(messageQueue);
            mockEventInfo.Setup(mock => mock.Engine).Returns(rulesEngine);
            mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);

            var testCases = new[]
            {
                new
                {
                    Direction         = DataDirection.Origin,
                    InsertAtBeginning = true,
                    ExpectedVariables = toOriginVariables
                },
                new
                {
                    Direction         = DataDirection.Origin,
                    InsertAtBeginning = false,
                    ExpectedVariables = toOriginVariables
                },
                new
                {
                    Direction         = DataDirection.Target,
                    InsertAtBeginning = true,
                    ExpectedVariables = toTargetVariables
                },
                new
                {
                    Direction         = DataDirection.Target,
                    InsertAtBeginning = false,
                    ExpectedVariables = toTargetVariables
                }
            };

            foreach (var testCase in testCases)
            {
                ThenAddMessage then = new ThenAddMessage()
                {
                    Direction         = testCase.Direction,
                    InsertAtBeginning = testCase.InsertAtBeginning,
                    MessageText       = messageTextString
                };


                mockMessageQueue.Reset();

                if (testCase.InsertAtBeginning)
                {
                    mockMessageQueue.Setup(mock => mock.AddFirst(It.IsAny <EventInfo>())).Callback((EventInfo eventInfoParam) =>
                    {
                        Assert.AreEqual(testCase.ExpectedVariables, eventInfoParam.Variables);
                        Assert.AreEqual(messageText, eventInfoParam.Message.RawText);
                    });

                    Assert.AreEqual(ThenResponse.Continue, then.Perform(eventInfo));

                    mockMessageQueue.Verify(mock => mock.AddFirst(It.IsAny <EventInfo>()), Times.Once);
                }
                else
                {
                    mockMessageQueue.Setup(mock => mock.AddLast(It.IsAny <EventInfo>())).Callback((EventInfo eventInfoParam) =>
                    {
                        Assert.AreEqual(testCase.ExpectedVariables, eventInfoParam.Variables);
                        Assert.AreEqual(messageText, eventInfoParam.Message.RawText);
                    });

                    Assert.AreEqual(ThenResponse.Continue, then.Perform(eventInfo));

                    mockMessageQueue.Verify(mock => mock.AddLast(It.IsAny <EventInfo>()), Times.Once);
                }
            }
        }
Beispiel #23
0
        public void WhenMatchesText_IsMatch_MessageValue_WithIdentifierTests()
        {
            string sourceString = "TestString";
            string identifier   = "Ident";

            List <MessageValue> testableValues = new List <MessageValue>
            {
                MessageValue.HttpHeader
            };

            Mock <EventInfo>       mockEventInfo       = new Mock <EventInfo>();
            Mock <ProxyInfo>       mockProxyInfo       = new Mock <ProxyInfo>();
            Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
            Mock <HttpMessage>     mockHttpMessage     = new Mock <HttpMessage>();
            Mock <HttpHeaders>     mockHttpHeaders     = new Mock <HttpHeaders>();
            Mock <VariableString>  mockIdentiferString = new Mock <VariableString>(It.IsAny <string>(), null);

            EventInfo       eventInfo       = mockEventInfo.Object;
            ProxyConnection proxyConnection = mockProxyConnection.Object;
            ProxyInfo       proxyInfo       = mockProxyInfo.Object;
            HttpMessage     httpMessage     = mockHttpMessage.Object;
            HttpHeaders     httpHeaders     = mockHttpHeaders.Object;
            VariableString  identiferString = mockIdentiferString.Object;

            mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
            mockEventInfo.Setup(mock => mock.Message).Returns(httpMessage);
            mockProxyConnection.Setup(mock => mock.ProxyInfo).Returns(proxyInfo);
            mockHttpHeaders.Setup(mock => mock.GetOrDefault(identifier)).Returns(sourceString);
            mockIdentiferString.Setup(mock => mock.GetText(It.IsAny <Variables>())).Returns(identifier);

            var testCases = new[]
            {
                new
                {
                    MatchString = GetMockVariableString("Test"),
                    MatchType   = MatchType.BeginsWith,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("est"),
                    MatchType   = MatchType.Contains,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("ing"),
                    MatchType   = MatchType.EndsWith,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("TestString"),
                    MatchType   = MatchType.Equals,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString(".*Str.*"),
                    MatchType   = MatchType.Regex,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.BeginsWith,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.Contains,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.EndsWith,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.Equals,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.Regex,
                    Matches     = false
                }
            };

            foreach (MessageValue messageValue in testableValues)
            {
                mockHttpMessage.Reset();
                mockHttpMessage.Setup(mock => mock.Headers).Returns(httpHeaders);

                foreach (var testCase in testCases)
                {
                    WhenMatchesText when = new WhenMatchesText()
                    {
                        MessageValue    = messageValue,
                        UseMessageValue = true,
                        MatchText       = testCase.MatchString,
                        MatchType       = testCase.MatchType,
                        Identifier      = identiferString
                    };

                    Assert.AreEqual(testCase.Matches, when.IsMatch(eventInfo));
                }
            }
        }
        private void Poll()
        {
            while (polling) {
                try {
                    if (!listener.Pending()) {
                        Thread.Sleep(500);
                        continue;
                    }

                    Socket socket = listener.AcceptSocket();
                    ProxyConnection conn = new ProxyConnection(this);
                    ThreadPool.QueueUserWorkItem(conn.Process, socket);
                } catch(Exception e) {
                    Logger.Warning("Socket Error while processing a proxy connection.", e);
                }
            }
        }
Beispiel #25
0
        public void WhenMatchesText_IsMatch_MessageValue_IntTests()
        {
            int sourceValue = 40494;

            List <MessageValue> testableValues = new List <MessageValue>
            {
                MessageValue.DestinationRemotePort,
                MessageValue.SourceRemotePort,
                MessageValue.LocalPort,
                MessageValue.HttpStatusCode
            };

            Mock <EventInfo>              mockEventInfo              = new Mock <EventInfo>();
            Mock <HttpMessage>            mockHttpMessage            = new Mock <HttpMessage>();
            Mock <ProxyConnection>        mockProxyConnection        = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
            Mock <ProxyInfo>              mockProxyInfo              = new Mock <ProxyInfo>();
            Mock <Channel>                mockChannel                = new Mock <Channel>(It.IsAny <TcpClient>());
            Mock <IPEndPoint>             mockIPEndPoint             = new Mock <IPEndPoint>(It.IsAny <long>(), It.IsAny <int>());
            Mock <IPAddress>              mockIPAddress              = new Mock <IPAddress>(It.IsAny <long>());
            Mock <HttpResponseStatusLine> mockHttpResponseStatusLine = new Mock <HttpResponseStatusLine>();

            EventInfo              eventInfo          = mockEventInfo.Object;
            ProxyConnection        proxyConnection    = mockProxyConnection.Object;
            ProxyInfo              proxyInfo          = mockProxyInfo.Object;
            HttpMessage            httpMessage        = mockHttpMessage.Object;
            HttpResponseStatusLine responseStatusLine = mockHttpResponseStatusLine.Object;
            Channel    channel    = mockChannel.Object;
            IPEndPoint ipEndpoint = mockIPEndPoint.Object;
            IPAddress  ipAddress  = mockIPAddress.Object;

            mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
            mockEventInfo.Setup(mock => mock.Message).Returns(httpMessage);
            mockProxyConnection.Setup(mock => mock.HasTargetConnection).Returns(true);
            mockProxyConnection.Setup(mock => mock.OriginChannel).Returns(channel);
            mockProxyConnection.Setup(mock => mock.TargetChannel).Returns(channel);
            mockProxyConnection.Setup(mock => mock.ProxyInfo).Returns(proxyInfo);
            mockChannel.Setup(mock => mock.LocalEndpoint).Returns(ipEndpoint);
            mockChannel.Setup(mock => mock.RemoteEndpoint).Returns(ipEndpoint);
            mockHttpMessage.Setup(mock => mock.StatusLine).Returns(responseStatusLine);
            ipEndpoint.Port = sourceValue;
            mockHttpResponseStatusLine.Setup(mock => mock.StatusCode).Returns(sourceValue);

            var testCases = new[]
            {
                new
                {
                    MatchString = GetMockVariableString("40"),
                    MatchType   = MatchType.BeginsWith,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("49"),
                    MatchType   = MatchType.Contains,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("94"),
                    MatchType   = MatchType.EndsWith,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("40494"),
                    MatchType   = MatchType.Equals,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString(".*49.*"),
                    MatchType   = MatchType.Regex,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("65"),
                    MatchType   = MatchType.BeginsWith,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("65"),
                    MatchType   = MatchType.Contains,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("65"),
                    MatchType   = MatchType.EndsWith,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("65"),
                    MatchType   = MatchType.Equals,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("65"),
                    MatchType   = MatchType.Regex,
                    Matches     = false
                }
            };

            foreach (MessageValue messageValue in testableValues)
            {
                foreach (var testCase in testCases)
                {
                    WhenMatchesText when = new WhenMatchesText()
                    {
                        MessageValue    = messageValue,
                        UseMessageValue = true,
                        MatchText       = testCase.MatchString,
                        MatchType       = testCase.MatchType
                    };

                    Assert.AreEqual(testCase.Matches, when.IsMatch(eventInfo));
                }
            }
        }
Beispiel #26
0
        public void WhenMatchesText_IsMatch_MessageValue_SimpleStringTests()
        {
            string sourceString = "TestString";

            List <MessageValue> testableValues = new List <MessageValue>
            {
                MessageValue.DestinationRemoteAddress,
                MessageValue.HttpMethod,
                MessageValue.HttpRequestUri,
                MessageValue.LocalAddress,
                MessageValue.Protocol,
                MessageValue.SourceRemoteAddress,
                MessageValue.HttpBody,
                MessageValue.Message,
                MessageValue.HttpHeaders,
                MessageValue.HttpStatusLine,
                MessageValue.HttpVersion,
                MessageValue.HttpStatusMessage
            };

            Mock <EventInfo>              mockEventInfo              = new Mock <EventInfo>();
            Mock <ProxyInfo>              mockProxyInfo              = new Mock <ProxyInfo>();
            Mock <ProxyConnection>        mockProxyConnection        = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
            Mock <HttpMessage>            mockHttpMessage            = new Mock <HttpMessage>();
            Mock <HttpResponseStatusLine> mockHttpResponseStatusLine = new Mock <HttpResponseStatusLine>();
            Mock <HttpRequestStatusLine>  mockHttpRequestStatusLine  = new Mock <HttpRequestStatusLine>();
            Mock <HttpBody>    mockHttpBody    = new Mock <HttpBody>();
            Mock <HttpHeaders> mockHttpHeaders = new Mock <HttpHeaders>();
            Mock <Channel>     mockChannel     = new Mock <Channel>(It.IsAny <TcpClient>());
            Mock <IPEndPoint>  mockIPEndPoint  = new Mock <IPEndPoint>(It.IsAny <long>(), It.IsAny <int>());
            Mock <IPAddress>   mockIPAddress   = new Mock <IPAddress>(It.IsAny <long>());

            EventInfo              eventInfo          = mockEventInfo.Object;
            ProxyConnection        proxyConnection    = mockProxyConnection.Object;
            ProxyInfo              proxyInfo          = mockProxyInfo.Object;
            HttpMessage            httpMessage        = mockHttpMessage.Object;
            HttpResponseStatusLine responseStatusLine = mockHttpResponseStatusLine.Object;
            HttpRequestStatusLine  requestStatusLine  = mockHttpRequestStatusLine.Object;
            HttpBody    httpBody    = mockHttpBody.Object;
            HttpHeaders httpHeaders = mockHttpHeaders.Object;
            Channel     channel     = mockChannel.Object;
            IPEndPoint  ipEndpoint  = mockIPEndPoint.Object;
            IPAddress   ipAddress   = mockIPAddress.Object;

            mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
            mockEventInfo.Setup(mock => mock.Message).Returns(httpMessage);
            mockProxyConnection.Setup(mock => mock.HasTargetConnection).Returns(true);
            mockProxyConnection.Setup(mock => mock.HasOriginConnection).Returns(true);
            mockProxyConnection.Setup(mock => mock.OriginChannel).Returns(channel);
            mockProxyConnection.Setup(mock => mock.TargetChannel).Returns(channel);
            mockProxyConnection.Setup(mock => mock.ProxyInfo).Returns(proxyInfo);
            mockChannel.Setup(mock => mock.LocalEndpoint).Returns(ipEndpoint);
            mockChannel.Setup(mock => mock.RemoteEndpoint).Returns(ipEndpoint);
            ipEndpoint.Address = ipAddress;
            mockHttpHeaders.Setup(mock => mock.ToString()).Returns(sourceString);
            mockHttpBody.Setup(mock => mock.ToString()).Returns(sourceString);
            mockIPAddress.Setup(mock => mock.ToString()).Returns(sourceString);
            mockHttpResponseStatusLine.Setup(mock => mock.ToString()).Returns(sourceString);
            mockHttpResponseStatusLine.Setup(mock => mock.StatusMessage).Returns(sourceString);
            mockHttpResponseStatusLine.Setup(mock => mock.Version).Returns(sourceString);
            mockHttpRequestStatusLine.Setup(mock => mock.ToString()).Returns(sourceString);
            mockHttpRequestStatusLine.Setup(mock => mock.Method).Returns(sourceString);
            mockHttpRequestStatusLine.Setup(mock => mock.Uri).Returns(sourceString);
            mockHttpRequestStatusLine.Setup(mock => mock.Version).Returns(sourceString);

            var testCases = new[]
            {
                new
                {
                    MatchString = GetMockVariableString("Test"),
                    MatchType   = MatchType.BeginsWith,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("est"),
                    MatchType   = MatchType.Contains,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("ing"),
                    MatchType   = MatchType.EndsWith,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("TestString"),
                    MatchType   = MatchType.Equals,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString(".*Str.*"),
                    MatchType   = MatchType.Regex,
                    Matches     = true
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.BeginsWith,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.Contains,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.EndsWith,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.Equals,
                    Matches     = false
                },
                new
                {
                    MatchString = GetMockVariableString("MatchString"),
                    MatchType   = MatchType.Regex,
                    Matches     = false
                }
            };

            foreach (MessageValue messageValue in testableValues)
            {
                mockHttpMessage.Reset();

                switch (messageValue)
                {
                case MessageValue.HttpStatusLine:
                case MessageValue.HttpVersion:
                case MessageValue.HttpStatusMessage:
                    mockHttpMessage.Setup(mock => mock.Body).Returns(httpBody);
                    mockHttpMessage.Setup(mock => mock.Headers).Returns(httpHeaders);
                    mockHttpMessage.Setup(mock => mock.RawText).Returns(sourceString);
                    mockHttpMessage.Setup(mock => mock.Protocol).Returns(sourceString);
                    mockHttpMessage.Setup(mock => mock.ToString()).Returns(sourceString);
                    mockHttpMessage.Setup(mock => mock.StatusLine).Returns(responseStatusLine);
                    break;

                default:
                    mockHttpMessage.Setup(mock => mock.Body).Returns(httpBody);
                    mockHttpMessage.Setup(mock => mock.Headers).Returns(httpHeaders);
                    mockHttpMessage.Setup(mock => mock.RawText).Returns(sourceString);
                    mockHttpMessage.Setup(mock => mock.Protocol).Returns(sourceString);
                    mockHttpMessage.Setup(mock => mock.ToString()).Returns(sourceString);
                    mockHttpMessage.Setup(mock => mock.StatusLine).Returns(requestStatusLine);
                    break;
                }

                foreach (var testCase in testCases)
                {
                    WhenMatchesText when = new WhenMatchesText()
                    {
                        MessageValue    = messageValue,
                        UseMessageValue = true,
                        MatchText       = testCase.MatchString,
                        MatchType       = testCase.MatchType
                    };

                    Assert.AreEqual(testCase.Matches, when.IsMatch(eventInfo));
                }
            }
        }
Beispiel #27
0
 private static void Connections_OnConnectionRegistered(ConnectionTable connectionTable, ProxyConnection connection)
 {
     ProcessConnectionEvent(connectionTable, connection, "connected");
 }
Beispiel #28
0
        public void ThenHttpConnect_PerformTest()
        {
            string hostname = "www.google.com";
            int    port     = 90;

            Mock <EventInfo>       mockEventInfo       = new Mock <EventInfo>();
            Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
            Mock <HttpMessage>     mockHttpMessage     = new Mock <HttpMessage>();
            Mock <HttpHeaders>     mockHttpHeaders     = new Mock <HttpHeaders>();

            EventInfo       eventInfo       = mockEventInfo.Object;
            ProxyConnection proxyConnection = mockProxyConnection.Object;
            HttpMessage     httpMessage     = mockHttpMessage.Object;
            HttpHeaders     httpHeaders     = mockHttpHeaders.Object;

            mockHttpMessage.SetupGet(mock => mock.Headers).Returns(httpHeaders);

            var testCases = new[]
            {
                new
                {
                    HasTargetConnection       = false,
                    DataDirection             = DataDirection.Target,
                    OverrideCurrentConnection = false,
                    HeaderValue = (string)null,
                    InitTargetChannelSuccess = false,
                    InitTargetChannelCalled  = false,
                    ExpectedThenResponse     = ThenResponse.BreakRules,
                    ExpectedHostname         = (string)null,
                    ExpectedPort             = (int?)null
                },
                new
                {
                    HasTargetConnection       = true,
                    DataDirection             = DataDirection.Target,
                    OverrideCurrentConnection = true,
                    HeaderValue = $"{hostname}:{port}",
                    InitTargetChannelSuccess = true,
                    InitTargetChannelCalled  = true,
                    ExpectedThenResponse     = ThenResponse.Continue,
                    ExpectedHostname         = hostname,
                    ExpectedPort             = (int?)port
                },
                new
                {
                    HasTargetConnection       = false,
                    DataDirection             = DataDirection.Target,
                    OverrideCurrentConnection = false,
                    HeaderValue = $"{hostname}:{port}",
                    InitTargetChannelSuccess = true,
                    InitTargetChannelCalled  = true,
                    ExpectedThenResponse     = ThenResponse.Continue,
                    ExpectedHostname         = hostname,
                    ExpectedPort             = (int?)port
                },
                new
                {
                    HasTargetConnection       = false,
                    DataDirection             = DataDirection.Target,
                    OverrideCurrentConnection = false,
                    HeaderValue = $"{hostname}",
                    InitTargetChannelSuccess = true,
                    InitTargetChannelCalled  = true,
                    ExpectedThenResponse     = ThenResponse.Continue,
                    ExpectedHostname         = hostname,
                    ExpectedPort             = (int?)80
                },
                new
                {
                    HasTargetConnection       = false,
                    DataDirection             = DataDirection.Target,
                    OverrideCurrentConnection = false,
                    HeaderValue = $"{hostname}:{port}",
                    InitTargetChannelSuccess = false,
                    InitTargetChannelCalled  = true,
                    ExpectedThenResponse     = ThenResponse.BreakRules,
                    ExpectedHostname         = hostname,
                    ExpectedPort             = (int?)port
                }
            };

            foreach (var testCase in testCases)
            {
                ThenHttpConnect then = new ThenHttpConnect();

                mockEventInfo.Reset();
                mockProxyConnection.Reset();
                mockHttpHeaders.Reset();

                mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
                mockEventInfo.Setup(mock => mock.Direction).Returns(testCase.DataDirection);
                mockEventInfo.Setup(mock => mock.Message).Returns(httpMessage);
                mockHttpHeaders.Setup(mock => mock.GetOrDefault("Host")).Returns(testCase.HeaderValue);
                mockProxyConnection.Setup(mock => mock.HasTargetConnection).Returns(testCase.HasTargetConnection);

                if (testCase.InitTargetChannelCalled)
                {
                    then.OverrideCurrentConnection = testCase.OverrideCurrentConnection;

                    mockProxyConnection.Setup(mock => mock.InitConnection(It.IsAny <DataDirection>(), It.IsAny <string>(), It.IsAny <int>())).Returns(testCase.InitTargetChannelSuccess);

                    Assert.AreEqual(testCase.ExpectedThenResponse, then.Perform(eventInfo));

                    mockProxyConnection.Verify(mock => mock.InitConnection(testCase.DataDirection, testCase.ExpectedHostname, testCase.ExpectedPort.GetValueOrDefault()), Times.Once);
                }
                else
                {
                    then.OverrideCurrentConnection = testCase.OverrideCurrentConnection;

                    Assert.AreEqual(testCase.ExpectedThenResponse, then.Perform(eventInfo));

                    mockProxyConnection.Verify(mock => mock.InitConnection(It.IsAny <DataDirection>(), It.IsAny <string>(), It.IsAny <int>()), Times.Never);
                }
            }
        }
Beispiel #29
0
        public void SessionContentLengthTest()
        {
            var clientTcp  = new TestTcpClient();
            var connection = new ProxyConnection(clientTcp)
            {
                CreateTcpClientForServer = (host, port) => new TestTcpClient(host, port)
            };

            connection.StartReceiving();

            var tcsRequest = new TaskCompletionSource <IReadOnlyHttpRequest>();

            connection.HttpRequestSent += result => tcsRequest.TrySetResult(result);

            var tcsSession = new TaskCompletionSource <IReadOnlySession>();

            connection.HttpResponseSent += result => tcsSession.TrySetResult(result);

            var tcsClose = new TaskCompletionSource <ProxyConnection>();

            connection.Disposing += result => tcsClose.TrySetResult(result);

            var request =
                @"GET http://203.104.209.71/kcs2/resources/voice/titlecall_1/005.mp3 HTTP/1.1
Host: 203.104.209.71
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36
Accept: */*
Referer: http://203.104.209.71/kcs2/index.php?api_root=/kcsapi&voice_root=/kcs/sound&osapi_root=osapi.example.com&version=4.1.1.4
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

";

            clientTcp.WriteToInput(request);

            //var tcsRequestSuccess = tcsRequest.Task.Wait(1000);
            //if (!tcsRequestSuccess)
            //    Assert.False(true, "request timeout");
            var requestResult = tcsRequest.GetResult();

            connection.serverConnection.client.AsTest().WriteFileToInput("TestData/ResponseContentLength");

            //var tcsSessionSuccess = tcsSession.Task.Wait(1000);
            //if (!tcsSessionSuccess)
            //    Assert.False(true, "session timeout");
            var sessionResult = tcsSession.GetResult();

            var requestHeaders = sessionResult.Request.Headers as HttpHeaders;

            sessionResult.Request.RequestLine.HttpVersion.Is(new Version(1, 1));
            sessionResult.Request.RequestLine.Method.Is(HttpMethod.Get);
            sessionResult.Request.RequestLine.RequestTarget.Is("http://203.104.209.71/kcs2/resources/voice/titlecall_1/005.mp3");
            requestHeaders.Host.Is("203.104.209.71");
            requestHeaders.GetFirstValue("Connection").Is("keep-alive");
            requestHeaders.GetFirstValue("User-Agent").Is("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36");
            requestHeaders.GetFirstValue("Accept").Is("*/*");
            requestHeaders.GetFirstValue("Referer").Is("http://203.104.209.71/kcs2/index.php?api_root=/kcsapi&voice_root=/kcs/sound&osapi_root=osapi.example.com&version=4.1.1.4");
            requestHeaders.GetFirstValue("Accept-Encoding").Is("gzip, deflate");
            requestHeaders.GetFirstValue("Accept-Language").Is("en-US,en;q=0.9");
            requestHeaders.HasHeader("Via").IsFalse();
            sessionResult.Request.Body.IsNull();


            var response = sessionResult.Response as HttpResponse;

            response.StatusLine.HttpVersion.Is(new Version(1, 1));
            response.StatusLine.StatusCode.Is(HttpStatusCode.OK);
            response.StatusLine.ReasonPhrase.Is("OK");
            response.Headers.ContentLength.Exists.Is(true);
            response.Headers.ContentLength.Is(47);
            response.Headers.TransferEncoding.Exists.Is(false);
            response.Headers.IsChunked.Is(false);
            response.Headers.GetFirstValue("Access-Control-Allow-Credentials").Is("true");
            response.Headers.GetFirstValue("Access-Control-Allow-Methods").Is("POST,GET,HEAD,OPTIONS");
            response.Headers.GetFirstValue("Access-Control-Allow-Origin").Is("http://d.hatena.ne.jp");
            response.Headers.GetFirstValue("Cache-Control").Is("no-store, no-cache");
            response.Headers.ContentType.Is("application/json");
            response.Headers.GetFirstValue("Date").Is("Thu, 20 Sep 2018 01:59:09 GMT");
            response.Headers.GetFirstValue("Expires").Is("Mon, 15 Jun 1998 00:00:00 GMT");
            response.Headers.GetFirstValue("Pragma").Is("no-cache");
            response.Headers.GetFirstValue("Server").Is("Adtech Adserver");
            response.GetBodyAsString().Is(@"{""id"":""31259257328373081"",""seatbid"":[],""nbr"":1}");



            //connection.serverConnection.client.AsTest().Close();    // サーバーから閉じる
            clientTcp.Close();  // クライアントから閉じる

            tcsClose.GetResult().Is(connection);

            connection.Dispose();
        }
Beispiel #30
0
 public TamperClient(TamperServer server, TcpClient tcpClient)
 {
     parent                      = server;
     ProxyConnection             = new ProxyConnection(tcpClient);
     ProxyConnection.Interceptor = this;
 }
Beispiel #31
0
            private IEnumerable<HttpResponseDataChunk> GetResponse(ProxyConnection conn, Uri url, bool headRequest)
            {
                try
                {
                    DataReader reader = new DataReader(conn.DataAdapter.Coupling);

                    HttpParserConfig config = new HttpParserConfig();
                    config.StreamBody = true;

                    if (_server._config.Version10Proxy)
                    {
                        config.DowngradeChunkedToHttp10 = true;
                    }

                    _logger.LogVerbose("Starting processing of {0}", url);

                    HttpResponseHeader response = HttpParser.ReadResponseHeader(reader, false, _logger);

                    // If 100 continue then read out just that response then restart read
                    if (response.Is100Continue)
                    {
                        foreach (HttpResponseDataChunk chunk in response.ReadChunks(config))
                        {
                            _logger.LogVerbose("Read 100 continue chunk for {0} {1} {2}", url, chunk.Body.Length, chunk.FinalChunk);

                            yield return chunk;
                        }

                        response = HttpParser.ReadResponseHeader(reader, false, _logger);
                    }

                    _logger.LogVerbose("Read response header {0}", response.ResponseCode);

                    response.SetHeadRequest(headRequest);

                    foreach (HttpResponseDataChunk newChunk in response.ReadChunks(config))
                    {
                        _logger.LogVerbose("Read chunk for {0} {1} {2}", url, newChunk.Body.Length, newChunk.FinalChunk);

                        yield return newChunk;
                    }
                }
                finally
                {
                    bool closeSuccess = false;
                    try
                    {
                        conn.DataAdapter.Coupling.Close();
                        lock (_graphs)
                        {
                            _graphs.Remove(conn.Graph);
                        }
                        closeSuccess = true;
                    }
                    catch (OperationCanceledException)
                    {
                    }
                    catch (ObjectDisposedException)
                    {
                    }

                    if (!closeSuccess)
                    {
                        lock (_graphs)
                        {
                            // Force close
                            _service.CloseConnection(conn.Graph);
                            _graphs.Remove(conn.Graph);
                        }
                    }
                }
            }
Beispiel #32
0
        public void WhenProxyType_IsMatchTest()
        {
            var testCases = new[]
            {
                new
                {
                    InputEventInfo = ((Func <EventInfo>)(() =>
                    {
                        Mock <EventInfo> mockEventInfo = new Mock <EventInfo>();
                        Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
                        Mock <ProxyInfo> mockProxyInfo = new Mock <ProxyInfo>();

                        EventInfo eventInfo = mockEventInfo.Object;
                        ProxyConnection proxyConnection = mockProxyConnection.Object;
                        ProxyInfo proxyInfo = mockProxyInfo.Object;

                        mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
                        mockProxyConnection.SetupGet(mock => mock.ProxyInfo).Returns(proxyInfo);
                        mockProxyInfo.SetupGet(mock => mock.DataType).Returns(ProxyDataType.Http);
                        return(eventInfo);
                    })).Invoke(),
                    Type      = ProxyDataType.Http,
                    WillMatch = true
                },
                new
                {
                    InputEventInfo = ((Func <EventInfo>)(() =>
                    {
                        Mock <EventInfo> mockEventInfo = new Mock <EventInfo>();
                        Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
                        Mock <ProxyInfo> mockProxyInfo = new Mock <ProxyInfo>();

                        EventInfo eventInfo = mockEventInfo.Object;
                        ProxyConnection proxyConnection = mockProxyConnection.Object;
                        ProxyInfo proxyInfo = mockProxyInfo.Object;

                        mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
                        mockProxyConnection.SetupGet(mock => mock.ProxyInfo).Returns(proxyInfo);
                        mockProxyInfo.SetupGet(mock => mock.DataType).Returns(ProxyDataType.Text);
                        return(eventInfo);
                    })).Invoke(),
                    Type      = ProxyDataType.Text,
                    WillMatch = true
                },
                new
                {
                    InputEventInfo = ((Func <EventInfo>)(() =>
                    {
                        Mock <EventInfo> mockEventInfo = new Mock <EventInfo>();
                        Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
                        Mock <ProxyInfo> mockProxyInfo = new Mock <ProxyInfo>();

                        EventInfo eventInfo = mockEventInfo.Object;
                        ProxyConnection proxyConnection = mockProxyConnection.Object;
                        ProxyInfo proxyInfo = mockProxyInfo.Object;

                        mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
                        mockProxyConnection.SetupGet(mock => mock.ProxyInfo).Returns(proxyInfo);
                        mockProxyInfo.SetupGet(mock => mock.DataType).Returns(ProxyDataType.Http);
                        return(eventInfo);
                    })).Invoke(),
                    Type      = ProxyDataType.Text,
                    WillMatch = false
                },
                new
                {
                    InputEventInfo = ((Func <EventInfo>)(() =>
                    {
                        Mock <EventInfo> mockEventInfo = new Mock <EventInfo>();
                        Mock <ProxyConnection> mockProxyConnection = new Mock <ProxyConnection>(It.IsAny <ProxyHost>(), It.IsAny <ProxyInfo>(), It.IsAny <TcpClient>());
                        Mock <ProxyInfo> mockProxyInfo = new Mock <ProxyInfo>();

                        EventInfo eventInfo = mockEventInfo.Object;
                        ProxyConnection proxyConnection = mockProxyConnection.Object;
                        ProxyInfo proxyInfo = mockProxyInfo.Object;

                        mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
                        mockProxyConnection.SetupGet(mock => mock.ProxyInfo).Returns(proxyInfo);
                        mockProxyInfo.SetupGet(mock => mock.DataType).Returns(ProxyDataType.Text);
                        return(eventInfo);
                    })).Invoke(),
                    Type      = ProxyDataType.Http,
                    WillMatch = false
                }
            };

            foreach (var testCase in testCases)
            {
                WhenProxyType when = new WhenProxyType()
                {
                    ProxyType = testCase.Type
                };
                Assert.AreEqual(testCase.WillMatch, when.IsMatch(testCase.InputEventInfo));
            }
        }
Beispiel #33
0
            public override void Write(DataFrame frame)
            {
                Uri currUri = null;

                HttpRequestDataChunk chunk = frame.Root.GetValue(DATA_NAME).Value;

                if (chunk.ChunkNumber == 0)
                {
                    int error = 0;
                    string message = null;

                    if (_currOutConn == null)
                    {
                        try
                        {
                            _logger.LogVerbose("Received new connection to {0}", chunk.Path);

                            currUri = new Uri(chunk.Path, UriKind.Absolute);

                            chunk.Path = currUri.PathAndQuery;

                            // Upgrade to at least version 1.0
                            if (chunk.Version.IsVersionUnknown)
                            {
                                chunk.Version = HttpVersion.Version10;
                            }

                            // Add a Connection: close header?

                            _currOutConn = new ProxyConnection();
                            _currOutConn.DataAdapter = new HttpProxyDataAdapter(currUri, _cancellationSource.Token);

                            _currOutConn.Graph = ConnectClient(_currOutConn.DataAdapter);
                            if (_currOutConn.Graph == null)
                            {
                                _currOutConn.DataAdapter.Close();
                                error = 404;
                                message = "Not Found";
                                _currOutConn = null;
                            }
                            else
                            {
                                _currOutConn.ResponseReader = GetResponse(_currOutConn, currUri, chunk.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase));
                                _conns.Enqueue(_currOutConn);
                            }
                        }
                        catch (UriFormatException)
                        {
                            error = 400;
                            message = "Bad Request";
                        }

                        if (error != 0)
                        {
                            ProxyConnection conn = new ProxyConnection();

                            conn.ResponseReader = new[] { BuildError(error, message, chunk.Method, chunk.Version) };
                            _conns.Enqueue(conn);
                        }
                    }
                }

                if (_currOutConn != null)
                {
                    DataWriter writer = new DataWriter(new DataAdapterToStream(_currOutConn.DataAdapter.Coupling));

                    chunk.WriteChunk(writer);

                    if (chunk.FinalChunk)
                    {
                        _currOutConn = null;
                    }
                }
                else
                {
                    // Do nothing
                }
            }