Пример #1
0
        private void DoProxy(object ox)
        {
            TcpClient client  = (TcpClient)ox;
            string    content = "";
            var       ns      = client.GetStream();

            using (StreamReader reader = new StreamReader(ns))
            {
                while (ns.CanRead)
                {
                    string t = reader.ReadLine();
                    if (String.IsNullOrEmpty(t))
                    {
                        break;
                    }
                    else
                    {
                        content += t;
                        content += "\r\n";
                    }
                }
                SetStrDelegate del = SetStr;
                //textBox1.Invoke(del, content);
                try
                {
                    ResolvedHttpProxyRequest request = HTTPRequestParser.ResolveHTTPProxyRequest(content);

                    if (request.Method.ToLower() == "connect")
                    {
                        TcpClient cst     = new TcpClient();
                        string[]  spchost = request.Host.Value.Split(':');
                        //MessageBox.Show(Convert.ToString(port));
                        string s = HTTPRequestParser.DeleteFrontWhiteSpace(spchost[0]);
                        cst.Connect(Dns.GetHostEntry(HTTPRequestParser.DeleteFrontWhiteSpace(spchost[0])).AddressList[0], request.Port);
                        // MessageBox.Show(Convert.ToString(cst.Connected));
                        textBox1.Invoke(del, request.RequestString);
                        NetworkStream serverstream = cst.GetStream();
                        string        res          = "HTTP/1.1 200 Connection Established\r\n\r\n";
                        if (cst.Connected)
                        {
                        }
                        else
                        {
                            res = "HTTP/1.1 404 Error\r\n\r\n";
                        }
                        byte[] buf = Encoding.ASCII.GetBytes(res);
                        ns.Write(buf, 0, buf.Length);
                        ns.Flush();
                        //MessageBox.Show(res);
                        // object box1 = (object)(new TcpClient[] { client, cst });
                        object box2 = (object)(new TcpClient[] { cst, client });
                        //ThreadPool.QueueUserWorkItem(new WaitCallback(TunnelCon), box1);
                        Thread Wt = new Thread(new ParameterizedThreadStart(TunnelCon));
                        Wt.IsBackground = true;
                        Wt.Start(box2);
                        try
                        {
                            NetworkStream ns1 = client.GetStream();
                            NetworkStream ns2 = cst.GetStream();
                            int           hasRead;
                            do
                            {
                                Thread.Sleep(1);
                                byte[] buf2 = new byte[4096];
                                hasRead = ns1.Read(buf2, 0, 4096);
                                ns2.Write(buf2, 0, hasRead);
                            } while (hasRead >= 0);
                        }
                        catch (Exception ex)
                        {
                            client.Close();
                            cst.Close();
                        }
                    }
                    else
                    {
                        TcpClient cst     = new TcpClient();
                        string[]  spchost = request.Host.Value.Split(':');
                        string    s       = HTTPRequestParser.DeleteFrontWhiteSpace(spchost[0]);
                        MessageBox.Show(request.RequestString);
                        cst.Connect(Dns.GetHostEntry(HTTPRequestParser.DeleteFrontWhiteSpace(spchost[0])).AddressList[0], request.Port);
                        textBox1.Invoke(del, request.RequestString);
                        NetworkStream serverstream = cst.GetStream();
                        byte[]        buffer       = Encoding.ASCII.GetBytes(request.RequestString);
                        serverstream.Write(buffer, 0, buffer.Length);
                        serverstream.Flush();
                        BridgeCon(serverstream, ns);
                    }
                    // MessageBox.Show(spchost[0]);
                    //MessageBox.Show(spchost[1]);
                }
                catch (Exception ex)
                {
                    //  MessageBox.Show(ex.Message);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// 解析HTTP报文的头部
        /// </summary>
        /// <param name="rawRequest">未经分析的原始报文头部</param>
        /// <returns>返回一个包含各种HTTP信息的解析结果</returns>
        public static ResolvedHttpProxyRequest ResolveHTTPProxyRequest(string rawRequest)
        {
            char[] spc = { '\r', '\n' };
            //将HTTP报文头部按照以"\r\n"结尾分成多行
            string[] allHeaders = rawRequest.Split(spc);
            //单独处理第一行,第一行包含HTTP请求方法,URI和HTTP版本。按照空格将第一行分为三部分
            string[] firstLineParas = allHeaders[0].Split(' ');
            //分别赋值
            string Method = firstLineParas[0]; string URI = firstLineParas[1]; string HttpInfo = firstLineParas[2];
            //原始头部集合(List类似于C++中的Vector)
            List <HeaderPair> rawHeader       = new List <HeaderPair>();

            //对于每一个头部进行处理
            for (int i = 1; i < allHeaders.Length; i++)
            {
                if (String.IsNullOrWhiteSpace(allHeaders[i]))
                {
                    continue;
                }
                //获取该头部=
                string header = allHeaders[i];
                //将头部按照“:“分为多部分
                string[] head = header.Split(':');
                //获取该头部的名称(key)和值(value)
                string key   = head[0];
                string value = "";
                for (int j = 1; j < head.Length; j++)
                {
                    value += head[j];
                }
                value = DeleteFrontWhiteSpace(head[1]);
                //添加到原始头部集合中
                rawHeader.Add(new HeaderPair(key, value));

                /*
                 * if (key.ToLower() == "host")
                 * {
                 *  if(head.Length>2)
                 *  Host = HTTPRequestParser.DeleteFrontWhiteSpace(head[1] + ":" + head[2]);
                 *  else
                 *      Host = HTTPRequestParser.DeleteFrontWhiteSpace(head[1]);
                 * }
                 */
            }
            //初始化解析结果并将原头部添加进去等待下一步处理
            List <HeaderPair> resovledheaders = new List <HeaderPair>();

            foreach (HeaderPair raw in rawHeader)
            {
                //这里的特判是为了不让代理将本该发给代理的头部发给HTTP服务器
                if (raw.Key.ToLower() == "proxy-connection")
                {
                    continue;
                }
                resovledheaders.Add(raw);
            }
            //对一些头部进行特殊处理
            foreach (HeaderPair header in resovledheaders)
            {
                if (header.Key.ToLower() == "connection")
                {
                    header.Value = "close";
                }
                if (header.Key.ToLower() == "proxy-connection")
                {
                    header.Value = "close";
                }
            }
            //获取解析后的报文头
            string resolvedreq                = "";

            resolvedreq += Method + " ";
            resolvedreq += URI + " ";
            resolvedreq += HttpInfo + "\r\n";
            foreach (HeaderPair header in resovledheaders)
            {
                resolvedreq += header.ToString() + "\r\n";
            }
            resolvedreq += "\r\n";
            //生成结果并返回
            ResolvedHttpProxyRequest result = new ResolvedHttpProxyRequest(Method, resolvedreq, URI, HttpInfo, resovledheaders);

            return(result);
        }