private bool Receive()
        {
            SupportedProtocols protocol = CurrentRequest.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(CurrentRequest.CurrentUri) : CurrentRequest.ProtocolHandler;

            if (HTTPManager.Logger.Level == Logger.Loglevels.All)
            {
                HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Receive - protocol: {1}", this.CurrentRequest.CurrentUri.ToString(), protocol.ToString()));
            }

            CurrentRequest.Response = HTTPProtocolFactory.Get(protocol, CurrentRequest, Stream, CurrentRequest.UseStreaming, false);

            if (!CurrentRequest.Response.Receive())
            {
                if (HTTPManager.Logger.Level == Logger.Loglevels.All)
                {
                    HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Receive - Failed! Response will be null, returning with false.", this.CurrentRequest.CurrentUri.ToString()));
                }
                CurrentRequest.Response = null;
                return(false);
            }

            if (CurrentRequest.Response.StatusCode == 304
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                && !CurrentRequest.DisableCache
#endif
                )
            {
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                if (CurrentRequest.IsRedirected)
                {
                    if (!LoadFromCache(CurrentRequest.RedirectUri))
                    {
                        LoadFromCache(CurrentRequest.Uri);
                    }
                }
                else
                {
                    LoadFromCache(CurrentRequest.Uri);
                }
#else
                return(false);
#endif
            }

            if (HTTPManager.Logger.Level == Logger.Loglevels.All)
            {
                HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Receive - Finished Successfully!", this.CurrentRequest.CurrentUri.ToString()));
            }

            return(true);
        }
Beispiel #2
0
        /// <summary>
        /// Writes out the Headers to the stream.
        /// </summary>
        /// <param name="stream"></param>
        private void SendHeaders(BinaryWriter stream)
        {
            if (!HasHeader("Host"))
            {
                SetHeader("Host", CurrentUri.Host);
            }

            if (IsRedirected && !HasHeader("Referer"))
            {
                AddHeader("Referer", Uri.ToString());
            }

            if (!HasHeader("Accept-Encoding"))
            {
                AddHeader("Accept-Encoding", "gzip, identity");
            }

            if (HasProxy && !HasHeader("Proxy-Connection"))
            {
                AddHeader("Proxy-Connection", IsKeepAlive ? "Keep-Alive" : "Close");
            }

            if (!HasHeader("Connection"))
            {
                AddHeader("Connection", IsKeepAlive ? "Keep-Alive, TE" : "Close, TE");
            }

            if (!HasHeader("TE"))
            {
                AddHeader("TE", "identity");
            }

            if (!HasHeader("User-Agent"))
            {
                AddHeader("User-Agent", "BestHTTP");
            }

            byte[] entityBody    = GetEntityBody();
            int    contentLength = entityBody != null ? entityBody.Length : 0;

            if (RawData == null && (FormImpl != null || (FieldCollector != null && !FieldCollector.IsEmpty)))
            {
                SelectFormImplementation();
                if (FormImpl != null)
                {
                    FormImpl.PrepareRequest(this);
                }
            }

            if (!HasHeader("Content-Length") && contentLength != 0)
            {
                AddHeader("Content-Length", contentLength.ToString());
            }

            // Proxy Authentication
            if (HasProxy && Proxy.Credentials != null)
            {
                switch (Proxy.Credentials.Type)
                {
                case AuthenticationTypes.Basic:
                    // With Basic authentication we don't want to wait for a challange, we will send the hash with the first request
                    SetHeader("Proxy-Authorization", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password))));
                    break;

                case AuthenticationTypes.Unknown:
                case AuthenticationTypes.Digest:
                    var digest = DigestStore.Get(Proxy.Address);
                    if (digest != null)
                    {
                        string authentication = digest.GenerateResponseHeader(this, Proxy.Credentials);
                        if (!string.IsNullOrEmpty(authentication))
                        {
                            SetHeader("Proxy-Authorization", authentication);
                        }
                    }

                    break;
                }
            }

            // Server authentication
            if (Credentials != null)
            {
                switch (Credentials.Type)
                {
                case AuthenticationTypes.Basic:
                    // With Basic authentication we don't want to wait for a challange, we will send the hash with the first request
                    SetHeader("Authorization", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password))));
                    break;

                case AuthenticationTypes.Unknown:
                case AuthenticationTypes.Digest:
                    var digest = DigestStore.Get(this.CurrentUri);
                    if (digest != null)
                    {
                        string authentication = digest.GenerateResponseHeader(this, Credentials);
                        if (!string.IsNullOrEmpty(authentication))
                        {
                            SetHeader("Authorization", authentication);
                        }
                    }

                    break;
                }
            }

            // Cookies
            if (IsCookiesEnabled)
            {
                var cookies = CookieJar.Get(CurrentUri);

                // http://tools.ietf.org/html/rfc6265#section-5.4
                //  -When the user agent generates an HTTP request, the user agent MUST NOT attach more than one Cookie header field.
                if (cookies != null && cookies.Count > 0)
                {
                    // TODO:
                    //   2. The user agent SHOULD sort the cookie-list in the following order:
                    //      *  Cookies with longer paths are listed before cookies with shorter paths.
                    //      *  Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times.

                    bool   first     = true;
                    string cookieStr = string.Empty;

                    foreach (var cookie in cookies)
                    {
                        if ((!cookie.IsSecure || (cookie.IsSecure && HTTPProtocolFactory.IsSecureProtocol(CurrentUri))) &&
                            (!cookie.IsHttpOnly || (cookie.IsHttpOnly && HTTPProtocolFactory.GetProtocolFromUri(CurrentUri) == SupportedProtocols.HTTP)))
                        {
                            if (!first)
                            {
                                cookieStr += "; ";
                            }
                            else
                            {
                                first = false;
                            }

                            cookieStr += cookie.ToString();

                            // 3. Update the last-access-time of each cookie in the cookie-list to the current date and time.
                            cookie.LastAccess = DateTime.UtcNow;
                        }
                    }

                    SetHeader("Cookie", cookieStr);
                }
            }

            // Write out the headers to the stream
            foreach (var kvp in Headers)
            {
                byte[] headerName = string.Concat(kvp.Key, ": ").GetASCIIBytes();

                for (int i = 0; i < kvp.Value.Count; ++i)
                {
                    stream.Write(headerName);
                    stream.Write(kvp.Value[i].GetASCIIBytes());
                    stream.Write(EOL);
                }
            }
        }
        private bool Receive()
        {
            SupportedProtocols protocol = (base.CurrentRequest.ProtocolHandler != SupportedProtocols.Unknown) ? base.CurrentRequest.ProtocolHandler : HTTPProtocolFactory.GetProtocolFromUri(base.CurrentRequest.CurrentUri);

            if (HTTPManager.Logger.Level == Loglevels.All)
            {
                HTTPManager.Logger.Verbose("HTTPConnection", $"{base.CurrentRequest.CurrentUri.ToString()} - Receive - protocol: {protocol.ToString()}");
            }
            base.CurrentRequest.Response = HTTPProtocolFactory.Get(protocol, base.CurrentRequest, this.Stream, base.CurrentRequest.UseStreaming, false);
            if (!base.CurrentRequest.Response.Receive(-1, true))
            {
                if (HTTPManager.Logger.Level == Loglevels.All)
                {
                    HTTPManager.Logger.Verbose("HTTPConnection", $"{base.CurrentRequest.CurrentUri.ToString()} - Receive - Failed! Response will be null, returning with false.");
                }
                base.CurrentRequest.Response = null;
                return(false);
            }
            if ((base.CurrentRequest.Response.StatusCode == 0x130) && !base.CurrentRequest.DisableCache)
            {
                if (base.CurrentRequest.IsRedirected)
                {
                    if (!this.LoadFromCache(base.CurrentRequest.RedirectUri))
                    {
                        this.LoadFromCache(base.CurrentRequest.Uri);
                    }
                }
                else
                {
                    this.LoadFromCache(base.CurrentRequest.Uri);
                }
            }
            if (HTTPManager.Logger.Level == Loglevels.All)
            {
                HTTPManager.Logger.Verbose("HTTPConnection", $"{base.CurrentRequest.CurrentUri.ToString()} - Receive - Finished Successfully!");
            }
            return(true);
        }
Beispiel #4
0
        private bool Receive()
        {
            SupportedProtocols protocol = CurrentRequest.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(CurrentRequest.CurrentUri) : CurrentRequest.ProtocolHandler;

            if (HTTPManager.Logger.Level == Logger.Loglevels.All)
            {
                HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Receive - protocol: {1}", this.CurrentRequest.CurrentUri.ToString(), protocol.ToString()));
            }

            CurrentRequest.Response = HTTPProtocolFactory.Get(protocol, CurrentRequest, Stream, CurrentRequest.UseStreaming, false);

            if (!CurrentRequest.Response.Receive())
            {
                if (HTTPManager.Logger.Level == Logger.Loglevels.All)
                {
                    HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Receive - Failed! Response will be null, returning with false.", this.CurrentRequest.CurrentUri.ToString()));
                }
                CurrentRequest.Response = null;
                return(false);
            }

            // We didn't check HTTPManager.IsCachingDisabled's value on purpose. (sending out a request with conditional get then change IsCachingDisabled to true may produce undefined behavior)
            if (CurrentRequest.Response.StatusCode == 304)
            {
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                if (CurrentRequest.IsRedirected)
                {
                    if (!LoadFromCache(CurrentRequest.RedirectUri))
                    {
                        LoadFromCache(CurrentRequest.Uri);
                    }
                }
                else
                {
                    LoadFromCache(CurrentRequest.Uri);
                }
#else
                return(false);
#endif
            }

            if (HTTPManager.Logger.Level == Logger.Loglevels.All)
            {
                HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Receive - Finished Successfully!", this.CurrentRequest.CurrentUri.ToString()));
            }

            return(true);
        }
Beispiel #5
0
        void OnResponse(int httpStatus, byte[] buffer)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Stream = ms;

                    XHR_GetStatusLine(NativeId, OnBufferCallback);
                    XHR_GetResponseHeaders(NativeId, OnBufferCallback);

                    if (buffer != null && buffer.Length > 0)
                    {
                        ms.Write(buffer, 0, buffer.Length);
                    }

                    ms.Seek(0L, SeekOrigin.Begin);

                    SupportedProtocols protocol = CurrentRequest.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(CurrentRequest.CurrentUri) : CurrentRequest.ProtocolHandler;
                    CurrentRequest.Response = HTTPProtocolFactory.Get(protocol, CurrentRequest, ms, CurrentRequest.UseStreaming, false);

                    CurrentRequest.Response.Receive(buffer != null && buffer.Length > 0 ? (int)buffer.Length : -1, true);
                }
            }
            catch (Exception e)
            {
                HTTPManager.Logger.Exception(this.NativeId + " WebGLConnection", "OnResponse", e);

                if (CurrentRequest != null)
                {
                    // Something gone bad, Response must be null!
                    CurrentRequest.Response = null;

                    switch (State)
                    {
                    case HTTPConnectionStates.AbortRequested:
                        CurrentRequest.State = HTTPRequestStates.Aborted;
                        break;

                    case HTTPConnectionStates.TimedOut:
                        CurrentRequest.State = HTTPRequestStates.TimedOut;
                        break;

                    default:
                        CurrentRequest.Exception = e;
                        CurrentRequest.State     = HTTPRequestStates.Error;
                        break;
                    }
                }
            }
            finally
            {
                Connections.Remove(NativeId);

                Stream = null;

                if (CurrentRequest != null)
                {
                    lock (HTTPManager.Locker)
                    {
                        State = HTTPConnectionStates.Closed;
                        if (CurrentRequest.State == HTTPRequestStates.Processing)
                        {
                            if (CurrentRequest.Response != null)
                            {
                                CurrentRequest.State = HTTPRequestStates.Finished;
                            }
                            else
                            {
                                CurrentRequest.State = HTTPRequestStates.Error;
                            }
                        }
                    }
                }

                LastProcessTime = DateTime.UtcNow;

                if (OnConnectionRecycled != null)
                {
                    RecycleNow();
                }

                XHR_Release(NativeId);
            }
        }
Beispiel #6
0
        private bool Receive()
        {
            SupportedProtocols protocol = CurrentRequest.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(CurrentRequest.CurrentUri) : CurrentRequest.ProtocolHandler;

            CurrentRequest.Response = HTTPProtocolFactory.Get(protocol, CurrentRequest, Stream, CurrentRequest.UseStreaming, false);

            if (!CurrentRequest.Response.Receive())
            {
                CurrentRequest.Response = null;
                return(false);
            }

            // We didn't check HTTPManager.IsCachingDisabled's value on purpose. (sending out a request with conditional get then change IsCachingDisabled to true may produce undefined behavior)
            if (CurrentRequest.Response.StatusCode == 304)
            {
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                if (CurrentRequest.IsRedirected)
                {
                    if (!LoadFromCache(CurrentRequest.RedirectUri))
                    {
                        LoadFromCache(CurrentRequest.Uri);
                    }
                }
                else
                {
                    LoadFromCache(CurrentRequest.Uri);
                }
#else
                return(false);
#endif
            }

            return(true);
        }