Пример #1
0
        public static ServerInfo sendHTTPSRequest(int count, string host, int port, string request, int timeout, string encoding, bool foward_302)
        {
            HTTP.index += 1L;
            object[]  objArray1 = new object[] { Thread.CurrentThread.Name, "-", count, "-", HTTP.index };
            string    str       = string.Concat(objArray1);
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            ServerInfo info      = new ServerInfo();
            Encoding   encoding2 = Encoding.GetEncoding(encoding);
            int        offset    = 0;
            TcpClient  client    = null;

            try
            {
                if ((port <= 0) || (port > 0x10014))
                {
                    return(info);
                }
                client = new TimeOutSocket().Connect(host, port);
                client.ReceiveTimeout = timeout;
                SslStream stream = null;
                if (client.Connected)
                {
                    stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(HTTP.ValidateServerCertificate));
                    SslProtocols enabledSslProtocols = SslProtocols.Default | SslProtocols.Ssl2;
                    stream.AuthenticateAsClient(host, null, enabledSslProtocols, false);
                    if (stream.IsAuthenticated)
                    {
                        int index = request.IndexOf("\r\n\r\n");
                        info.reuqestHeader = request;
                        if (index != -1)
                        {
                            info.reuqestHeader = request.Substring(0, index);
                            info.reuqestBody   = request.Substring(index + 4, (request.Length - index) - 4);
                            int    length      = Encoding.UTF8.GetBytes(info.reuqestBody).Length;
                            string replacement = "Content-Length: " + length;
                            if (request.IndexOf("Content-Length: ") != -1)
                            {
                                request = Regex.Replace(request, @"Content-Length: \d+", replacement);
                            }
                            else
                            {
                                request = request.Insert(index, "\r\n" + replacement);
                            }
                        }
                        else
                        {
                            request = Regex.Replace(request, @"content-length: \d+", "Content-Length: 0");
                            request = request + "\r\n\r\n";
                        }
                        byte[] bytes = Encoding.UTF8.GetBytes(request);
                        stream.Write(bytes);
                        stream.Flush();
                    }
                }
                info.request = request;
                byte[]        buffer   = new byte[0x32000];
                int           num2     = 0;
                string        str2     = "";
                StringBuilder builder  = new StringBuilder();
                StringBuilder builder2 = new StringBuilder();
                do
                {
                    byte[] buffer3 = new byte[1];
                    char   ch      = (char)stream.ReadByte();
                    builder.Append(ch);
                    if (ch.Equals('\n'))
                    {
                        object[] objArray2 = new object[] { builder[builder.Length - 4], builder[builder.Length - 3], builder[builder.Length - 2], ch };
                        str2 = string.Concat(objArray2);
                    }
                }while (!str2.Equals("\r\n\r\n") && (stopwatch.ElapsedMilliseconds < timeout));
                info.header = builder.ToString().Replace("\r\n\r\n", "");
                string[] strArray = Regex.Split(info.header, "\r\n");
                for (int i = 0; i < strArray.Length; i++)
                {
                    if (i == 0)
                    {
                        char[] separator = new char[] { ' ' };
                        string s         = strArray[i].Split(separator)[1];
                        if (s != null)
                        {
                            info.code = int.Parse(s);
                        }
                        else
                        {
                            info.code = 0;
                        }
                    }
                    else
                    {
                        string[] strArray2 = Regex.Split(strArray[i], ": ");
                        string   key       = strArray2[0].ToLower();
                        if (!info.headers.ContainsKey(key))
                        {
                            if (strArray2.Length > 1)
                            {
                                info.headers.Add(key, strArray2[1] ?? "");
                            }
                            else
                            {
                                info.headers.Add(key, "");
                            }
                        }
                    }
                }
                if (((info.code == 0x12e) || (info.code == 0x12d)) & foward_302)
                {
                    int num7 = info.request.IndexOf(" ");
                    int num8 = info.request.IndexOf(" HTTP");
                    if ((num7 != -1) && (num8 != -1))
                    {
                        string oldValue = info.request.Substring(num7 + 1, (num8 - num7) - 1);
                        if (!info.headers["location"].StartsWith("/") && !info.headers["location"].StartsWith("https"))
                        {
                            info.request = info.request.Replace(oldValue, Tools.getCurrentPath(oldValue) + info.headers["location"]);
                        }
                        else
                        {
                            info.request = info.request.Replace(oldValue, info.headers["location"]);
                        }
                        return(sendHTTPSRequest(count, host, port, info.request, timeout, encoding, false));
                    }
                }
                if (info.headers.ContainsKey("content-length"))
                {
                    int num9 = int.Parse(info.headers["content-length"]);
                    while ((offset < num9) && (stopwatch.ElapsedMilliseconds < timeout))
                    {
                        num2 = stream.Read(buffer, offset, num9 - offset);
                        if (num2 > 0)
                        {
                            offset += num2;
                        }
                    }
                }
                else
                {
                    if (!info.headers.ContainsKey("transfer-encoding"))
                    {
                        goto Label_070C;
                    }
                    int    num10   = 0;
                    byte[] buffer4 = new byte[1];
                    offset = 0;
                    do
                    {
                        string str7 = "";
                        do
                        {
                            num2 = stream.Read(buffer4, 0, 1);
                            str7 = str7 + Encoding.UTF8.GetString(buffer4);
                        }while ((str7.IndexOf("\r\n") == -1) && (stopwatch.ElapsedMilliseconds < timeout));
                        num10 = Tools.convertToIntBy16(str7.Replace("\r\n", ""));
                        if (!str7.Equals("\r\n"))
                        {
                            if (num10 == 0)
                            {
                                break;
                            }
                            int num11 = 0;
                            while ((num11 < num10) && (stopwatch.ElapsedMilliseconds < timeout))
                            {
                                num2 = stream.Read(buffer, offset, num10 - num11);
                                if (num2 > 0)
                                {
                                    num11  += num2;
                                    offset += num2;
                                }
                            }
                        }
                    }while (stopwatch.ElapsedMilliseconds < timeout);
                }
                goto Label_071E;
Label_06B3:
                if (client.Client.Poll(timeout, SelectMode.SelectRead))
                {
                    if (client.Available <= 0)
                    {
                        goto Label_071E;
                    }
                    num2 = stream.Read(buffer, offset, 0x32000 - offset);
                    if (num2 > 0)
                    {
                        offset += num2;
                    }
                }
Label_070C:
                if (stopwatch.ElapsedMilliseconds < timeout)
                {
                    goto Label_06B3;
                }
Label_071E:
                if (info.headers.ContainsKey("content-encoding"))
                {
                    info.body = unGzip(buffer, offset, encoding2);
                }
                else
                {
                    info.body = encoding2.GetString(buffer, 0, offset);
                }
            }
            catch (Exception exception)
            {
                Exception exception2 = new Exception("HTTPS发包错误!错误消息:" + exception.Message + "----发包编号:" + str);
                throw exception2;
            }
            finally
            {
                stopwatch.Stop();
                info.length  = offset;
                info.runTime = (int)stopwatch.ElapsedMilliseconds;
                if (client != null)
                {
                    client.Close();
                }
            }
            return(info);
        }
Пример #2
0
        public static ServerInfo sendHTTPRequest(int count, string host, int port, string request, int timeout, string encoding, bool foward_302)
        {
            HTTP.index += 1L;
            object[]  objArray1 = new object[] { Thread.CurrentThread.Name, "-", count, "-", HTTP.index };
            string    str       = string.Concat(objArray1);
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            ServerInfo info      = new ServerInfo();
            TcpClient  client    = null;
            Encoding   encoding2 = Encoding.GetEncoding(encoding);
            int        offset    = 0;

            try
            {
                if ((port <= 0) || (port > 0x10014))
                {
                    return(info);
                }
                info.request          = request;
                client                = new TimeOutSocket().Connect(host, port);
                client.ReceiveTimeout = timeout;
                if (!client.Connected)
                {
                    return(info);
                }
                int index = request.IndexOf("\r\n\r\n");
                info.reuqestHeader = request;
                if (index != -1)
                {
                    info.reuqestHeader = request.Substring(0, index);
                    info.reuqestBody   = request.Substring(index + 4, (request.Length - index) - 4);
                    int    length      = Encoding.UTF8.GetBytes(info.reuqestBody).Length;
                    string replacement = "Content-Length: " + length;
                    if (request.IndexOf("Content-Length: ") != -1)
                    {
                        request = Regex.Replace(request, @"Content-Length: \d+", replacement);
                    }
                    else
                    {
                        request = request.Insert(index, "\r\n" + replacement);
                    }
                }
                else
                {
                    request = Regex.Replace(request, @"content-length: \d+", "Content-Length: 0");
                    request = request + "\r\n\r\n";
                }
                info.request = request;
                byte[] bytes = Encoding.UTF8.GetBytes(request);
                client.Client.Send(bytes);
                byte[]        buffer  = new byte[0x32000];
                int           num3    = 0;
                string        str2    = "";
                StringBuilder builder = new StringBuilder();
                stopwatch.Start();
                do
                {
                    byte[] buffer3 = new byte[1];
                    if (client.Client.Receive(buffer3, 1, SocketFlags.None) == 1)
                    {
                        char ch = (char)buffer3[0];
                        builder.Append(ch);
                        if (ch.Equals('\n'))
                        {
                            object[] objArray2 = new object[] { builder[builder.Length - 4], builder[builder.Length - 3], builder[builder.Length - 2], ch };
                            str2 = string.Concat(objArray2);
                        }
                    }
                }while (!str2.Equals("\r\n\r\n") && (stopwatch.ElapsedMilliseconds < timeout));
                info.header = builder.ToString().Replace("\r\n\r\n", "");
                string[] strArray = Regex.Split(info.header, "\r\n");
                if ((strArray == null) || (strArray.Length <= 0))
                {
                    return(info);
                }
                for (int i = 0; i < strArray.Length; i++)
                {
                    if (i == 0)
                    {
                        char[] separator = new char[] { ' ' };
                        string s         = strArray[i].Split(separator)[1];
                        if (s != null)
                        {
                            info.code = int.Parse(s);
                        }
                        else
                        {
                            info.code = 0;
                        }
                    }
                    else
                    {
                        string[] strArray2 = Regex.Split(strArray[i], ": ");
                        if (strArray2 != null)
                        {
                            string key = strArray2[0].ToLower();
                            if (!info.headers.ContainsKey(key))
                            {
                                if (strArray2.Length > 1)
                                {
                                    info.headers.Add(key, strArray2[1] ?? "");
                                }
                                else
                                {
                                    info.headers.Add(key, "");
                                }
                            }
                        }
                    }
                }
                if (((info.code == 0x12e) || (info.code == 0x12d)) & foward_302)
                {
                    StringBuilder builder2   = new StringBuilder(info.request);
                    int           startIndex = info.request.IndexOf(" ") + 1;
                    int           num7       = info.request.IndexOf(" HTTP");
                    if ((startIndex != -1) && (num7 != -1))
                    {
                        string url = info.request.Substring(startIndex, num7 - startIndex);
                        builder2.Remove(startIndex, url.Length);
                        string str7 = info.headers["location"];
                        if (!info.headers["location"].StartsWith("/") && !info.headers["location"].StartsWith("http"))
                        {
                            str7 = Tools.getCurrentPath(url) + str7;
                        }
                        builder2.Insert(startIndex, str7);
                        return(sendHTTPRequest(count, host, port, builder2.ToString(), timeout, encoding, false));
                    }
                }
                if (info.headers.ContainsKey("content-length"))
                {
                    int num8 = int.Parse(info.headers["content-length"]);
                    while ((offset < num8) && (stopwatch.ElapsedMilliseconds < timeout))
                    {
                        int size = num8 - offset;
                        num3 = client.Client.Receive(buffer, offset, size, SocketFlags.None);
                        if (num3 > 0)
                        {
                            offset += num3;
                        }
                    }
                }
                else
                {
                    if (!info.headers.ContainsKey("transfer-encoding"))
                    {
                        goto Label_0711;
                    }
                    int    num10   = 0;
                    byte[] buffer4 = new byte[1];
                    offset = 0;
                    do
                    {
                        string str8 = "";
                        do
                        {
                            num3 = client.Client.Receive(buffer4, 1, SocketFlags.None);
                            str8 = str8 + Encoding.UTF8.GetString(buffer4);
                        }while ((str8.IndexOf("\r\n") == -1) && (stopwatch.ElapsedMilliseconds < timeout));
                        num10 = Tools.convertToIntBy16(str8.Replace("\r\n", ""));
                        if (!str8.Equals("\r\n"))
                        {
                            if (num10 == 0)
                            {
                                break;
                            }
                            int num11 = 0;
                            while ((num11 < num10) && (stopwatch.ElapsedMilliseconds < timeout))
                            {
                                num3 = client.Client.Receive(buffer, offset, num10 - num11, SocketFlags.None);
                                if (num3 > 0)
                                {
                                    num11  += num3;
                                    offset += num3;
                                }
                            }
                        }
                    }while (stopwatch.ElapsedMilliseconds < timeout);
                }
                goto Label_0723;
Label_06B5:
                if (client.Client.Poll(timeout, SelectMode.SelectRead))
                {
                    if (client.Available <= 0)
                    {
                        goto Label_0723;
                    }
                    num3 = client.Client.Receive(buffer, offset, 0x32000 - offset, SocketFlags.None);
                    if (num3 > 0)
                    {
                        offset += num3;
                    }
                }
Label_0711:
                if (stopwatch.ElapsedMilliseconds < timeout)
                {
                    goto Label_06B5;
                }
Label_0723:
                if (info.headers.ContainsKey("content-encoding"))
                {
                    info.body = unGzip(buffer, offset, encoding2);
                }
                else
                {
                    info.body = encoding2.GetString(buffer, 0, offset);
                }
            }
            catch (Exception exception)
            {
                string[]  textArray1 = new string[] { "HTTP发包错误!错误消息:", exception.Message, exception.TargetSite.Name, "----发包编号:", str };
                Exception exception2 = new Exception(string.Concat(textArray1));
                throw exception2;
            }
            finally
            {
                stopwatch.Stop();
                info.length  = offset;
                info.runTime = (int)stopwatch.ElapsedMilliseconds;
                if (client != null)
                {
                    client.Close();
                }
            }
            return(info);
        }
Пример #3
0
        private static ServerInfo sendHTTPSRequest(String host, int port, String request, int timeout, String encoding, Boolean foward_302, Boolean redirectDoGet)
        {
            Interlocked.Increment(ref HTTP.index);
            String    index = Thread.CurrentThread.Name + Interlocked.Read(ref HTTP.index);
            Stopwatch sw    = new Stopwatch();

            sw.Start();
            ServerInfo server           = new ServerInfo();
            Boolean    isupdateEncoding = false;
            int        sum = 0;

            TcpClient clientSocket = null;;

            try
            {
                if (port > 0 && port <= 65556)
                {
                    TimeOutSocket tos = new TimeOutSocket();
                    clientSocket = tos.Connect(host, port, timeout);
                    if (sw.ElapsedMilliseconds >= timeout)
                    {
                        return(server);
                    }
                    clientSocket.SendTimeout = timeout - tos.useTime;

                    SslStream ssl = null;
                    if (clientSocket.Connected)
                    {
                        ssl = new SslStream(clientSocket.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate));
                        SslProtocols protocol = SslProtocols.Ssl3 | SslProtocols.Ssl2 | SslProtocols.Tls;
                        ssl.AuthenticateAsClient(host, null, protocol, false);
                        if (ssl.IsAuthenticated)
                        {
                            checkContentLength(ref server, ref request);
                            server.request = request;
                            byte[] requestByte = Encoding.UTF8.GetBytes(request);
                            ssl.Write(requestByte);
                            ssl.Flush();
                        }
                    }
                    server.request = request;
                    byte[] responseBody = new byte[1024 * 1000];
                    int    len          = 0;
                    //获取header头
                    String tmp = "";

                    StringBuilder sb      = new StringBuilder();
                    StringBuilder bulider = new StringBuilder();
                    clientSocket.ReceiveTimeout = timeout - (int)sw.ElapsedMilliseconds;
                    do
                    {
                        byte[] responseHeader = new byte[1];
                        int    read           = ssl.ReadByte();
                        if (read <= 0)
                        {
                            Thread.Sleep(WaitTime);
                        }
                        char c = (char)read;
                        sb.Append(c);
                        if (c.Equals(T))
                        {
                            tmp = String.Concat(sb[sb.Length - 4], sb[sb.Length - 3], sb[sb.Length - 2], c);
                        }
                    } while (!tmp.Equals(CTRL) && sw.ElapsedMilliseconds < timeout);

                    server.header = sb.ToString().Replace(CTRL, "");
                    String[] headers = Regex.Split(server.header, CT);
                    //处理header
                    doHeader(ref server, ref headers, ref encoding);
                    //302 301跳转
                    if ((server.code == 302 || server.code == 301) && foward_302)
                    {
                        StringBuilder rsb      = new StringBuilder(server.request);
                        int           urlStart = server.request.IndexOf(" ") + 1;
                        int           urlEnd   = server.request.IndexOf(" HTTP");
                        if (urlStart != -1 && urlEnd != -1)
                        {
                            String url = server.request.Substring(urlStart, urlEnd - urlStart);
                            rsb.Remove(urlStart, url.Length);
                            String location = server.headers["location"];
                            if (!server.headers["location"].StartsWith("/") && !server.headers["location"].StartsWith("http"))
                            {
                                location = Tools.getCurrentPath(url) + location;
                            }
                            location = location.Replace(" ", "%20");
                            rsb.Insert(urlStart, location);
                            String newReuqest = rsb.ToString();
                            if (rsb.ToString().StartsWith("POST") && redirectDoGet)
                            {
                                rsb.Remove(0, 4);
                                rsb.Insert(0, "GET");
                            }

                            return(sendHTTPSRequest(host, port, rsb.ToString(), timeout, encoding, false, redirectDoGet));
                        }
                    }


                    //根据请求头解析
                    if (server.headers.ContainsKey(Content_Length))
                    {
                        int length = int.Parse(server.headers[Content_Length]);
                        while (sum < length && sw.ElapsedMilliseconds < timeout)
                        {
                            len = ssl.Read(responseBody, sum, length - sum);
                            if (len > 0)
                            {
                                sum += len;
                            }
                            if (len <= 0 && sum < length)
                            {
                                Thread.Sleep(WaitTime);
                            }
                        }
                    }
                    //解析chunked传输
                    else if (server.headers.ContainsKey(Transfer_Encoding))
                    {
                        //读取长度
                        int    chunkedSize = 0;
                        byte[] chunkedByte = new byte[1];
                        //读取总长度
                        sum = 0;
                        do
                        {
                            String ctmp = "";
                            do
                            {
                                len = ssl.Read(chunkedByte, 0, 1);
                                if (len <= 0)
                                {
                                    Thread.Sleep(WaitTime);
                                }
                                ctmp += Encoding.UTF8.GetString(chunkedByte);
                            } while (ctmp.IndexOf(CT) == -1 && sw.ElapsedMilliseconds < timeout);

                            chunkedSize = Tools.convertToIntBy16(ctmp.Replace(CT, ""));

                            //chunked的结束0\r\n\r\n是结束标志,单个chunked块\r\n结束
                            if (ctmp.Equals(CT))
                            {
                                continue;
                            }
                            if (chunkedSize == 0)
                            {
                                //结束了
                                break;
                            }
                            int onechunkLen = 0;

                            while (onechunkLen < chunkedSize && sw.ElapsedMilliseconds < timeout)
                            {
                                len = ssl.Read(responseBody, sum, chunkedSize - onechunkLen);
                                if (len > 0)
                                {
                                    onechunkLen += len;
                                    sum         += len;
                                }
                                if (len <= 0 && onechunkLen < chunkedSize)
                                {
                                    Thread.Sleep(WaitTime);
                                }
                            }

                            //判断
                        } while (sw.ElapsedMilliseconds < timeout);
                    }
                    //connection close方式或未知body长度
                    else
                    {
                        while (sw.ElapsedMilliseconds < timeout)
                        {
                            if (clientSocket.Client.Poll(timeout, SelectMode.SelectRead))
                            {
                                if (clientSocket.Available > 0)
                                {
                                    len = ssl.Read(responseBody, sum, (1024 * 200) - sum);
                                    if (len > 0)
                                    {
                                        sum += len;
                                    }
                                    else
                                    {
                                        Thread.Sleep(WaitTime);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    //自动识别编码
                    if ("".Equals(encoding))
                    {
                        if (!String.IsNullOrEmpty(server.encoding))
                        {
                            encoding = server.encoding;//header找到编码
                        }
                        else
                        {
                            encoding         = "UTF-8"; //默认一个编码
                            isupdateEncoding = true;    //body找编码
                        }
                        Encoding encod = Encoding.GetEncoding(encoding);
                        getBody(ref server, ref responseBody, ref sum, ref encod, ref index);
                        //修正编码
                        if (isupdateEncoding)
                        {
                            String cEncoding = getHTMLEncoding("", server.body);
                            if (!String.IsNullOrEmpty(cEncoding))
                            {
                                server.encoding = cEncoding;//body找到编码
                                getBody(ref server, ref responseBody, ref sum, ref encod, ref index);
                            }
                        }
                    }
                    else
                    {
                        //指定编码
                        Encoding encod = Encoding.GetEncoding(encoding);
                        getBody(ref server, ref responseBody, ref sum, ref encod, ref index);
                    }
                }
            }
            catch (Exception e)
            {
                Exception ee = new Exception("HTTPS发包错误!错误消息:" + e.Message + "----发包编号:" + index);
                if (ee.Message.IndexOf("doHeader") != -1)
                {
                    String a = e.Message;
                }
                throw ee;
            }
            finally
            {
                sw.Stop();
                server.length  = sum;
                server.runTime = (int)sw.ElapsedMilliseconds;

                if (clientSocket != null)
                {
                    clientSocket.Close();
                }
            }
            return(server);
        }