/// <summary> /// 获得返回 /// </summary> /// <param name="status"></param> /// <param name="bodyString"></param> /// <param name="contentType"></param> /// <returns></returns> private DefaultFullHttpResponse GetResponse(HttpResponseStatus status, string bodyString = "", string contentType = "text/html; charset=UTF-8") { byte[] body = Encoding.UTF8.GetBytes(bodyString); DefaultFullHttpResponse response = GetResponse(status, body, contentType); return(response); }
protected internal override bool handleResponse(IChannelHandlerContext ctx, object response) { if ((response is IFullHttpResponse) || (response is DefaultHttpResponse)) { DefaultHttpResponse def = (DefaultHttpResponse)response; if (def != null) { status = def.Status; inboundHeaders = def.Headers; } } bool finished = response is ILastHttpContent; if (finished) { if (status == null) { throw new HttpProxyConnectException(exceptionMessage("missing response"), inboundHeaders); } if (status.Code != 200) { throw new HttpProxyConnectException(exceptionMessage("status: " + status), inboundHeaders); } } return(finished); }
/// <summary> /// Create a new object to contain the response data /// </summary> /// <param name="streamId">The stream associated with the response</param> /// <param name="http2Headers">The initial set of HTTP/2 headers to create the response with</param> /// <param name="alloc">The <see cref="IByteBufferAllocator"/> to use to generate the content of the message</param> /// <param name="validateHttpHeaders"><c>true</c> to validate HTTP headers in the http-codec /// <para><c>false</c> not to validate HTTP headers in the http-codec</para></param> /// <returns>A new response object which represents headers/data</returns> /// <exception cref="Http2Exception">see <see cref="AddHttp2ToHttpHeaders(int, IHttp2Headers, IFullHttpMessage, bool)"/></exception> public static IFullHttpResponse ToFullHttpResponse(int streamId, IHttp2Headers http2Headers, IByteBufferAllocator alloc, bool validateHttpHeaders) { HttpResponseStatus status = ParseStatus(http2Headers.Status); // HTTP/2 does not define a way to carry the version or reason phrase that is included in an // HTTP/1.1 status line. IFullHttpResponse msg = new DefaultFullHttpResponse(DotNettyHttpVersion.Http11, status, alloc.Buffer(), validateHttpHeaders); try { AddHttp2ToHttpHeaders(streamId, http2Headers, msg, false); } catch (Http2Exception) { _ = msg.Release(); throw; } catch (Exception t) { _ = msg.Release(); ThrowHelper.ThrowStreamError_Http2ToHttp1HeadersConversionError(streamId, t); } return(msg); }
public HttpServerResponse(Version httpVersion, HttpResponseStatus status) { _headers = new List <IHttpHeader>(); HttpVersion = httpVersion; ResponseStatus = status; }
protected override bool HandleResponse(IChannelHandlerContext ctx, object response) { if (response is IHttpResponse) { if (_status != null) { throw new HttpProxyConnectException(ExceptionMessage("too many responses"), /*headers=*/ null); } IHttpResponse res = (IHttpResponse)response; _status = res.Status; _inboundHeaders = res.Headers; } bool finished = response is ILastHttpContent; if (finished) { if (_status == null) { throw new HttpProxyConnectException(ExceptionMessage("missing response"), _inboundHeaders); } if (_status.Code != 200) { throw new HttpProxyConnectException(ExceptionMessage("status: " + _status), _inboundHeaders); } } return(finished); }
internal HttpServerResponse(Version httpVersion, HttpResponseStatus status) { _headers = new List<IHttpHeader>(); HttpVersion = httpVersion; ResponseStatus = status; }
/// <summary> /// Process server response: /// <![CDATA[ /// HTTP/1.1 101 Switching Protocols /// Upgrade: websocket /// Connection: Upgrade /// Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= /// Sec-WebSocket-Protocol: chat /// ]]> /// </summary> /// <param name="response">HTTP response returned from the server for the request sent by beginOpeningHandshake00().</param> /// <exception cref="WebSocketHandshakeException">if handshake response is invalid.</exception> protected override void Verify(IFullHttpResponse response) { HttpResponseStatus status = HttpResponseStatus.SwitchingProtocols; HttpHeaders headers = response.Headers; if (!response.Status.Equals(status)) { ThrowHelper.ThrowWebSocketHandshakeException_InvalidHandshakeResponseGS(response); } if (!headers.TryGet(HttpHeaderNames.Upgrade, out ICharSequence upgrade) || !HttpHeaderValues.Websocket.ContentEqualsIgnoreCase(upgrade)) { ThrowHelper.ThrowWebSocketHandshakeException_InvalidHandshakeResponseU(upgrade); } if (!headers.ContainsValue(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade, true)) { _ = headers.TryGet(HttpHeaderNames.Connection, out upgrade); ThrowHelper.ThrowWebSocketHandshakeException_InvalidHandshakeResponseConn(upgrade); } if (!headers.TryGet(HttpHeaderNames.SecWebsocketAccept, out ICharSequence accept) || !accept.Equals(_expectedChallengeResponseString)) { ThrowHelper.ThrowWebSocketHandshakeException_InvalidChallenge(accept, _expectedChallengeResponseString); } }
public void ParseLineAsciiStringCustomCodeAndPhrase() { HttpResponseStatus customStatus = HttpResponseStatus.ParseLine(new AsciiString("612 FOO")); Assert.Equal(612, customStatus.Code); Assert.Equal("FOO", customStatus.ReasonPhrase); }
protected override void Verify(IFullHttpResponse response) { HttpResponseStatus status = HttpResponseStatus.SwitchingProtocols; HttpHeaders headers = response.Headers; if (!response.Status.Equals(status)) { throw new WebSocketHandshakeException($"Invalid handshake response getStatus: {response.Status}"); } if (headers.TryGet(HttpHeaderNames.Upgrade, out ICharSequence upgrade) || !HttpHeaderValues.Websocket.ContentEqualsIgnoreCase(upgrade)) { throw new WebSocketHandshakeException($"Invalid handshake response upgrade: {upgrade}"); } if (!headers.ContainsValue(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade, true)) { headers.TryGet(HttpHeaderNames.Connection, out upgrade); throw new WebSocketHandshakeException($"Invalid handshake response connection: {upgrade}"); } if (headers.TryGet(HttpHeaderNames.SecWebsocketAccept, out ICharSequence accept) || !accept.Equals(this.expectedChallengeResponseString)) { throw new WebSocketHandshakeException($"Invalid challenge. Actual: {accept}. Expected: {this.expectedChallengeResponseString}"); } }
/// <summary> /// Constructor. /// </summary> /// <param name="result"></param> // mbr - 2009-08-26 - added RespondingUrl... internal HttpResult(object rawResult, HttpResponseStatus responseStatus, HttpStatusCode status, Uri respondingUrl, WebException exception) { _rawResult = rawResult; _responseStatus = responseStatus; _status = status; _respondingUrl = respondingUrl; _exception = exception; }
private byte[] GetErrorBody(int errorCode) { var data = File.ReadAllText(Path.Combine(DirectoryRoot, "pages", "error.html")); data = data.Replace("{CODE}", errorCode.ToString()); data = data.Replace("{CODE-DESCRIPTION}", HttpResponseStatus.Get(errorCode)); data = data.Replace("{SERVER}", ServerName + " / " + Environment.OSVersion); return(Encoding.UTF8.GetBytes(data)); }
public void StatusInformationalTransferEncoding() { EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); for (int code = 100; code < 200; code++) { HttpResponseStatus status = HttpResponseStatus.ValueOf(code); AssertEmptyResponse(channel, status, HttpHeaderNames.TransferEncoding, code != 101); } Assert.False(channel.Finish()); }
public void StatusInformational() { EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); for (int code = 100; code < 200; code++) { HttpResponseStatus status = HttpResponseStatus.ValueOf(code); AssertEmptyResponse(channel, status, null, false); } Assert.False(channel.Finish()); }
/// <summary> /// 获得返回 /// </summary> /// <param name="status"></param> /// <param name="bodyString"></param> /// <param name="contentType"></param> /// <returns></returns> private DefaultFullHttpResponse GetResponse(HttpResponseStatus status, string bodyString = "", string contentType = "text/html; charset=UTF-8") { IByteBuffer body = Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(bodyString)); var response = new DefaultFullHttpResponse(HttpVersion.Http11, status, body); response.Headers.Set(HttpHeaderNames.AccessControlAllowOrigin, "*"); response.Headers.Set(HttpHeaderNames.ContentType, $"{contentType}"); response.Headers.Set(HttpHeaderNames.ContentLength, body.ReadableBytes); response.Headers.Set(HttpHeaderNames.Date, DateTime.Now); response.Headers.Set(HttpHeaderNames.Server, "Materal.ConDep"); return(response); }
/// <summary> /// 获得返回 /// </summary> /// <param name="status"></param> /// <param name="body"></param> /// <param name="contentType"></param> /// <returns></returns> private DefaultFullHttpResponse GetResponse(HttpResponseStatus status, byte[] body, string contentType = "text/html; charset=UTF-8") { IByteBuffer bodyBuffer = Unpooled.WrappedBuffer(body); var response = new DefaultFullHttpResponse(HttpVersion.Http11, status, bodyBuffer); response.Headers.Set(HttpHeaderNames.AccessControlAllowOrigin, "*"); response.Headers.Set(HttpHeaderNames.ContentType, $"{contentType}"); response.Headers.Set(HttpHeaderNames.ContentLength, bodyBuffer.ReadableBytes); response.Headers.Set(HttpHeaderNames.Date, DateTime.Now); response.Headers.Set(HttpHeaderNames.Server, "Materal.MicroFront"); return(response); }
protected internal virtual void SendError(ChannelHandlerContext ctx, string message , HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HttpVersion.Http11, status); response.SetHeader(HttpHeaders.Names.ContentType, "text/plain; charset=UTF-8"); // Put shuffle version into http header response.SetHeader(ShuffleHeader.HttpHeaderName, ShuffleHeader.DefaultHttpHeaderName ); response.SetHeader(ShuffleHeader.HttpHeaderVersion, ShuffleHeader.DefaultHttpHeaderVersion ); response.SetContent(ChannelBuffers.CopiedBuffer(message, CharsetUtil.Utf8)); // Close the connection as soon as the error message is sent. ctx.GetChannel().Write(response).AddListener(ChannelFutureListener.Close); }
public HttpResponse(HttpResponseStatus status, string contentType = DEFAULT_CONTENT_TYPE, string charset = DEFAULT_CHARSET) { try { Encoding = Encoding.GetEncoding(charset); } catch { Encoding = Encoding.UTF8; } Cookies = new HttpCookies(); Headers = new HttpResponseHeaders(); Headers[HttpResponseHeaders.Date] = DateTime.Now.ToUniversalTime().ToString("r"); Headers[HttpResponseHeaders.ContentType] = string.Format("{0}; charset={1}", contentType, charset); Status = status; }
private static void AssertEmptyResponse(EmbeddedChannel channel, HttpResponseStatus status, AsciiString headerName, bool headerStripped) { var response = new DefaultHttpResponse(HttpVersion.Http11, status); if (HttpHeaderNames.ContentLength.ContentEquals(headerName)) { response.Headers.Set(headerName, "0"); } else if (HttpHeaderNames.TransferEncoding.ContentEquals(headerName)) { response.Headers.Set(headerName, HttpHeaderValues.Chunked); } Assert.True(channel.WriteOutbound(response)); Assert.True(channel.WriteOutbound(EmptyLastHttpContent.Default)); var buffer = channel.ReadOutbound <IByteBuffer>(); StringBuilder responseText = new StringBuilder(); responseText.Append(HttpVersion.Http11.ToString()).Append(' ').Append(status.ToString()).Append("\r\n"); if (!headerStripped && headerName != null) { responseText.Append(headerName).Append(": "); if (HttpHeaderNames.ContentLength.ContentEquals(headerName)) { responseText.Append('0'); } else { responseText.Append(HttpHeaderValues.Chunked.ToString()); } responseText.Append("\r\n"); } responseText.Append("\r\n"); Assert.Equal(responseText.ToString(), buffer.ToString(Encoding.ASCII)); buffer.Release(); buffer = channel.ReadOutbound <IByteBuffer>(); buffer.Release(); }
/// <summary> /// 基础返回 /// </summary> /// <param name="status">状态吗</param> /// <param name="body"></param> /// <param name="headers"></param> private IFullHttpResponse GetHttpResponse(HttpResponseStatus status, byte[] body, Dictionary <AsciiString, object> headers) { DefaultFullHttpResponse result; if (body != null && body.Length > 0) { IByteBuffer bodyBuffer = Unpooled.WrappedBuffer(body); result = new DefaultFullHttpResponse(HttpVersion.Http11, status, bodyBuffer); } else { result = new DefaultFullHttpResponse(HttpVersion.Http11, status); } foreach ((AsciiString key, object value) in headers) { result.Headers.Set(key, value); } return(result); }
protected override void Encode(IChannelHandlerContext ctx, IResponseMessage msg, List <object> output) { var buf = msg.ToBodyBuffer(); var status = HttpResponseStatus.ValueOf(Convert.ToInt32(msg.Headers.Get(Constants.ResponseStatusCode))); var response = new DefaultFullHttpResponse(HttpVersion.Http11, status, buf, false); HttpHeaders headers = response.Headers; headers.Set(HttpHeaderNames.Server, AsciiString.Cached(Options.Name)); headers.Set(HttpHeaderNames.Date, this.date); headers.Set(HttpHeaderNames.ContentLength, AsciiString.Cached($"{msg.Headers.Get(Constants.Headers.ContentLength)}")); if (Convert.ToInt32(msg.Headers.Get(Constants.Headers.ContractId)) == (int)ContractType.HandShake) { headers.Set(HttpHeaderNames.ContentType, AsciiString.Cached("text/plain")); } else { headers.Set(HttpHeaderNames.ContentType, AsciiString.Cached(msg.Headers.Get(Constants.Headers.ContentType))); } output.Add(response); }
static void SendHttpResponse(IChannelHandlerContext ctx, IFullHttpRequest req, IFullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). HttpResponseStatus responseStatus = res.Status; if (responseStatus.Code != 200) { ByteBufferUtil.WriteUtf8(res.Content, responseStatus.ToString()); HttpUtil.SetContentLength(res, res.Content.ReadableBytes); } // Send the response and close the connection if necessary. var keepAlive = HttpUtil.IsKeepAlive(req) && responseStatus.Code == 200; HttpUtil.SetKeepAlive(res, keepAlive); var future = ctx.WriteAndFlushAsync(res); if (!keepAlive) { future.CloseOnComplete(ctx.Channel); } }
/// <summary> /// Apply HTTP/2 rules while translating status code to <see cref="HttpResponseStatus"/> /// </summary> /// <param name="status">The status from an HTTP/2 frame</param> /// <returns>The HTTP/1.x status</returns> /// <exception cref="Http2Exception">If there is a problem translating from HTTP/2 to HTTP/1.x</exception> public static HttpResponseStatus ParseStatus(ICharSequence status) { HttpResponseStatus result = null; try { result = HttpResponseStatus.ParseLine(status); if (result == HttpResponseStatus.SwitchingProtocols) { ThrowHelper.ThrowConnectionError_InvalidHttp2StatusCode(result.Code); } } catch (Http2Exception) { throw; } catch (Exception t) { ThrowHelper.ThrowConnectionError_UnrecognizedHttpStatusCode(t, status); } return(result); }
public static HttpServerResponse Create(Version httpVersion, HttpResponseStatus status) { return new HttpServerResponse(httpVersion, status); }
public static HttpServerResponse Create(HttpResponseStatus status) { return Create(new Version(1, 1), status); }
public ByteResponse Execute(string str, string clientIp) { HttpRequest requestObject = null; HttpResponse httpResponse = null; try { requestObject = new HttpRequest(str); } catch { httpResponse = new NotFound().HttpResponse; } var virtualHost = VirtualHostList.GetVirtualHost(requestObject != null ? requestObject.Host : ""); var request = new Request(requestObject, virtualHost); var accessLogHandler = new AccessLogHandler(Path.Combine(DirectoryRoot, "logs", virtualHost.AccessLog), clientIp, requestObject != null ? requestObject.UserAgent : ""); if (httpResponse == null) { httpResponse = ChainControllerHandler.Execute(request).HttpResponse; } accessLogHandler.WriteInfo(request.Object.Method + " /" + request.Object.Uri.Url + " " + HttpResponseStatus.Get(httpResponse.HttpStatusCode)); httpResponse.Headers.Add("Server", HttpServer.HttpServerName); httpResponse.Headers.Add("Date", new HttpDate(DateTime.Now).ToString()); if (httpResponse.Content.IncludeBody && httpResponse.Content.Data == null) { httpResponse.Content.Data = GetErrorBody(httpResponse.HttpStatusCode); } return(new ByteResponse(httpResponse.GetBytes(), request.Object.KeepAlive)); }
public static HttpServerResponse Create(Version httpVersion, HttpResponseStatus status) { return(new HttpServerResponse(httpVersion, status)); }
/// <summary> /// 获得Http返回 /// </summary> /// <param name="status"></param> /// <param name="body"></param> /// <param name="headers"></param> /// <returns></returns> protected IFullHttpResponse GetHttpResponse(HttpResponseStatus status, string body, Dictionary <AsciiString, object> headers) { byte[] bodyData = string.IsNullOrEmpty(body) ? new byte[0] : Encoding.UTF8.GetBytes(body); return(GetHttpResponse(status, bodyData, headers)); }
/// <summary> /// 获得Http返回 /// </summary> /// <param name="status"></param> /// <param name="headers"></param> /// <returns></returns> protected IFullHttpResponse GetHttpResponse(HttpResponseStatus status, Dictionary <AsciiString, object> headers) { return(GetHttpResponse(status, string.Empty, headers)); }
/// <summary> /// 获得Http返回 /// </summary> /// <param name="status"></param> /// <param name="body"></param> /// <returns></returns> protected IFullHttpResponse GetHttpResponse(HttpResponseStatus status, byte[] body) { Dictionary <AsciiString, object> headers = GetDefaultHeaders("application/octet-stream"); return(GetHttpResponse(status, body, headers)); }
/// <summary> /// 获得Http返回 /// </summary> /// <param name="status"></param> /// <param name="body"></param> /// <returns></returns> protected IFullHttpResponse GetHttpResponse(HttpResponseStatus status, string body) { Dictionary <AsciiString, object> headers = GetDefaultHeaders("text/plain;charset=UTF-8"); return(GetHttpResponse(status, body, headers)); }
/// <summary> /// 获得Http返回 /// </summary> /// <param name="status"></param> /// <returns></returns> protected IFullHttpResponse GetHttpResponse(HttpResponseStatus status) { Dictionary <AsciiString, object> headers = GetDefaultHeaders(); return(GetHttpResponse(status, headers)); }
public static HttpServerResponse Create(HttpResponseStatus status) { return(Create(new Version(1, 1), status)); }
public void PipelineKeepAlive(bool isKeepAliveResponseExpected, HttpVersion httpVersion, HttpResponseStatus responseStatus, string sendKeepAlive, int setSelfDefinedMessageLength, ICharSequence setResponseConnection) { var channel = new EmbeddedChannel(new HttpServerKeepAliveHandler()); var firstRequest = new DefaultFullHttpRequest(httpVersion, HttpMethod.Get, "/v1/foo/bar"); HttpUtil.SetKeepAlive(firstRequest, true); var secondRequest = new DefaultFullHttpRequest(httpVersion, HttpMethod.Get, "/v1/foo/bar"); HttpUtil.SetKeepAlive(secondRequest, RequestKeepAlive.Equals(sendKeepAlive)); var finalRequest = new DefaultFullHttpRequest(httpVersion, HttpMethod.Get, "/v1/foo/bar"); HttpUtil.SetKeepAlive(finalRequest, false); var response = new DefaultFullHttpResponse(httpVersion, responseStatus); var informationalResp = new DefaultFullHttpResponse(httpVersion, Processing); HttpUtil.SetKeepAlive(response, true); HttpUtil.SetContentLength(response, 0); HttpUtil.SetKeepAlive(informationalResp, true); Assert.True(channel.WriteInbound(firstRequest, secondRequest, finalRequest)); var requestForwarded = channel.ReadInbound <object>(); Assert.Equal(firstRequest, requestForwarded); ReferenceCountUtil.Release(requestForwarded); channel.WriteAndFlushAsync(response.Duplicate().Retain()).Wait(TimeSpan.FromSeconds(1)); var firstResponse = channel.ReadOutbound <IHttpResponse>(); Assert.True(channel.Open); Assert.True(HttpUtil.IsKeepAlive(firstResponse)); ReferenceCountUtil.Release(firstResponse); requestForwarded = channel.ReadInbound <object>(); Assert.Equal(secondRequest, requestForwarded); ReferenceCountUtil.Release(requestForwarded); channel.WriteAndFlushAsync(informationalResp).Wait(TimeSpan.FromSeconds(1)); var writtenInfoResp = channel.ReadOutbound <IHttpResponse>(); Assert.True(channel.Open); Assert.True(HttpUtil.IsKeepAlive(writtenInfoResp)); ReferenceCountUtil.Release(writtenInfoResp); if (!CharUtil.IsNullOrEmpty(setResponseConnection)) { response.Headers.Set(HttpHeaderNames.Connection, setResponseConnection); } else { response.Headers.Remove(HttpHeaderNames.Connection); } SetupMessageLength(setSelfDefinedMessageLength, response); channel.WriteAndFlushAsync(response.Duplicate().Retain()).Wait(TimeSpan.FromSeconds(1)); var secondResponse = channel.ReadOutbound <IHttpResponse>(); Assert.Equal(isKeepAliveResponseExpected, channel.Open); Assert.Equal(isKeepAliveResponseExpected, HttpUtil.IsKeepAlive(secondResponse)); ReferenceCountUtil.Release(secondResponse); requestForwarded = channel.ReadInbound <object>(); Assert.Equal(finalRequest, requestForwarded); ReferenceCountUtil.Release(requestForwarded); if (isKeepAliveResponseExpected) { channel.WriteAndFlushAsync(response).Wait(TimeSpan.FromSeconds(1)); var finalResponse = channel.ReadOutbound <IHttpResponse>(); Assert.False(channel.Open); Assert.False(HttpUtil.IsKeepAlive(finalResponse)); } ReferenceCountUtil.Release(response); Assert.False(channel.FinishAndReleaseAll()); }
public HttpStatusException(HttpResponseStatus responseCode) : base(responseCode.ToResponseHeaderText()) { ResponseCode = responseCode; }
protected internal virtual void SendError(ChannelHandlerContext ctx, HttpResponseStatus status) { this.SendError(ctx, string.Empty, status); }