io.undertow.UndertowLogger Java Examples

The following examples show how to use io.undertow.UndertowLogger. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: quarkus-http   Author: quarkusio   File: LoggingExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void handleCustomLog(HttpServerExchange exchange, Throwable t, Logger.Level level, Logger.Level stackTraceLevel, String category) {
    BasicLogger logger = UndertowLogger.REQUEST_LOGGER;
    if (!category.isEmpty()) {
        logger = Logger.getLogger(category);
    }
    boolean stackTrace = true;
    if (stackTraceLevel.ordinal() > level.ordinal()) {
        if (!logger.isEnabled(stackTraceLevel)) {
            stackTrace = false;
        }
    }
    if (stackTrace) {
        logger.logf(level, t, "Exception handling request to %s", exchange.getRequestURI());
    } else {
        logger.logf(level, "Exception handling request to %s: %s", exchange.getRequestURI(), t.getMessage());
    }
}
 
Example #2
Source Project: quarkus-http   Author: quarkusio   File: AsyncContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void complete() {
    if (complete) {
        UndertowLogger.REQUEST_LOGGER.trace("Ignoring call to AsyncContext.complete() as it has already been called");
        return;
    }
    complete = true;
    if (timeoutKey != null) {
        timeoutKey.cancel(false);
        timeoutKey = null;
    }
    if (!dispatched) {
        completeInternal(false);
    } else {
        onAsyncComplete();
    }
    if (previousAsyncContext != null) {
        previousAsyncContext.complete();
    }
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: BlockingSenderImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void send(final ByteBuffer[] buffer, final IoCallback callback) {
    if (inCall) {
        queue(buffer, callback);
        return;
    } else {
        long responseContentLength = exchange.getResponseContentLength();
        if(responseContentLength > 0 && Buffers.remaining(buffer) > responseContentLength) {
            callback.onException(exchange, this, UndertowLogger.ROOT_LOGGER.dataLargerThanContentLength(Buffers.remaining(buffer), responseContentLength));
            return;
        }
        if (!exchange.isResponseStarted() && callback == IoCallback.END_EXCHANGE) {
            if (responseContentLength == -1 && !exchange.getResponseHeaders().contains(Headers.TRANSFER_ENCODING)) {
                exchange.setResponseContentLength(Buffers.remaining(buffer));
            }
        }
    }
    if (!writeBuffer(buffer, callback)) {
        return;
    }
    invokeOnComplete(callback);
}
 
Example #4
Source Project: lams   Author: lamsfoundation   File: ProxyHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
void cancel(final HttpServerExchange exchange) {
    final ProxyConnection connectionAttachment = exchange.getAttachment(CONNECTION);
    if (connectionAttachment != null) {
        ClientConnection clientConnection = connectionAttachment.getConnection();
        UndertowLogger.PROXY_REQUEST_LOGGER.timingOutRequest(clientConnection.getPeerAddress() + "" + exchange.getRequestURI());
        IoUtils.safeClose(clientConnection);
    } else {
        UndertowLogger.PROXY_REQUEST_LOGGER.timingOutRequest(exchange.getRequestURI());
    }
    if (exchange.isResponseStarted()) {
        IoUtils.safeClose(exchange.getConnection());
    } else {
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
    }
}
 
Example #5
Source Project: quarkus-http   Author: quarkusio   File: ServletSecurityConstraintHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String path = exchange.getRelativePath();
    SecurityPathMatch securityMatch = securityPathMatches.getSecurityInfo(path, exchange.getRequestMethod());
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    List<SingleConstraintMatch> list = servletRequestContext.getRequiredConstrains();
    if (list == null) {
        servletRequestContext.setRequiredConstrains(list = new ArrayList<>());
    }
    list.add(securityMatch.getMergedConstraint());
    TransportGuaranteeType type = servletRequestContext.getTransportGuarenteeType();
    if (type == null || type.ordinal() < securityMatch.getTransportGuaranteeType().ordinal()) {
        servletRequestContext.setTransportGuarenteeType(securityMatch.getTransportGuaranteeType());
    }

    UndertowLogger.SECURITY_LOGGER.debugf("Security constraints for request %s are %s", exchange.getRequestURI(), list);
    next.handleRequest(exchange);
}
 
Example #6
Source Project: quarkus-http   Author: quarkusio   File: JsrWebSocketFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent se) {
    HttpSessionImpl session = (HttpSessionImpl) se.getSession();
    final Session underlying;
    if (System.getSecurityManager() == null) {
        underlying = session.getSession();
    } else {
        underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }
    List<UndertowSession> connections = (List<UndertowSession>) underlying.getAttribute(SESSION_ATTRIBUTE);
    if (connections != null) {
        synchronized (underlying) {
            for (UndertowSession c : connections) {
                try {
                    c.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, ""));
                } catch (IOException e) {
                    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                }
            }
        }
    }
}
 
Example #7
Source Project: thorntail   Author: thorntail   File: InVMConnection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConduitStreamSinkChannel getSinkChannel() {

    ConduitStreamSinkChannel sinkChannel = new ConduitStreamSinkChannel(
            Configurable.EMPTY,
            new BufferedStreamSinkConduit(
                    new NullStreamSinkConduit(worker.getIoThread()),
                    new PooledAdaptor(bufferPool.allocate())
            )
    );
    sinkChannel.setCloseListener(conduitStreamSinkChannel -> {
        for (CloseListener l : closeListeners) {
            try {
                l.closed(InVMConnection.this);
            } catch (Throwable e) {
                UndertowLogger.REQUEST_LOGGER.exceptionInvokingCloseListener(l, e);
            }
        }
    });
    return sinkChannel;
}
 
Example #8
Source Project: lams   Author: lamsfoundation   File: Http2OpenListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void handleEvent(final StreamConnection channel, PooledByteBuffer buffer) {
    if (UndertowLogger.REQUEST_LOGGER.isTraceEnabled()) {
        UndertowLogger.REQUEST_LOGGER.tracef("Opened HTTP/2 connection with %s", channel.getPeerAddress());
    }

    //cool, we have a Http2 connection.
    Http2Channel http2Channel = new Http2Channel(channel, protocol, bufferPool, buffer, false, false, undertowOptions);
    Integer idleTimeout = undertowOptions.get(UndertowOptions.IDLE_TIMEOUT);
    if (idleTimeout != null && idleTimeout > 0) {
        http2Channel.setIdleTimeout(idleTimeout);
    }
    if(statisticsEnabled) {
        channel.getSinkChannel().setConduit(new BytesSentStreamSinkConduit(channel.getSinkChannel().getConduit(), connectorStatistics.sentAccumulator()));
        channel.getSourceChannel().setConduit(new BytesReceivedStreamSourceConduit(channel.getSourceChannel().getConduit(), connectorStatistics.receivedAccumulator()));
        connectorStatistics.incrementConnectionCount();
        http2Channel.addCloseTask(closeTask);
    }
    http2Channel.getReceiveSetter().set(new Http2ReceiveListener(rootHandler, getUndertowOptions(), bufferSize, connectorStatistics));
    http2Channel.resumeReceives();

}
 
Example #9
Source Project: quarkus-http   Author: quarkusio   File: PredicatesHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HandlerWrapper build(Map<String, Object> config) {
    return new HandlerWrapper() {
        @Override
        public HttpHandler wrap(final HttpHandler handler) {
            return new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    Integer restarts = exchange.getAttachment(RESTART_COUNT);
                    if(restarts == null) {
                        restarts = 1;
                    } else {
                        restarts++;
                    }
                    exchange.putAttachment(RESTART_COUNT, restarts);
                    if(restarts > MAX_RESTARTS) {
                        throw UndertowLogger.ROOT_LOGGER.maxRestartsExceeded(MAX_RESTARTS);
                    }
                    exchange.putAttachment(RESTART, true);
                }
            };
        }
    };
}
 
Example #10
Source Project: rpc-benchmark   Author: hank-whu   File: AsyncHttpHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * response
 * 
 * @param exchange
 * @param statusCode
 * @param output
 *            auto release
 */
protected final void send(HttpServerExchange exchange, int statusCode, PooledByteBufferOutputStream output) {
	try {
		output.flip();

		StreamSinkChannel channel = getResponseChannel(exchange);
		Sender sender = exchange.getResponseSender();

		setStatusCode(exchange, statusCode);
		setResponseChannel(sender, channel);
		setPooledBuffers(sender, output.getPooledByteBuffers());

		sender.send(output.getByteBuffers());
	} catch (Throwable t) {
		UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
	}
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: AbstractFramedChannel.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Called when a source sub channel fails to fulfil its contract, and leaves the channel in an inconsistent state.
 * <p>
 * The underlying read side will be forcibly closed.
 *
 * @param cause The possibly null cause
 */
@SuppressWarnings({"unchecked", "rawtypes"})
protected void markReadsBroken(Throwable cause) {
    if (readsBrokenUpdater.compareAndSet(this, 0, 1)) {
        if(UndertowLogger.REQUEST_IO_LOGGER.isDebugEnabled()) {
            UndertowLogger.REQUEST_IO_LOGGER.debugf(new ClosedChannelException(), "Marking reads broken on channel %s", this);
        }
        if(receiver != null) {
            receiver.markStreamBroken();
        }
        for(AbstractFramedStreamSourceChannel<C, R, S> r : new ArrayList<>(getReceivers())) {
            r.markStreamBroken();
        }

        handleBrokenSourceChannel(cause);
        safeClose(channel.getSourceChannel());
        closeSubChannels();
    }
}
 
Example #12
Source Project: quarkus-http   Author: quarkusio   File: SslSessionConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setSessionId(final HttpServerExchange exchange, final String sessionId) {
    UndertowLogger.SESSION_LOGGER.tracef("Setting SSL session id %s on %s", sessionId, exchange);
    SSLSessionInfo sslSession = exchange.getSslSessionInfo();
    if (sslSession == null) {
        if (fallbackSessionConfig != null) {
            fallbackSessionConfig.setSessionId(exchange, sessionId);
        }
    } else {
        Key key = new Key(sslSession.getSessionId());
        synchronized (this) {
            sessions.put(key, sessionId);
            reverse.put(sessionId, key);
        }
    }
}
 
Example #13
Source Project: quarkus-http   Author: quarkusio   File: SslSessionConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void clearSession(final HttpServerExchange exchange, final String sessionId) {
    UndertowLogger.SESSION_LOGGER.tracef("Clearing SSL session id %s on %s", sessionId, exchange);
    SSLSessionInfo sslSession = exchange.getSslSessionInfo();
    if (sslSession == null) {
        if (fallbackSessionConfig != null) {
            fallbackSessionConfig.clearSession(exchange, sessionId);
        }
    } else {
        synchronized (this) {
            Key sid = reverse.remove(sessionId);
            if (sid != null) {
                sessions.remove(sid);
            }
        }
    }
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: FormEncodedDataDefinition.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public FormDataParser create(final HttpServerExchange exchange)  {
    String mimeType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (forceCreation || (mimeType != null && mimeType.startsWith(APPLICATION_X_WWW_FORM_URLENCODED))) {

        String charset = defaultEncoding;
        String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
        if (contentType != null) {
            String cs = Headers.extractQuotedValueFromHeader(contentType, "charset");
            if (cs != null) {
                charset = cs;
            }
        }
        UndertowLogger.REQUEST_LOGGER.tracef("Created form encoded parser for %s", exchange);
        return new FormEncodedDataParser(charset, exchange);
    }
    return null;
}
 
Example #15
Source Project: quarkus-http   Author: quarkusio   File: MultiPartParserDefinition.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (exchange.isReadable()) {
        try {
            ByteBuf buffer = exchange.readAsync();
            if (buffer == null) {
                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();
                }
                return;
            } else {
                parser.parse(buffer);
            }
        } catch (IOException e) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            exchange.endExchange();
        }
    }
    exchange.setReadHandler(this, exchange);
}
 
Example #16
Source Project: lams   Author: lamsfoundation   File: AbstractFramedChannel.java    License: GNU General Public License v2.0 6 votes vote down vote up
private ReferenceCountedPooled allocateReferenceCountedBuffer() {
    if(maxQueuedBuffers > 0) {
        int expect;
        do {
            expect = outstandingBuffersUpdater.get(this);
            if (expect == maxQueuedBuffers) {
                synchronized (this) {
                    //we need to re-read in a sync block, to prevent races
                    expect = outstandingBuffersUpdater.get(this);
                    if (expect == maxQueuedBuffers) {
                        if(UndertowLogger.REQUEST_IO_LOGGER.isTraceEnabled()) {
                            UndertowLogger.REQUEST_IO_LOGGER.tracef("Suspending reads on %s due to too many outstanding buffers", this);
                        }
                        channel.getSourceChannel().suspendReads();
                        return null;
                    }
                }
            }
        } while (!outstandingBuffersUpdater.compareAndSet(this, expect, expect + 1));
    }
    PooledByteBuffer buf = bufferPool.allocate();
    return this.readData = new ReferenceCountedPooled(buf, 1, maxQueuedBuffers > 0 ? freeNotifier : null);
}
 
Example #17
Source Project: quarkus-http   Author: quarkusio   File: PathResource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serveAsync(OutputChannel stream, HttpServerExchange exchange) {
    //TODO: do this properly
    //todo implement non blocking IO
    exchange.dispatch(new Runnable() {
        @Override
        public void run() {
            try {
                serveBlocking(exchange.getOutputStream(), exchange);
            } catch (IOException e) {
                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                exchange.endExchange();
            }
        }
    });
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: SslConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void runReadListener(final boolean resumeInListener) {
    try {
        if(readListenerInvocationCount++ == MAX_READ_LISTENER_INVOCATIONS) {
            UndertowLogger.REQUEST_LOGGER.sslReadLoopDetected(this);
            IoUtils.safeClose(connection, delegate);
            close();
            return;
        }
        if(resumeInListener) {
            delegate.getIoThread().execute(runReadListenerAndResumeCommand);
        } else {
            delegate.getIoThread().execute(runReadListenerCommand);
        }
    } catch (Throwable e) {
        //will only happen on shutdown
        IoUtils.safeClose(connection, delegate);
        UndertowLogger.REQUEST_IO_LOGGER.debugf(e, "Failed to queue read listener invocation");
    }
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: ChunkedStreamSinkConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void terminateWrites() throws IOException {
    if(anyAreSet(state, FLAG_WRITES_SHUTDOWN)) {
        return;
    }
    if (this.chunkleft != 0) {
        UndertowLogger.REQUEST_IO_LOGGER.debugf("Channel closed mid-chunk");
        next.truncateWrites();
    }
    if (!anyAreSet(state, FLAG_FIRST_DATA_WRITTEN)) {
        //if no data was actually sent we just remove the transfer encoding header, and set content length 0
        //TODO: is this the best way to do it?
        //todo: should we make this behaviour configurable?
        responseHeaders.put(Headers.CONTENT_LENGTH, "0"); //according to the spec we don't actually need this, but better to be safe
        responseHeaders.remove(Headers.TRANSFER_ENCODING);
        state |= FLAG_NEXT_SHUTDOWN | FLAG_WRITES_SHUTDOWN;
        if(anyAreSet(state, CONF_FLAG_PASS_CLOSE)) {
            next.terminateWrites();
        }
    } else {
        createLastChunk(false);
        state |= FLAG_WRITES_SHUTDOWN;
    }
}
 
Example #20
Source Project: quarkus-http   Author: quarkusio   File: HttpServerExchange.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Change the status code for this response.  If not specified, the code will be a {@code 200}.  Setting
 * the status code after the response headers have been transmitted has no effect.
 *
 * @param statusCode the new code
 * @throws IllegalStateException if a response or upgrade was already sent
 */
public HttpServerExchange setStatusCode(final int statusCode) {
    if (statusCode < 0 || statusCode > 999) {
        throw new IllegalArgumentException("Invalid response code");
    }
    int oldVal = state;
    if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) {
        throw UndertowMessages.MESSAGES.responseAlreadyStarted();
    }
    if (statusCode >= 500) {
        if (UndertowLogger.ERROR_RESPONSE.isDebugEnabled()) {
            UndertowLogger.ERROR_RESPONSE.debugf(new RuntimeException(), "Setting error code %s for exchange %s", statusCode, this);
        }
    }
    delegate.setStatusCode(statusCode);
    return this;
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: ReadTimeoutStreamSourceConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    handle = null;
    if (expireTime == -1) {
        return;
    }
    long current = System.currentTimeMillis();
    if (current  < expireTime) {
        //timeout has been bumped, re-schedule
        handle = WorkerUtils.executeAfter(connection.getIoThread(),timeoutCommand, (expireTime - current) + FUZZ_FACTOR, TimeUnit.MILLISECONDS);
        return;
    }
    UndertowLogger.REQUEST_LOGGER.tracef("Timing out channel %s due to inactivity", connection.getSourceChannel());
    IoUtils.safeClose(connection);
    if (connection.getSourceChannel().isReadResumed()) {
        ChannelListeners.invokeChannelListener(connection.getSourceChannel(), connection.getSourceChannel().getReadListener());
    }
    if (connection.getSinkChannel().isWriteResumed()) {
        ChannelListeners.invokeChannelListener(connection.getSinkChannel(), connection.getSinkChannel().getWriteListener());
    }
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: MCMPHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #23
Source Project: quarkus-http   Author: quarkusio   File: RequestDispatcherImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void setupIncludeImpl(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
    final ServletRequestContext servletRequestContext = SecurityActions.currentServletRequestContext();
    if(servletRequestContext == null) {
        UndertowLogger.REQUEST_LOGGER.debugf("No servlet request context for %s, dispatching mock request", request);
        mock(request, response);
        return;
    }
    final HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
    final HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
    ServletContextImpl oldServletContext = null;
    HttpSessionImpl oldSession = null;
    if (servletRequestContext.getCurrentServletContext() != this.servletContext) {
        //cross context request, we need to run the thread setup actions
        oldServletContext = servletRequestContext.getCurrentServletContext();
        oldSession = servletRequestContext.getSession();
        servletRequestContext.setSession(null);
        servletRequestContext.setCurrentServletContext(this.servletContext);
        try {
            servletRequestContext.getCurrentServletContext().invokeAction(servletRequestContext.getExchange(), new ThreadSetupHandler.Action<Void, Object>() {
                @Override
                public Void call(HttpServerExchange exchange, Object context) throws Exception {
                    includeImpl(request, response, servletRequestContext, requestImpl, responseImpl);
                    return null;
                }
            });
        } finally {
            // update time in new context and run the requestDone for the session
            servletRequestContext.getCurrentServletContext().updateSessionAccessTime(servletRequestContext.getExchange());
            servletRequestContext.setSession(oldSession);
            servletRequestContext.setCurrentServletContext(oldServletContext);
        }
    } else {
        includeImpl(request, response, servletRequestContext, requestImpl, responseImpl);
    }
}
 
Example #24
Source Project: quarkus-http   Author: quarkusio   File: HttpServletResponseImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void responseDone() {
    if (responseDone || treatAsCommitted) {
        return;
    }
    responseDone = true;
    try {
        closeStreamAndWriter();
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    } finally {
        servletContext.updateSessionAccessTime(exchange);
    }
}
 
Example #25
Source Project: quarkus-http   Author: quarkusio   File: SavedRequest.java    License: Apache License 2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange) {
    int maxSize = getMaxBufferSizeToSave(exchange);
    if (maxSize > 0) {
        //if this request has a body try and cache the response
        if (!exchange.isRequestComplete()) {
            final long requestContentLength = exchange.getRequestContentLength();
            if (requestContentLength > maxSize) {
                UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
                return;//failed to save the request, we just return
            }
            //TODO: we should really be used pooled buffers
            //TODO: we should probably limit the number of saved requests at any given time
            byte[] buffer = new byte[maxSize];
            int read = 0;
            int res = 0;
            InputStream in = exchange.getInputStream();
            try {
                while ((res = in.read(buffer, read, buffer.length - read)) > 0) {
                    read += res;
                    if (read == maxSize) {
                        UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
                        return;//failed to save the request, we just return
                    }
                }
                //save request from buffer
                trySaveRequest(exchange, buffer, read);
            } catch (IOException e) {
                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
            }
        }
    }
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: DetachableStreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void handleEvent(final StreamSinkChannel channel) {
    ChannelListener<? super StreamSinkChannel> channelListener = setter.get();
    if(channelListener != null) {
        ChannelListeners.invokeChannelListener(this.channel, channelListener);
    } else {
        UndertowLogger.REQUEST_LOGGER.debugf("suspending writes on %s to prevent listener runaway", channel);
        channel.suspendWrites();
    }
}
 
Example #27
Source Project: quarkus-http   Author: quarkusio   File: AsyncUpgradeServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(final WebConnection wc) {
    Listener listener = new Listener(wc);
    try {
        //we have to set the write listener before the read listener
        //otherwise the output stream could be written to before it is
        //in async mode
        wc.getOutputStream().setWriteListener(listener);
        wc.getInputStream().setReadListener(listener);
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    }
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: ProxyHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void handleFailure(HttpServerExchange exchange, ProxyClientHandler proxyClientHandler, Predicate idempotentRequestPredicate, IOException e) {
    UndertowLogger.PROXY_REQUEST_LOGGER.proxyRequestFailed(exchange.getRequestURI(), e);
    if(exchange.isResponseStarted()) {
        IoUtils.safeClose(exchange.getConnection());
    } else if(idempotentRequestPredicate.resolve(exchange) && proxyClientHandler != null) {
        proxyClientHandler.failed(exchange); //this will attempt a retry if configured to do so
    } else {
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
    }
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: DefaultAccessLogReceiver.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void doRotate() {
    forceLogRotation = false;
    if (!rotate) {
        return;
    }
    try {
        if (writer != null) {
            writer.flush();
            writer.close();
            writer = null;
        }
        if (!Files.exists(defaultLogFile)) {
            return;
        }
        Path newFile = outputDirectory.resolve(logBaseName + currentDateString + "." + logNameSuffix);
        int count = 0;
        while (Files.exists(newFile)) {
            ++count;
            newFile = outputDirectory.resolve(logBaseName + currentDateString + "-" + count + "." + logNameSuffix);
        }
        Files.move(defaultLogFile, newFile);
    } catch (IOException e) {
        UndertowLogger.ROOT_LOGGER.errorRotatingAccessLog(e);
    } finally {
        calculateChangeOverPoint();
    }
}
 
Example #30
Source Project: quarkus-http   Author: quarkusio   File: SecurityContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate() {
    UndertowLogger.SECURITY_LOGGER.tracef("Attempting to authenticate %s, authentication required: %s", exchange.getRequestPath(), isAuthenticationRequired());
    if(authenticationState == AuthenticationState.ATTEMPTED || (authenticationState == AuthenticationState.CHALLENGE_SENT && !exchange.isResponseStarted())) {
        //we are re-attempted, so we just reset the state
        //see UNDERTOW-263
        authenticationState = AuthenticationState.NOT_ATTEMPTED;
    }
    return !authTransition();
}