org.apache.mina.core.filterchain.IoFilter.NextFilter Java Examples

The following examples show how to use org.apache.mina.core.filterchain.IoFilter.NextFilter. 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: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
    AbstractIoSession s = (AbstractIoSession) session;
    try {
        s.getHandler().sessionClosed(session);
    } finally {
        try {
            s.getWriteRequestQueue().dispose(session);
        } finally {
            try {
                s.getAttributeMap().dispose(session);
            } finally {
                try {
                    // Remove all filters.
                    session.getFilterChain().clear();
                } finally {
                    if (s.getConfig().isUseReadOperation()) {
                        s.offerClosedReadFuture();
                    }
                }
            }
        }
    }
}
 
Example #2
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
    AbstractIoSession s = (AbstractIoSession) session;
    if (!(message instanceof IoBuffer)) {
        s.increaseReadMessages(System.currentTimeMillis());
    } else if (!((IoBuffer) message).hasRemaining()) {
        s.increaseReadMessages(System.currentTimeMillis());
    }

    try {
        session.getHandler().messageReceived(s, message);
    } finally {
        if (s.getConfig().isUseReadOperation()) {
            s.offerReadFuture(message);
        }
    }
}
 
Example #3
Source File: IoSessionEvent.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Static method which effectively delivers the specified event to the next filter
 * <code>nextFilter</code> on the <code>session</code>.
 * 
 * @param nextFilter the next filter
 * @param session the session on which the event occured
 * @param type the event type
 * @param status the idle status should only be non null only if the event type is 
 * {@link IoSessionEventType#IDLE} 
 */
private static void deliverEvent(final NextFilter nextFilter, final IoSession session,
        final IoSessionEventType type, final IdleStatus status) {
    switch (type) {
    case CREATED:
        nextFilter.sessionCreated(session);
        break;
    case OPENED:
        nextFilter.sessionOpened(session);
        break;
    case IDLE:
        nextFilter.sessionIdle(session, status);
        break;
    case CLOSED:
        nextFilter.sessionClosed(session);
        break;
    }
}
 
Example #4
Source File: SslHandler.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
void flushScheduledEvents() throws Exception {
	scheduledEvents.getAndIncrement();

	// Fire events only when the lock is available for this handler.
	if (sslLock.tryLock()) {
		try {
			do {
				Entry<NextFilter, WriteRequest> eventW;
				// We need synchronization here inevitably because filterWrite can be
				// called simultaneously and cause 'bad record MAC' integrity error.
				while ((eventW = filterWriteEventQueue.poll()) != null)
					eventW.getKey().filterWrite(eventW.getValue());

				Entry<NextFilter, Object> eventR;
				while ((eventR = messageReceivedEventQueue.poll()) != null)
					eventR.getKey().messageReceived(eventR.getValue());
			} while (scheduledEvents.decrementAndGet() > 0);
		} finally {
			sslLock.unlock();
		}
	}
}
 
Example #5
Source File: HttpBasicAuthLogicHandler.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doHandshake(final NextFilter nextFilter) throws ProxyAuthException {
    logger.debug(" doHandshake()");

    if (step > 0) {
        throw new ProxyAuthException("Authentication request already sent");
    }

    // Send request
    HttpProxyRequest req = (HttpProxyRequest) request;
    Map<String, List<String>> headers = req.getHeaders() != null ? req.getHeaders()
            : new HashMap<String, List<String>>();

    String username = req.getProperties().get(HttpProxyConstants.USER_PROPERTY);
    String password = req.getProperties().get(HttpProxyConstants.PWD_PROPERTY);

    StringUtilities.addValueToHeader(headers, "Proxy-Authorization",
            "Basic " + createAuthorization(username, password), true);

    addKeepAliveHeaders(headers);
    req.setHeaders(headers);

    writeRequest(nextFilter, req);
    step++;
}
 
Example #6
Source File: Socks5LogicHandler.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Handles incoming data during the handshake process. Should consume only the
 * handshake data from the buffer, leaving any extra data in place.
 * 
 * @param nextFilter the next filter
 * @param buf the buffered data received 
 */
public synchronized void messageReceived(final NextFilter nextFilter, final IoBuffer buf) {
    try {
        int step = ((Integer) getSession().getAttribute(HANDSHAKE_STEP)).intValue();

        if (step == SocksProxyConstants.SOCKS5_GREETING_STEP && buf.get(0) != SocksProxyConstants.SOCKS_VERSION_5) {
            throw new IllegalStateException("Wrong socks version running on server");
        }

        if ((step == SocksProxyConstants.SOCKS5_GREETING_STEP || step == SocksProxyConstants.SOCKS5_AUTH_STEP)
                && buf.remaining() >= 2) {
            handleResponse(nextFilter, buf, step);
        } else if (step == SocksProxyConstants.SOCKS5_REQUEST_STEP && buf.remaining() >= 5) {
            handleResponse(nextFilter, buf, step);
        }
    } catch (Exception ex) {
        closeSession("Proxy handshake failed: ", ex);
    }
}
 
Example #7
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private void callNextExceptionCaught(Entry entry, IoSession session, Throwable cause) {
    // Notify the related future.
    ConnectFuture future = (ConnectFuture) session.removeAttribute(SESSION_CREATED_FUTURE);
    if (future == null) {
        try {
            IoFilter filter = entry.getFilter();
            NextFilter nextFilter = entry.getNextFilter();
            filter.exceptionCaught(nextFilter, session, cause);
        } catch (Throwable e) {
            LOGGER.warn("Unexpected exception from exceptionCaught handler.", e);
        }
    } else {
        // Please note that this place is not the only place that
        // calls ConnectFuture.setException().
        session.close(true);
        future.setException(cause);
    }
}
 
Example #8
Source File: Socks4LogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Perform the handshake.
 * 
 * @param nextFilter the next filter
 */
public void doHandshake(final NextFilter nextFilter) {
    logger.debug(" doHandshake()");

    // Send request
    writeRequest(nextFilter, request);
}
 
Example #9
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception {
    AbstractIoSession s = (AbstractIoSession) session;
    try {
        s.getHandler().exceptionCaught(s, cause);
    } finally {
        if (s.getConfig().isUseReadOperation()) {
            s.offerFailedReadFuture(cause);
        }
    }
}
 
Example #10
Source File: Socks4LogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handle incoming data during the handshake process. Should consume only the
 * handshake data from the buffer, leaving any extra data in place.
 * 
 * @param nextFilter the next filter
 * @param buf the server response data buffer
 */
public void messageReceived(final NextFilter nextFilter, final IoBuffer buf) {
    try {
        if (buf.remaining() >= SocksProxyConstants.SOCKS_4_RESPONSE_SIZE) {
            handleResponse(buf);
        }
    } catch (Exception ex) {
        closeSession("Proxy handshake failed: ", ex);
    }
}
 
Example #11
Source File: Socks4LogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Encode a SOCKS4/SOCKS4a request and writes it to the next filter
 * so it can be sent to the proxy server.
 * 
 * @param nextFilter the next filter
 * @param request the request to send.
 */
protected void writeRequest(final NextFilter nextFilter, final SocksProxyRequest request) {
    try {
        boolean isV4ARequest = Arrays.equals(request.getIpAddress(), SocksProxyConstants.FAKE_IP);
        byte[] userID = request.getUserName().getBytes("ASCII");
        byte[] host = isV4ARequest ? request.getHost().getBytes("ASCII") : null;

        int len = 9 + userID.length;

        if (isV4ARequest) {
            len += host.length + 1;
        }

        IoBuffer buf = IoBuffer.allocate(len);

        buf.put(request.getProtocolVersion());
        buf.put(request.getCommandCode());
        buf.put(request.getPort());
        buf.put(request.getIpAddress());
        buf.put(userID);
        buf.put(SocksProxyConstants.TERMINATOR);

        if (isV4ARequest) {
            buf.put(host);
            buf.put(SocksProxyConstants.TERMINATOR);
        }

        if (isV4ARequest) {
            logger.debug("  sending SOCKS4a request");
        } else {
            logger.debug("  sending SOCKS4 request");
        }

        buf.flip();
        writeData(nextFilter, buf);
    } catch (Exception ex) {
        closeSession("Unable to send Socks request: ", ex);
    }
}
 
Example #12
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {

    AbstractIoSession s = (AbstractIoSession) session;

    // Maintain counters.
    if (writeRequest.getMessage() instanceof IoBuffer) {
        IoBuffer buffer = (IoBuffer) writeRequest.getMessage();
        // I/O processor implementation will call buffer.reset()
        // it after the write operation is finished, because
        // the buffer will be specified with messageSent event.
        buffer.mark();
        int remaining = buffer.remaining();

        if (remaining == 0) {
            // Zero-sized buffer means the internal message
            // delimiter.
            s.increaseScheduledWriteMessages();
        } else {
            s.increaseScheduledWriteBytes(remaining);
        }
    } else {
        s.increaseScheduledWriteMessages();
    }

    WriteRequestQueue writeRequestQueue = s.getWriteRequestQueue();

    if (!s.isWriteSuspended()) {
        if (writeRequestQueue.size() == 0) {
            // We can write directly the message
            s.getProcessor().write(s, writeRequest);
        } else {
            s.getWriteRequestQueue().offer(s, writeRequest);
            s.getProcessor().flush(s);
        }
    } else {
        s.getWriteRequestQueue().offer(s, writeRequest);
    }
}
 
Example #13
Source File: AbstractProxyLogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Enqueue a message to be written once handshaking is complete.
 */
public synchronized void enqueueWriteRequest(final NextFilter nextFilter, final WriteRequest writeRequest) {
    if (writeRequestQueue == null) {
        writeRequestQueue = new LinkedList<Event>();
    }

    writeRequestQueue.offer(new Event(nextFilter, writeRequest));
}
 
Example #14
Source File: Socks5LogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Encodes a SOCKS5 request and writes it to the next filter
 * so it can be sent to the proxy server.
 * 
 * @param nextFilter the next filter
 * @param request the request to send.
 * @param step the current step in the handshake process
 */
private void writeRequest(final NextFilter nextFilter, final SocksProxyRequest request, int step) {
    try {
        IoBuffer buf = null;

        if (step == SocksProxyConstants.SOCKS5_GREETING_STEP) {
            buf = encodeInitialGreetingPacket(request);
        } else if (step == SocksProxyConstants.SOCKS5_AUTH_STEP) {
            // This step can happen multiple times like in GSSAPI auth for instance
            buf = encodeAuthenticationPacket(request);
            // If buf is null then go to the next step
            if (buf == null) {
                step = SocksProxyConstants.SOCKS5_REQUEST_STEP;
            }
        }

        if (step == SocksProxyConstants.SOCKS5_REQUEST_STEP) {
            buf = encodeProxyRequestPacket(request);
        }

        buf.flip();
        writeData(nextFilter, buf);

    } catch (Exception ex) {
        closeSession("Unable to send Socks request: ", ex);
    }
}
 
Example #15
Source File: AbstractProxyLogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Writes data to the proxy server.
 * 
 * @param nextFilter the next filter
 * @param data Data buffer to be written.
 */
protected WriteFuture writeData(final NextFilter nextFilter, final IoBuffer data) {
    // write net data
    ProxyHandshakeIoBuffer writeBuffer = new ProxyHandshakeIoBuffer(data);

    LOGGER.debug("   session write: {}", writeBuffer);

    WriteFuture writeFuture = new DefaultWriteFuture(getSession());
    getProxyFilter().writeData(nextFilter, getSession(), new DefaultWriteRequest(writeBuffer, writeFuture), true);

    return writeFuture;
}
 
Example #16
Source File: Socks5LogicHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Performs the handshake process.
 * 
 * @param nextFilter the next filter
 */
public synchronized void doHandshake(final NextFilter nextFilter) {
    LOGGER.debug(" doHandshake()");

    // Send request
    writeRequest(nextFilter, request, ((Integer) getSession().getAttribute(HANDSHAKE_STEP)).intValue());
}
 
Example #17
Source File: IoFilterEvent.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public IoFilterEvent(NextFilter nextFilter, IoEventType type, IoSession session, Object parameter) {
    super(type, session, parameter);

    if (nextFilter == null) {
        throw new IllegalArgumentException("nextFilter must not be null");
    }

    this.nextFilter = nextFilter;
}
 
Example #18
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
    try {
        session.getHandler().sessionCreated(session);
    } finally {
        // Notify the related future.
        ConnectFuture future = (ConnectFuture) session.removeAttribute(SESSION_CREATED_FUTURE);
        if (future != null) {
            future.setSession(session);
        }
    }
}
 
Example #19
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callNextMessageReceived(Entry entry, IoSession session, Object message) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.messageReceived(nextFilter, session, message);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}
 
Example #20
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callPreviousFilterClose(Entry entry, IoSession session) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.filterClose(nextFilter, session);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}
 
Example #21
Source File: SslHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void renegotiateIfNeeded(NextFilter nextFilter, SSLEngineResult res) throws SSLException {
    if ((res.getStatus() != SSLEngineResult.Status.CLOSED)
            && (res.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW)
            && (res.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING)) {
        // Renegotiation required.
        handshakeComplete = false;
        handshakeStatus = res.getHandshakeStatus();
        handshake(nextFilter);
    }
}
 
Example #22
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callPreviousFilterWrite(Entry entry, IoSession session, WriteRequest writeRequest) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.filterWrite(nextFilter, session, writeRequest);
    } catch (Throwable e) {
        writeRequest.getFuture().setException(e);
        fireExceptionCaught(e);
    }
}
 
Example #23
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callNextMessageSent(Entry entry, IoSession session, WriteRequest writeRequest) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.messageSent(nextFilter, session, writeRequest);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}
 
Example #24
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public NextFilter getNextFilter(String name) {
    Entry e = getEntry(name);
    if (e == null) {
        return null;
    }

    return e.getNextFilter();
}
 
Example #25
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public NextFilter getNextFilter(IoFilter filter) {
    Entry e = getEntry(filter);
    if (e == null) {
        return null;
    }

    return e.getNextFilter();
}
 
Example #26
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public NextFilter getNextFilter(Class<? extends IoFilter> filterType) {
    Entry e = getEntry(filterType);
    if (e == null) {
        return null;
    }

    return e.getNextFilter();
}
 
Example #27
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callNextSessionCreated(Entry entry, IoSession session) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.sessionCreated(nextFilter, session);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}
 
Example #28
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callNextSessionOpened(Entry entry, IoSession session) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.sessionOpened(nextFilter, session);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}
 
Example #29
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callNextSessionClosed(Entry entry, IoSession session) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.sessionClosed(nextFilter, session);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}
 
Example #30
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void callNextSessionIdle(Entry entry, IoSession session, IdleStatus status) {
    try {
        IoFilter filter = entry.getFilter();
        NextFilter nextFilter = entry.getNextFilter();
        filter.sessionIdle(nextFilter, session, status);
    } catch (Throwable e) {
        fireExceptionCaught(e);
    }
}