/// <summary> /// Protocol negotiation finished successfully. /// </summary> private void OnNegotiationDataReceived(NegotiationData data) { #if !BESTHTTP_DISABLE_WEBSOCKET if (data.TryWebSockets) { Transport = new WebSocketTransport(this); #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS NextProtocolToTry = SupportedProtocols.ServerSentEvents; #else NextProtocolToTry = SupportedProtocols.HTTP; #endif } else #endif { #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS Transport = new ServerSentEventsTransport(this); // Long-Poll NextProtocolToTry = SupportedProtocols.HTTP; #else Transport = new PollingTransport(this); NextProtocolToTry = SupportedProtocols.Unknown; #endif } this.State = ConnectionStates.Connecting; TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); }
private bool Receive() { SupportedProtocols protocol = (base.CurrentRequest.ProtocolHandler != 0) ? base.CurrentRequest.ProtocolHandler : HTTPProtocolFactory.GetProtocolFromUri(base.CurrentRequest.CurrentUri); base.CurrentRequest.Response = HTTPProtocolFactory.Get(protocol, base.CurrentRequest, Stream, base.CurrentRequest.UseStreaming, isFromCache: false); if (!base.CurrentRequest.Response.Receive()) { base.CurrentRequest.Response = null; return(false); } if (base.CurrentRequest.Response.StatusCode == 304) { if (base.CurrentRequest.IsRedirected) { if (!LoadFromCache(base.CurrentRequest.RedirectUri)) { LoadFromCache(base.CurrentRequest.Uri); } } else { LoadFromCache(base.CurrentRequest.Uri); } } return(true); }
private bool TryFallbackTransport() { if (State == ConnectionStates.Connecting) { if (BufferedMessages != null) { BufferedMessages.Clear(); } Transport.Stop(); Transport = null; switch (NextProtocolToTry) { case SupportedProtocols.ServerSentEvents: Transport = new ServerSentEventsTransport(this); NextProtocolToTry = SupportedProtocols.HTTP; break; case SupportedProtocols.HTTP: Transport = new PollingTransport(this); NextProtocolToTry = SupportedProtocols.Unknown; break; case SupportedProtocols.Unknown: return(false); } TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); if (PingRequest != null) { PingRequest.Abort(); } return(true); } return(false); }
public static Option <PortAndProtocol> Parse(string name) { if (string.IsNullOrWhiteSpace(name)) { return(empty); } string[] portProtocol = name.Split('/', StringSplitOptions.RemoveEmptyEntries); if (portProtocol.Length > 2) { return(empty); } if (!int.TryParse(portProtocol[0], out int port)) { return(empty); } // Docker defaults to TCP if not specified. string protocol = defaultProtocol; if (portProtocol.Length > 1) { if (!SupportedProtocols.TryGetValue(portProtocol[1], out protocol)) { return(empty); } } return(Option.Some(new PortAndProtocol(port, protocol))); }
private void OnNegotiationDataReceived(NegotiationData data) { int num = -1; for (int i = 0; i < ClientProtocols.Length; i++) { if (num != -1) { break; } if (data.ProtocolVersion == ClientProtocols[i]) { num = i; } } if (num == -1) { num = 2; HTTPManager.Logger.Warning("SignalR Connection", "Unknown protocol version: " + data.ProtocolVersion); } Protocol = (ProtocolVersions)num; if (data.TryWebSockets) { Transport = new WebSocketTransport(this); NextProtocolToTry = SupportedProtocols.ServerSentEvents; } else { Transport = new ServerSentEventsTransport(this); NextProtocolToTry = SupportedProtocols.HTTP; } State = ConnectionStates.Connecting; TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); }
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); }
private bool Receive(HTTPRequest request) { SupportedProtocols protocol = request.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri) : request.ProtocolHandler; if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("HTTPConnection", string.Format("[{0}] - Receive - protocol: {1}", this.ToString(), protocol.ToString()), this.Context, request.Context); } request.Response = HTTPProtocolFactory.Get(protocol, request, this.conn.connector.Stream, request.UseStreaming, false); if (!request.Response.Receive()) { if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("HTTP1Handler", string.Format("[{0}] - Receive - Failed! Response will be null, returning with false.", this.ToString()), this.Context, request.Context); } request.Response = null; return(false); } if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("HTTP1Handler", string.Format("[{0}] - Receive - Finished Successfully!", this.ToString()), this.Context, request.Context); } return(true); }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { case SupportedProtocols.WebSocket: return new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache); default: return new HTTPResponse(request, stream, isStreamed, isFromCache); } }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { if (protocol != SupportedProtocols.WebSocket) { return(new HTTPResponse(request, stream, isStreamed, isFromCache)); } return(new WebSocketResponse(request, stream, isStreamed, isFromCache)); }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { case SupportedProtocols.WebSocket: return(new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache)); default: return(new HTTPResponse(request, stream, isStreamed, isFromCache)); } }
/// <summary> /// Creates a deep copy of this instance for the specified ETP version. /// Any protocol handlers not supported by the specified version will be removed from the clone. /// </summary> /// <param name="version">The ETP version for the clone.</param> /// <returns>A deep copy of this instance.</returns> public EtpEndpointParameters CloneForVersion(EtpVersion version) { return(new EtpEndpointParameters( new EtpEndpointCapabilities(Capabilities), SupportedProtocols.Where(p => version == EtpVersion.Unknown || p.EtpVersion == EtpVersion.Unknown || p.EtpVersion == version).Select(p => p.Clone()).ToList(), new List <EtpSupportedDataObject>(SupportedDataObjects), new List <string>(SupportedCompression), new List <string>(SupportedFormats) )); }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.WebSocket: return(new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache)); #endif default: return(new HTTPResponse(request, new Extensions.ReadOnlyBufferedStream(stream), isStreamed, isFromCache)); } }
/// <summary> /// Protocol negotiation finished successfully. /// </summary> private void OnNegotiationDataReceived(NegotiationData data) { // Find out what supported protocol the server speak int protocolIdx = -1; for (int i = 0; i < ClientProtocols.Length && protocolIdx == -1; ++i) { if (data.ProtocolVersion == ClientProtocols[i]) { protocolIdx = i; } } // No supported protocol found? Try using the latest one. if (protocolIdx == -1) { protocolIdx = (byte)ProtocolVersions.Protocol_2_2; HTTPManager.Logger.Warning("SignalR Connection", "Unknown protocol version: " + data.ProtocolVersion); } this.Protocol = (ProtocolVersions)protocolIdx; #if !BESTHTTP_DISABLE_WEBSOCKET if (data.TryWebSockets) { Transport = new WebSocketTransport(this); #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS NextProtocolToTry = SupportedProtocols.ServerSentEvents; #else NextProtocolToTry = SupportedProtocols.HTTP; #endif } else #endif { #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS Transport = new ServerSentEventsTransport(this); // Long-Poll NextProtocolToTry = SupportedProtocols.HTTP; #else Transport = new PollingTransport(this); NextProtocolToTry = SupportedProtocols.Unknown; #endif } this.State = ConnectionStates.Connecting; TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); }
/// <summary> /// Try to fall back to next transport. If no more transport to try, it will return false. /// </summary> private bool TryFallbackTransport() { if (this.State == ConnectionStates.Connecting) { if (BufferedMessages != null) { BufferedMessages.Clear(); } // stop the current transport Transport.Stop(); Transport = null; switch (NextProtocolToTry) { #if !BESTHTTP_DISABLE_WEBSOCKET case SupportedProtocols.WebSocket: Transport = new WebSocketTransport(this); break; #endif #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS case SupportedProtocols.ServerSentEvents: Transport = new ServerSentEventsTransport(this); NextProtocolToTry = SupportedProtocols.HTTP; break; #endif case SupportedProtocols.HTTP: Transport = new PollingTransport(this); NextProtocolToTry = SupportedProtocols.Unknown; break; case SupportedProtocols.Unknown: return(false); } TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); if (PingRequest != null) { PingRequest.Abort(); } return(true); } return(false); }
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 && !CurrentRequest.DisableCache #endif ) { #if !BESTHTTP_DISABLE_CACHING 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); }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.WebSocket: return(new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache)); #endif #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.ServerSentEvents: return(new ServerSentEvents.EventSourceResponse(request, stream, isStreamed, isFromCache)); #endif default: return(new HTTPResponse(request, stream, isStreamed, isFromCache)); } }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.WebSocket: return new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache); #endif #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.ServerSentEvents: return new ServerSentEvents.EventSourceResponse(request, stream, isStreamed, isFromCache); #endif default: return new HTTPResponse(request, stream, isStreamed, isFromCache); } }
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); }
public static Option <PortAndProtocol> Parse(string name) { if (string.IsNullOrWhiteSpace(name)) { return(Option.None <PortAndProtocol>()); } string[] portProtocol = name.Split('/', StringSplitOptions.RemoveEmptyEntries); if (portProtocol.Length != 2) { return(Option.None <PortAndProtocol>()); } if (!int.TryParse(portProtocol[0], out int port) || !SupportedProtocols.TryGetValue(portProtocol[1], out string protocol)) { return(Option.None <PortAndProtocol>()); } return(Option.Some(new PortAndProtocol(port, protocol))); }
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); }
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) int bodyLength; using (var cacheStream = HTTPCacheService.GetBody(CurrentRequest.CurrentUri, out bodyLength)) { if (!CurrentRequest.Response.HasHeader("content-length")) { CurrentRequest.Response.Headers.Add("content-length", new List <string>(1) { bodyLength.ToString() }); } CurrentRequest.Response.IsFromCache = true; CurrentRequest.Response.ReadRaw(cacheStream, bodyLength); } #else return(false); #endif } return(true); }
void OnResponse(int httpStatus, byte[] buffer, int bufferLength) { HTTPConnectionStates proposedConnectionState = HTTPConnectionStates.Processing; bool resendRequest = false; try { if (this.CurrentRequest.IsCancellationRequested) { return; } using (var ms = new BufferPoolMemoryStream()) { Stream = ms; XHR_GetStatusLine(NativeId, OnBufferCallback); XHR_GetResponseHeaders(NativeId, OnBufferCallback); if (buffer != null && bufferLength > 0) { ms.Write(buffer, 0, bufferLength); } ms.Seek(0L, SeekOrigin.Begin); var internalBuffer = ms.GetBuffer(); string tmp = System.Text.Encoding.UTF8.GetString(internalBuffer); HTTPManager.Logger.Information(this.NativeId + " OnResponse - full response ", tmp, this.Context); 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 && bufferLength > 0 ? (int)bufferLength : -1, true); KeepAliveHeader keepAlive = null; ConnectionHelper.HandleResponse(this.ToString(), this.CurrentRequest, out resendRequest, out proposedConnectionState, ref keepAlive); } } catch (Exception e) { HTTPManager.Logger.Exception(this.NativeId + " WebGLConnection", "OnResponse", e, this.Context); if (this.ShutdownType == ShutdownTypes.Immediate) { return; } #if !BESTHTTP_DISABLE_CACHING if (this.CurrentRequest.UseStreaming) { HTTPCacheService.DeleteEntity(this.CurrentRequest.CurrentUri); } #endif // Something gone bad, Response must be null! this.CurrentRequest.Response = null; if (!this.CurrentRequest.IsCancellationRequested) { this.CurrentRequest.Exception = e; this.CurrentRequest.State = HTTPRequestStates.Error; } proposedConnectionState = HTTPConnectionStates.Closed; } finally { // Exit ASAP if (this.ShutdownType != ShutdownTypes.Immediate) { if (this.CurrentRequest.IsCancellationRequested) { // we don't know what stage the request is cancelled, we can't safely reuse the tcp channel. proposedConnectionState = HTTPConnectionStates.Closed; this.CurrentRequest.Response = null; this.CurrentRequest.State = this.CurrentRequest.IsTimedOut ? HTTPRequestStates.TimedOut : HTTPRequestStates.Aborted; } else if (resendRequest) { RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.CurrentRequest, RequestEvents.Resend)); } else if (this.CurrentRequest.Response != null && this.CurrentRequest.Response.IsUpgraded) { proposedConnectionState = HTTPConnectionStates.WaitForProtocolShutdown; } else if (this.CurrentRequest.State == HTTPRequestStates.Processing) { if (this.CurrentRequest.Response != null) { this.CurrentRequest.State = HTTPRequestStates.Finished; } else { this.CurrentRequest.Exception = new Exception(string.Format("[{0}] Remote server closed the connection before sending response header! Previous request state: {1}. Connection state: {2}", this.ToString(), this.CurrentRequest.State.ToString(), this.State.ToString())); this.CurrentRequest.State = HTTPRequestStates.Error; proposedConnectionState = HTTPConnectionStates.Closed; } } this.CurrentRequest = null; if (proposedConnectionState == HTTPConnectionStates.Processing) { proposedConnectionState = HTTPConnectionStates.Closed; } ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this, proposedConnectionState)); } } }
/// <summary> /// Protocol negotiation finished successfully. /// </summary> private void OnNegotiationDataReceived(NegotiationData data) { // Find out what supported protocol the server speak int protocolIdx = -1; for (int i = 0; i < ClientProtocols.Length && protocolIdx == -1; ++i) if (data.ProtocolVersion == ClientProtocols[i]) protocolIdx = i; // No supported protocol found? Try using the latest one. if (protocolIdx == -1) { protocolIdx = (byte)ProtocolVersions.Protocol_2_2; HTTPManager.Logger.Warning("SignalR Connection", "Unknown protocol version: " + data.ProtocolVersion); } this.Protocol = (ProtocolVersions)protocolIdx; #if !BESTHTTP_DISABLE_WEBSOCKET if (data.TryWebSockets) { Transport = new WebSocketTransport(this); #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS NextProtocolToTry = SupportedProtocols.ServerSentEvents; #else NextProtocolToTry = SupportedProtocols.HTTP; #endif } else #endif { #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS Transport = new ServerSentEventsTransport(this); // Long-Poll NextProtocolToTry = SupportedProtocols.HTTP; #else Transport = new PollingTransport(this); NextProtocolToTry = SupportedProtocols.Unknown; #endif } this.State = ConnectionStates.Connecting; TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); }
/// <summary> /// Initializes a new instance of the <see cref="MockServiceSignature"/> /// class. /// </summary> /// <param name="version">The version.</param> /// <param name="serviceName">Name of the service.</param> /// <param name="protocols">The protocols.</param> public MockServiceSignature(string version, string serviceName, SupportedProtocols protocols) : base(version, serviceName, protocols) { }
void OnResponse(int httpStatus, byte[] buffer, int bufferLength) { try { using (var ms = new BufferPoolMemoryStream()) { Stream = ms; XHR_GetStatusLine(NativeId, OnBufferCallback); XHR_GetResponseHeaders(NativeId, OnBufferCallback); if (buffer != null && bufferLength > 0) { ms.Write(buffer, 0, bufferLength); } ms.Seek(0L, SeekOrigin.Begin); var internalBuffer = ms.GetBuffer(); string tmp = System.Text.Encoding.UTF8.GetString(internalBuffer); HTTPManager.Logger.Information(this.NativeId + " OnResponse - full response ", tmp); 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 && bufferLength > 0 ? (int)bufferLength : -1, true); #if !BESTHTTP_DISABLE_COOKIES if (CurrentRequest.IsCookiesEnabled) { BestHTTP.Cookies.CookieJar.Set(CurrentRequest.Response); } #endif } } 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); } }
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); } }
private void SendHeaders(BinaryWriter stream) { if (!this.HasHeader("Host")) { this.SetHeader("Host", this.CurrentUri.Authority); } if (this.IsRedirected && !this.HasHeader("Referer")) { this.AddHeader("Referer", this.Uri.ToString()); } if (!this.HasHeader("Accept-Encoding")) { this.AddHeader("Accept-Encoding", "gzip, identity"); } if (this.HasProxy && !this.HasHeader("Proxy-Connection")) { this.AddHeader("Proxy-Connection", (!this.IsKeepAlive) ? "Close" : "Keep-Alive"); } if (!this.HasHeader("Connection")) { this.AddHeader("Connection", (!this.IsKeepAlive) ? "Close, TE" : "Keep-Alive, TE"); } if (!this.HasHeader("TE")) { this.AddHeader("TE", "identity"); } if (!this.HasHeader("User-Agent")) { this.AddHeader("User-Agent", "BestHTTP"); } long num; if (this.UploadStream == null) { byte[] entityBody = this.GetEntityBody(); num = (long)((entityBody == null) ? 0 : entityBody.Length); if (this.RawData == null && (this.FormImpl != null || (this.FieldCollector != null && !this.FieldCollector.IsEmpty))) { this.SelectFormImplementation(); if (this.FormImpl != null) { this.FormImpl.PrepareRequest(this); } } } else { num = this.UploadStreamLength; if (num == -1L) { this.SetHeader("Transfer-Encoding", "Chunked"); } if (!this.HasHeader("Content-Type")) { this.SetHeader("Content-Type", "application/octet-stream"); } } if (num != -1L && !this.HasHeader("Content-Length")) { this.SetHeader("Content-Length", num.ToString()); } if (this.HasProxy && this.Proxy.Credentials != null) { switch (this.Proxy.Credentials.Type) { case AuthenticationTypes.Unknown: case AuthenticationTypes.Digest: { Digest digest = DigestStore.Get(this.Proxy.Address); if (digest != null) { string value = digest.GenerateResponseHeader(this, this.Proxy.Credentials); if (!string.IsNullOrEmpty(value)) { this.SetHeader("Proxy-Authorization", value); } } break; } case AuthenticationTypes.Basic: this.SetHeader("Proxy-Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password))); break; } } if (this.Credentials != null) { switch (this.Credentials.Type) { case AuthenticationTypes.Unknown: case AuthenticationTypes.Digest: { Digest digest2 = DigestStore.Get(this.CurrentUri); if (digest2 != null) { string value2 = digest2.GenerateResponseHeader(this, this.Credentials); if (!string.IsNullOrEmpty(value2)) { this.SetHeader("Authorization", value2); } } break; } case AuthenticationTypes.Basic: this.SetHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password))); break; } } List <Cookie> list = (!this.IsCookiesEnabled) ? null : CookieJar.Get(this.CurrentUri); if (list == null) { list = this.customCookies; } else if (this.customCookies != null) { list.AddRange(this.customCookies); } if (list != null && list.Count > 0) { bool flag = true; string text = string.Empty; bool flag2 = HTTPProtocolFactory.IsSecureProtocol(this.CurrentUri); SupportedProtocols protocolFromUri = HTTPProtocolFactory.GetProtocolFromUri(this.CurrentUri); foreach (Cookie current in list) { if ((!current.IsSecure || (current.IsSecure && flag2)) && (!current.IsHttpOnly || (current.IsHttpOnly && protocolFromUri == SupportedProtocols.HTTP))) { if (!flag) { text += "; "; } else { flag = false; } text += current.ToString(); current.LastAccess = DateTime.UtcNow; } } this.SetHeader("Cookie", text); } foreach (KeyValuePair <string, List <string> > current2 in this.Headers) { byte[] aSCIIBytes = (current2.Key + ": ").GetASCIIBytes(); for (int i = 0; i < current2.Value.Count; i++) { stream.Write(aSCIIBytes); stream.Write(current2.Value[i].GetASCIIBytes()); stream.Write(HTTPRequest.EOL); } } }
/// <summary> /// Protected constructor. /// </summary> /// <param name="version">Service version.</param> /// <param name="serviceName">Service name.</param> /// <param name="protocol">The supported protocol.</param> protected ServiceSignature(string version, string serviceName, SupportedProtocols protocol) { this.version = version; this.serviceName = serviceName; this.supportedProtocol = protocol; }
public void Connect(HTTPRequest request) { string negotiatedProtocol = HTTPProtocolFactory.W3C_HTTP1; Uri uri = #if !BESTHTTP_DISABLE_PROXY request.HasProxy ? request.Proxy.Address : #endif request.CurrentUri; #region TCP Connection if (Client == null) { Client = new TcpClient(); } if (!Client.Connected) { Client.ConnectTimeout = request.ConnectTimeout; #if NETFX_CORE Client.UseHTTPSProtocol = #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) !Request.UseAlternateSSL && #endif HTTPProtocolFactory.IsSecureProtocol(uri); #endif if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Connecting to {1}:{2}", request.CurrentUri.ToString(), uri.Host, uri.Port.ToString()), request.Context); } #if !NETFX_CORE && (!UNITY_WEBGL || UNITY_EDITOR) Client.SendBufferSize = HTTPManager.SendBufferSize; Client.ReceiveBufferSize = HTTPManager.ReceiveBufferSize; if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Buffer sizes - Send: {1} Receive: {2} Blocking: {3}", request.CurrentUri.ToString(), Client.SendBufferSize.ToString(), Client.ReceiveBufferSize.ToString(), Client.Client.Blocking.ToString()), request.Context); } #endif #if NETFX_CORE && !UNITY_EDITOR && !ENABLE_IL2CPP try { Client.Connect(uri.Host, uri.Port); } finally { request.Timing.Add(TimingEventNames.TCP_Connection); } #else System.Net.IPAddress[] addresses = null; try { if (Client.ConnectTimeout > TimeSpan.Zero) { // https://forum.unity3d.com/threads/best-http-released.200006/page-37#post-3150972 using (System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false)) { IAsyncResult result = System.Net.Dns.BeginGetHostAddresses(uri.Host, (res) => { try { mre.Set(); } catch { } }, null); bool success = mre.WaitOne(Client.ConnectTimeout); if (success) { addresses = System.Net.Dns.EndGetHostAddresses(result); } else { throw new TimeoutException("DNS resolve timed out!"); } } } else { addresses = System.Net.Dns.GetHostAddresses(uri.Host); } } finally { request.Timing.Add(TimingEventNames.DNS_Lookup); } if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - DNS Query returned with addresses: {1}", request.CurrentUri.ToString(), addresses != null ? addresses.Length : -1), request.Context); } if (request.IsCancellationRequested) { throw new Exception("IsCancellationRequested"); } try { Client.Connect(addresses, uri.Port, request); } finally { request.Timing.Add(TimingEventNames.TCP_Connection); } if (request.IsCancellationRequested) { throw new Exception("IsCancellationRequested"); } #endif if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) { HTTPManager.Logger.Information("TCPConnector", "Connected to " + uri.Host + ":" + uri.Port.ToString(), request.Context); } } else if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) { HTTPManager.Logger.Information("TCPConnector", "Already connected to " + uri.Host + ":" + uri.Port.ToString(), request.Context); } #endregion if (Stream == null) { bool isSecure = HTTPProtocolFactory.IsSecureProtocol(request.CurrentUri); // set the stream to Client.GetStream() so the proxy, if there's any can use it directly. this.Stream = this.TopmostStream = Client.GetStream(); /*if (Stream.CanTimeout) * Stream.ReadTimeout = Stream.WriteTimeout = (int)Request.Timeout.TotalMilliseconds;*/ #if !BESTHTTP_DISABLE_PROXY if (request.HasProxy) { try { request.Proxy.Connect(this.Stream, request); } finally { request.Timing.Add(TimingEventNames.Proxy_Negotiation); } } if (request.IsCancellationRequested) { throw new Exception("IsCancellationRequested"); } #endif // proxy connect is done, we can set the stream to a buffered one. HTTPProxy requires the raw NetworkStream for HTTPResponse's ReadUnknownSize! this.Stream = this.TopmostStream = new BufferedReadNetworkStream(Client.GetStream(), Math.Max(8 * 1024, HTTPManager.ReceiveBufferSize)); // We have to use Request.CurrentUri here, because uri can be a proxy uri with a different protocol if (isSecure) { DateTime tlsNegotiationStartedAt = DateTime.Now; #region SSL Upgrade #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) if (request.UseAlternateSSL) { var handler = new TlsClientProtocol(this.Stream, new BestHTTP.SecureProtocol.Org.BouncyCastle.Security.SecureRandom()); List <string> protocols = new List <string>(); #if !BESTHTTP_DISABLE_HTTP2 SupportedProtocols protocol = request.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri) : request.ProtocolHandler; if (protocol == SupportedProtocols.HTTP) { // http/2 over tls (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids) protocols.Add(HTTPProtocolFactory.W3C_HTTP2); } #endif protocols.Add(HTTPProtocolFactory.W3C_HTTP1); AbstractTlsClient tlsClient = null; if (HTTPManager.TlsClientFactory == null) { tlsClient = HTTPManager.DefaultTlsClientFactory(request, protocols); } else { try { tlsClient = HTTPManager.TlsClientFactory(request, protocols); } catch { } if (tlsClient == null) { tlsClient = HTTPManager.DefaultTlsClientFactory(request, protocols); } } tlsClient.LoggingContext = request.Context; handler.Connect(tlsClient); if (!string.IsNullOrEmpty(tlsClient.ServerSupportedProtocol)) { negotiatedProtocol = tlsClient.ServerSupportedProtocol; } Stream = handler.Stream; } else #endif { #if !NETFX_CORE SslStream sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) => { return(request.CallCustomCertificationValidator(cert, chain)); }); if (!sslStream.IsAuthenticated) { sslStream.AuthenticateAsClient(request.CurrentUri.Host); } Stream = sslStream; #else Stream = Client.GetStream(); #endif } #endregion request.Timing.Add(TimingEventNames.TLS_Negotiation, DateTime.Now - tlsNegotiationStartedAt); } } this.NegotiatedProtocol = negotiatedProtocol; }
/// <summary> /// Protocol negotiation finished successfully. /// </summary> private void OnNegotiationDataReceived(NegotiationData data) { if (data.TryWebSockets) { Transport = new WebSocketTransport(this); NextProtocolToTry = SupportedProtocols.ServerSentEvents; } else { Transport = new ServerSentEventsTransport(this); // Long-Poll NextProtocolToTry = SupportedProtocols.HTTP; } this.State = ConnectionStates.Connecting; TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); }
public void Connect(HTTPRequest request) { string negotiatedProtocol = HTTPProtocolFactory.W3C_HTTP1; Uri uri = #if !BESTHTTP_DISABLE_PROXY request.HasProxy ? request.Proxy.Address : #endif request.CurrentUri; #region TCP Connection if (Client == null) { Client = new TcpClient(); } if (!Client.Connected) { Client.ConnectTimeout = request.ConnectTimeout; #if NETFX_CORE Client.UseHTTPSProtocol = #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) !Request.UseAlternateSSL && #endif HTTPProtocolFactory.IsSecureProtocol(uri); #endif if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Connecting to {1}:{2}", request.CurrentUri.ToString(), uri.Host, uri.Port.ToString())); } #if !NETFX_CORE && (!UNITY_WEBGL || UNITY_EDITOR) Client.SendBufferSize = HTTPManager.SendBufferSize; Client.ReceiveBufferSize = HTTPManager.ReceiveBufferSize; if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Buffer sizes - Send: {1} Receive: {2} Blocking: {3}", request.CurrentUri.ToString(), Client.SendBufferSize.ToString(), Client.ReceiveBufferSize.ToString(), Client.Client.Blocking.ToString())); } #endif Client.Connect(uri.Host, uri.Port); if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) { HTTPManager.Logger.Information("TCPConnector", "Connected to " + uri.Host + ":" + uri.Port.ToString()); } } else if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) { HTTPManager.Logger.Information("TCPConnector", "Already connected to " + uri.Host + ":" + uri.Port.ToString()); } #endregion if (Stream == null) { bool isSecure = HTTPProtocolFactory.IsSecureProtocol(request.CurrentUri); this.Stream = this.TopmostStream = Client.GetStream(); /*if (Stream.CanTimeout) * Stream.ReadTimeout = Stream.WriteTimeout = (int)Request.Timeout.TotalMilliseconds;*/ #if !BESTHTTP_DISABLE_PROXY if (request.Proxy != null) { request.Proxy.Connect(this.Stream, request); } #endif // We have to use Request.CurrentUri here, because uri can be a proxy uri with a different protocol if (isSecure) { #region SSL Upgrade #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) if (request.UseAlternateSSL) { var handler = new TlsClientProtocol(Client.GetStream(), new BestHTTP.SecureProtocol.Org.BouncyCastle.Security.SecureRandom()); // http://tools.ietf.org/html/rfc3546#section-3.1 // -It is RECOMMENDED that clients include an extension of type "server_name" in the client hello whenever they locate a server by a supported name type. // -Literal IPv4 and IPv6 addresses are not permitted in "HostName". // User-defined list has a higher priority List <string> hostNames = request.CustomTLSServerNameList; // If there's no user defined one and the host isn't an IP address, add the default one if ((hostNames == null || hostNames.Count == 0) && !request.CurrentUri.IsHostIsAnIPAddress()) { hostNames = new List <string>(1); hostNames.Add(request.CurrentUri.Host); } List <string> protocols = new List <string>(); #if !BESTHTTP_DISABLE_HTTP2 SupportedProtocols protocol = request.ProtocolHandler == SupportedProtocols.Unknown ? HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri) : request.ProtocolHandler; if (protocol == SupportedProtocols.HTTP) { // http/2 over tls (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids) protocols.Add(HTTPProtocolFactory.W3C_HTTP2); } #endif protocols.Add(HTTPProtocolFactory.W3C_HTTP1); var tlsClient = new LegacyTlsClient(request.CurrentUri, request.CustomCertificateVerifyer == null ? new AlwaysValidVerifyer() : request.CustomCertificateVerifyer, request.CustomClientCredentialsProvider, hostNames, protocols); handler.Connect(tlsClient); if (!string.IsNullOrEmpty(tlsClient.ServerSupportedProtocol)) { negotiatedProtocol = tlsClient.ServerSupportedProtocol; } Stream = handler.Stream; } else #endif { #if !NETFX_CORE SslStream sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) => { return(request.CallCustomCertificationValidator(cert, chain)); }); if (!sslStream.IsAuthenticated) { sslStream.AuthenticateAsClient(request.CurrentUri.Host); } Stream = sslStream; #else Stream = Client.GetStream(); #endif } #endregion } } this.NegotiatedProtocol = negotiatedProtocol; }
public void EnumerateHeaders(OnHeaderEnumerationDelegate callback) { if (!HasHeader("Host")) { SetHeader("Host", CurrentUri.Authority); } 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) ? "Close" : "Keep-Alive"); } if (!HasHeader("Connection")) { AddHeader("Connection", (!IsKeepAlive) ? "Close, TE" : "Keep-Alive, TE"); } if (!HasHeader("TE")) { AddHeader("TE", "identity"); } if (!HasHeader("User-Agent")) { AddHeader("User-Agent", "VRC.Core.BestHTTP"); } long num = -1L; if (UploadStream == null) { byte[] entityBody = GetEntityBody(); num = ((entityBody != null) ? entityBody.Length : 0); if (RawData == null && (FormImpl != null || (FieldCollector != null && !FieldCollector.IsEmpty))) { SelectFormImplementation(); if (FormImpl != null) { FormImpl.PrepareRequest(this); } } } else { num = UploadStreamLength; if (num == -1) { SetHeader("Transfer-Encoding", "Chunked"); } if (!HasHeader("Content-Type")) { SetHeader("Content-Type", "application/octet-stream"); } } if (num != -1 && !HasHeader("Content-Length")) { SetHeader("Content-Length", num.ToString()); } if (HasProxy && Proxy.Credentials != null) { switch (Proxy.Credentials.Type) { case AuthenticationTypes.Basic: SetHeader("Proxy-Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":" + Proxy.Credentials.Password))); break; case AuthenticationTypes.Unknown: case AuthenticationTypes.Digest: { Digest digest = DigestStore.Get(Proxy.Address); if (digest != null) { string value = digest.GenerateResponseHeader(this, Proxy.Credentials); if (!string.IsNullOrEmpty(value)) { SetHeader("Proxy-Authorization", value); } } break; } } } if (Credentials != null) { switch (Credentials.Type) { case AuthenticationTypes.Basic: SetHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password))); break; case AuthenticationTypes.Unknown: case AuthenticationTypes.Digest: { Digest digest2 = DigestStore.Get(CurrentUri); if (digest2 != null) { string value2 = digest2.GenerateResponseHeader(this, Credentials); if (!string.IsNullOrEmpty(value2)) { SetHeader("Authorization", value2); } } break; } } } List <Cookie> list = (!IsCookiesEnabled) ? null : CookieJar.Get(CurrentUri); if (list == null || list.Count == 0) { list = customCookies; } else if (customCookies != null) { for (int i = 0; i < customCookies.Count; i++) { Cookie customCookie = customCookies[i]; int num2 = list.FindIndex((Cookie c) => c.Name.Equals(customCookie.Name)); if (num2 >= 0) { list[num2] = customCookie; } else { list.Add(customCookie); } } } if (list != null && list.Count > 0) { bool flag = true; string text = string.Empty; bool flag2 = HTTPProtocolFactory.IsSecureProtocol(CurrentUri); SupportedProtocols protocolFromUri = HTTPProtocolFactory.GetProtocolFromUri(CurrentUri); foreach (Cookie item in list) { if ((!item.IsSecure || (item.IsSecure && flag2)) && (!item.IsHttpOnly || (item.IsHttpOnly && protocolFromUri == SupportedProtocols.HTTP))) { if (!flag) { text += "; "; } else { flag = false; } text += item.ToString(); item.LastAccess = DateTime.UtcNow; } } SetHeader("Cookie", text); } if (callback != null) { foreach (KeyValuePair <string, List <string> > header in Headers) { callback(header.Key, header.Value); } } }
/// <summary> /// Try to fall back to next transport. If no more transport to try, it will return false. /// </summary> private bool TryFallbackTransport() { if (this.State == ConnectionStates.Connecting) { if (BufferedMessages != null) BufferedMessages.Clear(); // stop the current transport Transport.Stop(); Transport = null; switch(NextProtocolToTry) { #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS case SupportedProtocols.ServerSentEvents: Transport = new ServerSentEventsTransport(this); NextProtocolToTry = SupportedProtocols.HTTP; break; #endif case SupportedProtocols.HTTP: Transport = new PollingTransport(this); NextProtocolToTry = SupportedProtocols.Unknown; break; case SupportedProtocols.Unknown: return false; } TransportConnectionStartedAt = DateTime.UtcNow; Transport.Connect(); if (PingRequest != null) PingRequest.Abort(); return true; } return false; }
/// <summary> /// Writes out the Headers to the stream. /// </summary> private void SendHeaders(BinaryWriter stream) { if (!HasHeader("Host")) { SetHeader("Host", CurrentUri.Authority); } 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"); } long contentLength = -1; if (UploadStream == null) { byte[] entityBody = GetEntityBody(); contentLength = entityBody != null ? entityBody.Length : 0; if (RawData == null && (FormImpl != null || (FieldCollector != null && !FieldCollector.IsEmpty))) { SelectFormImplementation(); if (FormImpl != null) { FormImpl.PrepareRequest(this); } } } else { contentLength = UploadStreamLength; if (contentLength == -1) { SetHeader("Transfer-Encoding", "Chunked"); } if (!HasHeader("Content-Type")) { SetHeader("Content-Type", "application/octet-stream"); } } if (contentLength != -1 && !HasHeader("Content-Length")) { 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. // User added cookies are sent even when IsCookiesEnabled is set to false List <Cookie> cookies = IsCookiesEnabled ? CookieJar.Get(CurrentUri) : null; // Merge server sent cookies with user-set cookies if (cookies == null) { cookies = this.customCookies; } else if (this.customCookies != null) { cookies.AddRange(this.customCookies); } // 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; bool isSecureProtocolInUse = HTTPProtocolFactory.IsSecureProtocol(CurrentUri); SupportedProtocols protocolInUse = HTTPProtocolFactory.GetProtocolFromUri(CurrentUri); foreach (var cookie in cookies) { if ((!cookie.IsSecure || (cookie.IsSecure && isSecureProtocolInUse)) && (!cookie.IsHttpOnly || (cookie.IsHttpOnly && protocolInUse == 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); } } }