Esempio n. 1
0
        /// <summary>
        /// Process Authorisation result when using localhost method.
        /// </summary>
        private void Server_RequestComplete(object sender, RequestCompleteEventArgs e)
        {
            var server = sender as AuthListener;

            server.Stop();

            ParseUrl(e.QueryTokens);
        }
        private void OnRequestComplete(HttpWebRequest request, WebResponse response)
        {
            if (response == null)
            {
                return;
            }

            string responseBody;

            using (var responseStream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(responseStream))
                {
                    responseBody = reader.ReadToEnd();
                }
            }

            if (RequestComplete != null)
            {
                RequestCompleteEventArgs args = new RequestCompleteEventArgs(request, response, responseBody);
                RequestComplete(this, args);
            }
        }
Esempio n. 3
0
            private void DoWork()
            {
                var work = this.work;

                byte[]           buffer   = new byte[BUFFER_LENGTH];
                bool             doSwap   = false;
                Task <IPAddress> taskSwap = null;
                int counter = 0;
                var timeout = DateTime.UtcNow.AddMilliseconds(Settings.ConnectionTimeout);

                try
                {
                    while (!work.abort)
                    {
                        string request;
                        int    index;
                        bool   hasWork;

                        lock (work)
                        {
                            if (work.index < work.length)
                            {
                                do
                                {
                                    request = work.locations.Dequeue();
                                    index   = work.index++;
                                    if (hasWork = request != null)
                                    {
                                        break;
                                    }
                                }while (work.index < work.length);

                                if (!hasWork)
                                {
                                    if (!work.keepalive)
                                    {
                                        return;
                                    }
                                }
                            }
                            else if (!work.keepalive)
                            {
                                return;
                            }
                            else
                            {
                                work.waiter.Reset();

                                hasWork = false;
                                request = null;
                                index   = -1;
                            }
                        }

                        if (!hasWork)
                        {
                            work.waiter.WaitOne();
                            continue;
                        }

                        if (DateTime.UtcNow > timeout)
                        {
                            Close();
                        }

                        long mismatchLength = -1;
                        byte retry          = 10;
                        do
                        {
                            #region Remote connection

                            if (doSwap)
                            {
                                if (taskSwap.IsCompleted)
                                {
                                    if (taskSwap.Result != null)
                                    {
                                        ipPool.AddSample(taskSwap.Result, double.MaxValue);
                                    }
                                    else if (clientSwap != null && clientSwap.Connected)
                                    {
                                        if (client != null)
                                        {
                                            client.Close();
                                        }
                                        client            = clientSwap;
                                        clientSwap        = null;
                                        remoteEP          = (IPEndPoint)client.Client.RemoteEndPoint;
                                        stream.BaseStream = client.GetStream();
                                    }

                                    doSwap  = false;
                                    counter = 0;
                                }
                            }

                            if (client == null || !client.Connected)
                            {
                                client = new TcpClient()
                                {
                                    ReceiveTimeout = Settings.ConnectionTimeout,
                                    SendTimeout    = Settings.ConnectionTimeout
                                };

                                try
                                {
                                    remoteEP = new IPEndPoint(ipPool.GetIP(), 80);
                                    for (byte attempt = 10; attempt > 0; attempt--)
                                    {
                                        if (!client.ConnectAsync(remoteEP.Address, remoteEP.Port).Wait(Settings.ConnectionTimeout))
                                        {
                                            client.Close();

                                            if (work.abort || attempt == 1)
                                            {
                                                if (Error != null)
                                                {
                                                    Error(this, index, request, new TimeoutException("Unable to connect to host"));
                                                }
                                                return;
                                            }

                                            ipPool.AddSample(remoteEP.Address, double.MaxValue);
                                            Thread.Sleep(100);
                                            continue;
                                        }

                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ipPool.AddSample(remoteEP.Address, double.MaxValue);

                                    if (Error != null)
                                    {
                                        if (ex.InnerException != null)
                                        {
                                            Error(this, index, request, ex.InnerException);
                                        }
                                        else
                                        {
                                            Error(this, index, request, ex);
                                        }
                                    }

                                    return;
                                }

                                stream = new HttpStream(client.GetStream());
                            }

                            #endregion

                            #region Swap

                            if (++counter == 10)
                            {
                                var ip = ipPool.GetIP();

                                if (ip == remoteEP.Address)
                                {
                                    counter = 0;
                                }
                                else
                                {
                                    doSwap = true;

                                    taskSwap = Task.Run <IPAddress>(
                                        delegate
                                    {
                                        var clientSwap            = this.clientSwap = new TcpClient();
                                        clientSwap.ReceiveTimeout = clientSwap.SendTimeout = Settings.ConnectionTimeout;
                                        try
                                        {
                                            if (!clientSwap.ConnectAsync(ip, 80).Wait(Settings.ConnectionTimeout))
                                            {
                                                throw new TimeoutException();
                                            }

                                            return(null);
                                        }
                                        catch (Exception e)
                                        {
                                            clientSwap.Close();

                                            return(ip);
                                        }
                                    });
                                }
                            }

                            #endregion

                            if (RequestBegin != null)
                            {
                                RequestBegin(this, EventArgs.Empty);
                            }

                            try
                            {
                                WriteHeader(stream, work.host, request);

                                bool   delete = true;
                                string path   = Path.Combine(work.path, Util.FileName.FromAssetRequest(request) + ".tmp");
                                try
                                {
                                    HttpStatusCode code;

                                    using (var w = File.Create(path))
                                    {
                                        Net.HttpStream.HttpHeader header;
                                        int read;

                                        var  startTime = DateTime.UtcNow;
                                        long total     = read = stream.ReadHeader(buffer, 0, out header);

                                        if (read <= 0)
                                        {
                                            throw new EndOfStreamException();
                                        }

                                        var response = (Net.HttpStream.HttpResponseHeader)header;

                                        if (work.headersOnly)
                                        {
                                            if (BytesDownloaded != null)
                                            {
                                                BytesDownloaded(this, read);
                                            }

                                            w.Write(buffer, 0, read);
                                        }
                                        else
                                        {
                                            while (read > 0)
                                            {
                                                if (BytesDownloaded != null)
                                                {
                                                    BytesDownloaded(this, read);
                                                }

                                                w.Write(buffer, 0, read);
                                                read = stream.Read(buffer, 0, BUFFER_LENGTH);

                                                total += read;
                                            }
                                        }

                                        var elapsed = DateTime.UtcNow.Subtract(startTime).TotalMilliseconds;

                                        code = response.StatusCode;

                                        if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NotFound)
                                        {
                                            if (elapsed <= 0)
                                            {
                                                elapsed = 1;
                                            }
                                            ipPool.AddSample(remoteEP.Address, total / elapsed * 2);
                                            throw new Exception("Server returned a bad response");
                                        }
                                        else if (elapsed > 0)
                                        {
                                            ipPool.AddSample(remoteEP.Address, total / elapsed);
                                        }

                                        if (!work.headersOnly && response.ContentLength > 0 && stream.ContentLengthProcessed != response.ContentLength)
                                        {
                                            ipPool.AddSample(remoteEP.Address, double.MaxValue);
                                            if (mismatchLength == stream.ContentLengthProcessed)
                                            {
                                                retry = 1;
                                            }
                                            mismatchLength = stream.ContentLengthProcessed;
                                            throw new Exception("Content length doesn't match header");
                                        }

                                        timeout = DateTime.UtcNow.AddMilliseconds(Settings.ConnectionTimeout);

                                        if (!response.KeepAlive.keepAlive)
                                        {
                                            client.Close();
                                        }
                                    }

                                    retry = 1;
                                    string to = path.Substring(0, path.Length - 4);
                                    if (File.Exists(to))
                                    {
                                        File.Delete(to);
                                    }
                                    File.Move(path, to);
                                    delete = false;

                                    if (RequestComplete != null)
                                    {
                                        var e = new RequestCompleteEventArgs()
                                        {
                                            Index        = index,
                                            Location     = request,
                                            ContentBytes = stream.ContentLengthProcessed,
                                            StatusCode   = code,
                                            Retry        = false
                                        };
                                        RequestComplete(this, e);
                                        if (e.Retry)
                                        {
                                            request = e.Location;
                                            continue;
                                        }
                                    }

                                    break;
                                }
                                finally
                                {
                                    if (delete)
                                    {
                                        try
                                        {
                                            File.Delete(path);
                                        }
                                        catch { }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (!(ex is EndOfStreamException))
                                {
                                    Console.WriteLine("!EndOfStreamException");
                                }
                                client.Close();

                                if (work.abort || --retry == 0)
                                {
                                    if (Error != null)
                                    {
                                        Error(this, index, request, ex);
                                    }
                                    return;
                                }
                            }
                        }while (true);
                    }
                }
                finally
                {
                    Close();

                    if (Complete != null)
                    {
                        Complete(this, EventArgs.Empty);
                    }
                }
            }
 static void HandleConfigRequestCompleted(object sender, RequestCompleteEventArgs <HPCGetConfig> e)
 {
     var request = e.Request;
     // do something with the request
 }