Exemple #1
0
 public override void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
                                      ProxyConnectOptions options, ref BufStruct buf)
 {
     if ((options & ProxyConnectOptions.ContentIsRawHttp) == 0)
     {
         throw new NotImplementedException();
     }
 }
 public override void ProxyConnectUdp(Socket socket, ref StringEndPoint endPoint)
 {
     if (endPoint.stringIsAnIP)
     {
         throw new NotImplementedException();
     }
     else
     {
         ProxyConnectUdpUsingHost(socket, endPoint.ipOrHost, endPoint.port);
     }
 }
Exemple #3
0
        public override void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
            ProxyConnectOptions options, ref BufStruct buf)
        {
            BufStruct forwardBufStruct = default(BufStruct);
            host.Connect(socket, DnsPriority.IPv4ThenIPv6, ProxyConnectOptions.None, ref forwardBufStruct);
            if (forwardBufStruct.contentLength > 0)
            {
                throw new NotImplementedException();
            }

            if (endPoint.stringIsAnIP)
            {
                ProxyConnectTcpUsingIP(socket, endPoint.ipEndPoint.Address, endPoint.port);
            }
            else
            {
                ProxyConnectTcpUsingHost(socket, endPoint.ipOrHost, endPoint.port);
            }
        }
Exemple #4
0
 public InternetHost(String ipOrHost, UInt16 port, PriorityQuery <IPAddress> dnsPriorityQuery, Proxy proxy)
 {
     this.targetEndPoint   = new StringEndPoint(ipOrHost, port);
     this.dnsPriorityQuery = dnsPriorityQuery;
     this.proxy            = proxy;
 }
Exemple #5
0
 public override Boolean ProxyConnectAsyncTcp(Socket socket, ref StringEndPoint endPoint,
                                              ProxyConnectOptions options, ref BufStruct buf)
 {
     throw new NotImplementedException();
 }
Exemple #6
0
 public override void ProxyConnectUdp(Socket socket, ref StringEndPoint endPoint)
 {
     throw new NotSupportedException("The Http protocol does not support Udp (as far as I know)");
 }
Exemple #7
0
        public override void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
                                             ProxyConnectOptions options, ref BufStruct buf)
        {
            throw new NotImplementedException();

            /*
             * //
             * // Check if the proxy end point string is valid
             * //
             * socket.Send(Encoding.UTF8.GetBytes(String.Format(
             *  "CONNECT {0} HTTP/1.1\r\nHost: {0}:{1}\r\n\r\n",
             *  endpoint.unparsedIPOrHost, endpoint.port)));
             *
             * NetworkStream stream = new NetworkStream(socket);
             *
             * //
             * // Process first line
             * //
             * for (int i = 0; i < 9; i++)
             * {
             *  Int32 nextByte = stream.ReadByte();
             *  if ((nextByte & 0xFF) != nextByte) throw new SocketException();
             * }
             *
             * //
             * // Get response code
             * //
             * Char[] responseCodeChars = new Char[3];
             * responseCodeChars[0] = (Char)stream.ReadByte();
             * responseCodeChars[1] = (Char)stream.ReadByte();
             * responseCodeChars[2] = (Char)stream.ReadByte();
             * String responseCodeString = new String(responseCodeChars);
             *
             * Int32 responseCode;
             * if (!Int32.TryParse(responseCodeString, out responseCode))
             *  throw new InvalidOperationException(String.Format("First line of HTTP Connect response was not formatted correctly (Expected response code but got '{0}')", responseCodeString));
             *
             * if (responseCode != 200) throw new InvalidOperationException(String.Format("Expected response code 200 but got {0}", responseCode));
             *
             * //
             * // Read until end of response
             * //
             * Int32 lineLength = 12;
             *
             * while (true)
             * {
             *  Int32 nextByte = stream.ReadByte();
             *  //Console.WriteLine("[HttpsProxyDebug] Got Char '{0}'", (Char)nextByte);
             *  if ((nextByte & 0xFF) != nextByte) throw new SocketException();
             *
             *  if (nextByte != '\r')
             *  {
             *      lineLength++;
             *  }
             *  else
             *  {
             *      nextByte = stream.ReadByte();
             *      if ((nextByte & 0xFF) != nextByte) throw new SocketException();
             *      if (nextByte != '\n') throw new InvalidOperationException(String.Format(
             *           "Received '\\r' and expected '\\n' next but got (Char)'{0}' (Int32)'{1}'",
             *           (Char)nextByte, nextByte));
             *
             *
             *      if (lineLength <= 0) break;
             *
             *      lineLength = 0;
             *  }
             * }
             */
        }
Exemple #8
0
 public override void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
                                      ProxyConnectOptions options, ref BufStruct buf)
 {
     host.Connect(socket, DnsPriority.IPv4ThenIPv6, options, ref buf);
 }
Exemple #9
0
 public HttpClient(String ipOrHost, UInt16 port)
 {
     this.serverEndPoint = new StringEndPoint(ipOrHost, port);
 }
Exemple #10
0
 /// <summary>
 /// Setup a UDP proxy.
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="endpoint"></param>
 public abstract void ProxyConnectUdp(Socket socket, ref StringEndPoint endPoint);
Exemple #11
0
 public abstract Boolean ProxyConnectAsyncTcp(Socket socket, ref StringEndPoint endPoint,
                                              ProxyConnectOptions options, ref BufStruct buf);
Exemple #12
0
        /*
         * public String ConnectorString(StringEndPoint targetEndPoint)
         * {
         *  return String.Format("{0}:{1}:{2}%{3}", Type,
         *      ipOrHost, endPoint.Port, targetEndPoint);
         * }
         * public override String ToString()
         * {
         *  return String.Format("{0}:{1}:{2}", Type, ipOrHost, endPoint.Port);
         * }
         */

        // Design Note: The ProxyConnect method could also connect the socket, however,
        //              in some cases the socket will already be connected, so, this api
        //              doesn't wrap connecting the socket.  Note that this means typically
        //              this call will always follow immediately after calling socket.Connect()
        /// <summary>
        /// Setup the proxy connection. The given socket must already be connected.
        /// The endpoint should have been retrieved from the proxy's CreateEndpoint method.
        ///
        /// Once the method is done, any leftover data from the socket will be in the given buffer
        /// </summary>
        /// <param name="socket">A connected tcp socket</param>
        /// <param name="ipEndPoint">The final destination, retreived from calling proxy.CreateEndpoint(...).</param>
        public abstract void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
                                             ProxyConnectOptions options, ref BufStruct buf);
 public override void ProxyConnectUdp(Socket socket, ref StringEndPoint endPoint)
 {
     throw new NotImplementedException();
 }
Exemple #14
0
        public override void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
                                             ProxyConnectOptions options, ref BufStruct forwardBufStruct)
        {
            host.Connect(socket, DnsPriority.IPv4ThenIPv6, ProxyConnectOptions.None, ref forwardBufStruct);
            if (forwardBufStruct.contentLength > 0)
            {
                throw new NotImplementedException();
            }

            if ((options & ProxyConnectOptions.ContentIsRawHttp) != 0)
            {
                // do nothing
            }
            else
            {
                // send an HTTP CONNECT method
                unsafe
                {
                    AsciiPartsBuilder builder = new AsciiPartsBuilder(CONNECT_REQUEST_PARTS,
                                                                      endPoint.ipOrHost, endPoint.ipOrHost, endPoint.port.ToString());
                    UInt32 contentLength = builder.PrecalculateLength();
                    Byte[] buffer        = new Byte[(int)contentLength];
                    builder.BuildInto(buffer);

                    /*
                     * Console.Write("Request\n--------------------------\n");
                     * Console.Write(Encoding.ASCII.GetString(buffer));
                     * Console.Write("\n--------------------------\n");
                     */

                    socket.SendFullSize(buffer);

                    ByteBuilder responseBuilder   = new ByteBuilder(200);
                    int         endOfHeadersIndex = 0;
                    while (true)
                    {
                        int lastReceived = socket.Receive(buffer);
                        if (lastReceived <= 0)
                        {
                            /*
                             * Console.Write("Response\n--------------------------\n");
                             * Console.Write(Encoding.ASCII.GetString(responseBuilder.bytes, 0, (int)responseBuilder.contentLength));
                             * Console.Write("\n--------------------------\n");
                             */
                            throw new InvalidOperationException(String.Format("socket Receive returned {0} (received {1} bytes total)",
                                                                              lastReceived, responseBuilder.contentLength));
                        }
                        responseBuilder.Append(buffer, 0, (uint)lastReceived);
                        bool foundEndOfHeaders = false;
                        for (; endOfHeadersIndex + 3 < responseBuilder.contentLength; endOfHeadersIndex++)
                        {
                            if (responseBuilder.bytes[endOfHeadersIndex] == '\r' &&
                                responseBuilder.bytes[endOfHeadersIndex + 1] == '\n' &&
                                responseBuilder.bytes[endOfHeadersIndex + 2] == '\r' &&
                                responseBuilder.bytes[endOfHeadersIndex + 3] == '\n')
                            {
                                endOfHeadersIndex += 4;
                                foundEndOfHeaders  = true;
                                break;
                            }
                        }
                        if (foundEndOfHeaders)
                        {
                            break;
                        }
                        // rewind 3 characters in case we got a partial double newline
                        if (endOfHeadersIndex >= 3)
                        {
                            endOfHeadersIndex -= 3;
                        }
                    }

                    if (!responseBuilder.bytes.Equals(0, HTTP_VERSION_RESPONSE, 0, (uint)HTTP_VERSION_RESPONSE.Length))
                    {
                        throw new InvalidOperationException(String.Format(
                                                                "invalid HTTP response header (starts with \"{0}\")",
                                                                Encoding.ASCII.GetString(responseBuilder.bytes, 0,
                                                                                         (HTTP_VERSION_RESPONSE.Length <= responseBuilder.contentLength) ? HTTP_VERSION_RESPONSE.Length : (int)responseBuilder.contentLength)));
                    }
                    if (HTTP_VERSION_RESPONSE.Length + 3 > responseBuilder.contentLength)
                    {
                        throw new InvalidOperationException("invalid HTTP response header (it's too short)");
                    }
                    ResponseCode responseCode;
                    responseCode.a = (char)responseBuilder.bytes[HTTP_VERSION_RESPONSE.Length + 0];
                    responseCode.b = (char)responseBuilder.bytes[HTTP_VERSION_RESPONSE.Length + 1];
                    responseCode.c = (char)responseBuilder.bytes[HTTP_VERSION_RESPONSE.Length + 2];
                    if (responseCode.a != '2' && responseCode.b != '0' && responseCode.c != '0')
                    {
                        throw new InvalidOperationException(String.Format("expected response code 200 but got {0}{1}{2}",
                                                                          responseCode.a, responseCode.b, responseCode.c));
                    }

                    // TODO: receive the entire response if there is a content length!!
                    Console.Write("Response\n--------------------------\n");
                    Console.Write(Encoding.ASCII.GetString(responseBuilder.bytes, 0, (int)responseBuilder.contentLength));
                    Console.Write("\n--------------------------\n");
                    throw new NotImplementedException();
                }
            }
        }
Exemple #15
0
 public InternetHost(InternetHost other, UInt16 port)
 {
     this.targetEndPoint   = new StringEndPoint(other.targetEndPoint, port);
     this.dnsPriorityQuery = other.dnsPriorityQuery;
     this.proxy            = other.proxy;
 }
Exemple #16
0
 public override void ProxyConnectTcp(Socket socket, ref StringEndPoint endPoint,
                                      ProxyConnectOptions options, ref BufStruct buf)
 {
     endPoint.ForceIPResolution(DnsPriority.IPv4ThenIPv6);
     socket.Connect(endPoint.ipEndPoint);
 }
Exemple #17
0
 public InternetHost(InternetHost other, Proxy proxy)
 {
     this.targetEndPoint   = other.targetEndPoint;
     this.dnsPriorityQuery = other.dnsPriorityQuery;
     this.proxy            = proxy;
 }
Exemple #18
0
 public override void ProxyConnectUdp(Socket socket, ref StringEndPoint endPoint)
 {
 }
Exemple #19
0
 public HttpClient(StringEndPoint serverEndPoint)
 {
     this.serverEndPoint = serverEndPoint;
 }
Exemple #20
0
        void GotHeaders(ref SelectControl selectControl, Socket clientSocket, Byte[] headers, UInt32 totalLength)
        {
            String serverIPOrHost = null;
            UInt16 serverPort     = 0;

            try
            {
                serverIPOrHost = GetServerFromHeaders(out serverPort, out isConnect,
                                                      headers, ref headersLength, ref totalLength, clientLogString);
            }
            catch (Exception e)
            {
                if (AppLayerProxy.ErrorLogger != null)
                {
                    AppLayerProxy.ErrorLogger.WriteLine("{0} Failed to get server from HTTP Headers: {1}", clientLogString, e);
                }
            }

            if (serverIPOrHost == null)
            {
                selectControl.ShutdownDisposeAndRemoveReceiveSocket(clientSocket);
                return;
            }

            this.serverLogString = serverIPOrHost + ":" + serverPort.ToString();

            Boolean needToConnect;

            if (AppLayerProxy.ForwardProxy == null)
            {
                // TODO: Fix so this does not block during DNS resolution
                IPAddress serverIP;
                try
                {
                    serverIP = EndPoints.ParseIPOrResolveHost(serverIPOrHost, DnsPriority.IPv4ThenIPv6);
                }
                catch (SocketException)
                {
                    if (AppLayerProxy.ErrorLogger != null)
                    {
                        AppLayerProxy.ErrorLogger.WriteLine("{0} Failed to resolve server hostname '{1}'",
                                                            clientLogString, serverIPOrHost);
                    }
                    selectControl.ShutdownDisposeAndRemoveReceiveSocket(clientSocket);
                    return;
                }
                IPEndPoint serverEndPoint = new IPEndPoint(serverIP, serverPort);

                serverSocket          = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Blocking = false;
                needToConnect         = NonBlockingSocket.ConnectNonBlocking(serverSocket, serverEndPoint);
            }
            else
            {
                this.serverEndPointForProxy = new StringEndPoint(serverIPOrHost, serverPort);

                Console.WriteLine("[DEBUG] Connecting to proxy '{0}'", AppLayerProxy.ForwardProxy.host.CreateTargetString());
                serverSocket          = new Socket(AppLayerProxy.ForwardProxy.host.GetAddressFamilyForTcp(), SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Blocking = false;
                throw new NotImplementedException();
                //needToConnect = NonBlockingSocket.ConnectNonBlocking(serverSocket, AppLayerProxy.ForwardProxy.endPoint);
            }

            //Console.WriteLine("[DEBUG] {0} > {1} Connecting...", clientLogString, serverLogString);
            if (needToConnect)
            {
                selectControl.RemoveReceiveSocket(clientSocket); // Remove the clientSocket from the read list
                                                                 // until the connection gets established or lost
                selectControl.AddConnectSocket(serverSocket, ServerSocketConnected);

                // Save Data
                if (isConnect)
                {
                    if (totalLength == headersLength)
                    {
                        clientBuffer = null; // Clean up the client buffer (if there is one)
                    }
                }
                else
                {
                    if (clientBuffer == null)
                    {
                        clientBuffer = new ByteBuilder(totalLength);
                        Array.Copy(headers, clientBuffer.bytes, totalLength);
                        clientBuffer.contentLength = totalLength;
                    }
                    else
                    {
                        // Data already in the client buffer
                    }
                }
            }
            else
            {
                if (AppLayerProxy.Logger != null)
                {
                    AppLayerProxy.Logger.WriteLine("{0} > {1} Connection Completed Synchronously (CornerCase)", clientLogString, serverLogString);
                }

                if (!clientSocket.Connected)
                {
                    selectControl.DisposeAndRemoveReceiveSocket(clientSocket);
                    if (serverSocket.Connected)
                    {
                        if (AppLayerProxy.Logger != null)
                        {
                            AppLayerProxy.Logger.WriteLine("{0} > {1} Server Connected but Client Disconnected...Closing Server", clientLogString, serverLogString);
                        }
                        try { serverSocket.Shutdown(SocketShutdown.Both); }
                        catch (Exception) { }
                    }
                    else
                    {
                        if (AppLayerProxy.Logger != null)
                        {
                            AppLayerProxy.Logger.WriteLine("{0} > {1} Client disconnected before server could connect", clientLogString, serverLogString);
                        }
                    }
                    serverSocket.Close();
                }
                else if (!serverSocket.Connected)
                {
                    if (AppLayerProxy.Logger != null)
                    {
                        AppLayerProxy.Logger.WriteLine("{0} > {1} Failed to connect to server..Closing Client", clientLogString, serverLogString);
                    }
                    selectControl.ShutdownDisposeAndRemoveReceiveSocket(clientSocket);
                    serverSocket.Close();
                }
                else
                {
                    if (AppLayerProxy.Logger != null)
                    {
                        AppLayerProxy.Logger.WriteLine("{0} > {1} Connected to Server", clientLogString, serverLogString);
                    }

                    if (isConnect)
                    {
                        uint extraChars = totalLength - headersLength;
                        FinishConnection(headers, headersLength, extraChars);
                    }
                    else
                    {
                        FinishConnection(headers, 0, totalLength);
                    }

                    TcpBridge bridge = new TcpBridge(clientLogString, clientSocket, serverLogString, serverSocket);
                    selectControl.UpdateHandler(clientSocket, bridge.ReceiveHandler);
                    selectControl.AddReceiveSocket(serverSocket, bridge.ReceiveHandler);
                }
            }
        }