/** * Sends a continue response using blocking IO * * @param exchange The exchange */ public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException { if (!exchange.isResponseChannelAvailable()) { throw UndertowMessages.MESSAGES.cannotSendContinueResponse(); } if(exchange.getAttachment(ALREADY_SENT) != null) { return; } HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange); exchange.putAttachment(ALREADY_SENT, true); newExchange.setStatusCode(StatusCodes.CONTINUE); newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0); newExchange.startBlocking(); newExchange.getOutputStream().close(); newExchange.getInputStream().close(); }
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if(!exchange.getRequestHeaders().contains(Headers.HOST)) { exchange.getRequestHeaders().put(Headers.HOST, defaultHost + ":" + exchange.getDestinationAddress().getPort()); } next.handleRequest(exchange); } }
/** * Send a simple response string. * * @param exchange the http server exchange * @param response the response string */ static void sendResponse(final HttpServerExchange exchange, final String response) { exchange.setStatusCode(StatusCodes.OK); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); final Sender sender = exchange.getResponseSender(); UndertowLogger.ROOT_LOGGER.mcmpSendingResponse(exchange.getSourceAddress(), exchange.getStatusCode(), exchange.getResponseHeaders(), response); sender.send(response); }
@Override public void onError(Throwable ex) { logger.trace(this.logPrefix + "Failed to complete: " + ex.getMessage()); if (this.exchange.isResponseStarted()) { try { logger.debug(this.logPrefix + "Closing connection"); this.exchange.getConnection().close(); } catch (IOException ex2) { // ignore } } else { logger.debug(this.logPrefix + "Setting HttpServerExchange status to 500 Server Error"); this.exchange.setStatusCode(500); this.exchange.endExchange(); } }
@Override public void error(HttpServerExchange exchange, IOException e) { if(!exchange.isResponseStarted()) { exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); } exchange.setPersistent(false); UndertowLogger.REQUEST_IO_LOGGER.ioException(e); exchange.endExchange(); } };
@Override public boolean handleDefaultResponse(final HttpServerExchange exchange) { exchange.getResponseHeaders().put(Headers.LOCATION, location); exchange.setStatusCode(StatusCodes.FOUND); exchange.endExchange(); return true; } });
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { final HttpString method = exchange.getRequestMethod(); if(!handlesMethod(method)) { next.handleRequest(exchange); return; final InetSocketAddress addr = exchange.getConnection().getLocalAddress(InetSocketAddress.class); if (!addr.isUnresolved() && addr.getPort() != config.getManagementSocketAddress().getPort() || !Arrays.equals(addr.getAddress().getAddress(), config.getManagementSocketAddress().getAddress().getAddress())) { next.handleRequest(exchange); return; if(exchange.isInIoThread()) { exchange.dispatch(this); return; handleRequest(method, exchange); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.failedToProcessManagementReq(e); exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); final Sender sender = exchange.getResponseSender(); sender.send("failed to process management request");
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseHeaders().put( Headers.CONTENT_TYPE, "application/json"); Map<String, Object> resMap = new HashMap<>(); resMap.put("access_token", JwtIssuer.getJwt(mockClaims())); resMap.put("token_type", "bearer"); resMap.put("expires_in", 600); exchange.getResponseSender().send(ByteBuffer.wrap( Config.getInstance().getMapper().writeValueAsBytes( resMap))); }
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html"); exchange.setResponseCode(StatusCodes.OK); exchange.getResponseSender().send(html); exchange.endExchange(); } }
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { final String urlWithIdAndToken = exchange.getRequestURL() + "?" + exchange.getQueryString(); logger.log(Level.INFO, "Got a request to " + urlWithIdAndToken); queue.add(urlWithIdAndToken); TimeUnit.SECONDS.sleep(2); final OAuthWebResponse oauthWebResponse = (OAuthWebResponse) queue.take(); logger.log(Level.INFO, "Got an oauth response with code " + oauthWebResponse.getCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html"); exchange.setResponseCode(oauthWebResponse.getCode()); exchange.getResponseSender().send(oauthWebResponse.getBody()); exchange.endExchange(); queue.add(Boolean.TRUE); } }
/** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } if(!getRequestHeaders().contains(Headers.UPGRADE)) { throw UndertowMessages.MESSAGES.notAnUpgradeRequest(); } UndertowLogger.REQUEST_LOGGER.debugf("Upgrading request %s", this); connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); getResponseHeaders().put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; }
@Override public boolean handleDefaultResponse(final HttpServerExchange exchange) { if (!exchange.isResponseChannelAvailable()) { return false; } Set<Integer> codes = responseCodes; if (codes == null ? exchange.getStatusCode() >= StatusCodes.BAD_REQUEST : codes.contains(Integer.valueOf(exchange.getStatusCode()))) { final String errorPage = "<html><head><title>Error</title></head><body>" + exchange.getStatusCode() + " - " + StatusCodes.getReason(exchange.getStatusCode()) + "</body></html>"; exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + errorPage.length()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html"); Sender sender = exchange.getResponseSender(); sender.send(errorPage); return true; } return false; } };
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (isConfidential(exchange) || !confidentialityRequired(exchange)) { next.handleRequest(exchange); } else { try { URI redirectUri = getRedirectURI(exchange); UndertowLogger.SECURITY_LOGGER.debugf("Redirecting request %s to %s to meet confidentiality requirements", exchange, redirectUri); exchange.setStatusCode(StatusCodes.FOUND); exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri.toString()); } catch (Exception e) { UndertowLogger.REQUEST_LOGGER.exceptionProcessingRequest(e); exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); } exchange.endExchange(); } }
@Override public void receiveFullBytes(final FullBytesCallback callback, final ErrorCallback errorCallback) { if(done) { throw UndertowMessages.MESSAGES.requestBodyAlreadyRead(); throw UndertowMessages.MESSAGES.argumentCannotBeNull("callback"); if (exchange.isRequestComplete()) { callback.handle(exchange, EMPTY_BYTE_ARRAY); return; String contentLengthString = exchange.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH); long contentLength; final ByteArrayOutputStream sb; try (PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().getArrayBackedPool().allocate()) { while ((s = inputStream.read(pooled.getBuffer().array(), pooled.getBuffer().arrayOffset(), pooled.getBuffer().remaining())) > 0) { sb.write(pooled.getBuffer().array(), pooled.getBuffer().arrayOffset(), s);
public void handleRequest(final HttpServerExchange exchange) throws Exception { final List<String> upgradeStrings = exchange.getRequestHeaders().get(Headers.UPGRADE); if (upgradeStrings != null && exchange.getRequestMethod().equals(Methods.GET)) { for (String string : upgradeStrings) { final List<Holder> holders = handlers.get(string); if (holders != null) { for (Holder holder : holders) { final HttpUpgradeListener listener = holder.listener; if (holder.handshake != null) { if (!holder.handshake.handleUpgrade(exchange)) { //handshake did not match, try again continue; } } exchange.upgradeChannel(string,listener); exchange.endExchange(); return; } } } } nonUpgradeHandler.handleRequest(exchange); }
/** * Send an error message. * * @param type the error type * @param errString the error string * @param exchange the http server exchange */ static void processError(String type, String errString, HttpServerExchange exchange) { exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.getResponseHeaders().add(new HttpString("Version"), VERSION_PROTOCOL); exchange.getResponseHeaders().add(new HttpString("Type"), type); exchange.getResponseHeaders().add(new HttpString("Mess"), errString); exchange.endExchange(); UndertowLogger.ROOT_LOGGER.mcmpProcessingError(type, errString); }
@Override public void run() { try { final FormData existing = exchange.getAttachment(FORM_DATA); if (existing != null) { exchange.dispatch(SameThreadExecutor.INSTANCE, handler); return; PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate(); try { while (true) { } else if (c == -1) { if (parser.isComplete()) { exchange.putAttachment(FORM_DATA, data); exchange.dispatch(SameThreadExecutor.INSTANCE, handler); } else { UndertowLogger.REQUEST_IO_LOGGER.ioException(UndertowMessages.MESSAGES.connectionTerminatedReadingMultiPartData()); exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.endExchange(); UndertowLogger.REQUEST_IO_LOGGER.ioException(e); exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.endExchange(); } finally { pooled.close(); UndertowLogger.REQUEST_IO_LOGGER.debug("Exception parsing data", e); exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.endExchange();
@Override public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) { if(silent) { //if this is silent we only send a challenge if the request contained auth headers //otherwise we assume another method will send the challenge String authHeader = exchange.getRequestHeaders().getFirst(AUTHORIZATION); if(authHeader == null) { return ChallengeResult.NOT_SENT; } } exchange.getResponseHeaders().add(WWW_AUTHENTICATE, challenge); UndertowLogger.SECURITY_LOGGER.debugf("Sending basic auth challenge %s for %s", challenge, exchange); return new ChallengeResult(true, UNAUTHORIZED); }
private static StreamSinkConduit handleExplicitTransferEncoding(HttpServerExchange exchange, StreamSinkConduit channel, ConduitListener<StreamSinkConduit> finishListener, HeaderMap responseHeaders, String transferEncodingHeader, boolean headRequest) { HttpString transferEncoding = new HttpString(transferEncodingHeader); if (transferEncoding.equals(Headers.CHUNKED)) { if (headRequest) { return channel; } Boolean preChunked = exchange.getAttachment(HttpAttachments.PRE_CHUNKED_RESPONSE); if(preChunked != null && preChunked) { return new PreChunkedStreamSinkConduit(channel, finishListener, exchange); } else { return new ChunkedStreamSinkConduit(channel, exchange.getConnection().getByteBufferPool(), true, !exchange.isPersistent(), responseHeaders, finishListener, exchange); } } else { if (headRequest) { return channel; } log.trace("Cancelling persistence because response is identity with no content length"); // make it not persistent - very unfortunate for the next request handler really... exchange.setPersistent(false); responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString()); return new FinishableStreamSinkConduit(channel, terminateResponseListener(exchange)); } }
/** * If the process is OK, then add 200 HTTP status and its "OK" phrase * * @throws IOException */ static void processOK(HttpServerExchange exchange) throws IOException { exchange.setStatusCode(StatusCodes.OK); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.endExchange(); }