idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
30,100 | public static DirectoryClassLoader getInstance ( final File dir ) throws GuacamoleException { try { return AccessController . doPrivileged ( new PrivilegedExceptionAction < DirectoryClassLoader > ( ) { public DirectoryClassLoader run ( ) throws GuacamoleException { return new DirectoryClassLoader ( dir ) ; } } ) ; } catch ( PrivilegedActionException e ) { throw ( GuacamoleException ) e . getException ( ) ; } } | Returns an instance of DirectoryClassLoader configured to load . jar files from the given directory . Calling this function multiple times will not affect previously - returned instances of DirectoryClassLoader . |
30,101 | private static URL [ ] getJarURLs ( File dir ) throws GuacamoleException { if ( ! dir . isDirectory ( ) ) throw new GuacamoleException ( dir + " is not a directory." ) ; Collection < URL > jarURLs = new ArrayList < URL > ( ) ; File [ ] files = dir . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".jar" ) ; } } ) ; if ( files == null ) throw new GuacamoleException ( "Unable to read contents of directory " + dir ) ; for ( File file : files ) { try { jarURLs . add ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new GuacamoleException ( e ) ; } } URL [ ] urls = new URL [ jarURLs . size ( ) ] ; return jarURLs . toArray ( urls ) ; } | Returns all . jar files within the given directory as an array of URLs . |
30,102 | private void warnAuthProviderSkipped ( Throwable e ) { logger . warn ( "The \"{}\" authentication provider has been skipped due " + "to an internal error. If this is unexpected or you are the " + "developer of this authentication provider, you may wish to " + "enable debug-level logging: {}" , getIdentifier ( ) , e . getMessage ( ) ) ; logger . debug ( "Authentication provider skipped due to an internal failure." , e ) ; } | Logs a warning that this authentication provider is being skipped due to an internal error . If debug - level logging is enabled the full details of the internal error are also logged . |
30,103 | private void warnAuthAborted ( ) { String identifier = getIdentifier ( ) ; logger . warn ( "The \"{}\" authentication provider has encountered an " + "internal error which will halt the authentication " + "process. If this is unexpected or you are the developer of " + "this authentication provider, you may wish to enable " + "debug-level logging. If this is expected and you wish to " + "ignore such failures in the future, please set \"{}: {}\" " + "within your guacamole.properties." , identifier , ExtensionModule . SKIP_IF_UNAVAILABLE . getName ( ) , identifier ) ; } | Logs a warning that the authentication process will be entirely aborted due to an internal error advising the administrator to set the skip - if - unavailable property if error encountered is expected and should be tolerated . |
30,104 | public int getMaxConnections ( ) throws GuacamoleException { Integer value = getModel ( ) . getMaxConnections ( ) ; if ( value == null ) return environment . getDefaultMaxConnections ( ) ; return value ; } | Returns the maximum number of connections that should be allowed to this connection overall . If no limit applies zero is returned . |
30,105 | public int getMaxConnectionsPerUser ( ) throws GuacamoleException { Integer value = getModel ( ) . getMaxConnectionsPerUser ( ) ; if ( value == null ) return environment . getDefaultMaxConnectionsPerUser ( ) ; return value ; } | Returns the maximum number of connections that should be allowed to this connection for any individual user . If no limit applies zero is returned . |
30,106 | public GuacamoleProxyConfiguration getGuacamoleProxyConfiguration ( ) throws GuacamoleException { GuacamoleProxyConfiguration defaultConfig = environment . getDefaultGuacamoleProxyConfiguration ( ) ; String hostname = getModel ( ) . getProxyHostname ( ) ; Integer port = getModel ( ) . getProxyPort ( ) ; EncryptionMethod encryptionMethod = getModel ( ) . getProxyEncryptionMethod ( ) ; return new GuacamoleProxyConfiguration ( hostname != null ? hostname : defaultConfig . getHostname ( ) , port != null ? port : defaultConfig . getPort ( ) , encryptionMethod != null ? encryptionMethod : defaultConfig . getEncryptionMethod ( ) ) ; } | Returns the connection information which should be used to connect to guacd when establishing a connection to the remote desktop described by this connection . If no such information is defined for this specific remote desktop connection the default guacd connection information will be used instead as defined by JDBCEnvironment . |
30,107 | public void handleEvent ( Object event ) throws GuacamoleException { for ( final Listener listener : listeners ) { listener . handleEvent ( event ) ; } } | Notifies registered listeners than an event has occurred . Notification continues until a given listener throws a GuacamoleException or other runtime exception or until all listeners have been notified . |
30,108 | private Map < String , ProtocolInfo > readProtocols ( ) { Map < String , ProtocolInfo > protocols = new HashMap < String , ProtocolInfo > ( ) ; File protocol_directory = new File ( getGuacamoleHome ( ) , "protocols" ) ; if ( protocol_directory . isDirectory ( ) ) { File [ ] files = protocol_directory . listFiles ( new FilenameFilter ( ) { public boolean accept ( File file , String string ) { return string . endsWith ( ".json" ) ; } } ) ; if ( files == null ) { logger . error ( "Unable to read contents of \"{}\"." , protocol_directory . getAbsolutePath ( ) ) ; files = new File [ 0 ] ; } for ( File file : files ) { try { FileInputStream stream = new FileInputStream ( file ) ; ProtocolInfo protocol = readProtocol ( stream ) ; stream . close ( ) ; protocols . put ( protocol . getName ( ) , protocol ) ; } catch ( IOException e ) { logger . error ( "Unable to read connection parameter information from \"{}\": {}" , file . getAbsolutePath ( ) , e . getMessage ( ) ) ; logger . debug ( "Error reading protocol JSON." , e ) ; } } } for ( String protocol : KNOWN_PROTOCOLS ) { if ( ! protocols . containsKey ( protocol ) ) { InputStream stream = LocalEnvironment . class . getResourceAsStream ( "/org/apache/guacamole/protocols/" + protocol + ".json" ) ; if ( stream != null ) { try { protocols . put ( protocol , readProtocol ( stream ) ) ; } catch ( IOException e ) { logger . error ( "Unable to read pre-defined connection parameter information for protocol \"{}\": {}" , protocol , e . getMessage ( ) ) ; logger . debug ( "Error reading pre-defined protocol JSON." , e ) ; } } } } return protocols ; } | Reads through all pre - defined protocols and any protocols within the protocols subdirectory of GUACAMOLE_HOME returning a map containing each of these protocols . The key of each entry will be the name of that protocol as would be passed to guacd during connection . |
30,109 | private String getPropertyValue ( String name ) { if ( environmentPropertiesEnabled ) { final String envName = name . replace ( '-' , '_' ) . toUpperCase ( ) ; final String envValue = System . getenv ( envName ) ; if ( envValue != null ) { return envValue ; } } return properties . getProperty ( name ) ; } | Gets the string value for a property name . |
30,110 | private Credentials getCredentials ( HttpServletRequest request , String username , String password ) { if ( username == null && password == null ) { String authorization = request . getHeader ( "Authorization" ) ; if ( authorization != null && authorization . startsWith ( "Basic " ) ) { try { String basicBase64 = authorization . substring ( 6 ) ; String basicCredentials = new String ( BaseEncoding . base64 ( ) . decode ( basicBase64 ) , "UTF-8" ) ; int colon = basicCredentials . indexOf ( ':' ) ; if ( colon != - 1 ) { username = basicCredentials . substring ( 0 , colon ) ; password = basicCredentials . substring ( colon + 1 ) ; } else logger . debug ( "Invalid HTTP Basic \"Authorization\" header received." ) ; } catch ( UnsupportedEncodingException e ) { throw new UnsupportedOperationException ( "Unexpected lack of UTF-8 support." , e ) ; } } } return new Credentials ( username , password , request ) ; } | Returns the credentials associated with the given request using the provided username and password . |
30,111 | @ Path ( "/{token}" ) public void invalidateToken ( @ PathParam ( "token" ) String authToken ) throws GuacamoleException { if ( ! authenticationService . destroyGuacamoleSession ( authToken ) ) throw new GuacamoleResourceNotFoundException ( "No such token." ) ; } | Invalidates a specific auth token effectively logging out the associated user . |
30,112 | private static int parseInt ( String str , int defaultValue ) { if ( str == null ) return defaultValue ; return Integer . parseInt ( str ) ; } | Parse the given string as an integer returning the provided default value if the string is null . |
30,113 | public Set < String > getIdentifiersWithin ( ModeledAuthenticatedUser user , String identifier ) throws GuacamoleException { if ( user . getUser ( ) . isAdministrator ( ) ) return connectionGroupMapper . selectIdentifiersWithin ( identifier ) ; else return connectionGroupMapper . selectReadableIdentifiersWithin ( user . getUser ( ) . getModel ( ) , identifier , user . getEffectiveUserGroups ( ) ) ; } | Returns the set of all identifiers for all connection groups within the connection group having the given identifier . Only connection groups that the user has read access to will be returned . |
30,114 | private void fireTunnelConnectEvent ( AuthenticatedUser authenticatedUser , Credentials credentials , GuacamoleTunnel tunnel ) throws GuacamoleException { listenerService . handleEvent ( new TunnelConnectEvent ( authenticatedUser , credentials , tunnel ) ) ; } | Notifies bound listeners that a new tunnel has been connected . Listeners may veto a connected tunnel by throwing any GuacamoleException . |
30,115 | private void fireTunnelClosedEvent ( AuthenticatedUser authenticatedUser , Credentials credentials , GuacamoleTunnel tunnel ) throws GuacamoleException { listenerService . handleEvent ( new TunnelCloseEvent ( authenticatedUser , credentials , tunnel ) ) ; } | Notifies bound listeners that a tunnel is to be closed . Listeners are allowed to veto a request to close a tunnel by throwing any GuacamoleException . |
30,116 | protected GuacamoleClientInformation getClientInformation ( TunnelRequest request ) throws GuacamoleException { GuacamoleClientInformation info = new GuacamoleClientInformation ( ) ; Integer width = request . getWidth ( ) ; if ( width != null ) info . setOptimalScreenWidth ( width ) ; Integer height = request . getHeight ( ) ; if ( height != null ) info . setOptimalScreenHeight ( height ) ; Integer dpi = request . getDPI ( ) ; if ( dpi != null ) info . setOptimalResolution ( dpi ) ; List < String > audioMimetypes = request . getAudioMimetypes ( ) ; if ( audioMimetypes != null ) info . getAudioMimetypes ( ) . addAll ( audioMimetypes ) ; List < String > videoMimetypes = request . getVideoMimetypes ( ) ; if ( videoMimetypes != null ) info . getVideoMimetypes ( ) . addAll ( videoMimetypes ) ; List < String > imageMimetypes = request . getImageMimetypes ( ) ; if ( imageMimetypes != null ) info . getImageMimetypes ( ) . addAll ( imageMimetypes ) ; return info ; } | Reads and returns the client information provided within the given request . |
30,117 | protected GuacamoleTunnel createAssociatedTunnel ( final GuacamoleTunnel tunnel , final String authToken , final GuacamoleSession session , final UserContext context , final TunnelRequest . Type type , final String id ) throws GuacamoleException { UserTunnel monitoredTunnel = new UserTunnel ( context , tunnel ) { private final long connectionStartTime = System . currentTimeMillis ( ) ; public void close ( ) throws GuacamoleException { AuthenticatedUser authenticatedUser = session . getAuthenticatedUser ( ) ; fireTunnelClosedEvent ( authenticatedUser , authenticatedUser . getCredentials ( ) , tunnel ) ; long connectionEndTime = System . currentTimeMillis ( ) ; long duration = connectionEndTime - connectionStartTime ; switch ( type ) { case CONNECTION : logger . info ( "User \"{}\" disconnected from connection \"{}\". Duration: {} milliseconds" , session . getAuthenticatedUser ( ) . getIdentifier ( ) , id , duration ) ; break ; case CONNECTION_GROUP : logger . info ( "User \"{}\" disconnected from connection group \"{}\". Duration: {} milliseconds" , session . getAuthenticatedUser ( ) . getIdentifier ( ) , id , duration ) ; break ; default : assert ( false ) ; } try { session . removeTunnel ( getUUID ( ) . toString ( ) ) ; super . close ( ) ; } catch ( GuacamoleUnauthorizedException e ) { if ( authenticationService . destroyGuacamoleSession ( authToken ) ) logger . debug ( "Implicitly invalidated session for token \"{}\"." , authToken ) ; throw e ; } } } ; session . addTunnel ( monitoredTunnel ) ; return monitoredTunnel ; } | Associates the given tunnel with the given session returning a wrapped version of the same tunnel which automatically handles closure and removal from the session . |
30,118 | public GuacamoleTunnel createTunnel ( TunnelRequest request ) throws GuacamoleException { String authToken = request . getAuthenticationToken ( ) ; String id = request . getIdentifier ( ) ; TunnelRequest . Type type = request . getType ( ) ; String authProviderIdentifier = request . getAuthenticationProviderIdentifier ( ) ; GuacamoleClientInformation info = getClientInformation ( request ) ; GuacamoleSession session = authenticationService . getGuacamoleSession ( authToken ) ; AuthenticatedUser authenticatedUser = session . getAuthenticatedUser ( ) ; UserContext userContext = session . getUserContext ( authProviderIdentifier ) ; try { GuacamoleTunnel tunnel = createConnectedTunnel ( userContext , type , id , info , new StandardTokenMap ( authenticatedUser ) ) ; fireTunnelConnectEvent ( authenticatedUser , authenticatedUser . getCredentials ( ) , tunnel ) ; return createAssociatedTunnel ( tunnel , authToken , session , userContext , type , id ) ; } catch ( GuacamoleUnauthorizedException e ) { if ( authenticationService . destroyGuacamoleSession ( authToken ) ) logger . debug ( "Implicitly invalidated session for token \"{}\"." , authToken ) ; throw e ; } } | Creates a new tunnel using the parameters and credentials present in the given request . |
30,119 | @ Path ( "{tunnel}" ) public TunnelResource getTunnel ( @ PathParam ( "tunnel" ) String tunnelUUID ) throws GuacamoleException { Map < String , UserTunnel > tunnels = session . getTunnels ( ) ; final UserTunnel tunnel = tunnels . get ( tunnelUUID ) ; if ( tunnel == null ) throw new GuacamoleResourceNotFoundException ( "No such tunnel." ) ; return tunnelResourceFactory . create ( tunnel ) ; } | Retrieves the tunnel having the given UUID returning a TunnelResource representing that tunnel . If no such tunnel exists an exception will be thrown . |
30,120 | private void addConnections ( Collection < Connection > connections ) throws GuacamoleException { for ( Connection connection : connections ) { APIConnectionGroup parent = retrievedGroups . get ( connection . getParentIdentifier ( ) ) ; if ( parent != null ) { Collection < APIConnection > children = parent . getChildConnections ( ) ; if ( children == null ) { children = new ArrayList < APIConnection > ( ) ; parent . setChildConnections ( children ) ; } APIConnection apiConnection = new APIConnection ( connection ) ; retrievedConnections . put ( connection . getIdentifier ( ) , apiConnection ) ; children . add ( apiConnection ) ; } else logger . debug ( "Connection \"{}\" cannot be added to the tree: parent \"{}\" does not actually exist." , connection . getIdentifier ( ) , connection . getParentIdentifier ( ) ) ; } } | Adds each of the provided connections to the current tree as children of their respective parents . The parent connection groups must already be added . |
30,121 | private void addConnectionGroups ( Collection < ConnectionGroup > connectionGroups ) { for ( ConnectionGroup connectionGroup : connectionGroups ) { APIConnectionGroup parent = retrievedGroups . get ( connectionGroup . getParentIdentifier ( ) ) ; if ( parent != null ) { Collection < APIConnectionGroup > children = parent . getChildConnectionGroups ( ) ; if ( children == null ) { children = new ArrayList < APIConnectionGroup > ( ) ; parent . setChildConnectionGroups ( children ) ; } APIConnectionGroup apiConnectionGroup = new APIConnectionGroup ( connectionGroup ) ; retrievedGroups . put ( connectionGroup . getIdentifier ( ) , apiConnectionGroup ) ; children . add ( apiConnectionGroup ) ; } else logger . debug ( "Connection group \"{}\" cannot be added to the tree: parent \"{}\" does not actually exist." , connectionGroup . getIdentifier ( ) , connectionGroup . getParentIdentifier ( ) ) ; } } | Adds each of the provided connection groups to the current tree as children of their respective parents . The parent connection groups must already be added . |
30,122 | private void addSharingProfiles ( Collection < SharingProfile > sharingProfiles ) throws GuacamoleException { for ( SharingProfile sharingProfile : sharingProfiles ) { String primaryConnectionIdentifier = sharingProfile . getPrimaryConnectionIdentifier ( ) ; APIConnection primaryConnection = retrievedConnections . get ( primaryConnectionIdentifier ) ; if ( primaryConnection != null ) { Collection < APISharingProfile > children = primaryConnection . getSharingProfiles ( ) ; if ( children == null ) { children = new ArrayList < APISharingProfile > ( ) ; primaryConnection . setSharingProfiles ( children ) ; } children . add ( new APISharingProfile ( sharingProfile ) ) ; } else logger . debug ( "Sharing profile \"{}\" cannot be added to the " + "tree: primary connection \"{}\" does not actually " + "exist." , sharingProfile . getIdentifier ( ) , primaryConnectionIdentifier ) ; } } | Adds each of the provided sharing profiles to the current tree as children of their respective primary connections . The primary connections must already be added . |
30,123 | private void addConnectionGroupDescendants ( Collection < ConnectionGroup > parents , List < ObjectPermission . Type > permissions ) throws GuacamoleException { if ( parents . isEmpty ( ) ) return ; Collection < String > childConnectionIdentifiers = new ArrayList < String > ( ) ; Collection < String > childConnectionGroupIdentifiers = new ArrayList < String > ( ) ; for ( ConnectionGroup parent : parents ) { childConnectionIdentifiers . addAll ( parent . getConnectionIdentifiers ( ) ) ; childConnectionGroupIdentifiers . addAll ( parent . getConnectionGroupIdentifiers ( ) ) ; } if ( permissions != null && ! permissions . isEmpty ( ) ) childConnectionIdentifiers = connectionPermissions . getAccessibleObjects ( permissions , childConnectionIdentifiers ) ; if ( ! childConnectionIdentifiers . isEmpty ( ) ) { Collection < Connection > childConnections = connectionDirectory . getAll ( childConnectionIdentifiers ) ; addConnections ( childConnections ) ; addConnectionDescendants ( childConnections , permissions ) ; } if ( ! childConnectionGroupIdentifiers . isEmpty ( ) ) { Collection < ConnectionGroup > childConnectionGroups = connectionGroupDirectory . getAll ( childConnectionGroupIdentifiers ) ; addConnectionGroups ( childConnectionGroups ) ; addConnectionGroupDescendants ( childConnectionGroups , permissions ) ; } } | Adds all descendants of the given parent groups to their corresponding parents already stored under root . |
30,124 | private void addConnectionDescendants ( Collection < Connection > connections , List < ObjectPermission . Type > permissions ) throws GuacamoleException { if ( connections . isEmpty ( ) ) return ; Collection < String > identifiers = new ArrayList < String > ( ) ; for ( Connection connection : connections ) identifiers . addAll ( connection . getSharingProfileIdentifiers ( ) ) ; if ( permissions != null && ! permissions . isEmpty ( ) ) identifiers = sharingProfilePermissions . getAccessibleObjects ( permissions , identifiers ) ; if ( ! identifiers . isEmpty ( ) ) { Collection < SharingProfile > sharingProfiles = sharingProfileDirectory . getAll ( identifiers ) ; addSharingProfiles ( sharingProfiles ) ; } } | Adds all descendant sharing profiles of the given connections to their corresponding primary connections already stored under root . |
30,125 | public String getRequiredParameter ( String name ) throws GuacamoleException { String value = getParameter ( name ) ; if ( value == null ) throw new GuacamoleClientException ( "Parameter \"" + name + "\" is required." ) ; return value ; } | Returns the value of the parameter having the given name throwing an exception if the parameter is missing . |
30,126 | public Integer getIntegerParameter ( String name ) throws GuacamoleException { String value = getParameter ( name ) ; if ( value == null ) return null ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { throw new GuacamoleClientException ( "Parameter \"" + name + "\" must be a valid integer." , e ) ; } } | Returns the integer value of the parameter having the given name throwing an exception if the parameter cannot be parsed . |
30,127 | public Type getType ( ) throws GuacamoleException { String type = getRequiredParameter ( TYPE_PARAMETER ) ; for ( Type possibleType : Type . values ( ) ) { if ( type . equals ( possibleType . PARAMETER_VALUE ) ) return possibleType ; } throw new GuacamoleClientException ( "Illegal identifier - unknown type." ) ; } | Returns the type of object for which the tunnel is being requested . |
30,128 | private boolean matches ( String str , Pattern ... patterns ) { for ( Pattern pattern : patterns ) { Matcher matcher = pattern . matcher ( str ) ; if ( ! matcher . find ( ) ) return false ; } return true ; } | Returns whether the given string matches all of the provided regular expressions . |
30,129 | private boolean matchesPreviousPasswords ( String password , String username , int historySize ) { if ( historySize <= 0 ) return false ; List < PasswordRecordModel > history = passwordRecordMapper . select ( username , historySize ) ; for ( PasswordRecordModel record : history ) { byte [ ] hash = encryptionService . createPasswordHash ( password , record . getPasswordSalt ( ) ) ; if ( Arrays . equals ( hash , record . getPasswordHash ( ) ) ) return true ; } return false ; } | Returns whether the given password matches any of the user s previous passwords . Regardless of the value specified here the maximum number of passwords involved in this check depends on how many previous passwords were actually recorded which depends on the password policy . |
30,130 | public void verifyPassword ( String username , String password ) throws GuacamoleException { PasswordPolicy policy = environment . getPasswordPolicy ( ) ; if ( password . length ( ) < policy . getMinimumLength ( ) ) throw new PasswordMinimumLengthException ( "Password does not meet minimum length requirements." , policy . getMinimumLength ( ) ) ; if ( policy . isUsernameProhibited ( ) && password . toLowerCase ( ) . contains ( username . toLowerCase ( ) ) ) throw new PasswordContainsUsernameException ( "Password must not contain username." ) ; if ( policy . isMultipleCaseRequired ( ) && ! matches ( password , CONTAINS_LOWERCASE , CONTAINS_UPPERCASE ) ) throw new PasswordRequiresMultipleCaseException ( "Password must contain both uppercase and lowercase." ) ; if ( policy . isNumericRequired ( ) && ! matches ( password , CONTAINS_DIGIT ) ) throw new PasswordRequiresDigitException ( "Passwords must contain at least one digit." ) ; if ( policy . isNonAlphanumericRequired ( ) && ! matches ( password , CONTAINS_NON_ALPHANUMERIC ) ) throw new PasswordRequiresSymbolException ( "Passwords must contain at least one non-alphanumeric character." ) ; int historySize = policy . getHistorySize ( ) ; if ( matchesPreviousPasswords ( password , username , historySize ) ) throw new PasswordReusedException ( "Password matches a previously-used password." , historySize ) ; } | Verifies that the given new password complies with the password policy configured within guacamole . properties throwing a GuacamoleException if the policy is violated in any way . |
30,131 | private long getPasswordAge ( ModeledUser user ) { PasswordRecordModel passwordRecord = user . getPasswordRecord ( ) ; if ( passwordRecord == null ) return 0 ; long currentTime = System . currentTimeMillis ( ) ; long lastResetTime = passwordRecord . getPasswordDate ( ) . getTime ( ) ; return TimeUnit . DAYS . convert ( currentTime - lastResetTime , TimeUnit . MILLISECONDS ) ; } | Returns the age of the given user s password in days . The age of a user s password is the amount of time elapsed since the password was last changed or reset . |
30,132 | public void verifyPasswordAge ( ModeledUser user ) throws GuacamoleException { PasswordPolicy policy = environment . getPasswordPolicy ( ) ; long minimumAge = policy . getMinimumAge ( ) ; long passwordAge = getPasswordAge ( user ) ; if ( passwordAge < minimumAge ) throw new PasswordTooYoungException ( "Password was already recently changed." , minimumAge - passwordAge ) ; } | Verifies that the given user can change their password without violating password aging policy . If changing the user s password would violate the aging policy a GuacamoleException will be thrown . |
30,133 | public boolean isPasswordExpired ( ModeledUser user ) throws GuacamoleException { PasswordPolicy policy = environment . getPasswordPolicy ( ) ; int maxPasswordAge = policy . getMaximumAge ( ) ; if ( maxPasswordAge == 0 ) return false ; return getPasswordAge ( user ) >= maxPasswordAge ; } | Returns whether the given user s password is expired due to the password aging policy . |
30,134 | public void recordPassword ( ModeledUser user ) throws GuacamoleException { PasswordPolicy policy = environment . getPasswordPolicy ( ) ; int historySize = policy . getHistorySize ( ) ; if ( historySize <= 0 ) return ; passwordRecordMapper . insert ( user . getPasswordRecord ( ) , historySize ) ; } | Records the password that was associated with the given user at the time the user was queried such that future attempts to set that same password for that user will be denied . The number of passwords remembered for each user is limited by the password policy . |
30,135 | private static String sign ( String key , String data ) throws GuacamoleException { try { Mac mac = Mac . getInstance ( SIGNATURE_ALGORITHM ) ; mac . init ( new SecretKeySpec ( key . getBytes ( "UTF-8" ) , SIGNATURE_ALGORITHM ) ) ; return BaseEncoding . base16 ( ) . lowerCase ( ) . encode ( mac . doFinal ( data . getBytes ( "UTF-8" ) ) ) ; } catch ( InvalidKeyException e ) { throw new GuacamoleServerException ( "Signing key is invalid." , e ) ; } catch ( UnsupportedEncodingException e ) { throw new UnsupportedOperationException ( "Unexpected lack of UTF-8 support." , e ) ; } catch ( NoSuchAlgorithmException e ) { throw new UnsupportedOperationException ( "Unexpected lack of support " + "for required signature algorithm " + "\"" + SIGNATURE_ALGORITHM + "\"." , e ) ; } } | Signs the given arbitrary string data with the given key using the algorithm defined by SIGNATURE_ALGORITHM . Both the data and the key will be interpreted as UTF - 8 bytes . |
30,136 | public String setValue ( String name , String value ) { return values . put ( name , value ) ; } | Sets the value of the field having the given name . Any existing value for that field is replaced . |
30,137 | public String setValue ( Field field , String value ) { return setValue ( field . getName ( ) , value ) ; } | Sets the value of the given field . Any existing value for that field is replaced . |
30,138 | public boolean isAdministrator ( ) throws GuacamoleException { SystemPermissionSet systemPermissionSet = getEffective ( ) . getSystemPermissions ( ) ; return systemPermissionSet . hasPermission ( SystemPermission . Type . ADMINISTER ) ; } | Returns whether this entity is a system administrator and thus is not restricted by permissions taking into account permission inheritance via user groups . |
30,139 | public Permissions getEffective ( ) { final ModeledAuthenticatedUser authenticatedUser = getCurrentUser ( ) ; final Set < String > effectiveGroups ; if ( authenticatedUser . getIdentifier ( ) . equals ( getIdentifier ( ) ) ) effectiveGroups = entityService . retrieveEffectiveGroups ( this , authenticatedUser . getEffectiveUserGroups ( ) ) ; else effectiveGroups = getEffectiveUserGroups ( ) ; return new Permissions ( ) { public ObjectPermissionSet getActiveConnectionPermissions ( ) throws GuacamoleException { return activeConnectionPermissionService . getPermissionSet ( authenticatedUser , ModeledPermissions . this , effectiveGroups ) ; } public ObjectPermissionSet getConnectionGroupPermissions ( ) throws GuacamoleException { return connectionGroupPermissionService . getPermissionSet ( authenticatedUser , ModeledPermissions . this , effectiveGroups ) ; } public ObjectPermissionSet getConnectionPermissions ( ) throws GuacamoleException { return connectionPermissionService . getPermissionSet ( authenticatedUser , ModeledPermissions . this , effectiveGroups ) ; } public ObjectPermissionSet getSharingProfilePermissions ( ) throws GuacamoleException { return sharingProfilePermissionService . getPermissionSet ( authenticatedUser , ModeledPermissions . this , effectiveGroups ) ; } public SystemPermissionSet getSystemPermissions ( ) throws GuacamoleException { return systemPermissionService . getPermissionSet ( authenticatedUser , ModeledPermissions . this , effectiveGroups ) ; } public ObjectPermissionSet getUserPermissions ( ) throws GuacamoleException { return userPermissionService . getPermissionSet ( authenticatedUser , ModeledPermissions . this , effectiveGroups ) ; } public ObjectPermissionSet getUserGroupPermissions ( ) throws GuacamoleException { return userGroupPermissionService . getPermissionSet ( getCurrentUser ( ) , ModeledPermissions . this , effectiveGroups ) ; } } ; } | Returns a Permissions object which represents all permissions granted to this entity including any permissions inherited through group membership . |
30,140 | private RadiusClient createRadiusConnection ( ) throws GuacamoleException { try { return new RadiusClient ( InetAddress . getByName ( confService . getRadiusServer ( ) ) , confService . getRadiusSharedSecret ( ) , confService . getRadiusAuthPort ( ) , confService . getRadiusAcctPort ( ) , confService . getRadiusTimeout ( ) ) ; } catch ( UnknownHostException e ) { logger . debug ( "Failed to resolve host." , e ) ; throw new GuacamoleServerException ( "Unable to resolve RADIUS server host." , e ) ; } catch ( IOException e ) { logger . debug ( "Failed to communicate with host." , e ) ; throw new GuacamoleServerException ( "Failed to communicate with RADIUS server." , e ) ; } } | Creates a new instance of RadiusClient configured with parameters from guacamole . properties . |
30,141 | private RadiusAuthenticator setupRadiusAuthenticator ( RadiusClient radiusClient ) throws GuacamoleException { if ( radiusClient == null ) { logger . error ( "RADIUS client hasn't been set up, yet." ) ; logger . debug ( "We can't run this method until the RADIUS client has been set up." ) ; return null ; } RadiusAuthenticator radAuth = radiusClient . getAuthProtocol ( confService . getRadiusAuthProtocol ( ) ) ; if ( radAuth == null ) throw new GuacamoleException ( "Could not get a valid RadiusAuthenticator for specified protocol: " + confService . getRadiusAuthProtocol ( ) ) ; if ( radAuth instanceof PEAPAuthenticator || radAuth instanceof EAPTLSAuthenticator || radAuth instanceof EAPTTLSAuthenticator ) { File caFile = confService . getRadiusCAFile ( ) ; String caPassword = confService . getRadiusCAPassword ( ) ; File keyFile = confService . getRadiusKeyFile ( ) ; String keyPassword = confService . getRadiusKeyPassword ( ) ; if ( caFile != null ) { ( ( EAPTLSAuthenticator ) radAuth ) . setCaFile ( caFile . toString ( ) ) ; ( ( EAPTLSAuthenticator ) radAuth ) . setCaFileType ( confService . getRadiusCAType ( ) ) ; if ( caPassword != null ) ( ( EAPTLSAuthenticator ) radAuth ) . setCaPassword ( caPassword ) ; } if ( keyPassword != null ) ( ( EAPTLSAuthenticator ) radAuth ) . setKeyPassword ( keyPassword ) ; ( ( EAPTLSAuthenticator ) radAuth ) . setKeyFile ( keyFile . toString ( ) ) ; ( ( EAPTLSAuthenticator ) radAuth ) . setKeyFileType ( confService . getRadiusKeyType ( ) ) ; ( ( EAPTLSAuthenticator ) radAuth ) . setTrustAll ( confService . getRadiusTrustAll ( ) ) ; } if ( radAuth instanceof EAPTTLSAuthenticator ) { String innerProtocol = confService . getRadiusEAPTTLSInnerProtocol ( ) ; if ( innerProtocol == null ) throw new GuacamoleException ( "Trying to use EAP-TTLS, but no inner protocol specified." ) ; ( ( EAPTTLSAuthenticator ) radAuth ) . setInnerProtocol ( innerProtocol ) ; } return radAuth ; } | Creates a new instance of RadiusAuthentictor configured with parameters specified within guacamole . properties . |
30,142 | public RadiusPacket authenticate ( String username , String secret , byte [ ] state ) throws GuacamoleException { if ( username == null || username . isEmpty ( ) ) { logger . warn ( "Anonymous access not allowed with RADIUS client." ) ; return null ; } if ( secret == null || secret . isEmpty ( ) ) { logger . warn ( "Password/secret required for RADIUS authentication." ) ; return null ; } RadiusClient radiusClient = createRadiusConnection ( ) ; AttributeFactory . loadAttributeDictionary ( "net.jradius.dictionary.AttributeDictionaryImpl" ) ; if ( radiusClient == null ) return null ; RadiusAuthenticator radAuth = setupRadiusAuthenticator ( radiusClient ) ; if ( radAuth == null ) throw new GuacamoleException ( "Unknown RADIUS authentication protocol." ) ; try { AttributeList radAttrs = new AttributeList ( ) ; radAttrs . add ( new Attr_UserName ( username ) ) ; if ( state != null && state . length > 0 ) radAttrs . add ( new Attr_State ( state ) ) ; radAttrs . add ( new Attr_UserPassword ( secret ) ) ; radAttrs . add ( new Attr_CleartextPassword ( secret ) ) ; AccessRequest radAcc = new AccessRequest ( radiusClient ) ; if ( radAuth instanceof EAPTTLSAuthenticator ) { radAuth . setUsername ( new Attr_UserName ( username ) ) ; ( ( EAPTTLSAuthenticator ) radAuth ) . setTunneledAttributes ( radAttrs ) ; } else radAcc . addAttributes ( radAttrs ) ; radAuth . setupRequest ( radiusClient , radAcc ) ; radAuth . processRequest ( radAcc ) ; RadiusResponse reply = radiusClient . sendReceive ( radAcc , confService . getRadiusMaxRetries ( ) ) ; while ( ( reply instanceof AccessChallenge ) && ( reply . findAttribute ( Attr_ReplyMessage . TYPE ) == null ) ) { radAuth . processChallenge ( radAcc , reply ) ; reply = radiusClient . sendReceive ( radAcc , confService . getRadiusMaxRetries ( ) ) ; } return reply ; } catch ( RadiusException e ) { logger . error ( "Unable to complete authentication." , e . getMessage ( ) ) ; logger . debug ( "Authentication with RADIUS failed." , e ) ; return null ; } catch ( NoSuchAlgorithmException e ) { logger . error ( "No such RADIUS algorithm: {}" , e . getMessage ( ) ) ; logger . debug ( "Unknown RADIUS algorithm." , e ) ; return null ; } finally { radiusClient . close ( ) ; } } | Authenticate to the RADIUS server using existing state and a response |
30,143 | public RadiusPacket sendChallengeResponse ( String username , String response , byte [ ] state ) throws GuacamoleException { if ( username == null || username . isEmpty ( ) ) { logger . error ( "Challenge/response to RADIUS requires a username." ) ; return null ; } if ( state == null || state . length == 0 ) { logger . error ( "Challenge/response to RADIUS requires a prior state." ) ; return null ; } if ( response == null || response . isEmpty ( ) ) { logger . error ( "Challenge/response to RADIUS requires a response." ) ; return null ; } return authenticate ( username , response , state ) ; } | Send a challenge response to the RADIUS server by validating the input and then sending it along to the authenticate method . |
30,144 | private boolean canAlterRelation ( Collection < String > identifiers ) throws GuacamoleException { if ( getCurrentUser ( ) . getUser ( ) . isAdministrator ( ) ) return true ; if ( ! getParentObjectEffectivePermissionSet ( ) . hasPermission ( ObjectPermission . Type . UPDATE , parent . getIdentifier ( ) ) ) return false ; Collection < String > accessibleIdentifiers = getChildObjectEffectivePermissionSet ( ) . getAccessibleObjects ( Collections . singleton ( ObjectPermission . Type . UPDATE ) , identifiers ) ; return accessibleIdentifiers . size ( ) == identifiers . size ( ) ; } | Returns whether the current user has permission to alter the status of the relation between the parent object and the given child objects . |
30,145 | private boolean methodThrowsException ( Method method , Class < ? extends Exception > exceptionType ) { for ( Class < ? > thrownType : method . getExceptionTypes ( ) ) { if ( exceptionType . isAssignableFrom ( thrownType ) ) return true ; } return false ; } | Returns whether the given method throws the specified exception type including any subclasses of that type . |
30,146 | public GuacamoleHTTPTunnel get ( String uuid ) { GuacamoleHTTPTunnel tunnel = tunnelMap . get ( uuid ) ; if ( tunnel != null ) tunnel . access ( ) ; return tunnel ; } | Returns the GuacamoleTunnel having the given UUID wrapped within a GuacamoleHTTPTunnel . If the no tunnel having the given UUID is available null is returned . |
30,147 | public void put ( String uuid , GuacamoleTunnel tunnel ) { tunnelMap . put ( uuid , new GuacamoleHTTPTunnel ( tunnel ) ) ; } | Registers that a new connection has been established using HTTP via the given GuacamoleTunnel . |
30,148 | public void updateObject ( ExternalType modifiedObject ) throws GuacamoleException { if ( modifiedObject == null ) throw new GuacamoleClientException ( "Data must be submitted when updating objects." ) ; translator . filterExternalObject ( userContext , modifiedObject ) ; translator . applyExternalChanges ( object , modifiedObject ) ; directory . update ( object ) ; } | Updates an existing object . The changes to be made to the corresponding object within the directory indicated by the provided data . |
30,149 | public File getRadiusCAFile ( ) throws GuacamoleException { return environment . getProperty ( RadiusGuacamoleProperties . RADIUS_CA_FILE , new File ( environment . getGuacamoleHome ( ) , "ca.crt" ) ) ; } | Returns the CA file for validating certificates for encrypted connections to the RADIUS server as configured in guacamole . properties . |
30,150 | public File getRadiusKeyFile ( ) throws GuacamoleException { return environment . getProperty ( RadiusGuacamoleProperties . RADIUS_KEY_FILE , new File ( environment . getGuacamoleHome ( ) , "radius.key" ) ) ; } | Returns the key file for the client for creating encrypted connections to RADIUS servers as specified in guacamole . properties . By default a file called radius . pem is used . |
30,151 | protected boolean hasObjectPermission ( ModeledAuthenticatedUser user , String identifier , ObjectPermission . Type type ) throws GuacamoleException { ObjectPermissionSet permissionSet = getEffectivePermissionSet ( user ) ; return user . getUser ( ) . isAdministrator ( ) || permissionSet . hasPermission ( type , identifier ) ; } | Returns whether the given user has permission to perform a certain action on a specific object managed by this directory object service taking into account permission inheritance through user groups . |
30,152 | protected Collection < InternalType > getObjectInstances ( ModeledAuthenticatedUser currentUser , Collection < ModelType > models ) throws GuacamoleException { Collection < InternalType > objects = new ArrayList < InternalType > ( models . size ( ) ) ; for ( ModelType model : models ) objects . add ( getObjectInstance ( currentUser , model ) ) ; return objects ; } | Returns a collection of objects which are backed by the models in the given collection . |
30,153 | protected boolean isValidIdentifier ( String identifier ) { if ( identifier . isEmpty ( ) ) return false ; for ( int i = 0 ; i < identifier . length ( ) ; i ++ ) { if ( ! Character . isDigit ( identifier . charAt ( i ) ) ) return false ; } return true ; } | Returns whether the given string is a valid identifier within the JDBC authentication extension . Invalid identifiers may result in SQL errors from the underlying database when used in queries . |
30,154 | protected Collection < String > filterIdentifiers ( Collection < String > identifiers ) { Collection < String > validIdentifiers = new ArrayList < String > ( identifiers . size ( ) ) ; for ( String identifier : identifiers ) { if ( isValidIdentifier ( identifier ) ) validIdentifiers . add ( identifier ) ; } return validIdentifiers ; } | Filters the given collection of strings returning a new collection containing only those strings which are valid identifiers . If no strings within the collection are valid identifiers the returned collection will simply be empty . |
30,155 | protected Collection < ObjectPermissionModel > getImplicitPermissions ( ModeledAuthenticatedUser user , ModelType model ) { Collection < ObjectPermissionModel > implicitPermissions = new ArrayList < ObjectPermissionModel > ( IMPLICIT_OBJECT_PERMISSIONS . length ) ; UserModel userModel = user . getUser ( ) . getModel ( ) ; for ( ObjectPermission . Type permission : IMPLICIT_OBJECT_PERMISSIONS ) { ObjectPermissionModel permissionModel = new ObjectPermissionModel ( ) ; permissionModel . setEntityID ( userModel . getEntityID ( ) ) ; permissionModel . setType ( permission ) ; permissionModel . setObjectIdentifier ( model . getIdentifier ( ) ) ; implicitPermissions . add ( permissionModel ) ; } return implicitPermissions ; } | Returns a collection of permissions that should be granted due to the creation of the given object . These permissions need not be granted solely to the user creating the object . |
30,156 | private static String getMimeType ( ServletContext context , String path ) { String mimetype = context . getMimeType ( path ) ; if ( mimetype != null ) return mimetype ; return "application/octet-stream" ; } | Derives a mimetype from the filename within the given path using the given ServletContext if possible . |
30,157 | private void sweepExpiredNonces ( ) { long currentTime = System . currentTimeMillis ( ) ; if ( currentTime - lastSweep < SWEEP_INTERVAL ) return ; lastSweep = currentTime ; Iterator < Map . Entry < String , Long > > entries = nonces . entrySet ( ) . iterator ( ) ; while ( entries . hasNext ( ) ) { Map . Entry < String , Long > current = entries . next ( ) ; if ( current . getValue ( ) <= System . currentTimeMillis ( ) ) entries . remove ( ) ; } } | Iterates through the entire Map of generated nonces removing any nonce that has exceeded its expiration timestamp . If insufficient time has elapsed since the last sweep as dictated by SWEEP_INTERVAL this function has no effect . |
30,158 | public String generate ( long maxAge ) { sweepExpiredNonces ( ) ; String nonce = new BigInteger ( 130 , random ) . toString ( 32 ) ; nonces . put ( nonce , System . currentTimeMillis ( ) + maxAge ) ; return nonce ; } | Generates a cryptographically - secure nonce value . The nonce is intended to be used to prevent replay attacks . |
30,159 | public boolean isValid ( String nonce ) { Long expires = nonces . remove ( nonce ) ; if ( expires == null ) return false ; return expires > System . currentTimeMillis ( ) ; } | Returns whether the give nonce value is valid . A nonce is valid if and only if it was generated by this instance of the NonceService . Testing nonce validity through this function immediately and permanently invalidates that nonce . |
30,160 | public Map < String , String > retrieveParameters ( ModeledAuthenticatedUser user , String identifier ) { Map < String , String > parameterMap = new HashMap < String , String > ( ) ; boolean canRetrieveParameters ; try { canRetrieveParameters = hasObjectPermission ( user , identifier , ObjectPermission . Type . UPDATE ) ; } catch ( GuacamoleException e ) { return parameterMap ; } if ( canRetrieveParameters ) { for ( ConnectionParameterModel parameter : parameterMapper . select ( identifier ) ) parameterMap . put ( parameter . getName ( ) , parameter . getValue ( ) ) ; } return parameterMap ; } | Retrieves all parameters visible to the given user and associated with the connection having the given identifier . If the given user has no access to such parameters or no such connection exists the returned map will be empty . |
30,161 | protected List < ConnectionRecord > getObjectInstances ( List < ConnectionRecordModel > models ) { List < ConnectionRecord > objects = new ArrayList < ConnectionRecord > ( models . size ( ) ) ; for ( ConnectionRecordModel model : models ) objects . add ( getObjectInstance ( model ) ) ; return objects ; } | Returns a list of connection records objects which are backed by the models in the given list . |
30,162 | public List < ConnectionRecord > retrieveHistory ( ModeledAuthenticatedUser user , ModeledConnection connection ) throws GuacamoleException { String identifier = connection . getIdentifier ( ) ; if ( hasObjectPermission ( user , identifier , ObjectPermission . Type . READ ) ) { List < ConnectionRecordModel > models = connectionRecordMapper . select ( identifier ) ; List < ConnectionRecord > records = new ArrayList < ConnectionRecord > ( tunnelService . getActiveConnections ( connection ) ) ; Collections . reverse ( records ) ; for ( ConnectionRecordModel model : models ) records . add ( getObjectInstance ( model ) ) ; return records ; } throw new GuacamoleSecurityException ( "Permission denied." ) ; } | Retrieves the connection history of the given connection including any active connections . |
30,163 | public GuacamoleTunnel connect ( ModeledAuthenticatedUser user , ModeledConnection connection , GuacamoleClientInformation info , Map < String , String > tokens ) throws GuacamoleException { if ( hasObjectPermission ( user , connection . getIdentifier ( ) , ObjectPermission . Type . READ ) ) return tunnelService . getGuacamoleTunnel ( user , connection , info , tokens ) ; throw new GuacamoleSecurityException ( "Permission denied." ) ; } | Connects to the given connection as the given user using the given client information . If the user does not have permission to read the connection permission will be denied . |
30,164 | protected boolean canAlterPermissions ( ModeledAuthenticatedUser user , ModeledPermissions < ? extends EntityModel > targetEntity , Collection < ObjectPermission > permissions ) throws GuacamoleException { if ( user . getUser ( ) . isAdministrator ( ) ) return true ; ObjectPermissionSet permissionSet = getRelevantPermissionSet ( user . getUser ( ) , targetEntity ) ; if ( ! permissionSet . hasPermission ( ObjectPermission . Type . UPDATE , targetEntity . getIdentifier ( ) ) ) return false ; Collection < String > affectedIdentifiers = new HashSet < String > ( permissions . size ( ) ) ; for ( ObjectPermission permission : permissions ) affectedIdentifiers . add ( permission . getObjectIdentifier ( ) ) ; ObjectPermissionSet affectedPermissionSet = getPermissionSet ( user , user . getUser ( ) , user . getEffectiveUserGroups ( ) ) ; Collection < String > allowedSubset = affectedPermissionSet . getAccessibleObjects ( Collections . singleton ( ObjectPermission . Type . ADMINISTER ) , affectedIdentifiers ) ; return affectedIdentifiers . size ( ) == allowedSubset . size ( ) ; } | Determines whether the current user has permission to update the given target entity adding or removing the given permissions . Such permission depends on whether the current user is a system administrator whether they have explicit UPDATE permission on the target entity and whether they have explicit ADMINISTER permission on all affected objects . Permission inheritance via user groups is taken into account . |
30,165 | public List < String > getUsernameAttributes ( ) throws GuacamoleException { return environment . getProperty ( LDAPGuacamoleProperties . LDAP_USERNAME_ATTRIBUTE , Collections . singletonList ( "uid" ) ) ; } | Returns all username attributes which should be used to query and bind users using the LDAP directory . By default this will be uid - a common attribute used for this purpose . |
30,166 | public List < String > getGroupNameAttributes ( ) throws GuacamoleException { return environment . getProperty ( LDAPGuacamoleProperties . LDAP_GROUP_NAME_ATTRIBUTE , Collections . singletonList ( "cn" ) ) ; } | Returns all attributes which should be used to determine the unique identifier of each user group . By default this will be cn . |
30,167 | public LDAPSearchConstraints getLDAPSearchConstraints ( ) throws GuacamoleException { LDAPSearchConstraints constraints = new LDAPSearchConstraints ( ) ; constraints . setMaxResults ( getMaxResults ( ) ) ; constraints . setDereference ( getDereferenceAliases ( ) . DEREF_VALUE ) ; return constraints ; } | Returns a set of LDAPSearchConstraints to apply globally to all LDAP searches . |
30,168 | public List < String > getAttributes ( ) throws GuacamoleException { return environment . getProperty ( LDAPGuacamoleProperties . LDAP_USER_ATTRIBUTES , Collections . < String > emptyList ( ) ) ; } | Returns names for custom LDAP user attributes . |
30,169 | public void interceptStream ( int index , T stream ) throws GuacamoleException { InterceptedStream < T > interceptedStream ; String indexString = Integer . toString ( index ) ; synchronized ( tunnel ) { if ( ! tunnel . isOpen ( ) ) return ; interceptedStream = new InterceptedStream < T > ( indexString , stream ) ; streams . put ( interceptedStream ) ; } handleInterceptedStream ( interceptedStream ) ; streams . waitFor ( interceptedStream ) ; if ( interceptedStream . hasStreamError ( ) ) throw interceptedStream . getStreamError ( ) ; } | Intercept the stream having the given index producing or consuming its data as appropriate . The given stream object will automatically be closed when the stream ends . If there is no stream having the given index then the stream object will be closed immediately . This function will block until all data has been handled and the stream is ended . |
30,170 | public static DuoCookie parseDuoCookie ( String str ) throws GuacamoleException { String data ; try { data = new String ( BaseEncoding . base64 ( ) . decode ( str ) , "UTF-8" ) ; } catch ( IllegalArgumentException e ) { throw new GuacamoleClientException ( "Username is not correctly " + "encoded as base64." , e ) ; } catch ( UnsupportedEncodingException e ) { throw new UnsupportedOperationException ( "Unexpected lack of " + "UTF-8 support." , e ) ; } Matcher matcher = COOKIE_FORMAT . matcher ( data ) ; if ( ! matcher . matches ( ) ) throw new GuacamoleClientException ( "Format of base64-encoded " + "username is invalid." ) ; String username = matcher . group ( USERNAME_GROUP ) ; String key = matcher . group ( INTEGRATION_KEY_GROUP ) ; long expires ; try { expires = Long . parseLong ( matcher . group ( EXPIRATION_TIMESTAMP_GROUP ) ) ; } catch ( NumberFormatException e ) { throw new GuacamoleClientException ( "Expiration timestamp is " + "not valid." , e ) ; } return new DuoCookie ( username , key , expires ) ; } | Parses a base64 - encoded Duo cookie producing a new DuoCookie object containing the data therein . If the given string is not a valid Duo cookie an exception is thrown . Note that the cookie may be expired and must be checked for expiration prior to actual use . |
30,171 | public void init ( ModeledAuthenticatedUser currentUser , UserModel model , boolean exposeRestrictedAttributes ) { super . init ( currentUser , model ) ; this . exposeRestrictedAttributes = exposeRestrictedAttributes ; } | Initializes this ModeledUser associating it with the current authenticated user and populating it with data from the given user model . |
30,172 | private Calendar asCalendar ( Calendar base , Time time ) { Calendar timeCalendar = Calendar . getInstance ( ) ; timeCalendar . setTime ( time ) ; base . set ( Calendar . HOUR_OF_DAY , timeCalendar . get ( Calendar . HOUR_OF_DAY ) ) ; base . set ( Calendar . MINUTE , timeCalendar . get ( Calendar . MINUTE ) ) ; base . set ( Calendar . SECOND , timeCalendar . get ( Calendar . SECOND ) ) ; base . set ( Calendar . MILLISECOND , timeCalendar . get ( Calendar . MILLISECOND ) ) ; return base ; } | Converts a SQL Time to a Calendar independently of time zone using the given Calendar as a base . The time components will be copied to the given Calendar verbatim leaving the date and time zone components of the given Calendar otherwise intact . |
30,173 | private Calendar getAccessWindowStart ( ) { Time start = getModel ( ) . getAccessWindowStart ( ) ; if ( start == null ) return null ; return asCalendar ( Calendar . getInstance ( getTimeZone ( ) ) , start ) ; } | Returns the time during the current day when this user account can start being used . |
30,174 | private Calendar getAccessWindowEnd ( ) { Time end = getModel ( ) . getAccessWindowEnd ( ) ; if ( end == null ) return null ; return asCalendar ( Calendar . getInstance ( getTimeZone ( ) ) , end ) ; } | Returns the time during the current day when this user account can no longer be used . |
30,175 | private Calendar getValidFrom ( ) { Date validFrom = getModel ( ) . getValidFrom ( ) ; if ( validFrom == null ) return null ; Calendar validFromCalendar = Calendar . getInstance ( getTimeZone ( ) ) ; validFromCalendar . setTime ( validFrom ) ; validFromCalendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; validFromCalendar . set ( Calendar . MINUTE , 0 ) ; validFromCalendar . set ( Calendar . SECOND , 0 ) ; validFromCalendar . set ( Calendar . MILLISECOND , 0 ) ; return validFromCalendar ; } | Returns the date after which this account becomes valid . The time components of the resulting Calendar object will be set to midnight of the date in question . |
30,176 | private boolean isActive ( Calendar activeStart , Calendar inactiveStart ) { if ( inactiveStart != null && activeStart != null && inactiveStart . before ( activeStart ) ) return ! isActive ( inactiveStart , activeStart ) ; Calendar current = Calendar . getInstance ( ) ; return ! ( activeStart != null && current . before ( activeStart ) ) && ! ( inactiveStart != null && current . after ( inactiveStart ) ) ; } | Given a time when a particular state changes from inactive to active and a time when a particular state changes from active to inactive determines whether that state is currently active . |
30,177 | public int getMaxConnections ( ) throws GuacamoleException { Integer value = getModel ( ) . getMaxConnections ( ) ; if ( value == null ) return environment . getDefaultMaxGroupConnections ( ) ; return value ; } | Returns the maximum number of connections that should be allowed to this connection group overall . If no limit applies zero is returned . |
30,178 | public int getMaxConnectionsPerUser ( ) throws GuacamoleException { Integer value = getModel ( ) . getMaxConnectionsPerUser ( ) ; if ( value == null ) return environment . getDefaultMaxGroupConnectionsPerUser ( ) ; return value ; } | Returns the maximum number of connections that should be allowed to this connection group for any individual user . If no limit applies zero is returned . |
30,179 | public DecoratedUserContext getUserContext ( String authProviderIdentifier ) throws GuacamoleException { for ( DecoratedUserContext userContext : getUserContexts ( ) ) { AuthenticationProvider authProvider = userContext . getAuthenticationProvider ( ) ; if ( authProvider . getIdentifier ( ) . equals ( authProviderIdentifier ) ) return userContext ; } throw new GuacamoleResourceNotFoundException ( "Session not associated " + "with authentication provider \"" + authProviderIdentifier + "\"." ) ; } | Returns the UserContext associated with this session that originated from the AuthenticationProvider with the given identifier . If no such UserContext exists an exception is thrown . |
30,180 | public void invalidate ( ) { for ( GuacamoleTunnel tunnel : tunnels . values ( ) ) { try { tunnel . close ( ) ; } catch ( GuacamoleException e ) { logger . debug ( "Unable to close tunnel." , e ) ; } } for ( UserContext userContext : userContexts ) userContext . invalidate ( ) ; authenticatedUser . invalidate ( ) ; } | Closes all associated tunnels and prevents any further use of this session . |
30,181 | public static Integer parse ( String str ) throws NumberFormatException { if ( str == null || str . isEmpty ( ) ) return null ; return Integer . valueOf ( str ) ; } | Parses the given string as an integer where the given string is in the format required by a numeric field . |
30,182 | protected void sendError ( HttpServletResponse response , int guacamoleStatusCode , int guacamoleHttpCode , String message ) throws ServletException { try { if ( ! response . isCommitted ( ) ) { response . addHeader ( "Guacamole-Status-Code" , Integer . toString ( guacamoleStatusCode ) ) ; response . addHeader ( "Guacamole-Error-Message" , message ) ; response . sendError ( guacamoleHttpCode ) ; } } catch ( IOException ioe ) { throw new ServletException ( ioe ) ; } } | Sends an error on the given HTTP response using the information within the given GuacamoleStatus . |
30,183 | protected void handleTunnelRequest ( HttpServletRequest request , HttpServletResponse response ) throws ServletException { try { String query = request . getQueryString ( ) ; if ( query == null ) throw new GuacamoleClientException ( "No query string provided." ) ; if ( query . equals ( "connect" ) ) { GuacamoleTunnel tunnel = doConnect ( request ) ; if ( tunnel != null ) { registerTunnel ( tunnel ) ; try { response . setHeader ( "Cache-Control" , "no-cache" ) ; response . getWriter ( ) . print ( tunnel . getUUID ( ) . toString ( ) ) ; } catch ( IOException e ) { throw new GuacamoleServerException ( e ) ; } } else throw new GuacamoleResourceNotFoundException ( "No tunnel created." ) ; } else if ( query . startsWith ( READ_PREFIX ) ) doRead ( request , response , query . substring ( READ_PREFIX_LENGTH , READ_PREFIX_LENGTH + UUID_LENGTH ) ) ; else if ( query . startsWith ( WRITE_PREFIX ) ) doWrite ( request , response , query . substring ( WRITE_PREFIX_LENGTH , WRITE_PREFIX_LENGTH + UUID_LENGTH ) ) ; else throw new GuacamoleClientException ( "Invalid tunnel operation: " + query ) ; } catch ( GuacamoleClientException e ) { logger . warn ( "HTTP tunnel request rejected: {}" , e . getMessage ( ) ) ; sendError ( response , e . getStatus ( ) . getGuacamoleStatusCode ( ) , e . getStatus ( ) . getHttpStatusCode ( ) , e . getMessage ( ) ) ; } catch ( GuacamoleException e ) { logger . error ( "HTTP tunnel request failed: {}" , e . getMessage ( ) ) ; logger . debug ( "Internal error in HTTP tunnel." , e ) ; sendError ( response , e . getStatus ( ) . getGuacamoleStatusCode ( ) , e . getStatus ( ) . getHttpStatusCode ( ) , "Internal server error." ) ; } } | Dispatches every HTTP GET and POST request to the appropriate handler function based on the query string . |
30,184 | protected void doRead ( HttpServletRequest request , HttpServletResponse response , String tunnelUUID ) throws GuacamoleException { GuacamoleTunnel tunnel = getTunnel ( tunnelUUID ) ; if ( ! tunnel . isOpen ( ) ) throw new GuacamoleResourceNotFoundException ( "Tunnel is closed." ) ; GuacamoleReader reader = tunnel . acquireReader ( ) ; try { response . setContentType ( "application/octet-stream" ) ; response . setHeader ( "Cache-Control" , "no-cache" ) ; Writer out = new BufferedWriter ( new OutputStreamWriter ( response . getOutputStream ( ) , "UTF-8" ) ) ; try { char [ ] message = reader . read ( ) ; if ( message == null ) throw new GuacamoleConnectionClosedException ( "Tunnel reached end of stream." ) ; do { out . write ( message , 0 , message . length ) ; if ( ! reader . available ( ) ) { out . flush ( ) ; response . flushBuffer ( ) ; } if ( tunnel . hasQueuedReaderThreads ( ) ) break ; } while ( tunnel . isOpen ( ) && ( message = reader . read ( ) ) != null ) ; if ( message == null ) { deregisterTunnel ( tunnel ) ; tunnel . close ( ) ; } out . write ( "0.;" ) ; out . flush ( ) ; response . flushBuffer ( ) ; } catch ( GuacamoleConnectionClosedException e ) { deregisterTunnel ( tunnel ) ; tunnel . close ( ) ; out . write ( "0.;" ) ; out . flush ( ) ; response . flushBuffer ( ) ; } catch ( GuacamoleException e ) { deregisterTunnel ( tunnel ) ; tunnel . close ( ) ; throw e ; } finally { out . close ( ) ; } } catch ( IOException e ) { logger . debug ( "Error writing to servlet output stream" , e ) ; deregisterTunnel ( tunnel ) ; tunnel . close ( ) ; } finally { tunnel . releaseReader ( ) ; } } | Called whenever the JavaScript Guacamole client makes a read request . This function should in general not be overridden as it already contains a proper implementation of the read operation . |
30,185 | protected void doWrite ( HttpServletRequest request , HttpServletResponse response , String tunnelUUID ) throws GuacamoleException { GuacamoleTunnel tunnel = getTunnel ( tunnelUUID ) ; response . setContentType ( "application/octet-stream" ) ; response . setHeader ( "Cache-Control" , "no-cache" ) ; response . setContentLength ( 0 ) ; try { GuacamoleWriter writer = tunnel . acquireWriter ( ) ; Reader input = new InputStreamReader ( request . getInputStream ( ) , "UTF-8" ) ; try { int length ; char [ ] buffer = new char [ 8192 ] ; while ( tunnel . isOpen ( ) && ( length = input . read ( buffer , 0 , buffer . length ) ) != - 1 ) writer . write ( buffer , 0 , length ) ; } finally { input . close ( ) ; } } catch ( GuacamoleConnectionClosedException e ) { logger . debug ( "Connection to guacd closed." , e ) ; } catch ( IOException e ) { deregisterTunnel ( tunnel ) ; tunnel . close ( ) ; throw new GuacamoleServerException ( "I/O Error sending data to server: " + e . getMessage ( ) , e ) ; } finally { tunnel . releaseWriter ( ) ; } } | Called whenever the JavaScript Guacamole client makes a write request . This function should in general not be overridden as it already contains a proper implementation of the write operation . |
30,186 | public static String parse ( String str ) { if ( str == null || str . isEmpty ( ) ) return null ; return str ; } | Parses the given string interpreting empty strings as equivalent to null . For all other cases the given string is returned verbatim . |
30,187 | public void apply ( RelatedObjectSet objects ) throws GuacamoleException { if ( ! addedObjects . isEmpty ( ) ) objects . addObjects ( addedObjects ) ; if ( ! removedObjects . isEmpty ( ) ) objects . removeObjects ( removedObjects ) ; } | Applies all queued changes to the given RelatedObjectSet . |
30,188 | public void init ( AuthenticatedUser user , LDAPConnection ldapConnection ) throws GuacamoleException { userDirectory = new SimpleDirectory < > ( userService . getUsers ( ldapConnection ) ) ; userGroupDirectory = new SimpleDirectory < > ( userGroupService . getUserGroups ( ldapConnection ) ) ; connectionDirectory = new SimpleDirectory < > ( connectionService . getConnections ( user , ldapConnection ) ) ; rootGroup = new SimpleConnectionGroup ( LDAPAuthenticationProvider . ROOT_CONNECTION_GROUP , LDAPAuthenticationProvider . ROOT_CONNECTION_GROUP , connectionDirectory . getIdentifiers ( ) , Collections . < String > emptyList ( ) ) ; self = new SimpleUser ( user . getIdentifier ( ) ) { public ObjectPermissionSet getUserPermissions ( ) throws GuacamoleException { return new SimpleObjectPermissionSet ( userDirectory . getIdentifiers ( ) ) ; } public ObjectPermissionSet getUserGroupPermissions ( ) throws GuacamoleException { return new SimpleObjectPermissionSet ( userGroupDirectory . getIdentifiers ( ) ) ; } public ObjectPermissionSet getConnectionPermissions ( ) throws GuacamoleException { return new SimpleObjectPermissionSet ( connectionDirectory . getIdentifiers ( ) ) ; } public ObjectPermissionSet getConnectionGroupPermissions ( ) throws GuacamoleException { return new SimpleObjectPermissionSet ( Collections . singleton ( LDAPAuthenticationProvider . ROOT_CONNECTION_GROUP ) ) ; } } ; } | Initializes this UserContext using the provided AuthenticatedUser and LDAPConnection . |
30,189 | @ JsonProperty ( "keyUri" ) public URI getKeyURI ( ) throws GuacamoleException { if ( key == null ) return null ; String issuer = confService . getIssuer ( ) ; return UriBuilder . fromUri ( "otpauth://totp/" ) . path ( issuer + ":" + key . getUsername ( ) ) . queryParam ( "secret" , BASE32 . encode ( key . getSecret ( ) ) ) . queryParam ( "issuer" , issuer ) . queryParam ( "algorithm" , confService . getMode ( ) ) . queryParam ( "digits" , confService . getDigits ( ) ) . queryParam ( "period" , confService . getPeriod ( ) ) . build ( ) ; } | Returns the otpauth URI for the secret key used to generate TOTP codes for the current user . If the secret key is not being exposed to facilitate enrollment null is returned . |
30,190 | @ JsonProperty ( "qrCode" ) public String getQRCode ( ) throws GuacamoleException { URI keyURI = getKeyURI ( ) ; if ( keyURI == null ) return null ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; try { QRCodeWriter writer = new QRCodeWriter ( ) ; BitMatrix matrix = writer . encode ( keyURI . toString ( ) , BarcodeFormat . QR_CODE , QR_CODE_WIDTH , QR_CODE_HEIGHT ) ; MatrixToImageWriter . writeToStream ( matrix , "PNG" , stream ) ; } catch ( WriterException e ) { throw new IllegalArgumentException ( "QR code could not be " + "generated for TOTP key." , e ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Image stream of QR code could " + "not be written." , e ) ; } return "data:image/png;base64," + BaseEncoding . base64 ( ) . encode ( stream . toByteArray ( ) ) ; } | Returns the URL of a QR code describing the user s TOTP key and configuration . If the key is not being exposed for enrollment null is returned . |
30,191 | private void sendBlob ( String index , byte [ ] blob ) { sendInstruction ( new GuacamoleInstruction ( "blob" , index , BaseEncoding . base64 ( ) . encode ( blob ) ) ) ; } | Injects a blob instruction into the outbound Guacamole protocol stream as if sent by the connected client . blob instructions are used to send chunks of data along a stream . |
30,192 | private void readNextBlob ( InterceptedStream < InputStream > stream ) { try { byte [ ] blob = new byte [ 6048 ] ; int length = stream . getStream ( ) . read ( blob ) ; if ( length == - 1 ) { if ( closeInterceptedStream ( stream ) ) sendEnd ( stream . getIndex ( ) ) ; return ; } sendBlob ( stream . getIndex ( ) , Arrays . copyOf ( blob , length ) ) ; } catch ( IOException e ) { logger . debug ( "Unable to read data of intercepted input stream." , e ) ; if ( closeInterceptedStream ( stream ) ) sendEnd ( stream . getIndex ( ) ) ; } } | Reads the next chunk of data from the InputStream associated with an intercepted stream sending that data as a blob instruction over the GuacamoleTunnel associated with this filter . If the end of the InputStream is reached an end instruction will automatically be sent . |
30,193 | private void handleAck ( GuacamoleInstruction instruction ) { List < String > args = instruction . getArgs ( ) ; if ( args . size ( ) < 3 ) return ; String index = args . get ( 0 ) ; InterceptedStream < InputStream > stream = getInterceptedStream ( index ) ; if ( stream == null ) return ; String status = args . get ( 2 ) ; if ( ! status . equals ( "0" ) ) { int code ; try { code = Integer . parseInt ( status ) ; } catch ( NumberFormatException e ) { logger . debug ( "Translating invalid status code \"{}\" to SERVER_ERROR." , status ) ; code = GuacamoleStatus . SERVER_ERROR . getGuacamoleStatusCode ( ) ; } stream . setStreamError ( code , args . get ( 1 ) ) ; closeInterceptedStream ( stream ) ; return ; } readNextBlob ( stream ) ; } | Handles a single ack instruction sending yet more blobs or closing the stream depending on whether the ack indicates success or failure . If no InputStream is associated with the stream index within the ack instruction the instruction is ignored . |
30,194 | private GuacamoleInstruction expect ( GuacamoleReader reader , String opcode ) throws GuacamoleException { GuacamoleInstruction instruction = reader . readInstruction ( ) ; if ( instruction == null ) throw new GuacamoleServerException ( "End of stream while waiting for \"" + opcode + "\"." ) ; if ( ! instruction . getOpcode ( ) . equals ( opcode ) ) throw new GuacamoleServerException ( "Expected \"" + opcode + "\" instruction but instead received \"" + instruction . getOpcode ( ) + "\"." ) ; return instruction ; } | Waits for the instruction having the given opcode returning that instruction once it has been read . If the instruction is never read an exception is thrown . |
30,195 | @ Path ( "parameters" ) public Map < String , String > getConnectionParameters ( ) throws GuacamoleException { Permissions effective = userContext . self ( ) . getEffectivePermissions ( ) ; SystemPermissionSet systemPermissions = effective . getSystemPermissions ( ) ; ObjectPermissionSet connectionPermissions = effective . getConnectionPermissions ( ) ; String identifier = connection . getIdentifier ( ) ; if ( ! systemPermissions . hasPermission ( SystemPermission . Type . ADMINISTER ) && ! connectionPermissions . hasPermission ( ObjectPermission . Type . UPDATE , identifier ) ) throw new GuacamoleSecurityException ( "Permission to read connection parameters denied." ) ; GuacamoleConfiguration config = connection . getConfiguration ( ) ; return config . getParameters ( ) ; } | Retrieves the parameters associated with a single connection . |
30,196 | public String create ( GuacamoleConfiguration config ) throws GuacamoleException { String newConnectionId = Integer . toString ( getNextConnectionID ( ) ) ; String name = QCParser . getName ( config ) ; Connection connection = new SimpleConnection ( name , newConnectionId , config , true ) ; connection . setParentIdentifier ( QuickConnectUserContext . ROOT_IDENTIFIER ) ; add ( connection ) ; rootGroup . addConnectionIdentifier ( newConnectionId ) ; return newConnectionId ; } | Create a SimpleConnection object from a GuacamoleConfiguration obtain an identifier and place it on the tree returning the identifier value of the new connection . |
30,197 | @ Path ( "create" ) public Map < String , String > create ( @ FormParam ( "uri" ) String uri ) throws GuacamoleException { return Collections . singletonMap ( "identifier" , directory . create ( QCParser . getConfiguration ( uri ) ) ) ; } | Parse the URI read from the POST input add the connection to the directory and return a Map containing a single key identifier and the identifier of the new connection . |
30,198 | @ Path ( "self" ) public DirectoryObjectResource < User , APIUser > getSelfResource ( ) throws GuacamoleException { return userResourceFactory . create ( userContext , userContext . getUserDirectory ( ) , userContext . self ( ) ) ; } | Returns a new resource which represents the User whose access rights control the operations of the UserContext exposed by this UserContextResource . |
30,199 | @ Path ( "activeConnections" ) public DirectoryResource < ActiveConnection , APIActiveConnection > getActiveConnectionDirectoryResource ( ) throws GuacamoleException { return activeConnectionDirectoryResourceFactory . create ( userContext , userContext . getActiveConnectionDirectory ( ) ) ; } | Returns a new resource which represents the ActiveConnection Directory contained within the UserContext exposed by this UserContextResource . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.