Exemplo n.º 1
0
        public TrackerResponse MakeWebRequest(Uri uriQuest, string httpProtocol, string headers)
        {
            Encoding encoder = Encoding.GetEncoding(0x4e4);

            Socket = new SocketEx(Proxy, ProxyServer, ProxyPort, ProxyUser, ProxyPassword);
            Socket.SetTimeout(0x30d40);
            Socket.PreAuthenticate = false;
            log.Info($"Connecting to {uriQuest.Host}:{uriQuest.Port}");
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    Socket.Connect(uriQuest.Host, uriQuest.Port);
                    log.Info("Connected Successfully");
                    break;
                }
                catch (Exception ex)
                {
                    log.Warn(ex);
                    log.Warn("Failed connection attempt: " + i);
                }
            }
            if (!Socket.Connected)
            {
                log.Error("Unable to connect. Quitting...");
                return(null);
            }
            log.Info("======== Sending Command to Tracker ========");
            string cmd = "GET " + uriQuest.PathAndQuery + " " + httpProtocol + "\r\n" + headers.Replace("{host}", uriQuest.Host) + "\r\n";

            Socket.Send(encoder.GetBytes(cmd));

            try
            {
                byte[] data = new byte[32 * 1024];
                using (MemoryStream memStream = new MemoryStream())
                {
                    int dataLen = Socket.Receive(data);
                    while (dataLen > 0)
                    {
                        memStream.Write(data, 0, dataLen);
                        dataLen = Socket.Receive(data);
                    }

                    if (memStream.Length == 0)
                    {
                        log.Info("Error : Tracker Response is empty");
                        return(null);
                    }

                    TrackerResponse trackerResponse = new TrackerResponse(memStream);
                    memStream.Close();
                    Socket.Close();

                    if (trackerResponse.doRedirect)
                    {
                        return(MakeWebRequest(new Uri(trackerResponse.RedirectionURL), httpProtocol, headers));
                    }

                    log.Info("======== Tracker Response ========");
                    log.Info(trackerResponse.Headers.ToString());
                    if (trackerResponse.Dico == null)
                    {
                        log.Warn("*** Failed to decode tracker response :");
                        log.Warn(trackerResponse.Body);
                    }

                    return(trackerResponse);
                }
            }
            catch (Exception ex)
            {
                Socket.Close();
                log.Error(ex);
                return(null);
            }
        }