@Nullable private Request convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage req) throws Throwable { final String mappedPath = ctx.mappedPath(); final Request coyoteReq = new Request(); coyoteReq.scheme().setString(req.scheme()); coyoteReq.remoteAddr().setString(remoteAddr.getAddress().getHostAddress()); coyoteReq.remoteHost().setString(remoteAddr.getHostString()); coyoteReq.setRemotePort(remoteAddr.getPort()); coyoteReq.localAddr().setString(localAddr.getAddress().getHostAddress()); coyoteReq.localName().setString(hostName()); coyoteReq.setLocalPort(localAddr.getPort()); coyoteReq.serverName().setString(hostHeader); } else { coyoteReq.serverName().setString(hostHeader.substring(0, colonPos)); try { final int port = Integer.parseInt(hostHeader.substring(colonPos + 1)); coyoteReq.setServerPort(port); } catch (NumberFormatException e) { coyoteReq.method().setString(method.name()); coyoteReq.requestURI().setBytes(uriBytes, 0, uriBytes.length); coyoteReq.queryString().setString(ctx.query()); final MimeHeaders cHeaders = coyoteReq.getMimeHeaders();
@Override public void dispatch(ServletContext context, String path) { synchronized (asyncContextLock) { if (log.isDebugEnabled()) { logDebug("dispatch "); if (dispatch != null) { throw new IllegalStateException( sm.getString("asyncContextImpl.dispatchingStarted")); if (request.getAttribute(ASYNC_REQUEST_URI)==null) { request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI()); request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath()); request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath()); if (!(requestDispatcher instanceof AsyncDispatcher)) { throw new UnsupportedOperationException( sm.getString("asyncContextImpl.noAsyncDispatcher")); this.dispatch = new AsyncRunnable( request, applicationDispatcher, servletRequest, servletResponse); this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null); clearServletRequestResponse();
ByteChunk uriBC = req.requestURI().getByteChunk(); int semicolon = uriBC.indexOf(match, 0, match.length(), 0); int start = uriBC.getStart(); int end = uriBC.getEnd(); int semicolon2 = uriBC.indexOf(';', sessionIdStart); if (semicolon2 >= 0) { request.setRequestedSessionId (new String(uriBC.getBuffer(), start + sessionIdStart, semicolon2 - sessionIdStart)); uriBC.setBytes(buf, start, end - start - semicolon2 + semicolon); } else { request.setRequestedSessionId (new String(uriBC.getBuffer(), start + sessionIdStart, (end - start) - sessionIdStart)); uriBC.setEnd(start + semicolon); request.setRequestedSessionURL(true);
final synchronized boolean onDataAvailable() { if (readInterest) { if (log.isDebugEnabled()) { log.debug(sm.getString("stream.inputBuffer.dispatch")); } readInterest = false; coyoteRequest.action(ActionCode.DISPATCH_READ, null); // Always need to dispatch since this thread is processing // the incoming connection and streams are processed on their // own. coyoteRequest.action(ActionCode.DISPATCH_EXECUTE, null); return true; } else { if (log.isDebugEnabled()) { log.debug(sm.getString("stream.inputBuffer.signal")); } synchronized (inBuffer) { inBuffer.notifyAll(); } return false; } }
@Override public void complete() { if (log.isDebugEnabled()) { logDebug("complete "); } check(); request.getCoyoteRequest().action(ActionCode.COMMIT, null); request.getCoyoteRequest().action(ActionCode.ASYNC_COMPLETE, null); clearServletRequestResponse(); }
String password = null; final MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization"); if (authorization != null) { authorization.toBytes(); final ByteChunk authorizationBC = authorization.getByteChunk(); if (authorizationBC.startsWithIgnoreCase("basic ", 0)) { authorizationBC.setOffset(authorizationBC.getOffset() + 6); final byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength()); final Principal principal = context.getRealm().authenticate(username, password); if (principal != null) { register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password);
/** * Reject the request that was denied by this valve. * <p>If <code>invalidAuthenticationWhenDeny</code> is true * and the context has <code>preemptiveAuthentication</code> * set, set an invalid authorization header to trigger basic auth. * * @param request The servlet request to be processed * @param response The servlet response to be processed * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ protected void denyRequest(Request request, Response response) throws IOException, ServletException { if (invalidAuthenticationWhenDeny) { Context context = request.getContext(); if (context != null && context.getPreemptiveAuthentication()) { if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) { request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid"); } getNext().invoke(request, response); return; } } response.sendError(denyStatus); }
request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (authorizationBC.startsWithIgnoreCase("basic ", 0)) { authorizationBC.setOffset(authorizationBC.getOffset() + 6); CharChunk authorizationCC = authorization.getCharChunk(); Base64.decode(authorizationBC, authorizationCC); try { MessageBytes authenticate = response.getCoyoteResponse().getMimeHeaders() .addValue(AUTHENTICATE_BYTES, 0, AUTHENTICATE_BYTES.length); CharChunk authenticateCC = authenticate.getCharChunk(); authenticateCC.append("Basic realm=\"");
private static HttpHeaders convertResponse(Response coyoteRes) { final HttpHeaders headers = HttpHeaders.of(HttpStatus.valueOf(coyoteRes.getStatus())); final String contentType = coyoteRes.getContentType(); if (contentType != null && !contentType.isEmpty()) { headers.set(HttpHeaderNames.CONTENT_TYPE, contentType); } final long contentLength = coyoteRes.getBytesWritten(true); // 'true' will trigger flush. final String method = coyoteRes.getRequest().method().toString(); if (!"HEAD".equals(method)) { headers.setLong(HttpHeaderNames.CONTENT_LENGTH, contentLength); } final MimeHeaders cHeaders = coyoteRes.getMimeHeaders(); final int numHeaders = cHeaders.size(); for (int i = 0; i < numHeaders; i++) { final AsciiString name = toHeaderName(cHeaders.getName(i)); if (name == null) { continue; } final String value = toHeaderValue(cHeaders.getValue(i)); if (value == null) { continue; } headers.add(name.toLowerCase(), value); } return headers; }
/* */ public String getRemoteHost() /* */ { /* 1181 */ if (this.remoteHost == null) { /* 1182 */ if (!this.connector.getEnableLookups()) { /* 1183 */ this.remoteHost = getRemoteAddr(); /* */ } else { /* 1185 */ this.coyoteRequest.action(ActionCode.ACTION_REQ_HOST_ATTRIBUTE, this.coyoteRequest); /* */ /* 1187 */ this.remoteHost = this.coyoteRequest.remoteHost().toString(); /* */ } /* */ } /* 1190 */ return this.remoteHost; /* */ } /* */
final boolean receivedEndOfHeaders() throws ConnectionException { if (coyoteRequest.method().isNull() || coyoteRequest.scheme().isNull() || coyoteRequest.requestURI().isNull()) { throw new ConnectionException(sm.getString("stream.header.required", getConnectionId(), getIdentifier()), Http2Error.PROTOCOL_ERROR); } // Cookie headers need to be concatenated into a single header // See RFC 7540 8.1.2.5 // Can only do this once the headers are fully received if (cookieHeader != null) { coyoteRequest.getMimeHeaders().addValue("cookie").setString(cookieHeader.toString()); } return headerState == HEADER_STATE_REGULAR || headerState == HEADER_STATE_PSEUDO; }
/** * Check the configuration for aborted uploads and if configured to do so, * disable the swallowing of any remaining input and close the connection * once the response has been written. */ protected void checkSwallowInput() { Context context = getContext(); if (context != null && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } }
/** Called by the processor before recycling the request. It'll collect * statistic information. */ void updateCounters() { bytesReceived+=req.getBytesRead(); bytesSent+=req.getResponse().getContentWritten(); requestCount++; if( req.getResponse().getStatus() >=400 ) errorCount++; long t0=req.getStartTime(); long t1=System.currentTimeMillis(); long time=t1-t0; this.lastRequestProcessingTime = time; processingTime+=time; if( maxTime < time ) { maxTime=time; maxRequestUri=req.requestURI().toString(); } }
/** * Intercept the request and decide if we cache the static resource. If the * static resource is already cached, return it. */ public int handle(Request req, int handlerCode) throws IOException{ if (fileCache == null) return Handler.CONTINUE; if (handlerCode == Handler.RESPONSE_PROCEEDED && fileCache.isEnabled()){ String docroot = SelectorThread.getWebAppRootPath(); MessageBytes mb = req.requestURI(); ByteChunk requestURI = mb.getByteChunk(); String uri = req.requestURI().toString(); fileCache.add(FileCache.DEFAULT_SERVLET_NAME,docroot,uri, req.getResponse().getMimeHeaders(),false); } else if (handlerCode == Handler.HEADERS_PARSED) { ByteChunk requestURI = req.requestURI().getByteChunk(); if (fileCache.sendCache(requestURI.getBytes(), requestURI.getStart(), requestURI.getLength(), socketChannel, keepAlive(req))){ return Handler.BREAK; } } return Handler.CONTINUE; }
public boolean timeout() { AtomicBoolean result = new AtomicBoolean(); request.getCoyoteRequest().action(ActionCode.ASYNC_TIMEOUT, result); // Avoids NPEs during shutdown. A call to recycle will null this field. Context context = this.context; if (result.get()) { ClassLoader oldCL = context.bind(false, null); try { List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(); listenersCopy.addAll(listeners); for (AsyncListenerWrapper listener : listenersCopy) { try { listener.fireOnTimeout(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("asyncContextImpl.onTimeoutError", listener.getClass().getName()), t); } } request.getCoyoteRequest().action( ActionCode.ASYNC_IS_TIMINGOUT, result); } finally { context.unbind(false, oldCL); } } return !result.get(); }
/** * @return the remote IP address making this Request. */ @Override public String getRemoteAddr() { if (remoteAddr == null) { coyoteRequest.action (ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest); remoteAddr = coyoteRequest.remoteAddr().toString(); } return remoteAddr; }
/** * Returns the Internet Protocol (IP) address of the interface on * which the request was received. */ public String getLocalAddr(){ if (localAddr == null) { coyoteRequest.action (ActionCode.ACTION_REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest); localAddr = coyoteRequest.localAddr().toString(); } return localAddr; }
public void setStarted(Context context, ServletRequest request, ServletResponse response, boolean originalRequestResponse) { synchronized (asyncContextLock) { this.request.getCoyoteRequest().action( ActionCode.ASYNC_START, this); this.context = context; this.servletRequest = request; this.servletResponse = response; this.hasOriginalRequestAndResponse = originalRequestResponse; this.event = new AsyncEvent(this, request, response); List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(); listenersCopy.addAll(listeners); listeners.clear(); for (AsyncListenerWrapper listener : listenersCopy) { try { listener.fireOnStartAsync(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("asyncContextImpl.onStartAsyncError", listener.getClass().getName()), t); } } } }
/** Called by the processor before recycling the request. It'll collect * statistic information. */ void updateCounters() { bytesReceived+=req.getBytesRead(); bytesSent+=req.getResponse().getBytesWritten(); requestCount++; if( req.getResponse().getStatus() >=400 ) errorCount++; long t0=req.getStartTime(); long t1=System.currentTimeMillis(); long time=t1-t0; this.lastRequestProcessingTime = time; processingTime+=time; if( maxTime < time ) { maxTime=time; maxRequestUri=req.requestURI().toString(); } }
private void populateRequestMetadata(RequestMap metadata, Request req) { MimeHeaders headers = req.getMimeHeaders(); Enumeration nameEnum = headers.names(); while (nameEnum.hasMoreElements()) { Object nameObj = nameEnum.nextElement(); if (nameObj instanceof String) { Object valueObj = headers.getHeader((String) nameObj); metadata.put(nameObj, valueObj); } } metadata.put(HTTPMetadataConstants.METHODTYPE, req.method().getString()); metadata.put(HTTPMetadataConstants.PATH, req.requestURI().getString()); metadata.put(HTTPMetadataConstants.HTTPVERSION, req.protocol().getString()); }