Filter handshake related messages from reaching the messageSent callbacks of
downstream filters.

@param nextFilter the next filter in filter chain
@param session the session object
@param writeRequest the data written
347411
@Override
    public void messageSent(final NextFilter nextFilter,
            final IoSession session, final WriteRequest writeRequest)
            throws Exception {
        if (writeRequest.getMessage() != null
                && writeRequest.getMessage() instanceof ProxyHandshakeIoBuffer) {
            // Ignore buffers used in handshaking
            return;
        }

        nextFilter.messageSent(session, writeRequest);
    }
742278
public void doFilter(final HttpRequest httpRequest, MessageEvent e) throws IOException, ServletException  {
    	
    	HttpServletRequest servletRequest = new NettyHttpServletRequestAdaptor(httpRequest, e.getChannel());
        final HttpServletRequest hsRequest = (HttpServletRequest) servletRequest;
        if (urlRewriter != null) {
            String newUrl = urlRewriter.processRequest(hsRequest);
            if(!newUrl.equals(httpRequest.getUri()))
            {
            	if (log.isDebugEnabled())
            		log.debug("request rewrited from : [" + httpRequest.getUri() + "] to : ["+newUrl+"]");
            	httpRequest.setUri(newUrl);
            }
            else
            {
            	if (log.isDebugEnabled())
            		log.debug("request not rewrited : [" + httpRequest.getUri() + "]");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("urlRewriter engine not loaded ignoring request (could be a conf file problem)");
            }
        }
    }
1331215
void setHandshakeSessionSE(SSLSessionImpl handshakeSession) {
        if (conn != null) {
            conn.setHandshakeSession(handshakeSession);
        } else {
            engine.setHandshakeSession(handshakeSession);
        }
    }
424831
void securityMessageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
        final boolean loggerIsEnabled = logger != null && logger.isTraceEnabled();

        if (! httpRequestMessageReceived(nextFilter, session, message)) return;

        HttpRequestMessage httpRequest = (HttpRequestMessage) message;
        ResourceAddress httpAddress = httpRequest.getLocalAddress();
        
        if (alreadyLoggedIn(httpRequest)) {
            // KG-3232, KG-3267: we should never leave the login context unset
            // for unprotected services.
            if (httpRequest.getLoginContext() == null) {
                setUnprotectedLoginContext(httpRequest);
            }
            if (loggerIsEnabled) {
                logger.trace("HttpSubjectSecurityFilter skipped because we are already allowed or logged in.");
            }

            super.doMessageReceived(nextFilter, session, message);
            return;
        }

        HttpRealmInfo[] realms = httpAddress.getOption(HttpResourceAddress.REALMS);
        if (realms.length == 0) {
            setUnprotectedLoginContext(httpRequest);
            if (loggerIsEnabled) {
                logger.trace("HttpSecurityStandardFilter skipped because no realm is configured.");
            }
            super.doMessageReceived(nextFilter, session, message);
            return;
        }
        
        String challengeIdentity = httpRequest.getHeader(HEADER_SEC_CHALLENGE_IDENTITY);
        LoginContext[] loginContexts = getLoginContexts(challengeIdentity);
        int realmIndex = findCurrentRealm(loginContexts);
        HttpRealmInfo realm = realms[realmIndex];

        AuthenticationTokenExtractor tokenExtractor = DefaultAuthenticationTokenExtractor.INSTANCE;

        //
        // Login using the token; if login fails, the appropriate reply has already been sent from this filter
        // so stop the filter chain here.
        //

        DefaultAuthenticationToken authToken = (DefaultAuthenticationToken) tokenExtractor.extract(httpRequest, realm);

        String expectedChallengeScheme = getBaseAuthScheme(realm.getChallengeScheme());

        // Now set the expected challenge scheme on the AuthToken.  If the
        // client provided a scheme, the above check ensures that the
        // provided scheme matches our expected scheme, so calling setScheme()
        // does not harm anything.  If the client did NOT provide a scheme,
        // this properly sets one, for the benefit of login modules which
        // check for such things.
        if(authToken.getScheme() == null) {
            authToken.setScheme(expectedChallengeScheme);
        }

        // Suspend incoming events into this filter. Will resume after LoginContext.login() completion
        suspendIncoming(session);

        TypedCallbackHandlerMap additionalCallbacks = null;
        if (realmIndex > 0) {
            additionalCallbacks = new TypedCallbackHandlerMap();
            Function<String, Subject> subjects = name -> findNamedSubject(name, realms, realmIndex, loginContexts);
            NamedSubjectCallbackHandler callbackHandler = new NamedSubjectCallbackHandler(subjects);
            additionalCallbacks.put(NamedSubjectCallback.class, callbackHandler);
        }

        // Schedule LoginContext.login() execution using a separate thread
        LoginContextTask loginContextTask = new LoginContextTask(nextFilter, session, httpRequest, authToken, additionalCallbacks, realms, realmIndex, loginContexts);
        scheduler.execute(loginContextTask);
    }
871668
public function onKernelResponse(FilterResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        if (!$event->getRequest()->hasSession()) {
            return;
        }

        if (null !== $this->logger) {
            $this->logger->debug('Write SecurityContext in the session');
        }

        $request = $event->getRequest();
        $session = $request->getSession();

        if (null === $session) {
            return;
        }

        if ((null === $token = $this->context->getToken()) || ($token instanceof AnonymousToken)) {
            if ($request->hasPreviousSession()) {
                $session->remove('_security_'.$this->contextKey);
            }
        } else {
            $session->set('_security_'.$this->contextKey, serialize($token));
        }
    }
1283737
private static void excludeForwardedHeaders(HttpConnectSession connectSession) {
        connectSession.clearWriteHeaders(HEADER_FORWARDED);
        connectSession.clearWriteHeaders(HEADER_X_FORWARDED_FOR);
        connectSession.clearWriteHeaders(HEADER_X_FORWARDED_SERVER);
        connectSession.clearWriteHeaders(HEADER_X_FORWARDED_HOST);
        connectSession.clearWriteHeaders(HEADER_X_FORWARDED_PROTO);
    }
1129884
public void messageReceived(NextFilter nextFilter, ByteBuffer buf) throws SSLException {
        // append buf to inNetBuffer
        if (inNetBuffer == null) {
            inNetBuffer = allocator.wrap(allocator.allocate(buf.remaining())).setAutoExpander(allocator);
        }

        inNetBuffer.put(buf);
        if (!handshakeComplete) {
            handshake(nextFilter);
        }

        // Application data will be in the same message as the handshake
        // during False Start
        if (handshakeComplete) {
            decrypt(nextFilter);
        }

        if (isInboundDone()) {
            // Rewind the MINA buffer if not all data is processed and inbound is finished.
            int inNetBufferPosition = inNetBuffer == null? 0 : inNetBuffer.position();
            buf.position(buf.position() - inNetBufferPosition);
            inNetBuffer = null;
        }
    }
1224211
@Override
    public void doFilter(ResourceRequest request, ResourceResponse response, FilterChain chain) throws IOException,
            PortletException {
        doCommonFilter(request, response, chain);
    }
1229096
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest hreq = (HttpServletRequest)request;
			if(noAuthn(hreq)) {
				chain.doFilter(request, response);
			} else {
				HttpServletResponse hresp = (HttpServletResponse)response;
				TafResp tresp = httpChecker.validate(hreq, hresp);
				if(tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) {
						CadiWrap cw = new CadiWrap(hreq, tresp, httpChecker.getLur(),getConverter(hreq));
						if(httpChecker.notCadi(cw, hresp)) {
							chain.doFilter(cw,response);
						}
				}						
			}
		} catch (ClassCastException e) {
			throw new ServletException("CadiFilter expects Servlet to be an HTTP Servlet",e);
		}
	}
1107248
public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = WebFilter.request.get();
		
		try {
			WebFilter.request.set((HttpServletRequest) request);
			chain.doFilter(request, response);
		} finally {
			WebFilter.request.set(httpServletRequest);
		}
	}
1279544
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);
        }
    }
968751
@Override
    public void doFilterWrite(final long sessionId, final long sessionWrittenBytes, final WriteRequest writeRequest) throws
            Exception {
        Object message = writeRequest.getMessage();

        if (message instanceof IoBuffer) {
            ThreadGatewayStats stats = gatewayStats.get();
            stats.doFilterWrite((IoBuffer) message);
        }
    }
936420
@SuppressWarnings("unchecked")
    private boolean doHandShake(IoSession session, IoBuffer in) {
        if (log.isDebugEnabled()) {
            log.debug("Handshake: {}", in);
        }
        // incoming data
        byte[] data = null;
        // check for existing HS data
        if (session.containsAttribute(Constants.WS_HANDSHAKE)) {
            byte[] tmp = (byte[]) session.getAttribute(Constants.WS_HANDSHAKE);
            // size to hold existing and incoming
            data = new byte[tmp.length + in.remaining()];
            System.arraycopy(tmp, 0, data, 0, tmp.length);
            // get incoming bytes
            in.get(data, tmp.length, in.remaining());
        } else {
            // size for incoming bytes
            data = new byte[in.remaining()];
            // get incoming bytes
            in.get(data);
        }
        // ensure the incoming data is complete (ends with crlfcrlf)
        byte[] tail = Arrays.copyOfRange(data, data.length - 4, data.length);
        if (!Arrays.equals(tail, Constants.END_OF_REQ)) {
            // accumulate the HS data
            session.setAttribute(Constants.WS_HANDSHAKE, data);
            return false;
        }
        // create the connection obj
        WebSocketConnection conn = new WebSocketConnection(session);
        // mark as secure if using ssl
        if (session.getFilterChain().contains("sslFilter")) {
            conn.setSecure(true);
        }
        try {
            Map<String, Object> headers = parseClientRequest(conn, new String(data));
            if (log.isTraceEnabled()) {
                log.trace("Header map: {}", headers);
            }
            if (!headers.isEmpty() && headers.containsKey(Constants.WS_HEADER_KEY)) {
                // add the headers to the connection, they may be of use to implementers
                conn.setHeaders(headers);
                // add query string parameters
                if (headers.containsKey(Constants.URI_QS_PARAMETERS)) {
                    conn.setQuerystringParameters((Map<String, Object>) headers.remove(Constants.URI_QS_PARAMETERS));
                }
                // check the version
                if (!"13".equals(headers.get(Constants.WS_HEADER_VERSION))) {
                    log.info("Version 13 was not found in the request, communications may fail");
                }
                // get the path 
                String path = conn.getPath();
                // get the scope manager
                WebSocketScopeManager manager = (WebSocketScopeManager) session.getAttribute(Constants.MANAGER);
                if (manager == null) {
                    WebSocketPlugin plugin = (WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin");
                    manager = plugin.getManager(path);
                }
                // store manager in the current session
                session.setAttribute(Constants.MANAGER, manager);
                // TODO add handling for extensions

                // TODO expand handling for protocols requested by the client, instead of just echoing back
                if (headers.containsKey(Constants.WS_HEADER_PROTOCOL)) {
                    boolean protocolSupported = false;
                    String protocol = (String) headers.get(Constants.WS_HEADER_PROTOCOL);
                    log.debug("Protocol '{}' found in the request", protocol);
                    // add protocol to the connection
                    conn.setProtocol(protocol);
                    // TODO check listeners for "protocol" support
                    Set<IWebSocketDataListener> listeners = manager.getScope(path).getListeners();
                    for (IWebSocketDataListener listener : listeners) {
                        if (listener.getProtocol().equals(protocol)) {
                            //log.debug("Scope has listener support for the {} protocol", protocol);
                            protocolSupported = true;
                            break;
                        }
                    }
                    log.debug("Scope listener does{} support the '{}' protocol", (protocolSupported ? "" : "n't"), protocol);
                }
                // add connection to the manager
                manager.addConnection(conn);
                // prepare response and write it to the directly to the session
                HandshakeResponse wsResponse = buildHandshakeResponse(conn, (String) headers.get(Constants.WS_HEADER_KEY));
                // pass the handshake response to the ws connection so it can be sent outside the io thread and allow the decode to complete
                conn.sendHandshakeResponse(wsResponse);
                // remove the chunk attr
                session.removeAttribute(Constants.WS_HANDSHAKE);
                return true;
            }
            // set connection as native / direct
            conn.setType(ConnectionType.DIRECT);
        } catch (Exception e) {
            // input is not a websocket handshake request
            log.warn("Handshake failed", e);
        }
        return false;
    }
790025
function(isGlobal, server, msg, session, cb) {
  var fm;
  if(isGlobal) {
    fm = server.globalFilterService;
  } else {
    fm = server.filterService;
  }
  if(fm) {
    fm.beforeFilter(msg, session, cb);
  } else {
    utils.invokeCallback(cb);
  }
}
1286481
@Override
    public void onPreRemove(final IoFilterChain chain, final String name,
            final NextFilter nextFilter) {
        IoSession session = chain.getSession();
        session.removeAttribute(ProxyIoSession.PROXY_SESSION);
    }
828999
@Override
    public void filterWrite(NextFilter nextFilter, IoSession session,
            WriteRequest writeRequest) throws Exception {

        Object data = writeRequest.getMessage();

        if (data instanceof IoBuffer) {
            write(session, (IoBuffer) data);
        } else {
            throw new IllegalArgumentException(
                    "This filter should only buffer IoBuffer objects");
        }
    }
1264890
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException
	{
		servletRequest.setCharacterEncoding("UTF-8");
		httpRequest.set(servletRequest);
		httpResponse.set(servletResponse);

		Request appRequest = null;
		try
		{
//			String sessionToken = ServletSupport.getSessionTokenFromCookie(servletRequest);
			String sessionToken = ServletSupport.getCookieValue(servletRequest, SESSION_TOKEN_KEY);
			String userId = ServletSupport.getCookieValue(servletRequest, USER_ID_KEY);
			if("".equals(sessionToken))
			{
				sessionToken = null;
			}
			if("".equals(userId))
			{
				userId = null;
			}
 			if(accessManager != null) {
				appRequest = accessManager.bindRequest(this);
//				System.out.println("request bound!! " + appRequest);
				Session session = appRequest.resolveSession(sessionToken, userId);
			}

			if (this.syncUserPrefs &&  appRequest.getTimesEntered() == 0)
			{
				//pass user preferences here
				ServletSupport.importCookieValues(servletRequest,  appRequest.getUserSettings());
				ServletSupport.exportCookieValues(servletResponse,  appRequest.getUserSettings(), "/", userPrefsMaxAge, Arrays.asList(new String[]{SESSION_TOKEN_KEY}));
			}

			//if a user logged in, the user id must be stored
			if(userId == null)
			{
				User user = appRequest.getUser();
				if(user != null)
				{
					storeSessionDataInCookie(USER_ID_KEY, user.getId(), servletResponse);
				}
			}

			//role based access control
	//		checkAccess(servletRequest,  appRequest);

			//delegate request
			chain.doFilter(servletRequest, servletResponse);
		}
		catch (Throwable t)//make sure user gets a controlled response
		{
			//is this the actual entry point or is this entry point wrapped?
			if ( appRequest != null &&  appRequest.getTimesEntered() > 1)
			{
				//it's wrapped, so the exception must be thrown at the top entry point
				ServletSupport.rethrow(t);
			}
			handleException(servletRequest, servletResponse, t);
		}
		finally
		{
/*			if(loggingEnabled)
			{
				application.log(new PageVisitLogEntry((HttpServletRequest) servletRequest));
			}
			application.releaseRequest();  */
			if(accessManager != null) {
				accessManager.releaseRequest();
			}
		}
	}