idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
10,300
public static Object proprietaryEvaluate ( final String expression , final Class < ? > expectedType , final PageContext pageContext , final ProtectedFunctionMapper functionMap ) throws ELException { return "" ; }
directly referenced by JSPC - generated code
10,301
protected void loadConfiguredSinks ( String filename , String bugType ) { SINKS_LOADER . loadConfiguredSinks ( filename , bugType , new SinksLoader . InjectionPointReceiver ( ) { public void receiveInjectionPoint ( String fullMethodName , InjectionPoint injectionPoint ) { addParsedInjectionPoint ( fullMethodName , injectionPoint ) ; } } ) ; }
Loads taint sinks from configuration
10,302
protected void loadCustomSinks ( String fileName , String bugType ) { InputStream stream = null ; try { File file = new File ( fileName ) ; if ( file . exists ( ) ) { stream = new FileInputStream ( file ) ; loadConfiguredSinks ( stream , bugType ) ; } else { stream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; loadConfiguredSinks ( stream , bugType ) ; } } catch ( Exception ex ) { throw new RuntimeException ( "Cannot load custom injection sinks from " + fileName , ex ) ; } finally { IO . close ( stream ) ; } }
Loads taint sinks configuration file from file system . If the file doesn t exist on file system loads the file from classpath .
10,303
public DeploymentInfo addFirstAuthenticationMechanism ( final String name , final AuthenticationMechanism mechanism ) { authenticationMechanisms . put ( name , new ImmediateAuthenticationMechanismFactory ( mechanism ) ) ; if ( loginConfig == null ) { loginConfig = new LoginConfig ( null ) ; } loginConfig . addFirstAuthMethod ( new AuthMethodConfig ( name ) ) ; return this ; }
Adds an authentication mechanism directly to the deployment . This mechanism will be first in the list .
10,304
public DeploymentInfo addLastAuthenticationMechanism ( final String name , final AuthenticationMechanism mechanism ) { authenticationMechanisms . put ( name , new ImmediateAuthenticationMechanismFactory ( mechanism ) ) ; if ( loginConfig == null ) { loginConfig = new LoginConfig ( null ) ; } loginConfig . addLastAuthMethod ( new AuthMethodConfig ( name ) ) ; return this ; }
Adds an authentication mechanism directly to the deployment . This mechanism will be last in the list .
10,305
public DeploymentInfo addAuthenticationMechanism ( final String name , final AuthenticationMechanismFactory factory ) { authenticationMechanisms . put ( name . toUpperCase ( Locale . US ) , factory ) ; return this ; }
Adds an authentication mechanism . The name is case insenstive and will be converted to uppercase internally .
10,306
public boolean isAuthenticationMechanismPresent ( final String mechanismName ) { if ( loginConfig != null ) { for ( AuthMethodConfig method : loginConfig . getAuthMethods ( ) ) { if ( method . getName ( ) . equalsIgnoreCase ( mechanismName ) ) { return true ; } } } return false ; }
Returns true if the specified mechanism is present in the login config
10,307
public DeploymentInfo addPreCompressedResourceEncoding ( String encoding , String extension ) { preCompressedResources . put ( encoding , extension ) ; return this ; }
Adds a pre compressed resource encoding and maps it to a file extension
10,308
public static ServletContainer defaultContainer ( ) { if ( container != null ) { return container ; } synchronized ( Servlets . class ) { if ( container != null ) { return container ; } return container = ServletContainer . Factory . newInstance ( ) ; } }
Returns the default servlet container . For most embedded use cases this will be sufficient .
10,309
public static ServletInfo servlet ( final String name , final Class < ? extends Servlet > servletClass , final InstanceFactory < ? extends Servlet > servlet ) { return new ServletInfo ( name , servletClass , servlet ) ; }
Creates a new servlet description with the given name and class
10,310
public static FilterInfo filter ( final String name , final Class < ? extends Filter > filterClass ) { return new FilterInfo ( name , filterClass ) ; }
Creates a new filter description with the given name and class
10,311
public static MultipartConfigElement multipartConfig ( String location , long maxFileSize , long maxRequestSize , int fileSizeThreshold ) { return new MultipartConfigElement ( location , maxFileSize , maxRequestSize , fileSizeThreshold ) ; }
Creates a new multipart config element
10,312
public static ErrorPage errorPage ( String location , Class < ? extends Throwable > exceptionType ) { return new ErrorPage ( location , exceptionType ) ; }
Create an ErrorPage instance for a given exception type
10,313
private long doWrap ( ByteBuffer [ ] userBuffers , int off , int len ) throws IOException { if ( anyAreSet ( state , FLAG_CLOSED ) ) { throw new ClosedChannelException ( ) ; } if ( outstandingTasks > 0 ) { return 0 ; } if ( anyAreSet ( state , FLAG_WRITE_REQUIRES_READ ) ) { doUnwrap ( null , 0 , 0 ) ; if ( allAreClear ( state , FLAG_READ_REQUIRES_WRITE ) ) { return 0 ; } } if ( wrappedData != null ) { int res = sink . write ( wrappedData . getBuffer ( ) ) ; if ( res == 0 || wrappedData . getBuffer ( ) . hasRemaining ( ) ) { return 0 ; } wrappedData . getBuffer ( ) . clear ( ) ; } else { wrappedData = bufferPool . allocate ( ) ; } try { SSLEngineResult result = null ; while ( result == null || ( result . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_WRAP && result . getStatus ( ) != SSLEngineResult . Status . BUFFER_OVERFLOW ) ) { if ( userBuffers == null ) { result = engine . wrap ( EMPTY_BUFFER , wrappedData . getBuffer ( ) ) ; } else { result = engine . wrap ( userBuffers , off , len , wrappedData . getBuffer ( ) ) ; } } wrappedData . getBuffer ( ) . flip ( ) ; if ( result . getStatus ( ) == SSLEngineResult . Status . BUFFER_UNDERFLOW ) { throw new IOException ( "underflow" ) ; } else if ( result . getStatus ( ) == SSLEngineResult . Status . BUFFER_OVERFLOW ) { if ( ! wrappedData . getBuffer ( ) . hasRemaining ( ) ) { throw new IOException ( "overflow" ) ; } } if ( wrappedData . getBuffer ( ) . hasRemaining ( ) ) { sink . write ( wrappedData . getBuffer ( ) ) ; } if ( wrappedData . getBuffer ( ) . hasRemaining ( ) ) { return result . bytesConsumed ( ) ; } if ( ! handleHandshakeResult ( result ) ) { return 0 ; } if ( result . getStatus ( ) == SSLEngineResult . Status . CLOSED && userBuffers != null ) { notifyWriteClosed ( ) ; throw new ClosedChannelException ( ) ; } return result . bytesConsumed ( ) ; } catch ( RuntimeException | IOException | Error e ) { try { close ( ) ; } catch ( Throwable ex ) { UndertowLogger . REQUEST_LOGGER . debug ( "Exception closing SSLConduit after exception in doWrap()" , ex ) ; } throw e ; } finally { if ( wrappedData != null ) { if ( ! wrappedData . getBuffer ( ) . hasRemaining ( ) ) { wrappedData . close ( ) ; wrappedData = null ; } } } }
Wraps the user data and attempts to send it to the remote client . If data has already been buffered then this is attempted to be sent first .
10,314
private void runTasks ( ) { delegate . getSinkChannel ( ) . suspendWrites ( ) ; delegate . getSourceChannel ( ) . suspendReads ( ) ; List < Runnable > tasks = new ArrayList < > ( ) ; Runnable t = engine . getDelegatedTask ( ) ; while ( t != null ) { tasks . add ( t ) ; t = engine . getDelegatedTask ( ) ; } synchronized ( this ) { outstandingTasks += tasks . size ( ) ; for ( final Runnable task : tasks ) { getWorker ( ) . execute ( new Runnable ( ) { public void run ( ) { try { task . run ( ) ; } finally { synchronized ( SslConduit . this ) { if ( outstandingTasks == 1 ) { getWriteThread ( ) . execute ( new Runnable ( ) { public void run ( ) { synchronized ( SslConduit . this ) { SslConduit . this . notifyAll ( ) ; -- outstandingTasks ; try { doHandshake ( ) ; } catch ( IOException | RuntimeException | Error e ) { IoUtils . safeClose ( connection ) ; } if ( anyAreSet ( state , FLAG_READS_RESUMED ) ) { wakeupReads ( ) ; } if ( anyAreSet ( state , FLAG_WRITES_RESUMED ) ) { resumeWrites ( ) ; } } } } ) ; } else { outstandingTasks -- ; } } } } } ) ; } } }
Execute all the tasks in the worker
10,315
public int setMaximumConcurrentRequests ( int newMax ) { if ( newMax < 1 ) { throw new IllegalArgumentException ( "Maximum concurrent requests must be at least 1" ) ; } int oldMax = this . max ; this . max = newMax ; if ( newMax > oldMax ) { synchronized ( this ) { while ( ! queue . isEmpty ( ) ) { int oldVal , newVal ; do { oldVal = requests ; if ( oldVal >= max ) { return oldMax ; } newVal = oldVal + 1 ; } while ( ! requestsUpdater . compareAndSet ( this , oldVal , newVal ) ) ; SuspendedRequest res = queue . poll ( ) ; res . exchange . dispatch ( res . next ) ; } } } return oldMax ; }
Set the maximum concurrent requests . The value must be greater than or equal to one .
10,316
private ArrayList < E > toArrayList ( ) { ArrayList < E > list = new ArrayList < > ( ) ; for ( Node < E > p = first ( ) ; p != null ; p = succ ( p ) ) { E item = p . item ; if ( item != null ) list . add ( item ) ; } return list ; }
Creates an array list and fills it with elements of this list . Used by toArray .
10,317
public static String toExtensionHeader ( final List < WebSocketExtension > extensions ) { StringBuilder extensionsHeader = new StringBuilder ( ) ; if ( extensions != null && extensions . size ( ) > 0 ) { Iterator < WebSocketExtension > it = extensions . iterator ( ) ; while ( it . hasNext ( ) ) { WebSocketExtension extension = it . next ( ) ; extensionsHeader . append ( extension . getName ( ) ) ; for ( Parameter param : extension . getParameters ( ) ) { extensionsHeader . append ( "; " ) . append ( param . getName ( ) ) ; if ( param . getValue ( ) != null && param . getValue ( ) . length ( ) > 0 ) { extensionsHeader . append ( "=" ) . append ( param . getValue ( ) ) ; } } if ( it . hasNext ( ) ) { extensionsHeader . append ( ", " ) ; } } } return extensionsHeader . toString ( ) ; }
Compose a String from a list of extensions to be used in the response of a protocol negotiation .
10,318
public void restoreChannel ( final ConduitState state ) { channel . getSinkChannel ( ) . setConduit ( state . sink ) ; channel . getSourceChannel ( ) . setConduit ( state . source ) ; }
Restores the channel conduits to a previous state .
10,319
protected void handleRequest ( final HttpString method , HttpServerExchange exchange ) throws Exception { final RequestData requestData = parseFormData ( exchange ) ; boolean persistent = exchange . isPersistent ( ) ; exchange . setPersistent ( false ) ; if ( CONFIG . equals ( method ) ) { processConfig ( exchange , requestData ) ; } else if ( ENABLE_APP . equals ( method ) ) { processCommand ( exchange , requestData , MCMPAction . ENABLE ) ; } else if ( DISABLE_APP . equals ( method ) ) { processCommand ( exchange , requestData , MCMPAction . DISABLE ) ; } else if ( STOP_APP . equals ( method ) ) { processCommand ( exchange , requestData , MCMPAction . STOP ) ; } else if ( REMOVE_APP . equals ( method ) ) { processCommand ( exchange , requestData , MCMPAction . REMOVE ) ; } else if ( STATUS . equals ( method ) ) { processStatus ( exchange , requestData ) ; } else if ( INFO . equals ( method ) ) { processInfo ( exchange ) ; } else if ( DUMP . equals ( method ) ) { processDump ( exchange ) ; } else if ( PING . equals ( method ) ) { processPing ( exchange , requestData ) ; } else { exchange . setPersistent ( persistent ) ; next . handleRequest ( exchange ) ; } }
Handle a management + request .
10,320
void processCommand ( final HttpServerExchange exchange , final RequestData requestData , final MCMPAction action ) throws IOException { if ( exchange . getRequestPath ( ) . equals ( "*" ) || exchange . getRequestPath ( ) . endsWith ( "/*" ) ) { processNodeCommand ( exchange , requestData , action ) ; } else { processAppCommand ( exchange , requestData , action ) ; } }
Process a mod_cluster mgmt command .
10,321
void processNodeCommand ( final HttpServerExchange exchange , final RequestData requestData , final MCMPAction action ) throws IOException { final String jvmRoute = requestData . getFirst ( JVMROUTE ) ; if ( jvmRoute == null ) { processError ( TYPESYNTAX , SMISFLD , exchange ) ; return ; } if ( processNodeCommand ( jvmRoute , action ) ) { processOK ( exchange ) ; } else { processError ( MCMPErrorCode . CANT_UPDATE_NODE , exchange ) ; } }
Process a mgmt command targeting a node .
10,322
void processAppCommand ( final HttpServerExchange exchange , final RequestData requestData , final MCMPAction action ) throws IOException { final String contextPath = requestData . getFirst ( CONTEXT ) ; final String jvmRoute = requestData . getFirst ( JVMROUTE ) ; final String aliases = requestData . getFirst ( ALIAS ) ; if ( contextPath == null || jvmRoute == null || aliases == null ) { processError ( TYPESYNTAX , SMISFLD , exchange ) ; return ; } final List < String > virtualHosts = Arrays . asList ( aliases . split ( "," ) ) ; if ( virtualHosts == null || virtualHosts . isEmpty ( ) ) { processError ( TYPESYNTAX , SCONBAD , exchange ) ; return ; } String response = null ; switch ( action ) { case ENABLE : if ( ! container . enableContext ( contextPath , jvmRoute , virtualHosts ) ) { processError ( MCMPErrorCode . CANT_UPDATE_CONTEXT , exchange ) ; return ; } break ; case DISABLE : if ( ! container . disableContext ( contextPath , jvmRoute , virtualHosts ) ) { processError ( MCMPErrorCode . CANT_UPDATE_CONTEXT , exchange ) ; return ; } break ; case STOP : int i = container . stopContext ( contextPath , jvmRoute , virtualHosts ) ; final StringBuilder builder = new StringBuilder ( ) ; builder . append ( "Type=STOP-APP-RSP,JvmRoute=" ) . append ( jvmRoute ) ; builder . append ( "Alias=" ) . append ( aliases ) ; builder . append ( "Context=" ) . append ( contextPath ) ; builder . append ( "Requests=" ) . append ( i ) ; response = builder . toString ( ) ; break ; case REMOVE : if ( ! container . removeContext ( contextPath , jvmRoute , virtualHosts ) ) { processError ( MCMPErrorCode . CANT_UPDATE_CONTEXT , exchange ) ; return ; } break ; default : { processError ( TYPESYNTAX , SMISFLD , exchange ) ; return ; } } if ( response != null ) { sendResponse ( exchange , response ) ; } else { processOK ( exchange ) ; } }
Process a command targeting an application .
10,323
void processStatus ( final HttpServerExchange exchange , final RequestData requestData ) throws IOException { final String jvmRoute = requestData . getFirst ( JVMROUTE ) ; final String loadValue = requestData . getFirst ( LOAD ) ; if ( loadValue == null || jvmRoute == null ) { processError ( TYPESYNTAX , SMISFLD , exchange ) ; return ; } UndertowLogger . ROOT_LOGGER . receivedNodeLoad ( jvmRoute , loadValue ) ; final int load = Integer . parseInt ( loadValue ) ; if ( load > 0 || load == - 2 ) { final Node node = container . getNode ( jvmRoute ) ; if ( node == null ) { processError ( MCMPErrorCode . CANT_READ_NODE , exchange ) ; return ; } final NodePingUtil . PingCallback callback = new NodePingUtil . PingCallback ( ) { public void completed ( ) { final String response = "Type=STATUS-RSP&State=OK&JVMRoute=" + jvmRoute + "&id=" + creationTime ; try { if ( load > 0 ) { node . updateLoad ( load ) ; } sendResponse ( exchange , response ) ; } catch ( Exception e ) { UndertowLogger . ROOT_LOGGER . failedToSendPingResponse ( e ) ; } } public void failed ( ) { final String response = "Type=STATUS-RSP&State=NOTOK&JVMRoute=" + jvmRoute + "&id=" + creationTime ; try { node . markInError ( ) ; sendResponse ( exchange , response ) ; } catch ( Exception e ) { UndertowLogger . ROOT_LOGGER . failedToSendPingResponseDBG ( e , node . getJvmRoute ( ) , jvmRoute ) ; } } } ; node . ping ( exchange , callback ) ; } else if ( load == 0 ) { final Node node = container . getNode ( jvmRoute ) ; if ( node != null ) { node . hotStandby ( ) ; sendResponse ( exchange , "Type=STATUS-RSP&State=OK&JVMRoute=" + jvmRoute + "&id=" + creationTime ) ; } else { processError ( MCMPErrorCode . CANT_READ_NODE , exchange ) ; } } else if ( load == - 1 ) { final Node node = container . getNode ( jvmRoute ) ; if ( node != null ) { node . markInError ( ) ; sendResponse ( exchange , "Type=STATUS-RSP&State=NOTOK&JVMRoute=" + jvmRoute + "&id=" + creationTime ) ; } else { processError ( MCMPErrorCode . CANT_READ_NODE , exchange ) ; } } else { processError ( TYPESYNTAX , SMISFLD , exchange ) ; } }
Process the status request .
10,324
void processPing ( final HttpServerExchange exchange , final RequestData requestData ) throws IOException { final String jvmRoute = requestData . getFirst ( JVMROUTE ) ; final String scheme = requestData . getFirst ( SCHEME ) ; final String host = requestData . getFirst ( HOST ) ; final String port = requestData . getFirst ( PORT ) ; final String OK = "Type=PING-RSP&State=OK&id=" + creationTime ; final String NOTOK = "Type=PING-RSP&State=NOTOK&id=" + creationTime ; if ( jvmRoute != null ) { final Node nodeConfig = container . getNode ( jvmRoute ) ; if ( nodeConfig == null ) { sendResponse ( exchange , NOTOK ) ; return ; } final NodePingUtil . PingCallback callback = new NodePingUtil . PingCallback ( ) { public void completed ( ) { try { sendResponse ( exchange , OK ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } public void failed ( ) { try { nodeConfig . markInError ( ) ; sendResponse ( exchange , NOTOK ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; nodeConfig . ping ( exchange , callback ) ; } else { if ( scheme == null && host == null && port == null ) { sendResponse ( exchange , OK ) ; return ; } else { if ( host == null || port == null ) { processError ( TYPESYNTAX , SMISFLD , exchange ) ; return ; } checkHostUp ( scheme , host , Integer . parseInt ( port ) , exchange , new NodePingUtil . PingCallback ( ) { public void completed ( ) { sendResponse ( exchange , OK ) ; } public void failed ( ) { sendResponse ( exchange , NOTOK ) ; } } ) ; return ; } } }
Process the ping request .
10,325
protected void checkHostUp ( final String scheme , final String host , final int port , final HttpServerExchange exchange , final NodePingUtil . PingCallback callback ) { final XnioSsl xnioSsl = null ; final OptionMap options = OptionMap . builder ( ) . set ( Options . TCP_NODELAY , true ) . getMap ( ) ; try { if ( "ajp" . equalsIgnoreCase ( scheme ) || "http" . equalsIgnoreCase ( scheme ) ) { final URI uri = new URI ( scheme , null , host , port , "/" , null , null ) ; NodePingUtil . pingHttpClient ( uri , callback , exchange , container . getClient ( ) , xnioSsl , options ) ; } else { final InetSocketAddress address = new InetSocketAddress ( host , port ) ; NodePingUtil . pingHost ( address , exchange , callback , options ) ; } } catch ( URISyntaxException e ) { callback . failed ( ) ; } }
Check whether a host is up .
10,326
static void sendResponse ( final HttpServerExchange exchange , final String response ) { exchange . setStatusCode ( StatusCodes . OK ) ; exchange . getResponseHeaders ( ) . add ( Headers . CONTENT_TYPE , CONTENT_TYPE ) ; final Sender sender = exchange . getResponseSender ( ) ; UndertowLogger . ROOT_LOGGER . mcmpSendingResponse ( exchange . getSourceAddress ( ) , exchange . getStatusCode ( ) , exchange . getResponseHeaders ( ) , response ) ; sender . send ( response ) ; }
Send a simple response string .
10,327
static void processOK ( HttpServerExchange exchange ) throws IOException { exchange . setStatusCode ( StatusCodes . OK ) ; exchange . getResponseHeaders ( ) . add ( Headers . CONTENT_TYPE , CONTENT_TYPE ) ; exchange . endExchange ( ) ; }
If the process is OK then add 200 HTTP status and its OK phrase
10,328
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 ) ; }
Send an error message .
10,329
RequestData parseFormData ( final HttpServerExchange exchange ) throws IOException { final FormDataParser parser = parserFactory . createParser ( exchange ) ; final FormData formData = parser . parseBlocking ( ) ; final RequestData data = new RequestData ( ) ; for ( String name : formData ) { final HttpString key = new HttpString ( name ) ; data . add ( key , formData . get ( name ) ) ; } return data ; }
Transform the form data into an intermediate request data which can me used by the web manager
10,330
public static ConnectionBuilder connectionBuilder ( XnioWorker worker , ByteBufferPool bufferPool , URI uri ) { return new ConnectionBuilder ( worker , bufferPool , uri ) ; }
Creates a new connection builder that can be used to create a web socket connection .
10,331
public CharSequence evaluate ( CharSequence url , Resolver resolver ) { Pattern pattern = this . pattern . get ( ) ; if ( pattern == null ) { int flags = 0 ; if ( isNocase ( ) ) { flags |= Pattern . CASE_INSENSITIVE ; } pattern = Pattern . compile ( patternString , flags ) ; this . pattern . set ( pattern ) ; } Matcher matcher = pattern . matcher ( url ) ; if ( ! matcher . matches ( ) ) { return null ; } boolean done = false ; boolean rewrite = true ; Matcher lastMatcher = null ; int pos = 0 ; while ( ! done ) { if ( pos < conditions . length ) { rewrite = conditions [ pos ] . evaluate ( matcher , lastMatcher , resolver ) ; if ( rewrite ) { Matcher lastMatcher2 = conditions [ pos ] . getMatcher ( ) ; if ( lastMatcher2 != null ) { lastMatcher = lastMatcher2 ; } while ( pos < conditions . length && conditions [ pos ] . isOrnext ( ) ) { pos ++ ; } } else if ( ! conditions [ pos ] . isOrnext ( ) ) { done = true ; } pos ++ ; } else { done = true ; } } if ( rewrite ) { if ( isEnv ( ) ) { for ( int i = 0 ; i < envSubstitution . size ( ) ; i ++ ) { envResult . get ( i ) . set ( envSubstitution . get ( i ) . evaluate ( matcher , lastMatcher , resolver ) ) ; } } if ( isCookie ( ) ) { cookieResult . set ( cookieSubstitution . evaluate ( matcher , lastMatcher , resolver ) ) ; } if ( substitution != null ) { return substitution . evaluate ( matcher , lastMatcher , resolver ) ; } else { return url ; } } else { return null ; } }
Evaluate the rule based on the context
10,332
void rstStream ( ) { if ( reset ) { return ; } reset = true ; if ( ! isReadyForFlush ( ) ) { IoUtils . safeClose ( this ) ; } getChannel ( ) . removeStreamSink ( getStreamId ( ) ) ; }
Method that is invoked when the stream is reset .
10,333
public HttpSessionImpl getSession ( final String sessionId ) { final SessionManager sessionManager = deployment . getSessionManager ( ) ; Session session = sessionManager . getSession ( sessionId ) ; if ( session != null ) { return SecurityActions . forSession ( session , this , false ) ; } return null ; }
Gets the session with the specified ID if it exists
10,334
public PooledByteBuffer allocate ( ) { final Queue < Slice > sliceQueue = this . sliceQueue ; final Slice slice = sliceQueue . poll ( ) ; if ( slice == null && ( maxRegions <= 0 || regionUpdater . getAndIncrement ( this ) < maxRegions ) ) { final int bufferSize = this . bufferSize ; final int buffersPerRegion = this . buffersPerRegion ; final ByteBuffer region = allocator . allocate ( buffersPerRegion * bufferSize ) ; int idx = bufferSize ; for ( int i = 1 ; i < buffersPerRegion ; i ++ ) { sliceQueue . add ( new Slice ( region , idx , bufferSize ) ) ; idx += bufferSize ; } final Slice newSlice = new Slice ( region , 0 , bufferSize ) ; return new PooledByteBuffer ( newSlice , newSlice . slice ( ) , sliceQueue ) ; } if ( slice == null ) { return null ; } return new PooledByteBuffer ( slice , slice . slice ( ) , sliceQueue ) ; }
Allocates a new byte buffer if possible
10,335
public final void handshake ( final WebSocketHttpExchange exchange ) { exchange . putAttachment ( WebSocketVersion . ATTACHMENT_KEY , version ) ; handshakeInternal ( exchange ) ; }
Issue the WebSocket upgrade
10,336
protected final void performUpgrade ( final WebSocketHttpExchange exchange , final byte [ ] data ) { exchange . setResponseHeader ( Headers . CONTENT_LENGTH_STRING , String . valueOf ( data . length ) ) ; exchange . setResponseHeader ( Headers . UPGRADE_STRING , "WebSocket" ) ; exchange . setResponseHeader ( Headers . CONNECTION_STRING , "Upgrade" ) ; upgradeChannel ( exchange , data ) ; }
convenience method to perform the upgrade
10,337
protected final void selectSubprotocol ( final WebSocketHttpExchange exchange ) { String requestedSubprotocols = exchange . getRequestHeader ( Headers . SEC_WEB_SOCKET_PROTOCOL_STRING ) ; if ( requestedSubprotocols == null ) { return ; } String [ ] requestedSubprotocolArray = PATTERN . split ( requestedSubprotocols ) ; String subProtocol = supportedSubprotols ( requestedSubprotocolArray ) ; if ( subProtocol != null && ! subProtocol . isEmpty ( ) ) { exchange . setResponseHeader ( Headers . SEC_WEB_SOCKET_PROTOCOL_STRING , subProtocol ) ; } }
Selects the first matching supported sub protocol and add it the the headers of the exchange .
10,338
public static List < List < QValueResult > > parse ( List < String > headers ) { final List < QValueResult > found = new ArrayList < > ( ) ; QValueResult current = null ; for ( final String header : headers ) { final int l = header . length ( ) ; int stringStart = 0 ; for ( int i = 0 ; i < l ; ++ i ) { char c = header . charAt ( i ) ; switch ( c ) { case ',' : { if ( current != null && ( i - stringStart > 2 && header . charAt ( stringStart ) == 'q' && header . charAt ( stringStart + 1 ) == '=' ) ) { current . qvalue = header . substring ( stringStart + 2 , i ) ; current = null ; } else if ( stringStart != i ) { current = handleNewEncoding ( found , header , stringStart , i ) ; } stringStart = i + 1 ; break ; } case ';' : { if ( stringStart != i ) { current = handleNewEncoding ( found , header , stringStart , i ) ; stringStart = i + 1 ; } break ; } case ' ' : { if ( stringStart != i ) { if ( current != null && ( i - stringStart > 2 && header . charAt ( stringStart ) == 'q' && header . charAt ( stringStart + 1 ) == '=' ) ) { current . qvalue = header . substring ( stringStart + 2 , i ) ; } else { current = handleNewEncoding ( found , header , stringStart , i ) ; } } stringStart = i + 1 ; } } } if ( stringStart != l ) { if ( current != null && ( l - stringStart > 2 && header . charAt ( stringStart ) == 'q' && header . charAt ( stringStart + 1 ) == '=' ) ) { current . qvalue = header . substring ( stringStart + 2 , l ) ; } else { current = handleNewEncoding ( found , header , stringStart , l ) ; } } } Collections . sort ( found , Collections . reverseOrder ( ) ) ; String currentQValue = null ; List < List < QValueResult > > values = new ArrayList < > ( ) ; List < QValueResult > currentSet = null ; for ( QValueResult val : found ) { if ( ! val . qvalue . equals ( currentQValue ) ) { currentQValue = val . qvalue ; currentSet = new ArrayList < > ( ) ; values . add ( currentSet ) ; } currentSet . add ( val ) ; } return values ; }
Parses a set of headers that take q values to determine the most preferred one .
10,339
protected void queueFrame ( FrameCallBack callback , ByteBuffer ... data ) { queuedData += Buffers . remaining ( data ) ; bufferCount += data . length ; frameQueue . add ( new Frame ( callback , data , 0 , data . length ) ) ; }
Queues a frame for sending .
10,340
public int compareTo ( final HttpString other ) { if ( orderInt != 0 && other . orderInt != 0 ) { return signum ( orderInt - other . orderInt ) ; } final int len = Math . min ( bytes . length , other . bytes . length ) ; int res ; for ( int i = 0 ; i < len ; i ++ ) { res = signum ( higher ( bytes [ i ] ) - higher ( other . bytes [ i ] ) ) ; if ( res != 0 ) return res ; } return signum ( bytes . length - other . bytes . length ) ; }
Compare this string to another in a case - insensitive manner .
10,341
public String evaluate ( Matcher rule , Matcher cond , Resolver resolver ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < elements . length ; i ++ ) { buf . append ( elements [ i ] . evaluate ( rule , cond , resolver ) ) ; } return buf . toString ( ) ; }
Evaluate the substitution based on the context
10,342
public void invokeEndpointMethod ( final Runnable invocation ) { try { invokeEndpointTask . call ( null , invocation ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Directly invokes an endpoint method without dispatching to an executor
10,343
public synchronized void pause ( PauseListener listener ) { closed = true ; if ( configuredServerEndpoints . isEmpty ( ) ) { listener . paused ( ) ; return ; } if ( listener != null ) { pauseListeners . add ( listener ) ; } for ( ConfiguredServerEndpoint endpoint : configuredServerEndpoints ) { for ( final Session session : endpoint . getOpenSessions ( ) ) { ( ( UndertowSession ) session ) . getExecutor ( ) . execute ( new Runnable ( ) { public void run ( ) { try { session . close ( new CloseReason ( CloseReason . CloseCodes . GOING_AWAY , "" ) ) ; } catch ( Exception e ) { JsrWebSocketLogger . ROOT_LOGGER . couldNotCloseOnUndeploy ( e ) ; } } } ) ; } } Runnable done = new Runnable ( ) { int count = configuredServerEndpoints . size ( ) ; public synchronized void run ( ) { List < PauseListener > copy = null ; synchronized ( ServerWebSocketContainer . this ) { count -- ; if ( count == 0 ) { copy = new ArrayList < > ( pauseListeners ) ; pauseListeners . clear ( ) ; } } if ( copy != null ) { for ( PauseListener p : copy ) { p . paused ( ) ; } } } } ; for ( ConfiguredServerEndpoint endpoint : configuredServerEndpoints ) { endpoint . notifyClosed ( done ) ; } }
Pauses the container
10,344
public synchronized void resume ( ) { closed = false ; for ( PauseListener p : pauseListeners ) { p . resumed ( ) ; } pauseListeners . clear ( ) ; }
resumes a paused container
10,345
public String encodeRedirectURL ( String url ) { if ( isEncodeable ( toAbsolute ( url ) ) ) { return originalServletContext . getSessionConfig ( ) . rewriteUrl ( url , servletContext . getSession ( originalServletContext , exchange , true ) . getId ( ) ) ; } else { return url ; } }
Encode the session identifier associated with this response into the specified redirect URL if necessary .
10,346
public static boolean checkOrigin ( ServerEndpointConfig config , WebSocketHttpExchange exchange ) { ServerEndpointConfig . Configurator c = config . getConfigurator ( ) ; return c . checkOrigin ( exchange . getRequestHeader ( Headers . ORIGIN_STRING ) ) ; }
Checks the orgin against the
10,347
public static void prepareUpgrade ( final ServerEndpointConfig config , final WebSocketHttpExchange exchange ) { ExchangeHandshakeRequest request = new ExchangeHandshakeRequest ( exchange ) ; ExchangeHandshakeResponse response = new ExchangeHandshakeResponse ( exchange ) ; ServerEndpointConfig . Configurator c = config . getConfigurator ( ) ; c . modifyHandshake ( config , request , response ) ; response . update ( ) ; }
Prepare for upgrade
10,348
synchronized boolean update ( ) { int elected = this . elected ; int oldelected = this . oldelected ; int lbfactor = this . lbfactor ; if ( lbfactor > 0 ) { this . lbstatus = ( ( elected - oldelected ) * 1000 ) / lbfactor ; } this . oldelected = elected ; return elected != oldelected ; }
Update the load balancing status .
10,349
void handleRequest ( final ModClusterProxyTarget target , final HttpServerExchange exchange , final ProxyCallback < ProxyConnection > callback , long timeout , TimeUnit timeUnit , boolean exclusive ) { if ( addRequest ( ) ) { exchange . addExchangeCompleteListener ( new ExchangeCompletionListener ( ) { public void exchangeEvent ( HttpServerExchange exchange , NextListener nextListener ) { requestDone ( ) ; nextListener . proceed ( ) ; } } ) ; node . getConnectionPool ( ) . connect ( target , exchange , callback , timeout , timeUnit , exclusive ) ; } else { callback . failed ( exchange ) ; } }
Handle a proxy request for this context .
10,350
public static ByteRange parse ( String rangeHeader ) { if ( rangeHeader == null || rangeHeader . length ( ) < 7 ) { return null ; } if ( ! rangeHeader . startsWith ( "bytes=" ) ) { return null ; } List < Range > ranges = new ArrayList < > ( ) ; String [ ] parts = rangeHeader . substring ( 6 ) . split ( "," ) ; for ( String part : parts ) { try { int index = part . indexOf ( '-' ) ; if ( index == 0 ) { long val = Long . parseLong ( part . substring ( 1 ) ) ; if ( val < 0 ) { UndertowLogger . REQUEST_LOGGER . debugf ( "Invalid range spec %s" , rangeHeader ) ; return null ; } ranges . add ( new Range ( - 1 , val ) ) ; } else { if ( index == - 1 ) { UndertowLogger . REQUEST_LOGGER . debugf ( "Invalid range spec %s" , rangeHeader ) ; return null ; } long start = Long . parseLong ( part . substring ( 0 , index ) ) ; if ( start < 0 ) { UndertowLogger . REQUEST_LOGGER . debugf ( "Invalid range spec %s" , rangeHeader ) ; return null ; } long end ; if ( index + 1 < part . length ( ) ) { end = Long . parseLong ( part . substring ( index + 1 ) ) ; } else { end = - 1 ; } ranges . add ( new Range ( start , end ) ) ; } } catch ( NumberFormatException e ) { UndertowLogger . REQUEST_LOGGER . debugf ( "Invalid range spec %s" , rangeHeader ) ; return null ; } } if ( ranges . isEmpty ( ) ) { return null ; } return new ByteRange ( ranges ) ; }
Attempts to parse a range request . If the range request is invalid it will just return null so that it may be ignored .
10,351
public RangeResponseResult getResponseResult ( final long resourceContentLength , String ifRange , Date lastModified , String eTag ) { if ( ranges . isEmpty ( ) ) { return null ; } long start = getStart ( 0 ) ; long end = getEnd ( 0 ) ; long rangeLength ; if ( ifRange != null && ! ifRange . isEmpty ( ) ) { if ( ifRange . charAt ( 0 ) == '"' ) { if ( eTag != null && ! eTag . equals ( ifRange ) ) { return null ; } } else { Date ifDate = DateUtils . parseDate ( ifRange ) ; if ( ifDate != null && lastModified != null && ifDate . getTime ( ) < lastModified . getTime ( ) ) { return null ; } } } if ( start == - 1 ) { if ( end < 0 ) { return new RangeResponseResult ( 0 , 0 , 0 , "bytes */" + resourceContentLength , StatusCodes . REQUEST_RANGE_NOT_SATISFIABLE ) ; } start = Math . max ( resourceContentLength - end , 0 ) ; end = resourceContentLength - 1 ; rangeLength = resourceContentLength - start ; } else if ( end == - 1 ) { long toWrite = resourceContentLength - start ; if ( toWrite >= 0 ) { rangeLength = toWrite ; } else { return new RangeResponseResult ( 0 , 0 , 0 , "bytes */" + resourceContentLength , StatusCodes . REQUEST_RANGE_NOT_SATISFIABLE ) ; } end = resourceContentLength - 1 ; } else { end = Math . min ( end , resourceContentLength - 1 ) ; if ( start >= resourceContentLength || start > end ) { return new RangeResponseResult ( 0 , 0 , 0 , "bytes */" + resourceContentLength , StatusCodes . REQUEST_RANGE_NOT_SATISFIABLE ) ; } rangeLength = end - start + 1 ; } return new RangeResponseResult ( start , end , rangeLength , "bytes " + start + "-" + end + "/" + resourceContentLength , StatusCodes . PARTIAL_CONTENT ) ; }
Returns a representation of the range result . If this returns null then a 200 response should be sent instead
10,352
public int getLoad ( ) { final int status = this . state ; if ( anyAreSet ( status , ERROR ) ) { return - 1 ; } else if ( anyAreSet ( status , HOT_STANDBY ) ) { return 0 ; } else { return lbStatus . getLbFactor ( ) ; } }
Get the load information . Add the error information for clients .
10,353
protected void checkHealth ( long threshold , NodeHealthChecker healthChecker ) { final int state = this . state ; if ( anyAreSet ( state , REMOVED | ACTIVE_PING ) ) { return ; } healthCheckPing ( threshold , healthChecker ) ; }
Check the health of the node and try to ping it if necessary .
10,354
void ping ( final HttpServerExchange exchange , final NodePingUtil . PingCallback callback ) { NodePingUtil . pingNode ( this , exchange , callback ) ; }
Async ping from the user
10,355
Context registerContext ( final String path , final List < String > virtualHosts ) { VHostMapping host = null ; for ( final VHostMapping vhost : vHosts ) { if ( virtualHosts . equals ( vhost . getAliases ( ) ) ) { host = vhost ; break ; } } if ( host == null ) { host = new VHostMapping ( this , virtualHosts ) ; vHosts . add ( host ) ; } final Context context = new Context ( path , host , this ) ; contexts . add ( context ) ; return context ; }
Register a context .
10,356
Context getContext ( final String path , List < String > aliases ) { VHostMapping host = null ; for ( final VHostMapping vhost : vHosts ) { if ( aliases . equals ( vhost . getAliases ( ) ) ) { host = vhost ; break ; } } if ( host == null ) { return null ; } for ( final Context context : contexts ) { if ( context . getPath ( ) . equals ( path ) && context . getVhost ( ) == host ) { return context ; } } return null ; }
Get a context .
10,357
private int healthCheckFailed ( ) { int oldState , newState ; for ( ; ; ) { oldState = this . state ; if ( ( oldState & ERROR ) != ERROR ) { newState = oldState | ERROR ; UndertowLogger . ROOT_LOGGER . nodeIsInError ( jvmRoute ) ; } else if ( ( oldState & ERROR_MASK ) == ERROR_MASK ) { return ERROR_MASK ; } else { newState = oldState + 1 ; } if ( stateUpdater . compareAndSet ( this , oldState , newState ) ) { return newState & ERROR_MASK ; } } }
Mark a node in error . Mod_cluster has a threshold after which broken nodes get removed .
10,358
public static long parsePositiveLong ( String str ) { long value = 0 ; final int length = str . length ( ) ; if ( length == 0 ) { throw new NumberFormatException ( str ) ; } long multiplier = 1 ; for ( int i = length - 1 ; i >= 0 ; -- i ) { char c = str . charAt ( i ) ; if ( c < '0' || c > '9' ) { throw new NumberFormatException ( str ) ; } long digit = c - '0' ; value += digit * multiplier ; multiplier *= 10 ; } return value ; }
fast long parsing algorithm
10,359
void forceInit ( DispatcherType dispatcherType ) throws ServletException { if ( filters != null ) { List < ManagedFilter > list = filters . get ( dispatcherType ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( int i = 0 ; i < list . size ( ) ; ++ i ) { ManagedFilter filter = list . get ( i ) ; filter . forceInit ( ) ; } } } managedServlet . forceInit ( ) ; }
see UNDERTOW - 1132
10,360
public void ungetRequestBytes ( final PooledByteBuffer unget ) { if ( getExtraBytes ( ) == null ) { setExtraBytes ( unget ) ; } else { PooledByteBuffer eb = getExtraBytes ( ) ; ByteBuffer buf = eb . getBuffer ( ) ; final ByteBuffer ugBuffer = unget . getBuffer ( ) ; if ( ugBuffer . limit ( ) - ugBuffer . remaining ( ) > buf . remaining ( ) ) { ugBuffer . compact ( ) ; ugBuffer . put ( buf ) ; ugBuffer . flip ( ) ; eb . close ( ) ; setExtraBytes ( unget ) ; } else { final byte [ ] data = new byte [ ugBuffer . remaining ( ) + buf . remaining ( ) ] ; int first = ugBuffer . remaining ( ) ; ugBuffer . get ( data , 0 , ugBuffer . remaining ( ) ) ; buf . get ( data , first , buf . remaining ( ) ) ; eb . close ( ) ; unget . close ( ) ; final ByteBuffer newBuffer = ByteBuffer . wrap ( data ) ; setExtraBytes ( new ImmediatePooledByteBuffer ( newBuffer ) ) ; } } }
Pushes back the given data . This should only be used by transfer coding handlers that have read past the end of the request when handling pipelined requests
10,361
public synchronized void initialRequestDone ( ) { initialRequestDone = true ; if ( previousAsyncContext != null ) { previousAsyncContext . onAsyncStart ( this ) ; previousAsyncContext = null ; } if ( ! processingAsyncTask ) { processAsyncTask ( ) ; } initiatingThread = null ; }
Called by the container when the initial request is finished . If this request has a dispatch or complete call pending then this will be started .
10,362
public void run ( ) { if ( ! stateUpdater . compareAndSet ( this , 1 , 2 ) ) { return ; } List < JDBCLogAttribute > messages = new ArrayList < > ( ) ; JDBCLogAttribute msg = null ; for ( int i = 0 ; i < 1000 ; ++ i ) { msg = pendingMessages . poll ( ) ; if ( msg == null ) { break ; } messages . add ( msg ) ; } try { if ( ! messages . isEmpty ( ) ) { writeMessage ( messages ) ; } } finally { Executor executor = this . executor ; stateUpdater . set ( this , 0 ) ; if ( ! pendingMessages . isEmpty ( ) ) { if ( stateUpdater . compareAndSet ( this , 0 , 1 ) ) { executor . execute ( this ) ; } } } }
insert the log record to database
10,363
private V putInternal ( final K key , final V value ) { final Map < K , V > delegate = new HashMap < > ( this . delegate ) ; V existing = delegate . put ( key , value ) ; this . delegate = delegate ; return existing ; }
must be called under lock
10,364
private void checkUTF8 ( ByteBuffer buf , int position , int length ) throws UnsupportedEncodingException { int limit = position + length ; for ( int i = position ; i < limit ; i ++ ) { checkUTF8 ( buf . get ( i ) ) ; } }
Check if the given ByteBuffer contains non UTF - 8 data .
10,365
private SingleConstraintMatch mergeConstraints ( final RuntimeMatch currentMatch ) { if ( currentMatch . uncovered && denyUncoveredHttpMethods ) { return new SingleConstraintMatch ( SecurityInfo . EmptyRoleSemantic . DENY , Collections . < String > emptySet ( ) ) ; } final Set < String > allowedRoles = new HashSet < > ( ) ; for ( SingleConstraintMatch match : currentMatch . constraints ) { if ( match . getRequiredRoles ( ) . isEmpty ( ) ) { return new SingleConstraintMatch ( match . getEmptyRoleSemantic ( ) , Collections . < String > emptySet ( ) ) ; } else { allowedRoles . addAll ( match . getRequiredRoles ( ) ) ; } } return new SingleConstraintMatch ( SecurityInfo . EmptyRoleSemantic . PERMIT , allowedRoles ) ; }
merge all constraints as per 13 . 8 . 1 Combining Constraints
10,366
private static boolean shouldDecode ( final HttpServerExchange exchange ) { return ! exchange . getConnection ( ) . getUndertowOptions ( ) . get ( UndertowOptions . DECODE_URL , true ) && exchange . putAttachment ( ALREADY_DECODED , Boolean . TRUE ) == null ; }
attachment so that subsequent invocations will always return false .
10,367
void handleInitialRequest ( HttpServerExchange initial , Http2Channel channel , byte [ ] data ) { Http2HeadersStreamSinkChannel sink = channel . createInitialUpgradeResponseStream ( ) ; final Http2ServerConnection connection = new Http2ServerConnection ( channel , sink , undertowOptions , bufferSize , rootHandler ) ; HeaderMap requestHeaders = new HeaderMap ( ) ; for ( HeaderValues hv : initial . getRequestHeaders ( ) ) { requestHeaders . putAll ( hv . getHeaderName ( ) , hv ) ; } final HttpServerExchange exchange = new HttpServerExchange ( connection , requestHeaders , sink . getHeaders ( ) , maxEntitySize ) ; if ( initial . getRequestHeaders ( ) . contains ( Headers . EXPECT ) ) { HttpContinue . markContinueResponseSent ( exchange ) ; } if ( initial . getAttachment ( HttpAttachments . REQUEST_TRAILERS ) != null ) { exchange . putAttachment ( HttpAttachments . REQUEST_TRAILERS , initial . getAttachment ( HttpAttachments . REQUEST_TRAILERS ) ) ; } Connectors . setRequestStartTime ( initial , exchange ) ; connection . setExchange ( exchange ) ; exchange . setRequestScheme ( initial . getRequestScheme ( ) ) ; exchange . setRequestMethod ( initial . getRequestMethod ( ) ) ; exchange . setQueryString ( initial . getQueryString ( ) ) ; if ( data != null ) { Connectors . ungetRequestBytes ( exchange , new ImmediatePooledByteBuffer ( ByteBuffer . wrap ( data ) ) ) ; } else { Connectors . terminateRequest ( exchange ) ; } String uri = exchange . getQueryString ( ) . isEmpty ( ) ? initial . getRequestURI ( ) : initial . getRequestURI ( ) + '?' + exchange . getQueryString ( ) ; try { Connectors . setExchangeRequestPath ( exchange , uri , encoding , decode , allowEncodingSlash , decodeBuffer , maxParameters ) ; } catch ( ParameterLimitException e ) { exchange . setStatusCode ( StatusCodes . BAD_REQUEST ) ; exchange . endExchange ( ) ; return ; } handleCommonSetup ( sink , exchange , connection ) ; Connectors . executeRootHandler ( rootHandler , exchange ) ; }
Handles the initial request when the exchange was started by a HTTP ugprade .
10,368
private boolean checkRequestHeaders ( HeaderMap headers ) { if ( headers . count ( METHOD ) != 1 || headers . contains ( Headers . CONNECTION ) ) { return false ; } if ( headers . get ( METHOD ) . contains ( Methods . CONNECT_STRING ) ) { if ( headers . contains ( SCHEME ) || headers . contains ( PATH ) || headers . count ( AUTHORITY ) != 1 ) { return false ; } } else if ( headers . count ( SCHEME ) != 1 || headers . count ( PATH ) != 1 ) { return false ; } if ( headers . contains ( Headers . TE ) ) { for ( String value : headers . get ( Headers . TE ) ) { if ( ! value . equals ( "trailers" ) ) { return false ; } } } return true ; }
Performs HTTP2 specification compliance check for headers and pseudo - headers of a current request .
10,369
void updateContentSize ( long frameLength , boolean last ) { if ( contentLengthRemaining != - 1 ) { contentLengthRemaining -= frameLength ; if ( contentLengthRemaining < 0 ) { UndertowLogger . REQUEST_IO_LOGGER . debugf ( "Closing stream %s on %s as data length exceeds content size" , streamId , getFramedChannel ( ) ) ; getFramedChannel ( ) . sendRstStream ( streamId , Http2Channel . ERROR_PROTOCOL_ERROR ) ; } else if ( last && contentLengthRemaining != 0 ) { UndertowLogger . REQUEST_IO_LOGGER . debugf ( "Closing stream %s on %s as data length was less than content size" , streamId , getFramedChannel ( ) ) ; getFramedChannel ( ) . sendRstStream ( streamId , Http2Channel . ERROR_PROTOCOL_ERROR ) ; } } }
Checks that the actual content size matches the expected . We check this proactivly rather than as the data is read
10,370
private void exitRead ( long consumed ) throws IOException { long oldVal = state ; if ( consumed == - 1 ) { if ( anyAreSet ( oldVal , MASK_COUNT ) ) { invokeFinishListener ( ) ; state &= ~ MASK_COUNT ; throw UndertowMessages . MESSAGES . couldNotReadContentLengthData ( ) ; } return ; } long newVal = oldVal - consumed ; state = newVal ; }
Exit a read method .
10,371
private void invokeOnComplete ( ) { for ( ; ; ) { if ( pooledBuffers != null ) { for ( PooledByteBuffer buffer : pooledBuffers ) { buffer . close ( ) ; } pooledBuffers = null ; } IoCallback callback = this . callback ; this . buffer = null ; this . fileChannel = null ; this . callback = null ; inCallback = true ; try { callback . onComplete ( exchange , this ) ; } finally { inCallback = false ; } StreamSinkChannel channel = this . channel ; if ( this . buffer != null ) { long t = Buffers . remaining ( buffer ) ; final long total = t ; long written = 0 ; try { do { long res = channel . write ( buffer ) ; written += res ; if ( res == 0 ) { if ( writeListener == null ) { initWriteListener ( ) ; } channel . getWriteSetter ( ) . set ( writeListener ) ; channel . resumeWrites ( ) ; return ; } } while ( written < total ) ; } catch ( IOException e ) { invokeOnException ( callback , e ) ; } } else if ( this . fileChannel != null ) { if ( transferTask == null ) { transferTask = new TransferTask ( ) ; } if ( ! transferTask . run ( false ) ) { return ; } } else { return ; } } }
Invokes the onComplete method . If send is called again in onComplete then we loop and write it out . This prevents possible stack overflows due to recursion
10,372
protected static void parseCondFlag ( String line , RewriteCond condition , String flag ) { if ( flag . equals ( "NC" ) || flag . equals ( "nocase" ) ) { condition . setNocase ( true ) ; } else if ( flag . equals ( "OR" ) || flag . equals ( "ornext" ) ) { condition . setOrnext ( true ) ; } else { throw UndertowServletLogger . ROOT_LOGGER . invalidRewriteFlags ( line , flag ) ; } }
Parser for RewriteCond flags .
10,373
public void registerStream ( int streamId , int dependency , int weighting , boolean exclusive ) { final Http2PriorityNode node = new Http2PriorityNode ( streamId , weighting ) ; if ( exclusive ) { Http2PriorityNode existing = nodesByID . get ( dependency ) ; if ( existing != null ) { existing . exclusive ( node ) ; } } else { Http2PriorityNode existing = nodesByID . get ( dependency ) ; if ( existing != null ) { existing . addDependent ( node ) ; } } nodesByID . put ( streamId , node ) ; }
Resisters a stream with its dependency and dependent information
10,374
public void streamRemoved ( int streamId ) { Http2PriorityNode node = nodesByID . get ( streamId ) ; if ( node == null ) { return ; } if ( ! node . hasDependents ( ) ) { int toEvict = evictionQueue [ evictionQueuePosition ] ; evictionQueue [ evictionQueuePosition ++ ] = streamId ; Http2PriorityNode nodeToEvict = nodesByID . get ( toEvict ) ; if ( nodeToEvict != null && ! nodeToEvict . hasDependents ( ) ) { nodesByID . remove ( toEvict ) ; } } }
Method that is invoked when a stream has been removed
10,375
public Comparator < Integer > comparator ( ) { return new Comparator < Integer > ( ) { public int compare ( Integer o1 , Integer o2 ) { Http2PriorityNode n1 = nodesByID . get ( o1 ) ; Http2PriorityNode n2 = nodesByID . get ( o2 ) ; if ( n1 == null && n2 == null ) { return 0 ; } if ( n1 == null ) { return - 1 ; } if ( n2 == null ) { return 1 ; } double d1 = createWeightingProportion ( n1 ) ; double d2 = createWeightingProportion ( n2 ) ; return Double . compare ( d1 , d2 ) ; } } ; }
Creates a priority queue
10,376
boolean updateSettings ( List < Http2Setting > settings ) { for ( Http2Setting setting : settings ) { if ( setting . getId ( ) == Http2Setting . SETTINGS_INITIAL_WINDOW_SIZE ) { synchronized ( flowControlLock ) { int old = initialSendWindowSize ; if ( setting . getValue ( ) > Integer . MAX_VALUE ) { sendGoAway ( ERROR_FLOW_CONTROL_ERROR ) ; return false ; } initialSendWindowSize = ( int ) setting . getValue ( ) ; } } else if ( setting . getId ( ) == Http2Setting . SETTINGS_MAX_FRAME_SIZE ) { if ( setting . getValue ( ) > MAX_FRAME_SIZE || setting . getValue ( ) < DEFAULT_MAX_FRAME_SIZE ) { UndertowLogger . REQUEST_IO_LOGGER . debug ( "Invalid value received for SETTINGS_MAX_FRAME_SIZE " + setting . getValue ( ) ) ; sendGoAway ( ERROR_PROTOCOL_ERROR ) ; return false ; } sendMaxFrameSize = ( int ) setting . getValue ( ) ; } else if ( setting . getId ( ) == Http2Setting . SETTINGS_HEADER_TABLE_SIZE ) { synchronized ( this ) { encoder . setMaxTableSize ( ( int ) setting . getValue ( ) ) ; } } else if ( setting . getId ( ) == Http2Setting . SETTINGS_ENABLE_PUSH ) { int result = ( int ) setting . getValue ( ) ; if ( result == 0 ) { pushEnabled = false ; } else if ( result != 1 ) { UndertowLogger . REQUEST_IO_LOGGER . debug ( "Invalid value received for SETTINGS_ENABLE_PUSH " + result ) ; sendGoAway ( ERROR_PROTOCOL_ERROR ) ; return false ; } } else if ( setting . getId ( ) == Http2Setting . SETTINGS_MAX_CONCURRENT_STREAMS ) { sendMaxConcurrentStreams = ( int ) setting . getValue ( ) ; } } return true ; }
Setting have been received from the client
10,377
public synchronized Http2HeadersStreamSinkChannel createStream ( HeaderMap requestHeaders ) throws IOException { if ( ! isClient ( ) ) { throw UndertowMessages . MESSAGES . headersStreamCanOnlyBeCreatedByClient ( ) ; } if ( ! isOpen ( ) ) { throw UndertowMessages . MESSAGES . channelIsClosed ( ) ; } sendConcurrentStreamsAtomicUpdater . incrementAndGet ( this ) ; if ( sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams ) { throw UndertowMessages . MESSAGES . streamLimitExceeded ( ) ; } int streamId = streamIdCounter ; streamIdCounter += 2 ; Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel ( this , streamId , requestHeaders ) ; currentStreams . put ( streamId , new StreamHolder ( http2SynStreamStreamSinkChannel ) ) ; return http2SynStreamStreamSinkChannel ; }
Creates a strema using a HEADERS frame
10,378
int grabFlowControlBytes ( int bytesToGrab ) { if ( bytesToGrab <= 0 ) { return 0 ; } int min ; synchronized ( flowControlLock ) { min = ( int ) Math . min ( bytesToGrab , sendWindowSize ) ; if ( bytesToGrab > FLOW_CONTROL_MIN_WINDOW && min <= FLOW_CONTROL_MIN_WINDOW ) { return 0 ; } min = Math . min ( sendMaxFrameSize , min ) ; sendWindowSize -= min ; } return min ; }
Try and decrement the send window by the given amount of bytes .
10,379
public Http2HeadersStreamSinkChannel createInitialUpgradeResponseStream ( ) { if ( lastGoodStreamId != 0 ) { throw new IllegalStateException ( ) ; } lastGoodStreamId = 1 ; Http2HeadersStreamSinkChannel stream = new Http2HeadersStreamSinkChannel ( this , 1 ) ; StreamHolder streamHolder = new StreamHolder ( stream ) ; streamHolder . sourceClosed = true ; currentStreams . put ( 1 , streamHolder ) ; receiveConcurrentStreamsAtomicUpdater . getAndIncrement ( this ) ; return stream ; }
Creates a response stream to respond to the initial HTTP upgrade
10,380
static List < Integer > parseClientHello ( ByteBuffer source ) throws SSLException { ByteBuffer input = source . duplicate ( ) ; if ( isIncompleteHeader ( input ) ) { throw new BufferUnderflowException ( ) ; } byte firstByte = input . get ( ) ; byte secondByte = input . get ( ) ; byte thirdByte = input . get ( ) ; if ( ( firstByte & 0x80 ) != 0 && thirdByte == 0x01 ) { return null ; } else if ( firstByte == 22 ) { if ( secondByte == 3 && thirdByte >= 1 && thirdByte <= 3 ) { return exploreTLSRecord ( input , firstByte , secondByte , thirdByte ) ; } } return null ; }
Checks if a client handshake is offering ALPN and if so it returns a list of all ciphers . If ALPN is not being offered then this will return null .
10,381
public void awaitShutdown ( ) throws InterruptedException { synchronized ( lock ) { if ( ! shutdown ) { throw UndertowMessages . MESSAGES . handlerNotShutdown ( ) ; } while ( activeRequestsUpdater . get ( this ) > 0 ) { lock . wait ( ) ; } } }
Waits for the handler to shutdown .
10,382
public boolean awaitShutdown ( long millis ) throws InterruptedException { synchronized ( lock ) { if ( ! shutdown ) { throw UndertowMessages . MESSAGES . handlerNotShutdown ( ) ; } long end = System . currentTimeMillis ( ) + millis ; int count = ( int ) activeRequestsUpdater . get ( this ) ; while ( count != 0 ) { long left = end - System . currentTimeMillis ( ) ; if ( left <= 0 ) { return false ; } lock . wait ( left ) ; count = ( int ) activeRequestsUpdater . get ( this ) ; } return true ; } }
Waits a set length of time for the handler to shut down
10,383
public void addShutdownListener ( final ShutdownListener shutdownListener ) { synchronized ( lock ) { if ( ! shutdown ) { throw UndertowMessages . MESSAGES . handlerNotShutdown ( ) ; } long count = activeRequestsUpdater . get ( this ) ; if ( count == 0 ) { shutdownListener . shutdown ( true ) ; } else { shutdownListeners . add ( shutdownListener ) ; } } }
Adds a shutdown listener that will be invoked when all requests have finished . If all requests have already been finished the listener will be invoked immediately .
10,384
public void run ( ) { if ( ! stateUpdater . compareAndSet ( this , 1 , 2 ) ) { return ; } if ( forceLogRotation ) { doRotate ( ) ; } else if ( initialRun && Files . exists ( defaultLogFile ) ) { long lm = 0 ; try { lm = Files . getLastModifiedTime ( defaultLogFile ) . toMillis ( ) ; } catch ( IOException e ) { UndertowLogger . ROOT_LOGGER . errorRotatingAccessLog ( e ) ; } Calendar c = Calendar . getInstance ( ) ; c . setTimeInMillis ( changeOverPoint ) ; c . add ( Calendar . DATE , - 1 ) ; if ( lm <= c . getTimeInMillis ( ) ) { doRotate ( ) ; } } initialRun = false ; List < String > messages = new ArrayList < > ( ) ; String msg ; for ( int i = 0 ; i < 1000 ; ++ i ) { msg = pendingMessages . poll ( ) ; if ( msg == null ) { break ; } messages . add ( msg ) ; } try { if ( ! messages . isEmpty ( ) ) { writeMessage ( messages ) ; } } finally { stateUpdater . set ( this , 0 ) ; if ( ! pendingMessages . isEmpty ( ) || forceLogRotation ) { if ( stateUpdater . compareAndSet ( this , 0 , 1 ) ) { logWriteExecutor . execute ( this ) ; } } else if ( closed ) { try { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; writer = null ; } } catch ( IOException e ) { UndertowLogger . ROOT_LOGGER . errorWritingAccessLog ( e ) ; } } } }
processes all queued log messages
10,385
@ SuppressWarnings ( "unchecked" ) public static < T > AttachmentKey < AttachmentList < T > > createList ( final Class < ? super T > valueClass ) { return new ListAttachmentKey ( valueClass ) ; }
Construct a new list attachment key .
10,386
final SendFrameHeader getFrameHeader ( ) throws IOException { if ( header == null ) { header = createFrameHeader ( ) ; if ( header == null ) { header = new SendFrameHeader ( 0 , null ) ; } } return header ; }
Returns the header for the current frame .
10,387
public boolean send ( PooledByteBuffer pooled ) throws IOException { if ( isWritesShutdown ( ) ) { throw UndertowMessages . MESSAGES . channelIsClosed ( ) ; } boolean result = sendInternal ( pooled ) ; if ( result ) { flush ( ) ; } return result ; }
Send a buffer to this channel .
10,388
final void flushComplete ( ) throws IOException { synchronized ( lock ) { try { bufferFull = false ; int remaining = header . getRemainingInBuffer ( ) ; boolean finalFrame = finalFrameQueued ; boolean channelClosed = finalFrame && remaining == 0 && ! header . isAnotherFrameRequired ( ) ; if ( remaining > 0 ) { body . getBuffer ( ) . limit ( body . getBuffer ( ) . limit ( ) + remaining ) ; if ( finalFrame ) { this . finalFrameQueued = false ; } } else if ( header . isAnotherFrameRequired ( ) ) { this . finalFrameQueued = false ; if ( body != null ) { body . close ( ) ; body = null ; state &= ~ STATE_PRE_WRITE_CALLED ; } } else if ( body != null ) { body . close ( ) ; body = null ; state &= ~ STATE_PRE_WRITE_CALLED ; } if ( channelClosed ) { fullyFlushed = true ; if ( body != null ) { body . close ( ) ; body = null ; state &= ~ STATE_PRE_WRITE_CALLED ; } } else if ( body != null ) { body . getBuffer ( ) . compact ( ) ; writeBuffer = body ; body = null ; state &= ~ STATE_PRE_WRITE_CALLED ; } if ( header . getByteBuffer ( ) != null ) { header . getByteBuffer ( ) . close ( ) ; } header = null ; readyForFlush = false ; if ( isWriteResumed ( ) && ! channelClosed ) { wakeupWrites ( ) ; } else if ( isWriteResumed ( ) ) { ChannelListeners . invokeChannelListener ( getIoThread ( ) , ( S ) this , getWriteListener ( ) ) ; } final ChannelListener < ? super S > closeListener = this . closeSetter . get ( ) ; if ( channelClosed && closeListener != null ) { ChannelListeners . invokeChannelListener ( getIoThread ( ) , ( S ) AbstractFramedStreamSinkChannel . this , closeListener ) ; } handleFlushComplete ( channelClosed ) ; } finally { wakeupWaiters ( ) ; } } }
Method that is invoked when a frame has been fully flushed . This method is only invoked by the IO thread
10,389
boolean isAllowed ( String attribute ) { if ( attribute != null ) { for ( AclMatch rule : acl ) { if ( rule . matches ( attribute ) ) { return ! rule . isDeny ( ) ; } } } return defaultAllow ; }
package private for unit tests
10,390
public static PredicateHandler predicate ( final Predicate predicate , final HttpHandler trueHandler , final HttpHandler falseHandler ) { return new PredicateHandler ( predicate , trueHandler , falseHandler ) ; }
Returns a new predicate handler that will delegate to one of the two provided handlers based on the value of the provided predicate .
10,391
public static SetHeaderHandler header ( final HttpHandler next , final String headerName , final ExchangeAttribute headerValue ) { return new SetHeaderHandler ( next , headerName , headerValue ) ; }
Returns a handler that sets a response header
10,392
public static final AccessControlListHandler acl ( final HttpHandler next , boolean defaultAllow , ExchangeAttribute attribute ) { return new AccessControlListHandler ( next , attribute ) . setDefaultAllow ( defaultAllow ) ; }
Returns a new handler that can allow or deny access to a resource based an at attribute of the exchange
10,393
public static SetAttributeHandler setAttribute ( final HttpHandler next , final String attribute , final String value , final ClassLoader classLoader ) { return new SetAttributeHandler ( next , attribute , value , classLoader ) ; }
Returns an attribute setting handler that can be used to set an arbitrary attribute on the exchange . This includes functions such as adding and removing headers etc .
10,394
public static HttpHandler rewrite ( final String condition , final String target , final ClassLoader classLoader , final HttpHandler next ) { return predicateContext ( predicate ( PredicateParser . parse ( condition , classLoader ) , setAttribute ( next , "%R" , target , classLoader ) , next ) ) ; }
Creates the set of handlers that are required to perform a simple rewrite .
10,395
public static JvmRouteHandler jvmRoute ( final String sessionCookieName , final String jvmRoute , HttpHandler next ) { return new JvmRouteHandler ( next , sessionCookieName , jvmRoute ) ; }
Handler that appends the JVM route to the session cookie
10,396
public static RequestLimitingHandler requestLimitingHandler ( final int maxRequest , final int queueSize , HttpHandler next ) { return new RequestLimitingHandler ( maxRequest , queueSize , next ) ; }
Returns a handler that limits the maximum number of requests that can run at a time .
10,397
public static ProxyHandler proxyHandler ( ProxyClient proxyClient , HttpHandler next ) { return ProxyHandler . builder ( ) . setProxyClient ( proxyClient ) . setNext ( next ) . build ( ) ; }
Returns a handler that can act as a load balancing reverse proxy .
10,398
public static LearningPushHandler learningPushHandler ( int maxEntries , int maxAge , HttpHandler next ) { return new LearningPushHandler ( maxEntries , maxAge , next ) ; }
Creates a handler that automatically learns which resources to push based on the referer header
10,399
@ SuppressWarnings ( "unused" ) final void handleStatusCode ( ByteBuffer buffer , ResponseParseState state , HttpResponseBuilder builder ) { StringBuilder stringBuilder = state . stringBuilder ; while ( buffer . hasRemaining ( ) ) { final char next = ( char ) buffer . get ( ) ; if ( next == ' ' || next == '\t' ) { builder . setStatusCode ( Integer . parseInt ( stringBuilder . toString ( ) ) ) ; state . state = ResponseParseState . REASON_PHRASE ; state . stringBuilder . setLength ( 0 ) ; state . parseState = 0 ; state . pos = 0 ; state . nextHeader = null ; return ; } else { stringBuilder . append ( next ) ; } } }
Parses the status code . This is called from the generated bytecode .