use of io.undertow.server.HttpServerExchange in project wildfly by wildfly.
the class HTTPSchemeServerAuthModule method validateRequest.
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
HttpServerExchange exchange = (HttpServerExchange) messageInfo.getMap().get(JASPICAuthenticationMechanism.HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY);
SecurityContext securityContext = (SecurityContext) messageInfo.getMap().get(JASPICAuthenticationMechanism.SECURITY_CONTEXT_ATTACHMENT_KEY);
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
List<AuthenticationMechanism> mechanisms = src.getDeployment().getAuthenticationMechanisms();
try {
boolean success = false;
for (AuthenticationMechanism mechanism : mechanisms) {
AuthenticationMechanism.AuthenticationMechanismOutcome result = mechanism.authenticate(exchange, securityContext);
if (result == AUTHENTICATED) {
success = true;
break;
} else if (result == NOT_AUTHENTICATED) {
break;
}
}
if (!success) {
String mandatory = (String) messageInfo.getMap().get("javax.security.auth.message.MessagePolicy.isMandatory");
if (mandatory != null && mandatory.toLowerCase().equals("false")) {
return SUCCESS;
} else {
for (AuthenticationMechanism mechanism : mechanisms) {
AuthenticationMechanism.ChallengeResult challengeResult = mechanism.sendChallenge(exchange, securityContext);
if (challengeResult.getDesiredResponseCode() != null) {
exchange.setResponseCode(challengeResult.getDesiredResponseCode());
}
if (exchange.isResponseComplete()) {
break;
}
}
return SEND_CONTINUE;
}
}
} catch (Exception e) {
UndertowLogger.ROOT_LOGGER.debug(e);
throw new AuthException("Could not validateRequest using mechanisms [" + mechanisms + ".");
}
return SUCCESS;
}
use of io.undertow.server.HttpServerExchange in project undertow by undertow-io.
the class DefaultServlet method serveFileBlocking.
private void serveFileBlocking(final HttpServletRequest req, final HttpServletResponse resp, final Resource resource) throws IOException {
final ETag etag = resource.getETag();
final Date lastModified = resource.getLastModified();
if (req.getDispatcherType() != DispatcherType.INCLUDE) {
if (!ETagUtils.handleIfMatch(req.getHeader(Headers.IF_MATCH_STRING), etag, false) || !DateUtils.handleIfUnmodifiedSince(req.getHeader(Headers.IF_UNMODIFIED_SINCE_STRING), lastModified)) {
resp.setStatus(StatusCodes.PRECONDITION_FAILED);
return;
}
if (!ETagUtils.handleIfNoneMatch(req.getHeader(Headers.IF_NONE_MATCH_STRING), etag, true) || !DateUtils.handleIfModifiedSince(req.getHeader(Headers.IF_MODIFIED_SINCE_STRING), lastModified)) {
resp.setStatus(StatusCodes.NOT_MODIFIED);
return;
}
}
//we are going to proceed. Set the appropriate headers
if (resp.getContentType() == null) {
if (!resource.isDirectory()) {
final String contentType = deployment.getServletContext().getMimeType(resource.getName());
if (contentType != null) {
resp.setContentType(contentType);
} else {
resp.setContentType("application/octet-stream");
}
}
}
if (lastModified != null) {
resp.setHeader(Headers.LAST_MODIFIED_STRING, resource.getLastModifiedString());
}
if (etag != null) {
resp.setHeader(Headers.ETAG_STRING, etag.toString());
}
ByteRange.RangeResponseResult rangeResponse = null;
long start = -1, end = -1;
try {
//only set the content length if we are using a stream
//if we are using a writer who knows what the length will end up being
//todo: if someone installs a filter this can cause problems
//not sure how best to deal with this
//we also can't deal with range requests if a writer is in use
Long contentLength = resource.getContentLength();
if (contentLength != null) {
resp.getOutputStream();
if (contentLength > Integer.MAX_VALUE) {
resp.setContentLengthLong(contentLength);
} else {
resp.setContentLength(contentLength.intValue());
}
if (resource instanceof RangeAwareResource && ((RangeAwareResource) resource).isRangeSupported() && resource.getContentLength() != null) {
resp.setHeader(Headers.ACCEPT_RANGES_STRING, "bytes");
//TODO: figure out what to do with the content encoded resource manager
final ByteRange range = ByteRange.parse(req.getHeader(Headers.RANGE_STRING));
if (range != null) {
rangeResponse = range.getResponseResult(resource.getContentLength(), req.getHeader(Headers.IF_RANGE_STRING), resource.getLastModified(), resource.getETag() == null ? null : resource.getETag().getTag());
if (rangeResponse != null) {
start = rangeResponse.getStart();
end = rangeResponse.getEnd();
resp.setStatus(rangeResponse.getStatusCode());
resp.setHeader(Headers.CONTENT_RANGE_STRING, rangeResponse.getContentRange());
long length = rangeResponse.getContentLength();
if (length > Integer.MAX_VALUE) {
resp.setContentLengthLong(length);
} else {
resp.setContentLength((int) length);
}
if (rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
return;
}
}
}
}
}
} catch (IllegalStateException e) {
}
final boolean include = req.getDispatcherType() == DispatcherType.INCLUDE;
if (!req.getMethod().equals(Methods.HEAD_STRING)) {
HttpServerExchange exchange = SecurityActions.requireCurrentServletRequestContext().getOriginalRequest().getExchange();
if (rangeResponse == null) {
resource.serve(exchange.getResponseSender(), exchange, completionCallback(include));
} else {
((RangeAwareResource) resource).serveRange(exchange.getResponseSender(), exchange, start, end, completionCallback(include));
}
}
}
use of io.undertow.server.HttpServerExchange in project spring-framework by spring-projects.
the class UndertowRequestUpgradeStrategy method upgrade.
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
ServerHttpRequest request = exchange.getRequest();
Assert.isInstanceOf(UndertowServerHttpRequest.class, request, "UndertowServerHttpRequest required");
HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange();
Set<String> protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet());
Hybi13Handshake handshake = new Hybi13Handshake(protocols, false);
List<Handshake> handshakes = Collections.singletonList(handshake);
URI url = request.getURI();
HttpHeaders headers = request.getHeaders();
Mono<Principal> principal = exchange.getPrincipal();
HandshakeInfo info = new HandshakeInfo(url, headers, principal, subProtocol);
DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
try {
DefaultCallback callback = new DefaultCallback(info, handler, bufferFactory);
new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange);
} catch (Exception ex) {
return Mono.error(ex);
}
return Mono.empty();
}
use of io.undertow.server.HttpServerExchange in project camel by apache.
the class UndertowConsumer method handleRequest.
@Override
public void handleRequest(HttpServerExchange httpExchange) throws Exception {
HttpString requestMethod = httpExchange.getRequestMethod();
if (Methods.OPTIONS.equals(requestMethod) && !getEndpoint().isOptionsEnabled()) {
String allowedMethods;
if (getEndpoint().getHttpMethodRestrict() != null) {
allowedMethods = "OPTIONS," + getEndpoint().getHttpMethodRestrict();
} else {
allowedMethods = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
}
//return list of allowed methods in response headers
httpExchange.setStatusCode(StatusCodes.OK);
httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt"));
httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_LENGTH, 0);
httpExchange.getResponseHeaders().put(Headers.ALLOW, allowedMethods);
httpExchange.getResponseSender().close();
return;
}
//perform blocking operation on exchange
if (httpExchange.isInIoThread()) {
httpExchange.dispatch(this);
return;
}
//create new Exchange
//binding is used to extract header and payload(if available)
Exchange camelExchange = getEndpoint().createExchange(httpExchange);
//Unit of Work to process the Exchange
createUoW(camelExchange);
try {
getProcessor().process(camelExchange);
} catch (Exception e) {
getExceptionHandler().handleException(e);
} finally {
doneUoW(camelExchange);
}
Object body = getResponseBody(httpExchange, camelExchange);
TypeConverter tc = getEndpoint().getCamelContext().getTypeConverter();
if (body == null) {
LOG.trace("No payload to send as reply for exchange: " + camelExchange);
httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt"));
httpExchange.getResponseSender().send("No response available");
} else {
ByteBuffer bodyAsByteBuffer = tc.convertTo(ByteBuffer.class, body);
httpExchange.getResponseSender().send(bodyAsByteBuffer);
}
httpExchange.getResponseSender().close();
}
use of io.undertow.server.HttpServerExchange in project runwar by cfmlprojects.
the class Start method main.
public static void main(String[] args) throws Exception {
System.setProperty("log4j.configuration", "log4j.filelog.xml");
ServerOptions serverOptions = CommandLineHandler.parseLogArguments(args);
LoggerFactory.init(serverOptions);
if (args.length == 0) {
if (new File("server.json").exists()) {
serverOptions = new ConfigParser(new File("server.json")).getServerOptions();
} else {
// print usage
serverOptions = CommandLineHandler.parseArguments(args);
}
} else {
serverOptions = CommandLineHandler.parseArguments(args);
}
if (serverOptions.getLoadBalance() != null && serverOptions.getLoadBalance().length > 0) {
final List<String> balanceHosts = new ArrayList<String>();
RunwarLogger.LOG.info("Initializing...");
final LoadBalancingProxyClient loadBalancer = new LoadBalancingProxyClient();
for (String balanceHost : serverOptions.getLoadBalance()) {
if (serverOptions.getWarFile() != null) {
RunwarLogger.LOG.info("Starting instance of " + serverOptions.getWarFile().getParent() + "...");
launchServer(balanceHost, serverOptions);
}
loadBalancer.addHost(new URI(balanceHost));
balanceHosts.add(balanceHost);
RunwarLogger.LOG.info("Added balanced host: " + balanceHost);
Thread.sleep(3000);
}
int port = serverOptions.getPortNumber();
loadBalancer.setConnectionsPerThread(20);
RunwarLogger.LOG.info("Hosts loaded");
RunwarLogger.LOG.info("Starting load balancer on 127.0.0.1 port " + port + "...");
ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancer).setMaxRequestTime(30000).setNext(ResponseCodeHandler.HANDLE_404).build();
Undertow reverseProxy = Undertow.builder().addHttpListener(port, "localhost").setIoThreads(4).setHandler(proxyHandler).build();
reverseProxy.start();
RunwarLogger.LOG.info("View balancer admin on http://127.0.0.1:9080");
Undertow adminServer = Undertow.builder().addHttpListener(9080, "localhost").setHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
if (exchange.getQueryParameters().get("addHost") != null) {
String balanceHost = URLDecoder.decode(exchange.getQueryParameters().get("addHost").toString(), "UTF-8");
balanceHost = balanceHost.replaceAll("]|\\[", "");
loadBalancer.addHost(new URI(balanceHost));
balanceHosts.add(balanceHost);
}
if (exchange.getQueryParameters().get("removeHost") != null) {
String balanceHost = URLDecoder.decode(exchange.getQueryParameters().get("removeHost").toString(), "UTF-8");
balanceHost = balanceHost.replaceAll("]|\\[", "");
loadBalancer.removeHost(new URI(balanceHost));
balanceHosts.remove(balanceHost);
}
String response = "";
// response += URLDecoder.decode(exchange.getQueryString(),"UTF-8");
for (String balanceHost : balanceHosts) {
String[] schemeHostAndPort = balanceHost.split(":");
String host = schemeHostAndPort[1].replaceAll("^//", "");
int port = schemeHostAndPort.length > 2 ? Integer.parseInt(schemeHostAndPort[2]) : 80;
response += balanceHost + " <a href='?removeHost=" + balanceHost + "'>remove</a> Listening: " + serverListening(host, port) + "<br/>";
}
exchange.getResponseSender().send("<h3>Balanced Hosts</h3><form action='?'> Add Host:<input type='text' name='addHost' placeholder='http://127.0.0.1:7070'><input type='submit'></form>" + response);
}
}).build();
adminServer.start();
RunwarLogger.LOG.info("Started load balancer.");
} else {
Server server = new Server();
try {
server.startServer(serverOptions);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
Aggregations