Java Code Examples for org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState#CLOSED

The following examples show how to use org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState#CLOSED . 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 File: TestUpgradeInternalHandler.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public SocketState upgradeDispatch(SocketEvent status) {
    System.out.println("Processing: " + status);
    switch (status) {
    case OPEN_READ:
        // Note: there's always an initial read event at the moment (reading should be skipped since it ends up in the internal buffer)
        break;
    case OPEN_WRITE:
        break;
    case STOP:
    case DISCONNECT:
    case ERROR:
    case TIMEOUT:
    case CONNECT_FAIL:
        return SocketState.CLOSED;
    }
    return SocketState.UPGRADED;
}
 
Example 2
Source File: WsFrameServer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private SocketState doOnDataAvailable() throws IOException {
    onDataAvailable();
    while (isOpen()) {
        switch (getReadState()) {
        case PROCESSING:
            if (!changeReadState(ReadState.PROCESSING, ReadState.WAITING)) {
                continue;
            }
            return SocketState.UPGRADED;
        case SUSPENDING_PROCESS:
            if (!changeReadState(ReadState.SUSPENDING_PROCESS, ReadState.SUSPENDED)) {
                continue;
            }
            return SocketState.SUSPENDED;
        default:
            throw new IllegalStateException(
                    sm.getString("wsFrameServer.illegalReadState", getReadState()));
        }
    }

    return SocketState.CLOSED;
}
 
Example 3
Source File: WsFrameServer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
SocketState notifyDataAvailable() throws IOException {
    while (isOpen()) {
        switch (getReadState()) {
        case WAITING:
            if (!changeReadState(ReadState.WAITING, ReadState.PROCESSING)) {
                continue;
            }
            try {
                return doOnDataAvailable();
            } catch (IOException e) {
                changeReadState(ReadState.CLOSING);
                throw e;
            }
        case SUSPENDING_WAIT:
            if (!changeReadState(ReadState.SUSPENDING_WAIT, ReadState.SUSPENDED)) {
                continue;
            }
            return SocketState.SUSPENDED;
        default:
            throw new IllegalStateException(
                    sm.getString("wsFrameServer.illegalReadState", getReadState()));
        }
    }

    return SocketState.CLOSED;
}
 
Example 4
Source File: StreamProcessor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public SocketState service(SocketWrapperBase<?> socket) throws IOException {
    try {
        adapter.service(request, response);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("streamProcessor.service.error"), e);
        }
        response.setStatus(500);
        setErrorState(ErrorState.CLOSE_NOW, e);
    }

    if (!isAsync()) {
        // If this is an async request then the request ends when it has
        // been completed. The AsyncContext is responsible for calling
        // endRequest() in that case.
        endRequest();
    }

    if (getErrorState().isError()) {
        action(ActionCode.CLOSE, null);
        request.updateCounters();
        return SocketState.CLOSED;
    } else if (isAsync()) {
        return SocketState.LONG;
    } else {
        action(ActionCode.CLOSE, null);
        request.updateCounters();
        return SocketState.CLOSED;
    }
}
 
Example 5
Source File: Http11AprProcessor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Process pipelined HTTP requests using the specified input and output
 * streams.
 *
 * @throws IOException error during an I/O operation
 */
@Override
public SocketState event(SocketStatus status)
    throws IOException {

    RequestInfo rp = request.getRequestProcessor();

    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if (!getAdapter().event(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // 500 - Internal Server Error
        response.setStatus(500);
        setErrorState(ErrorState.CLOSE_NOW, t);
        getAdapter().log(request, response, 0);
        log.error(sm.getString("http11processor.request.process"), t);
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    if (getErrorState().isError() || status==SocketStatus.STOP) {
        return SocketState.CLOSED;
    } else if (!comet) {
        inputBuffer.nextRequest();
        outputBuffer.nextRequest();
        return SocketState.OPEN;
    } else {
        return SocketState.LONG;
    }
}
 
Example 6
Source File: AbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public SocketState asyncDispatch(SocketStatus status) {

    RequestInfo rp = request.getRequestProcessor();
    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if (!getAdapter().asyncDispatch(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
        resetTimeouts();
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        setErrorState(ErrorState.CLOSE_NOW, t);
        getLog().error(sm.getString("http11processor.request.process"), t);
    } finally {
        if (getErrorState().isError()) {
            // 500 - Internal Server Error
            response.setStatus(500);
            adapter.log(request, response, 0);
        }
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    if (getErrorState().isError()) {
        return SocketState.CLOSED;
    } else if (isAsync()) {
        return SocketState.LONG;
    } else {
        if (!keepAlive) {
            return SocketState.CLOSED;
        } else {
            getInputBuffer().nextRequest();
            getOutputBuffer().nextRequest();
            return SocketState.OPEN;
        }
    }
}
 
Example 7
Source File: Http11Processor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected SocketState dispatchEndRequest() {
    if (!keepAlive) {
        return SocketState.CLOSED;
    } else {
        endRequest();
        inputBuffer.nextRequest();
        outputBuffer.nextRequest();
        if (socketWrapper.isReadPending()) {
            return SocketState.LONG;
        } else {
            return SocketState.OPEN;
        }
    }
}
 
Example 8
Source File: Http11AprProcessor.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Process pipelined HTTP requests using the specified input and output
 * streams.
 *
 * @throws IOException error during an I/O operation
 */
@Override
public SocketState event(SocketStatus status)
    throws IOException {

    RequestInfo rp = request.getRequestProcessor();

    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if (!getAdapter().event(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // 500 - Internal Server Error
        response.setStatus(500);
        setErrorState(ErrorState.CLOSE_NOW, t);
        getAdapter().log(request, response, 0);
        log.error(sm.getString("http11processor.request.process"), t);
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    if (getErrorState().isError() || status==SocketStatus.STOP) {
        return SocketState.CLOSED;
    } else if (!comet) {
        inputBuffer.nextRequest();
        outputBuffer.nextRequest();
        return SocketState.OPEN;
    } else {
        return SocketState.LONG;
    }
}
 
Example 9
Source File: AbstractProcessor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public final SocketState dispatch(SocketEvent status) throws IOException {

    if (status == SocketEvent.OPEN_WRITE && response.getWriteListener() != null) {
        asyncStateMachine.asyncOperation();
        try {
            if (flushBufferedWrite()) {
                return SocketState.LONG;
            }
        } catch (IOException ioe) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Unable to write async data.", ioe);
            }
            status = SocketEvent.ERROR;
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
        }
    } else if (status == SocketEvent.OPEN_READ && request.getReadListener() != null) {
        dispatchNonBlockingRead();
    } else if (status == SocketEvent.ERROR) {
        // An I/O error occurred on a non-container thread. This includes:
        // - read/write timeouts fired by the Poller (NIO & APR)
        // - completion handler failures in NIO2

        if (request.getAttribute(RequestDispatcher.ERROR_EXCEPTION) == null) {
            // Because the error did not occur on a container thread the
            // request's error attribute has not been set. If an exception
            // is available from the socketWrapper, use it to set the
            // request's error attribute here so it is visible to the error
            // handling.
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, socketWrapper.getError());
        }

        if (request.getReadListener() != null || response.getWriteListener() != null) {
            // The error occurred during non-blocking I/O. Set the correct
            // state else the error handling will trigger an ISE.
            asyncStateMachine.asyncOperation();
        }
    }

    RequestInfo rp = request.getRequestProcessor();
    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if (!getAdapter().asyncDispatch(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_CONNECTION_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        setErrorState(ErrorState.CLOSE_NOW, t);
        getLog().error(sm.getString("http11processor.request.process"), t);
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    SocketState state;

    if (getErrorState().isError()) {
        request.updateCounters();
        state = SocketState.CLOSED;
    } else if (isAsync()) {
        state = SocketState.LONG;
    } else {
        request.updateCounters();
        state = dispatchEndRequest();
    }

    if (getLog().isDebugEnabled()) {
        getLog().debug("Socket: [" + socketWrapper +
                "], Status in: [" + status +
                "], State out: [" + state + "]");
    }

    return state;
}
 
Example 10
Source File: AbstractProcessorLight.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public SocketState process(SocketWrapperBase<?> socketWrapper, SocketEvent status)
        throws IOException {

    SocketState state = SocketState.CLOSED;
    Iterator<DispatchType> dispatches = null;
    do {
        if (dispatches != null) {
            DispatchType nextDispatch = dispatches.next();
            if (getLog().isDebugEnabled()) {
                getLog().debug("Processing dispatch type: [" + nextDispatch + "]");
            }
            state = dispatch(nextDispatch.getSocketStatus());
            if (!dispatches.hasNext()) {
                state = checkForPipelinedData(state, socketWrapper);
            }
        } else if (status == SocketEvent.DISCONNECT) {
            // Do nothing here, just wait for it to get recycled
        } else if (isAsync() || isUpgrade() || state == SocketState.ASYNC_END) {
            state = dispatch(status);
            state = checkForPipelinedData(state, socketWrapper);
        } else if (status == SocketEvent.OPEN_WRITE) {
            // Extra write event likely after async, ignore
            state = SocketState.LONG;
        } else if (status == SocketEvent.OPEN_READ) {
            /**
             * 调用对应的Service方法.
             * {@link Http11Processor#service(org.apache.tomcat.util.net.SocketWrapperBase)}
             */
            state = service(socketWrapper);
        } else if (status == SocketEvent.CONNECT_FAIL) {
            logAccess(socketWrapper);
        } else {
            // Default to closing the socket if the SocketEvent passed in
            // is not consistent with the current state of the Processor
            state = SocketState.CLOSED;
        }

        if (getLog().isDebugEnabled()) {
            getLog().debug("Socket: [" + socketWrapper +
                    "], Status in: [" + status +
                    "], State out: [" + state + "]");
        }

        if (state != SocketState.CLOSED && isAsync()) {
            state = asyncPostProcess();
            if (getLog().isDebugEnabled()) {
                getLog().debug("Socket: [" + socketWrapper +
                        "], State after async post processing: [" + state + "]");
            }
        }

        if (dispatches == null || !dispatches.hasNext()) {
            // Only returns non-null iterator if there are
            // dispatches to process.
            dispatches = getIteratorAndClearDispatches();
        }
    } while (state == SocketState.ASYNC_END ||
            dispatches != null && state != SocketState.CLOSED);

    return state;
}
 
Example 11
Source File: Nio2Endpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
protected void doRun() {
    boolean launch = false;
    try {
        int handshake = -1;

        try {
            if (socketWrapper.getSocket().isHandshakeComplete()) {
                // No TLS handshaking required. Let the handler
                // process this socket / event combination.
                handshake = 0;
            } else if (event == SocketEvent.STOP || event == SocketEvent.DISCONNECT ||
                    event == SocketEvent.ERROR) {
                // Unable to complete the TLS handshake. Treat it as
                // if the handshake failed.
                handshake = -1;
            } else {
                handshake = socketWrapper.getSocket().handshake();
                // The handshake process reads/writes from/to the
                // socket. status may therefore be OPEN_WRITE once
                // the handshake completes. However, the handshake
                // happens when the socket is opened so the status
                // must always be OPEN_READ after it completes. It
                // is OK to always set this as it is only used if
                // the handshake completes.
                event = SocketEvent.OPEN_READ;
            }
        } catch (IOException x) {
            handshake = -1;
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("endpoint.err.handshake"), x);
            }
        }
        if (handshake == 0) {
            SocketState state = SocketState.OPEN;
            // Process the request from this socket
            if (event == null) {
                state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);
            } else {
                state = getHandler().process(socketWrapper, event);
            }
            if (state == SocketState.CLOSED) {
                // Close socket and pool
                socketWrapper.close();
                if (running && !paused) {
                    if (!nioChannels.push(socketWrapper.getSocket())) {
                        socketWrapper.getSocket().free();
                    }
                }
            } else if (state == SocketState.UPGRADING) {
                launch = true;
            }
        } else if (handshake == -1 ) {
            getHandler().process(socketWrapper, SocketEvent.CONNECT_FAIL);
            socketWrapper.close();
            if (running && !paused) {
                if (!nioChannels.push(socketWrapper.getSocket())) {
                    socketWrapper.getSocket().free();
                }
            }
        }
    } catch (VirtualMachineError vme) {
        ExceptionUtils.handleThrowable(vme);
    } catch (Throwable t) {
        log.error(sm.getString("endpoint.processing.fail"), t);
        if (socketWrapper != null) {
            ((Nio2SocketWrapper) socketWrapper).close();
        }
    } finally {
        if (launch) {
            try {
                getExecutor().execute(new SocketProcessor(socketWrapper, SocketEvent.OPEN_READ));
            } catch (NullPointerException npe) {
                if (running) {
                    log.error(sm.getString("endpoint.launch.fail"),
                            npe);
                }
            }
        }
        socketWrapper = null;
        event = null;
        //return to cache
        if (running && !paused) {
            processorCache.push(this);
        }
    }
}
 
Example 12
Source File: NioEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 *  所以我们能看到,线程池中线程大部分都在等待I/O操作。
 *  故此线程池应该被优化。Tomcat就在JDK基础上进行了优化。
 * 1.握手,建立对应链接。
 * 2.调用对应的连接器去处理此类请求。{@link Http11Processor#service(org.apache.tomcat.util.net.SocketWrapperBase)}
 */
@Override
protected void doRun() {
    NioChannel socket = socketWrapper.getSocket();
    SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());

    try {
        //握手?
        int handshake = -1;

        try {
            if (key != null) {
                if (socket.isHandshakeComplete()) {
                    // No TLS handshaking required. Let the handler
                    // process this socket / event combination.
                    handshake = 0;
                } else if (event == SocketEvent.STOP || event == SocketEvent.DISCONNECT ||
                        event == SocketEvent.ERROR) {
                    // Unable to complete the TLS handshake. Treat it as
                    // if the handshake failed.
                    handshake = -1;
                } else {
                    handshake = socket.handshake(key.isReadable(), key.isWritable());
                    // The handshake process reads/writes from/to the
                    // socket. status may therefore be OPEN_WRITE once
                    // the handshake completes. However, the handshake
                    // happens when the socket is opened so the status
                    // must always be OPEN_READ after it completes. It
                    // is OK to always set this as it is only used if
                    // the handshake completes.
                    event = SocketEvent.OPEN_READ;
                }
            }
        } catch (IOException x) {
            handshake = -1;
            if (log.isDebugEnabled()) log.debug("Error during SSL handshake",x);
        } catch (CancelledKeyException ckx) {
            handshake = -1;
        }

        /**
         * 握手成功?
         */
        if (handshake == 0) {
            SocketState state = SocketState.OPEN;
            // Process the request from this socket
            if (event == null) {
                /**
                 * 处理关键点 ConnectionHandler调用处理方法.
                 * {@link AbstractProtocol.ConnectionHandler#process(org.apache.tomcat.util.net.SocketWrapperBase, org.apache.tomcat.util.net.SocketEvent)}
                 */
                state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);
            } else {
                state = getHandler().process(socketWrapper, event);
            }
            if (state == SocketState.CLOSED) {
                close(socket, key);
            }
        } else if (handshake == -1 ) {
            getHandler().process(socketWrapper, SocketEvent.CONNECT_FAIL);
            close(socket, key);
        } else if (handshake == SelectionKey.OP_READ){
            socketWrapper.registerReadInterest();
        } else if (handshake == SelectionKey.OP_WRITE){
            socketWrapper.registerWriteInterest();
        }
    } catch (CancelledKeyException cx) {
        socket.getPoller().cancelledKey(key);
    } catch (VirtualMachineError vme) {
        ExceptionUtils.handleThrowable(vme);
    } catch (Throwable t) {
        log.error("", t);
        socket.getPoller().cancelledKey(key);
    } finally {
        socketWrapper = null;
        event = null;
        //return to cache
        if (running && !paused) {
            processorCache.push(this);
        }
    }
}
 
Example 13
Source File: StreamInbound.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
public final SocketState onData() throws IOException {
    // Must be start the start of a message (which may consist of multiple
    // frames)
    WsInputStream wsIs = new WsInputStream(processor, getWsOutbound());

    try {
        WsFrame frame = wsIs.nextFrame(false);

        while (frame != null) {
            // TODO User defined extensions may define values for rsv
            if (frame.getRsv() > 0) {
                closeOutboundConnection(
                        Constants.STATUS_PROTOCOL_ERROR, null);
                return SocketState.CLOSED;
            }

            byte opCode = frame.getOpCode();

            if (opCode == Constants.OPCODE_BINARY) {
                doOnBinaryData(wsIs);
            } else if (opCode == Constants.OPCODE_TEXT) {
                InputStreamReader r =
                        new InputStreamReader(wsIs, new Utf8Decoder());
                doOnTextData(r);
            } else if (opCode == Constants.OPCODE_CLOSE){
                closeOutboundConnection(frame);
                return SocketState.CLOSED;
            } else if (opCode == Constants.OPCODE_PING) {
                getWsOutbound().pong(frame.getPayLoad());
            } else if (opCode == Constants.OPCODE_PONG) {
                doOnPong(frame.getPayLoad());
            } else {
                // Unknown OpCode
                closeOutboundConnection(
                        Constants.STATUS_PROTOCOL_ERROR, null);
                return SocketState.CLOSED;
            }
            frame = wsIs.nextFrame(false);
        }
    } catch (MalformedInputException mie) {
        // Invalid UTF-8
        closeOutboundConnection(Constants.STATUS_BAD_DATA, null);
        return SocketState.CLOSED;
    } catch (UnmappableCharacterException uce) {
        // Invalid UTF-8
        closeOutboundConnection(Constants.STATUS_BAD_DATA, null);
        return SocketState.CLOSED;
    } catch (IOException ioe) {
        // Given something must have gone to reach this point, this
        // might not work but try it anyway.
        closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null);
        return SocketState.CLOSED;
    }
    return SocketState.UPGRADED;
}
 
Example 14
Source File: AbstractAjpProcessor.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
public SocketState asyncDispatch(SocketStatus status) {

    RequestInfo rp = request.getRequestProcessor();
    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if(!getAdapter().asyncDispatch(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
        resetTimeouts();
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        setErrorState(ErrorState.CLOSE_NOW, t);
        getLog().error(sm.getString("http11processor.request.process"), t);
    } finally {
        if (getErrorState().isError()) {
            // 500 - Internal Server Error
            response.setStatus(500);
            adapter.log(request, response, 0);
        }
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    if (isAsync()) {
        if (getErrorState().isError()) {
            request.updateCounters();
            return SocketState.CLOSED;
        } else {
            return SocketState.LONG;
        }
    } else {
        request.updateCounters();
        if (getErrorState().isError()) {
            return SocketState.CLOSED;
        } else {
            return SocketState.OPEN;
        }
    }
}
 
Example 15
Source File: StreamProcessor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
protected final SocketState dispatchEndRequest() throws IOException {
    endRequest();
    return SocketState.CLOSED;
}
 
Example 16
Source File: Http11NioProcessor.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Process pipelined HTTP requests using the specified input and output
 * streams.
 *
 * @throws IOException error during an I/O operation
 */
@Override
public SocketState event(SocketStatus status) throws IOException {

    long soTimeout = endpoint.getSoTimeout();

    RequestInfo rp = request.getRequestProcessor();
    final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socketWrapper.getSocket().getAttachment();
    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if (!getAdapter().event(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
        if (!getErrorState().isError()) {
            if (attach != null) {
                attach.setComet(comet);
                if (comet) {
                    Integer comettimeout = (Integer) request.getAttribute(
                            org.apache.coyote.Constants.COMET_TIMEOUT_ATTR);
                    if (comettimeout != null) {
                        attach.setTimeout(comettimeout.longValue());
                    }
                } else {
                    //reset the timeout
                    if (keepAlive) {
                        attach.setTimeout(keepAliveTimeout);
                    } else {
                        attach.setTimeout(soTimeout);
                    }
                }

            }
        }
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // 500 - Internal Server Error
        response.setStatus(500);
        setErrorState(ErrorState.CLOSE_NOW, t);
        log.error(sm.getString("http11processor.request.process"), t);
        getAdapter().log(request, response, 0);
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    if (getErrorState().isError() || status==SocketStatus.STOP) {
        return SocketState.CLOSED;
    } else if (!comet) {
        if (keepAlive) {
            inputBuffer.nextRequest();
            outputBuffer.nextRequest();
            return SocketState.OPEN;
        } else {
            return SocketState.CLOSED;
        }
    } else {
        return SocketState.LONG;
    }
}
 
Example 17
Source File: JIoEndpoint.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    boolean launch = false;
    synchronized (socket) {
        try {
            SocketState state = SocketState.OPEN;

            try {
                // SSL handshake
                serverSocketFactory.handshake(socket.getSocket());
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("endpoint.err.handshake"), t);
                }
                // Tell to close the socket
                state = SocketState.CLOSED;
            }

            if ((state != SocketState.CLOSED)) {
                if (status == null) {
                    state = handler.process(socket, SocketStatus.OPEN_READ);
                } else {
                    state = handler.process(socket,status);
                }
            }
            if (state == SocketState.CLOSED) {
                // Close socket
                if (log.isTraceEnabled()) {
                    log.trace("Closing socket:"+socket);
                }
                countDownConnection();
                try {
                    socket.getSocket().close();
                } catch (IOException e) {
                    // Ignore
                }
            } else if (state == SocketState.OPEN ||
                    state == SocketState.UPGRADING ||
                    state == SocketState.UPGRADING_TOMCAT  ||
                    state == SocketState.UPGRADED){
                socket.setKeptAlive(true);
                socket.access();
                launch = true;
            } else if (state == SocketState.LONG) {
                socket.access();
                waitingRequests.add(socket);
            }
        } finally {
            if (launch) {
                try {
                    getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN_READ));
                } catch (RejectedExecutionException x) {
                    log.warn("Socket reprocessing request was rejected for:"+socket,x);
                    try {
                        //unable to handle connection at this time
                        handler.process(socket, SocketStatus.DISCONNECT);
                    } finally {
                        countDownConnection();
                    }


                } catch (NullPointerException npe) {
                    if (running) {
                        log.error(sm.getString("endpoint.launch.fail"),
                                npe);
                    }
                }
            }
        }
    }
    socket = null;
    // Finish up this request
}
 
Example 18
Source File: NioEndpoint.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void doRun(SelectionKey key, KeyAttachment ka) {
    try {
        int handshake = -1;

        try {
            if (key != null) {
                // For STOP there is no point trying to handshake as the
                // Poller has been stopped.
                if (socket.isHandshakeComplete() ||
                        status == SocketStatus.STOP) {
                    handshake = 0;
                } else {
                    handshake = socket.handshake(
                            key.isReadable(), key.isWritable());
                    // The handshake process reads/writes from/to the
                    // socket. status may therefore be OPEN_WRITE once
                    // the handshake completes. However, the handshake
                    // happens when the socket is opened so the status
                    // must always be OPEN_READ after it completes. It
                    // is OK to always set this as it is only used if
                    // the handshake completes.
                    status = SocketStatus.OPEN_READ;
                }
            }
        }catch ( IOException x ) {
            handshake = -1;
            if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
        }catch ( CancelledKeyException ckx ) {
            handshake = -1;
        }
        if ( handshake == 0 ) {
            SocketState state = SocketState.OPEN;
            // Process the request from this socket
            if (status == null) {
                state = handler.process(ka, SocketStatus.OPEN_READ);
            } else {
                state = handler.process(ka, status);
            }
            if (state == SocketState.CLOSED) {
                // Close socket and pool
                close(ka, socket, key, SocketStatus.ERROR);
            }
        } else if (handshake == -1 ) {
            close(ka, socket, key, SocketStatus.DISCONNECT);
        } else {
            ka.getPoller().add(socket, handshake);
        }
    } catch (CancelledKeyException cx) {
        socket.getPoller().cancelledKey(key, null, false);
    } catch (OutOfMemoryError oom) {
        try {
            oomParachuteData = null;
            log.error("", oom);
            if (socket != null) {
                socket.getPoller().cancelledKey(key,SocketStatus.ERROR, false);
            }
            releaseCaches();
        }catch ( Throwable oomt ) {
            try {
                System.err.println(oomParachuteMsg);
                oomt.printStackTrace();
            }catch (Throwable letsHopeWeDontGetHere){
                ExceptionUtils.handleThrowable(letsHopeWeDontGetHere);
            }
        }
    } catch (VirtualMachineError vme) {
        ExceptionUtils.handleThrowable(vme);
    }catch ( Throwable t ) {
        log.error("",t);
        if (socket != null) {
            socket.getPoller().cancelledKey(key,SocketStatus.ERROR,false);
        }
    } finally {
        socket = null;
        status = null;
        //return to cache
        if (running && !paused) {
            processorCache.offer(this);
        }
    }
}
 
Example 19
Source File: StreamInbound.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Override
public final SocketState onData() throws IOException {
    // Must be start the start of a message (which may consist of multiple
    // frames)
    WsInputStream wsIs = new WsInputStream(processor, getWsOutbound());

    try {
        WsFrame frame = wsIs.nextFrame(false);

        while (frame != null) {
            // TODO User defined extensions may define values for rsv
            if (frame.getRsv() > 0) {
                closeOutboundConnection(
                        Constants.STATUS_PROTOCOL_ERROR, null);
                return SocketState.CLOSED;
            }

            byte opCode = frame.getOpCode();

            if (opCode == Constants.OPCODE_BINARY) {
                doOnBinaryData(wsIs);
            } else if (opCode == Constants.OPCODE_TEXT) {
                InputStreamReader r =
                        new InputStreamReader(wsIs, new Utf8Decoder());
                doOnTextData(r);
            } else if (opCode == Constants.OPCODE_CLOSE){
                closeOutboundConnection(frame);
                return SocketState.CLOSED;
            } else if (opCode == Constants.OPCODE_PING) {
                getWsOutbound().pong(frame.getPayLoad());
            } else if (opCode == Constants.OPCODE_PONG) {
                doOnPong(frame.getPayLoad());
            } else {
                // Unknown OpCode
                closeOutboundConnection(
                        Constants.STATUS_PROTOCOL_ERROR, null);
                return SocketState.CLOSED;
            }
            frame = wsIs.nextFrame(false);
        }
    } catch (MalformedInputException mie) {
        // Invalid UTF-8
        closeOutboundConnection(Constants.STATUS_BAD_DATA, null);
        return SocketState.CLOSED;
    } catch (UnmappableCharacterException uce) {
        // Invalid UTF-8
        closeOutboundConnection(Constants.STATUS_BAD_DATA, null);
        return SocketState.CLOSED;
    } catch (IOException ioe) {
        // Given something must have gone to reach this point, this
        // might not work but try it anyway.
        closeOutboundConnection(Constants.STATUS_PROTOCOL_ERROR, null);
        return SocketState.CLOSED;
    }
    return SocketState.UPGRADED;
}
 
Example 20
Source File: AbstractAjpProcessor.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Override
public SocketState asyncDispatch(SocketStatus status) {

    RequestInfo rp = request.getRequestProcessor();
    try {
        rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
        if(!getAdapter().asyncDispatch(request, response, status)) {
            setErrorState(ErrorState.CLOSE_NOW, null);
        }
        resetTimeouts();
    } catch (InterruptedIOException e) {
        setErrorState(ErrorState.CLOSE_NOW, e);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        setErrorState(ErrorState.CLOSE_NOW, t);
        getLog().error(sm.getString("http11processor.request.process"), t);
    } finally {
        if (getErrorState().isError()) {
            // 500 - Internal Server Error
            response.setStatus(500);
            adapter.log(request, response, 0);
        }
    }

    rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);

    if (isAsync()) {
        if (getErrorState().isError()) {
            request.updateCounters();
            return SocketState.CLOSED;
        } else {
            return SocketState.LONG;
        }
    } else {
        request.updateCounters();
        if (getErrorState().isError()) {
            return SocketState.CLOSED;
        } else {
            recycle(false);
            return SocketState.OPEN;
        }
    }
}