idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
11,900 | public String getSymbolicLinkTarget ( String linkpath ) throws SftpStatusException , SshException { if ( version < 3 ) { throw new SftpStatusException ( SftpStatusException . SSH_FX_OP_UNSUPPORTED , "Symbolic links are not supported by the server SFTP version " + String . valueOf ( version ) ) ; } try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_READLINK ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( linkpath , CHARSET_ENCODING ) ; sendMessage ( msg ) ; SftpFile [ ] files = extractFiles ( getResponse ( requestId ) , null ) ; return files [ 0 ] . getAbsolutePath ( ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Get the target path of a symbolic link . | 230 | 9 |
11,901 | public String getAbsolutePath ( String path ) throws SftpStatusException , SshException { try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_REALPATH ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( path , CHARSET_ENCODING ) ; sendMessage ( msg ) ; SftpMessage bar = getResponse ( requestId ) ; if ( bar . getType ( ) == SSH_FXP_NAME ) { SftpFile [ ] files = extractFiles ( bar , null ) ; if ( files . length != 1 ) { close ( ) ; throw new SshException ( "Server responded to SSH_FXP_REALPATH with too many files!" , SshException . CHANNEL_FAILURE ) ; } return files [ 0 ] . getAbsolutePath ( ) ; } else if ( bar . getType ( ) == SSH_FXP_STATUS ) { int status = ( int ) bar . readInt ( ) ; if ( version >= 3 ) { String desc = bar . readString ( ) . trim ( ) ; throw new SftpStatusException ( status , desc ) ; } throw new SftpStatusException ( status ) ; } else { close ( ) ; throw new SshException ( "The server responded with an unexpected message" , SshException . CHANNEL_FAILURE ) ; } } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Get the absolute path of a file . | 360 | 8 |
11,902 | public void recurseMakeDirectory ( String path ) throws SftpStatusException , SshException { SftpFile file ; if ( path . trim ( ) . length ( ) > 0 ) { try { file = openDirectory ( path ) ; file . close ( ) ; } catch ( SshException ioe ) { int idx = 0 ; do { idx = path . indexOf ( ' ' , idx ) ; String tmp = ( idx > - 1 ? path . substring ( 0 , idx + 1 ) : path ) ; try { file = openDirectory ( tmp ) ; file . close ( ) ; } catch ( SshException ioe7 ) { makeDirectory ( tmp ) ; } } while ( idx > - 1 ) ; } } } | Recurse through a hierarchy of directories creating them as necessary . | 164 | 12 |
11,903 | public SftpFile openDirectory ( String path ) throws SftpStatusException , SshException { String absolutePath = getAbsolutePath ( path ) ; SftpFileAttributes attrs = getAttributes ( absolutePath ) ; if ( ! attrs . isDirectory ( ) ) { throw new SftpStatusException ( SftpStatusException . SSH_FX_FAILURE , path + " is not a directory" ) ; } try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_OPENDIR ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( path , CHARSET_ENCODING ) ; sendMessage ( msg ) ; byte [ ] handle = getHandleResponse ( requestId ) ; SftpFile file = new SftpFile ( absolutePath , attrs ) ; file . setHandle ( handle ) ; file . setSFTPSubsystem ( this ) ; return file ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Open a directory . | 262 | 4 |
11,904 | public void closeFile ( SftpFile file ) throws SftpStatusException , SshException { if ( file . getHandle ( ) != null ) { closeHandle ( file . getHandle ( ) ) ; EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_SFTP_FILE_CLOSED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FILE_NAME , file . getAbsolutePath ( ) ) ) ; file . setHandle ( null ) ; } } | Close a file or directory . | 127 | 6 |
11,905 | public void removeDirectory ( String path ) throws SftpStatusException , SshException { try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_RMDIR ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( path , CHARSET_ENCODING ) ; sendMessage ( msg ) ; getOKRequestStatus ( requestId ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_SFTP_DIRECTORY_DELETED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_DIRECTORY_PATH , path ) ) ; } | Remove an empty directory . | 211 | 5 |
11,906 | public void removeFile ( String filename ) throws SftpStatusException , SshException { try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_REMOVE ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( filename , CHARSET_ENCODING ) ; sendMessage ( msg ) ; getOKRequestStatus ( requestId ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_SFTP_FILE_DELETED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FILE_NAME , filename ) ) ; } | Remove a file . | 207 | 4 |
11,907 | public void renameFile ( String oldpath , String newpath ) throws SftpStatusException , SshException { if ( version < 2 ) { throw new SftpStatusException ( SftpStatusException . SSH_FX_OP_UNSUPPORTED , "Renaming files is not supported by the server SFTP version " + String . valueOf ( version ) ) ; } try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_RENAME ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( oldpath , CHARSET_ENCODING ) ; msg . writeString ( newpath , CHARSET_ENCODING ) ; sendMessage ( msg ) ; getOKRequestStatus ( requestId ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_SFTP_FILE_RENAMED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FILE_NAME , oldpath ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FILE_NEW_NAME , newpath ) ) ; } | Rename an existing file . | 315 | 6 |
11,908 | public SftpFileAttributes getAttributes ( SftpFile file ) throws SftpStatusException , SshException { try { if ( file . getHandle ( ) == null ) { return getAttributes ( file . getAbsolutePath ( ) ) ; } UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_FSTAT ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeBinaryString ( file . getHandle ( ) ) ; if ( version > 3 ) { msg . writeInt ( SftpFileAttributes . SSH_FILEXFER_ATTR_SIZE | SftpFileAttributes . SSH_FILEXFER_ATTR_PERMISSIONS | SftpFileAttributes . SSH_FILEXFER_ATTR_ACCESSTIME | SftpFileAttributes . SSH_FILEXFER_ATTR_CREATETIME | SftpFileAttributes . SSH_FILEXFER_ATTR_MODIFYTIME | SftpFileAttributes . SSH_FILEXFER_ATTR_ACL | SftpFileAttributes . SSH_FILEXFER_ATTR_OWNERGROUP | SftpFileAttributes . SSH_FILEXFER_ATTR_SUBSECOND_TIMES | SftpFileAttributes . SSH_FILEXFER_ATTR_EXTENDED ) ; } sendMessage ( msg ) ; return extractAttributes ( getResponse ( requestId ) ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Get the attributes of a file . | 366 | 7 |
11,909 | public void makeDirectory ( String path ) throws SftpStatusException , SshException { makeDirectory ( path , new SftpFileAttributes ( this , SftpFileAttributes . SSH_FILEXFER_TYPE_DIRECTORY ) ) ; } | Make a directory . If the directory exists this method will throw an exception . | 54 | 15 |
11,910 | public ServerAuthenticator startSession ( Socket s ) throws IOException { PushbackInputStream in = new PushbackInputStream ( s . getInputStream ( ) ) ; OutputStream out = s . getOutputStream ( ) ; int version = in . read ( ) ; if ( version == 5 ) { if ( ! selectSocks5Authentication ( in , out , 0 ) ) return null ; } else if ( version == 4 ) { //Else it is the request message allready, version 4 in . unread ( version ) ; } else return null ; return new ServerAuthenticatorNone ( in , out ) ; } | Grants access to everyone . Removes authentication related bytes from the stream when a SOCKS5 connection is being made selects an authentication NONE . | 130 | 30 |
11,911 | public void start ( ) throws IOException { remote_sock . setSoTimeout ( iddleTimeout ) ; client_sock . setSoTimeout ( iddleTimeout ) ; log ( "Starting UDP relay server on " + relayIP + ":" + relayPort ) ; log ( "Remote socket " + remote_sock . getLocalAddress ( ) + ":" + remote_sock . getLocalPort ( ) ) ; pipe_thread1 = new Thread ( this , "pipe1" ) ; pipe_thread2 = new Thread ( this , "pipe2" ) ; lastReadTime = System . currentTimeMillis ( ) ; pipe_thread1 . start ( ) ; pipe_thread2 . start ( ) ; } | Starts udp relay server . Spawns two threads of execution and returns . | 154 | 16 |
11,912 | public boolean startSubsystem ( String subsystem ) throws SshException { ByteArrayWriter request = new ByteArrayWriter ( ) ; try { request . writeString ( subsystem ) ; boolean success = sendRequest ( "subsystem" , true , request . toByteArray ( ) ) ; if ( success ) { EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_SUBSYSTEM_STARTED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_COMMAND , subsystem ) ) ; } else { EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_SUBSYSTEM_STARTED , false ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_COMMAND , subsystem ) ) ; } return success ; } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } finally { try { request . close ( ) ; } catch ( IOException e ) { } } } | SSH2 supports special subsystems that are identified by a name rather than a command string an example of an SSH2 subsystem is SFTP . | 251 | 29 |
11,913 | boolean requestX11Forwarding ( boolean singleconnection , String protocol , String cookie , int screen ) throws SshException { ByteArrayWriter request = new ByteArrayWriter ( ) ; try { request . writeBoolean ( singleconnection ) ; request . writeString ( protocol ) ; request . writeString ( cookie ) ; request . writeInt ( screen ) ; return sendRequest ( "x11-req" , true , request . toByteArray ( ) ) ; } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } finally { try { request . close ( ) ; } catch ( IOException e ) { } } } | Send a request for X Forwarding . | 145 | 8 |
11,914 | public boolean setEnvironmentVariable ( String name , String value ) throws SshException { ByteArrayWriter request = new ByteArrayWriter ( ) ; try { request . writeString ( name ) ; request . writeString ( value ) ; return sendRequest ( "env" , true , request . toByteArray ( ) ) ; } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } finally { try { request . close ( ) ; } catch ( IOException e ) { } } } | The SSH2 session supports the setting of environments variables however in our experiance no server to date allows unconditional setting of variables . This method should be called before the command is started . | 115 | 36 |
11,915 | protected void channelRequest ( String requesttype , boolean wantreply , byte [ ] requestdata ) throws SshException { try { if ( requesttype . equals ( "exit-status" ) ) { if ( requestdata != null ) { exitcode = ( int ) ByteArrayReader . readInt ( requestdata , 0 ) ; } } if ( requesttype . equals ( "exit-signal" ) ) { if ( requestdata != null ) { ByteArrayReader bar = new ByteArrayReader ( requestdata , 0 , requestdata . length ) ; try { exitsignalinfo = "Signal=" + bar . readString ( ) + " CoreDump=" + String . valueOf ( bar . read ( ) != 0 ) + " Message=" + bar . readString ( ) ; } finally { try { bar . close ( ) ; } catch ( IOException e ) { } } } } if ( requesttype . equals ( "xon-xoff" ) ) { flowControlEnabled = ( requestdata != null && requestdata [ 0 ] != 0 ) ; } super . channelRequest ( requesttype , wantreply , requestdata ) ; } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } } | This overidden method handles the exit - status exit - signal and xon - xoff channel requests . | 268 | 21 |
11,916 | public void startLocalForwarding ( String addressToBind , int portToBind , String hostToConnect , int portToConnect ) throws SshException { String key = generateKey ( addressToBind , portToBind ) ; SocketListener listener = new SocketListener ( addressToBind , portToBind , hostToConnect , portToConnect ) ; listener . start ( ) ; socketlisteners . put ( key , listener ) ; if ( ! outgoingtunnels . containsKey ( key ) ) { outgoingtunnels . put ( key , new Vector < ActiveTunnel > ( ) ) ; } for ( int i = 0 ; i < clientlisteners . size ( ) ; i ++ ) { ( ( ForwardingClientListener ) clientlisteners . elementAt ( i ) ) . forwardingStarted ( ForwardingClientListener . LOCAL_FORWARDING , key , hostToConnect , portToConnect ) ; } EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_FORWARDING_LOCAL_STARTED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FORWARDING_TUNNEL_ENTRANCE , key ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FORWARDING_TUNNEL_EXIT , hostToConnect + ":" + portToConnect ) ) ; } | Start s a local listening socket and forwards any connections made to the to the remote side . | 309 | 18 |
11,917 | public String [ ] getRemoteForwardings ( ) { String [ ] r = new String [ remoteforwardings . size ( ) - ( remoteforwardings . containsKey ( X11_KEY ) ? 1 : 0 ) ] ; int index = 0 ; for ( Enumeration < String > e = remoteforwardings . keys ( ) ; e . hasMoreElements ( ) ; ) { String key = e . nextElement ( ) ; if ( ! key . equals ( X11_KEY ) ) r [ index ++ ] = key ; } return r ; } | Returns the currently active remote forwarding listeners . | 126 | 8 |
11,918 | public String [ ] getLocalForwardings ( ) { String [ ] r = new String [ socketlisteners . size ( ) ] ; int index = 0 ; for ( Enumeration < String > e = socketlisteners . keys ( ) ; e . hasMoreElements ( ) ; ) { r [ index ++ ] = e . nextElement ( ) ; } return r ; } | Return the currently active local forwarding listeners . | 80 | 8 |
11,919 | public ActiveTunnel [ ] getRemoteForwardingTunnels ( ) throws IOException { Vector < ActiveTunnel > v = new Vector < ActiveTunnel > ( ) ; String [ ] remoteForwardings = getRemoteForwardings ( ) ; for ( int i = 0 ; i < remoteForwardings . length ; i ++ ) { ActiveTunnel [ ] tmp = getRemoteForwardingTunnels ( remoteForwardings [ i ] ) ; for ( int x = 0 ; x < tmp . length ; x ++ ) { v . add ( tmp [ x ] ) ; } } return ( ActiveTunnel [ ] ) v . toArray ( new ActiveTunnel [ v . size ( ) ] ) ; } | Get all the active remote forwarding tunnels | 155 | 7 |
11,920 | public ActiveTunnel [ ] getLocalForwardingTunnels ( ) throws IOException { Vector < ActiveTunnel > v = new Vector < ActiveTunnel > ( ) ; String [ ] localForwardings = getLocalForwardings ( ) ; for ( int i = 0 ; i < localForwardings . length ; i ++ ) { ActiveTunnel [ ] tmp = getLocalForwardingTunnels ( localForwardings [ i ] ) ; for ( int x = 0 ; x < tmp . length ; x ++ ) { v . add ( tmp [ x ] ) ; } } return ( ActiveTunnel [ ] ) v . toArray ( new ActiveTunnel [ v . size ( ) ] ) ; } | Get all the active local forwarding tunnels | 155 | 7 |
11,921 | public ActiveTunnel [ ] getX11ForwardingTunnels ( ) throws IOException { if ( incomingtunnels . containsKey ( X11_KEY ) ) { Vector < ActiveTunnel > v = incomingtunnels . get ( X11_KEY ) ; ActiveTunnel [ ] t = new ActiveTunnel [ v . size ( ) ] ; v . copyInto ( t ) ; return t ; } return new ActiveTunnel [ ] { } ; } | Get the active X11 forwarding channels . | 104 | 8 |
11,922 | public boolean requestRemoteForwarding ( String addressToBind , int portToBind , String hostToConnect , int portToConnect ) throws SshException { if ( ssh . requestRemoteForwarding ( addressToBind , portToBind , hostToConnect , portToConnect , forwardinglistener ) ) { String key = generateKey ( addressToBind , portToBind ) ; if ( ! incomingtunnels . containsKey ( key ) ) { incomingtunnels . put ( key , new Vector < ActiveTunnel > ( ) ) ; } remoteforwardings . put ( key , hostToConnect + ":" + portToConnect ) ; for ( int i = 0 ; i < clientlisteners . size ( ) ; i ++ ) { ( ( ForwardingClientListener ) clientlisteners . elementAt ( i ) ) . forwardingStarted ( ForwardingClientListener . REMOTE_FORWARDING , key , hostToConnect , portToConnect ) ; } return true ; } return false ; } | Requests that the remote side start listening for socket connections so that they may be forwarded to to the local destination . | 211 | 23 |
11,923 | public void cancelRemoteForwarding ( String bindAddress , int bindPort , boolean killActiveTunnels ) throws SshException { String key = generateKey ( bindAddress , bindPort ) ; boolean killedTunnels = false ; if ( killActiveTunnels ) { try { ActiveTunnel [ ] tunnels = getRemoteForwardingTunnels ( bindAddress , bindPort ) ; if ( tunnels != null ) { for ( int i = 0 ; i < tunnels . length ; i ++ ) { killedTunnels = true ; tunnels [ i ] . stop ( ) ; } } } catch ( IOException ex ) { } incomingtunnels . remove ( key ) ; } if ( ! remoteforwardings . containsKey ( key ) ) { if ( killActiveTunnels && killedTunnels ) { return ; } throw new SshException ( "Remote forwarding has not been started on " + key , SshException . FORWARDING_ERROR ) ; } // Check to see whether this is local or remote if ( ssh == null ) return ; ssh . cancelRemoteForwarding ( bindAddress , bindPort ) ; String destination = ( String ) remoteforwardings . get ( key ) ; int idx = destination . indexOf ( ":" ) ; String hostToConnect ; int portToConnect ; if ( idx == - 1 ) { throw new SshException ( "Invalid port reference in remote forwarding key!" , SshException . INTERNAL_ERROR ) ; } hostToConnect = destination . substring ( 0 , idx ) ; portToConnect = Integer . parseInt ( destination . substring ( idx + 1 ) ) ; for ( int i = 0 ; i < clientlisteners . size ( ) ; i ++ ) { if ( clientlisteners . elementAt ( i ) != null ) { ( ( ForwardingClientListener ) clientlisteners . elementAt ( i ) ) . forwardingStopped ( ForwardingClientListener . REMOTE_FORWARDING , key , hostToConnect , portToConnect ) ; } } remoteforwardings . remove ( key ) ; } | Requests that the remote side stop listening for socket connections . Please note that this feature is not available on SSH1 connections . The only way to stop the server from listening is to disconnect the connection . | 449 | 40 |
11,924 | public synchronized void cancelAllRemoteForwarding ( boolean killActiveTunnels ) throws SshException { if ( remoteforwardings == null ) { return ; } for ( Enumeration < String > e = remoteforwardings . keys ( ) ; e . hasMoreElements ( ) ; ) { String host = ( String ) e . nextElement ( ) ; if ( host == null ) return ; try { int idx = host . indexOf ( ' ' ) ; int port = - 1 ; if ( idx == - 1 ) { port = Integer . parseInt ( host ) ; host = "" ; } else { port = Integer . parseInt ( host . substring ( idx + 1 ) ) ; host = host . substring ( 0 , idx ) ; } cancelRemoteForwarding ( host , port , killActiveTunnels ) ; } catch ( NumberFormatException nfe ) { } } } | Stop all remote forwarding . | 198 | 5 |
11,925 | public synchronized void stopAllLocalForwarding ( boolean killActiveTunnels ) throws SshException { for ( Enumeration < String > e = socketlisteners . keys ( ) ; e . hasMoreElements ( ) ; ) { stopLocalForwarding ( ( String ) e . nextElement ( ) , killActiveTunnels ) ; } } | Stop all local forwarding | 74 | 4 |
11,926 | public synchronized void stopLocalForwarding ( String bindAddress , int bindPort , boolean killActiveTunnels ) throws SshException { String key = generateKey ( bindAddress , bindPort ) ; stopLocalForwarding ( key , killActiveTunnels ) ; } | Stops a local listening socket from accepting connections . | 56 | 10 |
11,927 | public synchronized void stopLocalForwarding ( String key , boolean killActiveTunnels ) throws SshException { if ( key == null ) return ; boolean killedTunnels = false ; if ( killActiveTunnels ) { try { ActiveTunnel [ ] tunnels = getLocalForwardingTunnels ( key ) ; if ( tunnels != null ) { for ( int i = 0 ; i < tunnels . length ; i ++ ) { tunnels [ i ] . stop ( ) ; killedTunnels = true ; } } } catch ( IOException ex ) { } outgoingtunnels . remove ( key ) ; } if ( ! socketlisteners . containsKey ( key ) ) { if ( killActiveTunnels && killedTunnels ) { return ; } throw new SshException ( "Local forwarding has not been started for " + key , SshException . FORWARDING_ERROR ) ; } // Stop the ServerSocket SocketListener listener = ( SocketListener ) socketlisteners . get ( key ) ; listener . stop ( ) ; // Remove the listener socketlisteners . remove ( key ) ; for ( int i = 0 ; i < clientlisteners . size ( ) ; i ++ ) { if ( clientlisteners . elementAt ( i ) != null ) { ( ( ForwardingClientListener ) clientlisteners . elementAt ( i ) ) . forwardingStopped ( ForwardingClientListener . LOCAL_FORWARDING , key , listener . hostToConnect , listener . portToConnect ) ; } } EventServiceImplementation . getInstance ( ) . fireEvent ( ( new Event ( this , J2SSHEventCodes . EVENT_FORWARDING_LOCAL_STOPPED , true ) ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FORWARDING_TUNNEL_ENTRANCE , key ) . addAttribute ( J2SSHEventCodes . ATTRIBUTE_FORWARDING_TUNNEL_EXIT , listener . hostToConnect + ":" + listener . portToConnect ) ) ; } | Stop a local listening socket from accepting connections . | 442 | 9 |
11,928 | public boolean verifySignature ( byte [ ] signature , byte [ ] data ) throws SshException { ByteArrayReader bar = new ByteArrayReader ( signature ) ; try { if ( signature . length != 40 // 160 bits && signature . length != 56 // 224 bits && signature . length != 64 ) { // 256 bits byte [ ] sig = bar . readBinaryString ( ) ; // log.debug("Signature blob is " + new String(sig)); String header = new String ( sig ) ; if ( ! header . equals ( "ssh-dss" ) ) { throw new SshException ( "The encoded signature is not DSA" , SshException . INTERNAL_ERROR ) ; } signature = bar . readBinaryString ( ) ; } int numSize = signature . length / 2 ; // Using a SimpleASNWriter ByteArrayOutputStream r = new ByteArrayOutputStream ( ) ; ByteArrayOutputStream s = new ByteArrayOutputStream ( ) ; SimpleASNWriter asn = new SimpleASNWriter ( ) ; asn . writeByte ( 0x02 ) ; if ( ( ( signature [ 0 ] & 0x80 ) == 0x80 ) && ( signature [ 0 ] != 0x00 ) ) { r . write ( 0 ) ; r . write ( signature , 0 , numSize ) ; } else { r . write ( signature , 0 , numSize ) ; } asn . writeData ( r . toByteArray ( ) ) ; asn . writeByte ( 0x02 ) ; if ( ( ( signature [ numSize ] & 0x80 ) == 0x80 ) && ( signature [ numSize ] != 0x00 ) ) { s . write ( 0 ) ; s . write ( signature , numSize , numSize ) ; } else { s . write ( signature , numSize , numSize ) ; } asn . writeData ( s . toByteArray ( ) ) ; SimpleASNWriter asnEncoded = new SimpleASNWriter ( ) ; asnEncoded . writeByte ( 0x30 ) ; asnEncoded . writeData ( asn . toByteArray ( ) ) ; byte [ ] encoded = asnEncoded . toByteArray ( ) ; Signature sig = JCEProvider . getProviderForAlgorithm ( JCEAlgorithms . JCE_SHA1WithDSA ) == null ? Signature . getInstance ( JCEAlgorithms . JCE_SHA1WithDSA ) : Signature . getInstance ( JCEAlgorithms . JCE_SHA1WithDSA , JCEProvider . getProviderForAlgorithm ( JCEAlgorithms . JCE_SHA1WithDSA ) ) ; sig . initVerify ( pubkey ) ; sig . update ( data ) ; return sig . verify ( encoded ) ; } catch ( Exception ex ) { throw new SshException ( SshException . JCE_ERROR , ex ) ; } finally { try { bar . close ( ) ; } catch ( IOException e ) { } } } | Verify the signature . | 645 | 5 |
11,929 | public static ComponentManager getInstance ( ) throws SshException { synchronized ( ComponentManager . class ) { if ( instance == null ) { instance = new JCEComponentManager ( ) ; instance . init ( ) ; } return instance ; } } | Get the installed component manager . Don t want to initialize this at class load time so use a singleton instead . Initialized on the first call to getInstance . | 51 | 33 |
11,930 | public void authenticate ( AuthenticationProtocol authentication , String servicename ) throws SshException , AuthenticationResult { try { if ( getUsername ( ) == null || getPassword ( ) == null ) { throw new SshException ( "Username or password not set!" , SshException . BAD_API_USAGE ) ; } if ( passwordChangeRequired && newpassword == null ) { throw new SshException ( "You must set a new password!" , SshException . BAD_API_USAGE ) ; } ByteArrayWriter msg = new ByteArrayWriter ( ) ; try { msg . writeBoolean ( passwordChangeRequired ) ; msg . writeString ( getPassword ( ) ) ; if ( passwordChangeRequired ) { msg . writeString ( newpassword ) ; } authentication . sendRequest ( getUsername ( ) , servicename , "password" , msg . toByteArray ( ) ) ; } finally { try { msg . close ( ) ; } catch ( IOException e ) { } } // We need to read the response since we may have password change. byte [ ] response = authentication . readMessage ( ) ; if ( response [ 0 ] != SSH_MSG_USERAUTH_PASSWD_CHANGEREQ ) { authentication . transport . disconnect ( TransportProtocol . PROTOCOL_ERROR , "Unexpected message received" ) ; throw new SshException ( "Unexpected response from Authentication Protocol" , SshException . PROTOCOL_VIOLATION ) ; } passwordChangeRequired = true ; throw new AuthenticationResult ( SshAuthentication . FAILED ) ; } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } } | Implementation of the authentication method . | 365 | 7 |
11,931 | public void put ( String localFileRegExp , String remoteFile , boolean recursive , FileTransferProgress progress ) throws SshException , ChannelOpenException { GlobRegExpMatching globMatcher = new GlobRegExpMatching ( ) ; String parentDir ; int fileSeparatorIndex ; parentDir = cwd . getAbsolutePath ( ) ; String relativePath = "" ; if ( ( fileSeparatorIndex = localFileRegExp . lastIndexOf ( System . getProperty ( "file.separator" ) ) ) > - 1 || ( fileSeparatorIndex = localFileRegExp . lastIndexOf ( ' ' ) ) > - 1 ) { relativePath = localFileRegExp . substring ( 0 , fileSeparatorIndex + 1 ) ; File rel = new File ( relativePath ) ; if ( rel . isAbsolute ( ) ) { parentDir = relativePath ; } else { parentDir += System . getProperty ( "file.separator" ) + relativePath ; } } File f = new File ( parentDir ) ; // this is 1.2 so do it the long way // f.listFiles(); String [ ] fileListingStrings = f . list ( ) ; File [ ] fileListing = new File [ fileListingStrings . length ] ; for ( int i = 0 ; i < fileListingStrings . length ; i ++ ) { fileListing [ i ] = new File ( parentDir + File . separator + fileListingStrings [ i ] ) ; } String [ ] matchedFiles = globMatcher . matchFileNamesWithPattern ( fileListing , localFileRegExp . substring ( fileSeparatorIndex + 1 ) ) ; if ( matchedFiles . length == 0 ) { throw new SshException ( localFileRegExp + "No file matches/File does not exist" , SshException . CHANNEL_FAILURE ) ; } /* * if(!relativePath.equals("")) for(int i=0;i<matchedFiles.length;i++) * matchedFiles[i] = relativePath + matchedFiles[i]; */ if ( matchedFiles . length > 1 ) { put ( matchedFiles , remoteFile , recursive , progress ) ; } else { putFile ( matchedFiles [ 0 ] , remoteFile , recursive , progress , false ) ; } } | pattern matches the files in the local directory using local as a glob Regular Expression . For the matching file array put is called to copy the file to the remote directory . | 500 | 33 |
11,932 | protected void open ( int remoteid , long remotewindow , int remotepacket ) throws IOException { this . remoteid = remoteid ; this . remotewindow = new DataWindow ( remotewindow , remotepacket ) ; this . state = CHANNEL_OPEN ; synchronized ( listeners ) { for ( Enumeration < ChannelEventListener > e = listeners . elements ( ) ; e . hasMoreElements ( ) ; ) { ( e . nextElement ( ) ) . channelOpened ( this ) ; } } } | Called once an SSH_MSG_CHANNEL_OPEN_CONFIRMATION has been sent . | 121 | 24 |
11,933 | protected void open ( int remoteid , long remotewindow , int remotepacket , byte [ ] responsedata ) throws IOException { open ( remoteid , remotewindow , remotepacket ) ; } | Once a SSH_MSG_CHANNEL_OPEN_CONFIRMATION message is received the framework calls this method to complete the channel open operation . | 50 | 33 |
11,934 | public void close ( ) { boolean performClose = false ; ; synchronized ( this ) { if ( ! closing && state == CHANNEL_OPEN ) { performClose = closing = true ; } } if ( performClose ) { synchronized ( listeners ) { for ( Enumeration < ChannelEventListener > e = listeners . elements ( ) ; e . hasMoreElements ( ) ; ) { ( e . nextElement ( ) ) . channelClosing ( this ) ; } } try { // Close the ChannelOutputStream out . close ( ! isLocalEOF ) ; // Send our close message ByteArrayWriter msg = new ByteArrayWriter ( 5 ) ; msg . write ( SSH_MSG_CHANNEL_CLOSE ) ; msg . writeInt ( remoteid ) ; try { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Sending SSH_MSG_CHANNEL_CLOSE id=" + channelid + " rid=" + remoteid ) ; } connection . sendMessage ( msg . toByteArray ( ) , true ) ; } catch ( SshException ex1 ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Exception attempting to send SSH_MSG_CHANNEL_CLOSE id=" + channelid + " rid=" + remoteid , ex1 ) ; } } finally { msg . close ( ) ; } this . state = CHANNEL_CLOSED ; } catch ( EOFException eof ) { // Ignore this is the message store informing of close/eof } catch ( SshIOException ex ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "SSH Exception during close reason=" + ex . getRealException ( ) . getReason ( ) + " id=" + channelid + " rid=" + remoteid , ex . getRealException ( ) ) ; } // IO Error during close so the connection has dropped connection . transport . disconnect ( TransportProtocol . CONNECTION_LOST , "IOException during channel close: " + ex . getMessage ( ) ) ; } catch ( IOException ex ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Exception during close id=" + channelid + " rid=" + remoteid , ex ) ; } // IO Error during close so the connection has dropped connection . transport . disconnect ( TransportProtocol . CONNECTION_LOST , "IOException during channel close: " + ex . getMessage ( ) ) ; } finally { checkCloseStatus ( ms . isClosed ( ) ) ; } } } | Closes the channel . No data may be sent or receieved after this method completes . | 555 | 18 |
11,935 | protected void channelRequest ( String requesttype , boolean wantreply , byte [ ] requestdata ) throws SshException { if ( wantreply ) { ByteArrayWriter msg = new ByteArrayWriter ( ) ; try { msg . write ( ( byte ) SSH_MSG_CHANNEL_FAILURE ) ; msg . writeInt ( remoteid ) ; connection . sendMessage ( msg . toByteArray ( ) , true ) ; } catch ( IOException e ) { throw new SshException ( e , SshException . INTERNAL_ERROR ) ; } finally { try { msg . close ( ) ; } catch ( IOException e ) { } } } } | Called when a channel request is received by default this method sends a failure message if the remote side requests a reply . Overidden methods should ALWAYS call this superclass method . | 140 | 35 |
11,936 | public void setPreferredCipherCS ( String name ) throws SshException { if ( name == null ) return ; if ( ciphersCS . contains ( name ) ) { prefCipherCS = name ; setCipherPreferredPositionCS ( name , 0 ) ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred cipher for the Client - > Server stream . | 93 | 12 |
11,937 | public void setPreferredCipherSC ( String name ) throws SshException { if ( name == null ) return ; if ( ciphersSC . contains ( name ) ) { prefCipherSC = name ; setCipherPreferredPositionSC ( name , 0 ) ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred cipher for the Server - > Client stream . | 93 | 12 |
11,938 | public void setPreferredMacCS ( String name ) throws SshException { if ( name == null ) return ; if ( macCS . contains ( name ) ) { prefMacCS = name ; setMacPreferredPositionCS ( name , 0 ) ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred mac for the Client - > Server stream . | 88 | 12 |
11,939 | public void setPreferredMacSC ( String name ) throws SshException { if ( name == null ) return ; if ( macSC . contains ( name ) ) { prefMacSC = name ; setMacPreferredPositionSC ( name , 0 ) ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred mac for the Server - > Client stream . | 88 | 12 |
11,940 | public void setPreferredCompressionCS ( String name ) throws SshException { if ( name == null ) return ; if ( compressionsCS . contains ( name ) ) { prefCompressionCS = name ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred compression for the Client - > Server stream . | 79 | 12 |
11,941 | public void setPreferredCompressionSC ( String name ) throws SshException { if ( name == null ) return ; if ( compressionsSC . contains ( name ) ) { prefCompressionSC = name ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred compression for the Server - > Client stream . | 79 | 12 |
11,942 | public void setPreferredKeyExchange ( String name ) throws SshException { if ( name == null ) return ; if ( keyExchanges . contains ( name ) ) { prefKeyExchange = name ; setKeyExchangePreferredPosition ( name , 0 ) ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred key exchange method . | 92 | 7 |
11,943 | public void setPreferredPublicKey ( String name ) throws SshException { if ( name == null ) return ; if ( publicKeys . contains ( name ) ) { prefPublicKey = name ; setPublicKeyPreferredPosition ( name , 0 ) ; } else { throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } } | Set the preferred public key algorithm . | 88 | 7 |
11,944 | public void close ( ) throws IOException { try { file . close ( ) ; UnsignedInteger32 requestid ; while ( outstandingRequests . size ( ) > 0 ) { requestid = ( UnsignedInteger32 ) outstandingRequests . elementAt ( 0 ) ; outstandingRequests . removeElementAt ( 0 ) ; sftp . getResponse ( requestid ) ; } } catch ( SshException ex ) { throw new SshIOException ( ex ) ; } catch ( SftpStatusException ex ) { throw new IOException ( ex . getMessage ( ) ) ; } } | Closes the SFTP file handle . | 124 | 8 |
11,945 | public static void debug ( Object source , String message , Throwable t ) { LoggerFactory . getInstance ( ) . log ( LoggerLevel . DEBUG , source , message , t ) ; } | An error log event | 41 | 4 |
11,946 | public static void debug ( Object source , String message ) { LoggerFactory . getInstance ( ) . log ( LoggerLevel . INFO , source , message ) ; } | A debug event | 35 | 3 |
11,947 | public static void error ( Object source , String message , Throwable t ) { LoggerFactory . getInstance ( ) . log ( LoggerLevel . ERROR , source , message , t ) ; } | An exception event | 41 | 3 |
11,948 | private void formRequest ( ) { byte [ ] user_bytes = userName . getBytes ( ) ; byte [ ] password_bytes = password . getBytes ( ) ; request = new byte [ 3 + user_bytes . length + password_bytes . length ] ; request [ 0 ] = ( byte ) 1 ; request [ 1 ] = ( byte ) user_bytes . length ; System . arraycopy ( user_bytes , 0 , request , 2 , user_bytes . length ) ; request [ 2 + user_bytes . length ] = ( byte ) password_bytes . length ; System . arraycopy ( password_bytes , 0 , request , 3 + user_bytes . length , password_bytes . length ) ; } | Convert UserName password in to binary form ready to be send to server | 151 | 15 |
11,949 | public void startTransportProtocol ( SshTransport provider , Ssh2Context context , String localIdentification , String remoteIdentification , Ssh2Client client ) throws SshException { try { this . transportIn = new DataInputStream ( provider . getInputStream ( ) ) ; this . transportOut = provider . getOutputStream ( ) ; this . provider = provider ; this . localIdentification = localIdentification ; this . remoteIdentification = remoteIdentification ; this . transportContext = context ; this . incomingMessage = new byte [ transportContext . getMaximumPacketLength ( ) ] ; this . outgoingMessage = new ByteArrayWriter ( transportContext . getMaximumPacketLength ( ) ) ; this . client = client ; // Negotiate the protocol version currentState = TransportProtocol . NEGOTIATING_PROTOCOL ; // Perform key exchange sendKeyExchangeInit ( false ) ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Waiting for transport protocol to complete initialization" ) ; } while ( processMessage ( readMessage ( ) ) && currentState != CONNECTED ) { ; } } catch ( IOException ex ) { throw new SshException ( ex , SshException . CONNECT_FAILED ) ; } if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Transport protocol initialized" ) ; } } | Starts the protocol on the provider . | 301 | 8 |
11,950 | public void disconnect ( int reason , String disconnectReason ) { ByteArrayWriter baw = new ByteArrayWriter ( ) ; try { this . disconnectReason = disconnectReason ; baw . write ( SSH_MSG_DISCONNECT ) ; baw . writeInt ( reason ) ; baw . writeString ( disconnectReason ) ; baw . writeString ( "" ) ; Log . info ( this , "Sending SSH_MSG_DISCONNECT [" + disconnectReason + "]" ) ; sendMessage ( baw . toByteArray ( ) , true ) ; } catch ( Throwable t ) { } finally { try { baw . close ( ) ; } catch ( IOException e ) { } internalDisconnect ( ) ; } } | Disconnect from the remote host . No more messages can be sent after this method has been called . | 156 | 20 |
11,951 | public byte [ ] nextMessage ( ) throws SshException { if ( Log . isDebugEnabled ( ) ) { if ( verbose ) { Log . debug ( this , "transport next message" ) ; } } synchronized ( transportIn ) { byte [ ] msg ; do { msg = readMessage ( ) ; } while ( processMessage ( msg ) ) ; return msg ; } } | Get the next message . The message returned will be the full message data so skipping the first 5 bytes is required before the message data can be read . | 81 | 30 |
11,952 | public void startService ( String servicename ) throws SshException { ByteArrayWriter baw = new ByteArrayWriter ( ) ; try { baw . write ( SSH_MSG_SERVICE_REQUEST ) ; baw . writeString ( servicename ) ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Sending SSH_MSG_SERVICE_REQUEST" ) ; } sendMessage ( baw . toByteArray ( ) , true ) ; byte [ ] msg ; do { msg = readMessage ( ) ; } while ( processMessage ( msg ) || msg [ 0 ] != SSH_MSG_SERVICE_ACCEPT ) ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Received SSH_MSG_SERVICE_ACCEPT" ) ; } } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } finally { try { baw . close ( ) ; } catch ( IOException e ) { } } } | Request that the remote server starts a transport protocol service . This is only available in CLIENT_MODE . | 229 | 20 |
11,953 | public boolean processMessage ( byte [ ] msg ) throws SshException { try { if ( msg . length < 1 ) { disconnect ( TransportProtocol . PROTOCOL_ERROR , "Invalid message received" ) ; throw new SshException ( "Invalid transport protocol message" , SshException . INTERNAL_ERROR ) ; } switch ( msg [ 0 ] ) { case SSH_MSG_DISCONNECT : { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Received SSH_MSG_DISCONNECT" ) ; } internalDisconnect ( ) ; ByteArrayReader bar = new ByteArrayReader ( msg , 5 , msg . length - 5 ) ; try { EventServiceImplementation . getInstance ( ) . fireEvent ( new Event ( this , J2SSHEventCodes . EVENT_RECEIVED_DISCONNECT , true ) ) ; throw new SshException ( bar . readString ( ) , SshException . REMOTE_HOST_DISCONNECTED ) ; } finally { bar . close ( ) ; } } case SSH_MSG_IGNORE : { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Received SSH_MSG_IGNORE" ) ; } return true ; } case SSH_MSG_DEBUG : { lastActivity = System . currentTimeMillis ( ) ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Received SSH_MSG_DEBUG" ) ; } return true ; } case SSH_MSG_NEWKEYS : { lastActivity = System . currentTimeMillis ( ) ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Received SSH_MSG_NEWKEYS" ) ; } return true ; } case SSH_MSG_KEX_INIT : { lastActivity = System . currentTimeMillis ( ) ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Received SSH_MSG_KEX_INIT" ) ; } if ( remotekex != null ) { disconnect ( TransportProtocol . PROTOCOL_ERROR , "Key exchange already in progress!" ) ; throw new SshException ( "Key exchange already in progress!" , SshException . PROTOCOL_VIOLATION ) ; } performKeyExchange ( msg ) ; return true ; } default : { lastActivity = System . currentTimeMillis ( ) ; // Not a transport protocol message return false ; } } } catch ( IOException ex1 ) { throw new SshException ( ex1 . getMessage ( ) , SshException . INTERNAL_ERROR ) ; } } | Process a message . This should be called when reading messages from outside of the transport protocol so that the transport protocol can parse its own messages . | 581 | 28 |
11,954 | public static String getFingerprint ( byte [ ] encoded , String algorithm ) throws SshException { Digest md5 = ( Digest ) ComponentManager . getInstance ( ) . supportedDigests ( ) . getInstance ( algorithm ) ; md5 . putBytes ( encoded ) ; byte [ ] digest = md5 . doFinal ( ) ; StringBuffer buf = new StringBuffer ( ) ; int ch ; for ( int i = 0 ; i < digest . length ; i ++ ) { ch = digest [ i ] & 0xFF ; if ( i > 0 ) { buf . append ( ' ' ) ; } buf . append ( HEX [ ( ch >>> 4 ) & 0x0F ] ) ; buf . append ( HEX [ ch & 0x0F ] ) ; } return buf . toString ( ) ; } | Generate an SSH key fingerprint with a specific algorithm . | 173 | 11 |
11,955 | public boolean canWrite ( ) throws SftpStatusException , SshException { // This is long hand because gcj chokes when it is not? Investigate why if ( ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IWUSR ) == SftpFileAttributes . S_IWUSR || ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IWGRP ) == SftpFileAttributes . S_IWGRP || ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IWOTH ) == SftpFileAttributes . S_IWOTH ) { return true ; } return false ; } | Determine whether the user has write access to the file . This checks the S_IWUSR flag is set in permissions . | 177 | 28 |
11,956 | public boolean canRead ( ) throws SftpStatusException , SshException { // This is long hand because gcj chokes when it is not? Investigate why if ( ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IRUSR ) == SftpFileAttributes . S_IRUSR || ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IRGRP ) == SftpFileAttributes . S_IRGRP || ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IROTH ) == SftpFileAttributes . S_IROTH ) { return true ; } return false ; } | Determine whether the user has read access to the file . This checks the S_IRUSR flag is set in permissions . | 171 | 27 |
11,957 | public SftpFileAttributes getAttributes ( ) throws SftpStatusException , SshException { if ( attrs == null ) { attrs = sftp . getAttributes ( getAbsolutePath ( ) ) ; } return attrs ; } | Get the files attributes . | 53 | 5 |
11,958 | public boolean isFifo ( ) throws SftpStatusException , SshException { // This is long hand because gcj chokes when it is not? Investigate why if ( ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IFIFO ) == SftpFileAttributes . S_IFIFO ) return true ; return false ; } | Determine whether the file is pointing to a pipe . | 88 | 12 |
11,959 | public boolean isBlock ( ) throws SftpStatusException , SshException { // This is long hand because gcj chokes when it is not? Investigate why if ( ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IFBLK ) == SftpFileAttributes . S_IFBLK ) { return true ; } return false ; } | Determine whether the file is pointing to a block special file . | 89 | 14 |
11,960 | public boolean isCharacter ( ) throws SftpStatusException , SshException { // This is long hand because gcj chokes when it is not? Investigate why if ( ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IFCHR ) == SftpFileAttributes . S_IFCHR ) { return true ; } return false ; } | Determine whether the file is pointing to a character mode device . | 87 | 14 |
11,961 | public boolean isSocket ( ) throws SftpStatusException , SshException { // This is long hand because gcj chokes when it is not? Investigate why if ( ( getAttributes ( ) . getPermissions ( ) . longValue ( ) & SftpFileAttributes . S_IFSOCK ) == SftpFileAttributes . S_IFSOCK ) { return true ; } return false ; } | Determine whether the file is pointing to a socket . | 89 | 12 |
11,962 | protected synchronized void write ( int b ) throws IOException { if ( closed ) { throw new IOException ( "The buffer is closed" ) ; } verifyBufferSize ( 1 ) ; buf [ writepos ] = ( byte ) b ; writepos ++ ; notifyAll ( ) ; } | Write a byte array to the buffer | 61 | 7 |
11,963 | protected synchronized int read ( ) throws IOException { try { block ( ) ; } catch ( InterruptedException ex ) { throw new InterruptedIOException ( "The blocking operation was interrupted" ) ; } if ( closed && available ( ) <= 0 ) { return - 1 ; } return buf [ readpos ++ ] ; } | Read a byte from the buffer | 67 | 6 |
11,964 | protected synchronized int read ( byte [ ] data , int offset , int len ) throws IOException { try { block ( ) ; } catch ( InterruptedException ex ) { throw new InterruptedIOException ( "The blocking operation was interrupted" ) ; } if ( closed && available ( ) <= 0 ) { return - 1 ; } int read = ( len > ( writepos - readpos ) ) ? ( writepos - readpos ) : len ; System . arraycopy ( buf , readpos , data , offset , read ) ; readpos += read ; return read ; } | Read a byte array from the buffer | 121 | 7 |
11,965 | public synchronized void add ( String name , Class < ? > cls ) { if ( locked ) { throw new IllegalStateException ( "Component factory is locked. Components cannot be added" ) ; } supported . put ( name , cls ) ; // add name to end of order vector if ( ! order . contains ( name ) ) order . addElement ( name ) ; } | Add a new component type to the factory . This method throws an exception if the class cannot be resolved . The name of the component IS NOT verified to allow component implementations to be overridden . | 78 | 38 |
11,966 | public Object getInstance ( String name ) throws SshException { if ( supported . containsKey ( name ) ) { try { return createInstance ( name , ( Class < ? > ) supported . get ( name ) ) ; } catch ( Throwable t ) { throw new SshException ( t . getMessage ( ) , SshException . INTERNAL_ERROR ) ; } } throw new SshException ( name + " is not supported" , SshException . UNSUPPORTED_ALGORITHM ) ; } | Get a new instance of a supported component . | 111 | 9 |
11,967 | private synchronized String createDelimitedList ( String preferred ) { StringBuffer listBuf = new StringBuffer ( ) ; int prefIndex = order . indexOf ( preferred ) ; // remove preferred and add it back at the end to ensure it is not // duplicated in the list returned if ( prefIndex != - 1 ) { listBuf . append ( preferred ) ; } for ( int i = 0 ; i < order . size ( ) ; i ++ ) { if ( prefIndex == i ) { continue ; } listBuf . append ( "," + ( String ) order . elementAt ( i ) ) ; } if ( prefIndex == - 1 && listBuf . length ( ) > 0 ) { return listBuf . toString ( ) . substring ( 1 ) ; } return listBuf . toString ( ) ; } | Create a delimited list of supported components . | 177 | 9 |
11,968 | public Socket accept ( ) throws IOException { Socket s ; if ( ! doing_direct ) { if ( proxy == null ) return null ; ProxyMessage msg = proxy . accept ( ) ; s = msg . ip == null ? new SocksSocket ( msg . host , msg . port , proxy ) : new SocksSocket ( msg . ip , msg . port , proxy ) ; //Set timeout back to 0 proxy . proxySocket . setSoTimeout ( 0 ) ; } else { //Direct Connection //Mimic the proxy behaviour, //only accept connections from the speciefed host. while ( true ) { s = super . accept ( ) ; if ( s . getInetAddress ( ) . equals ( remoteAddr ) ) { //got the connection from the right host //Close listenning socket. break ; } else s . close ( ) ; //Drop all connections from other hosts } } proxy = null ; //Return accepted socket return s ; } | Accepts the incoming connection . | 199 | 6 |
11,969 | public InetAddress getInetAddress ( ) { if ( localIP == null ) { try { localIP = InetAddress . getByName ( localHost ) ; } catch ( UnknownHostException e ) { return null ; } } return localIP ; } | Get address assigned by proxy to listen for incomming connections or the local machine address if doing direct connection . | 55 | 22 |
11,970 | public void setSoTimeout ( int timeout ) throws SocketException { super . setSoTimeout ( timeout ) ; if ( ! doing_direct ) proxy . proxySocket . setSoTimeout ( timeout ) ; } | Set Timeout . | 42 | 4 |
11,971 | public static String getStatusText ( int status ) { switch ( status ) { case SSH_FX_OK : return "OK" ; case SSH_FX_EOF : return "EOF" ; case SSH_FX_NO_SUCH_FILE : return "No such file." ; case SSH_FX_PERMISSION_DENIED : return "Permission denied." ; case SSH_FX_FAILURE : return "Server responded with an unknown failure." ; case SSH_FX_BAD_MESSAGE : return "Server responded to a bad message." ; case SSH_FX_NO_CONNECTION : return "No connection available." ; case SSH_FX_CONNECTION_LOST : return "Connection lost." ; case SSH_FX_OP_UNSUPPORTED : return "The operation is unsupported." ; case SSH_FX_INVALID_HANDLE : case INVALID_HANDLE : return "Invalid file handle." ; case SSH_FX_NO_SUCH_PATH : return "No such path." ; case SSH_FX_FILE_ALREADY_EXISTS : return "File already exists." ; case SSH_FX_WRITE_PROTECT : return "Write protect error." ; case SSH_FX_NO_MEDIA : return "No media at location" ; case SSH_FX_NO_SPACE_ON_FILESYSTEM : return "No space on filesystem" ; case SSH_FX_QUOTA_EXCEEDED : return "Quota exceeded" ; case SSH_FX_UNKNOWN_PRINCIPAL : return "Unknown principal" ; case SSH_FX_LOCK_CONFLICT : return "Lock conflict" ; case SSH_FX_DIR_NOT_EMPTY : return "Dir not empty" ; case SSH_FX_NOT_A_DIRECTORY : return "Not a directory" ; case SSH_FX_INVALID_FILENAME : return "Invalid filename" ; case SSH_FX_LINK_LOOP : return "Link loop" ; case SSH_FX_CANNOT_DELETE : return "Cannot delete" ; case SSH_FX_INVALID_PARAMETER : return "Invalid parameter" ; case SSH_FX_FILE_IS_A_DIRECTORY : return "File is a directory" ; case SSH_FX_BYTE_RANGE_LOCK_CONFLICT : return "Byte range lock conflict" ; case SSH_FX_BYTE_RANGE_LOCK_REFUSED : return "Byte range lock refused" ; case SSH_FX_DELETE_PENDING : return "Delete pending" ; case SSH_FX_FILE_CORRUPT : return "File corrupt" ; case SSH_FX_OWNER_INVALID : return "Owner invalid" ; case SSH_FX_GROUP_INVALID : return "Group invalid" ; case SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK : return "No matching byte range lock" ; case INVALID_RESUME_STATE : return "Invalid resume state" ; default : return "Unknown status type " + String . valueOf ( status ) ; } } | Convert a SSH_FXP_STATUS code into a readable string | 689 | 15 |
11,972 | public static SshPublicKeyFile parse ( byte [ ] formattedkey ) throws IOException { try { try { return new OpenSSHPublicKeyFile ( formattedkey ) ; } catch ( IOException ex ) { try { return new SECSHPublicKeyFile ( formattedkey ) ; } catch ( IOException ex2 ) { throw new IOException ( "Unable to parse key, format could not be identified" ) ; } } } catch ( OutOfMemoryError ex1 ) { throw new IOException ( "An error occurred parsing a public key file! Is the file corrupt?" ) ; } } | Parse a formatted public key and return a file representation . | 124 | 12 |
11,973 | public static BigInteger getSafePrime ( UnsignedInteger32 maximumSize ) { BigInteger prime = group1 ; for ( Iterator < BigInteger > it = safePrimes . iterator ( ) ; it . hasNext ( ) ; ) { BigInteger p = it . next ( ) ; int len = p . bitLength ( ) ; if ( len > maximumSize . intValue ( ) ) { break ; } prime = p ; } return prime ; } | get the biggest safe prime from the list that is < = maximumSize | 95 | 14 |
11,974 | public void read ( InputStream in , boolean clientMode ) throws SocksException , IOException { data = null ; ip = null ; DataInputStream di = new DataInputStream ( in ) ; version = di . readUnsignedByte ( ) ; command = di . readUnsignedByte ( ) ; if ( clientMode && command != 0 ) throw new SocksException ( command ) ; @ SuppressWarnings ( "unused" ) int reserved = di . readUnsignedByte ( ) ; addrType = di . readUnsignedByte ( ) ; byte addr [ ] ; switch ( addrType ) { case SOCKS_ATYP_IPV4 : addr = new byte [ 4 ] ; di . readFully ( addr ) ; host = bytes2IPV4 ( addr , 0 ) ; break ; case SOCKS_ATYP_IPV6 : addr = new byte [ SOCKS_IPV6_LENGTH ] ; //I believe it is 16 bytes,huge! di . readFully ( addr ) ; host = bytes2IPV6 ( addr , 0 ) ; break ; case SOCKS_ATYP_DOMAINNAME : //System.out.println("Reading ATYP_DOMAINNAME"); addr = new byte [ di . readUnsignedByte ( ) ] ; //Next byte shows the length di . readFully ( addr ) ; host = new String ( addr ) ; break ; default : throw ( new SocksException ( Proxy . SOCKS_JUST_ERROR ) ) ; } port = di . readUnsignedShort ( ) ; if ( addrType != SOCKS_ATYP_DOMAINNAME && doResolveIP ) { try { ip = InetAddress . getByName ( host ) ; } catch ( UnknownHostException uh_ex ) { } } } | Initialises Message from the stream . Reads server response or client request from given stream . | 386 | 18 |
11,975 | public void write ( OutputStream out ) throws SocksException , IOException { if ( data == null ) { Socks5Message msg ; if ( addrType == SOCKS_ATYP_DOMAINNAME ) msg = new Socks5Message ( command , host , port ) ; else { if ( ip == null ) { try { ip = InetAddress . getByName ( host ) ; } catch ( UnknownHostException uh_ex ) { throw new SocksException ( Proxy . SOCKS_JUST_ERROR ) ; } } msg = new Socks5Message ( command , ip , port ) ; } data = msg . data ; } out . write ( data ) ; } | Writes the message to the stream . | 145 | 8 |
11,976 | public InetAddress getInetAddress ( ) throws UnknownHostException { if ( ip != null ) return ip ; return ( ip = InetAddress . getByName ( host ) ) ; } | Returns IP field of the message as IP if the message was created with ATYP of HOSTNAME it will attempt to resolve the hostname which might fail . | 41 | 32 |
11,977 | public void run ( ) { if ( ! initProxy ( ) ) { // Check if we have been aborted if ( mode != OK_MODE ) return ; if ( net_thread != Thread . currentThread ( ) ) return ; mode = COMMAND_MODE ; warning_label . setText ( "Look up failed." ) ; warning_label . invalidate ( ) ; return ; } // System.out.println("Done!"); while ( ! warning_dialog . isShowing ( ) ) ; /* do nothing */ ; warning_dialog . dispose ( ) ; // dispose(); //End Dialog } | Resolves proxy address in other thread to avoid annoying blocking in GUI thread . | 127 | 15 |
11,978 | public void cdup ( ) throws SftpStatusException , SshException { SftpFile cd = sftp . getFile ( cwd ) ; SftpFile parent = cd . getParent ( ) ; if ( parent != null ) cwd = parent . getAbsolutePath ( ) ; } | Change the working directory to the parent directory | 67 | 8 |
11,979 | private boolean startsWithCustomRoot ( String path ) { for ( Enumeration < String > it = customRoots . elements ( ) ; it != null && it . hasMoreElements ( ) ; ) { if ( path . startsWith ( it . nextElement ( ) ) ) { return true ; } } return false ; } | Tests whether path starts with a custom file system root . | 69 | 12 |
11,980 | public boolean isDirectoryOrLinkedDirectory ( SftpFile file ) throws SftpStatusException , SshException { return file . isDirectory ( ) || ( file . isLink ( ) && stat ( file . getAbsolutePath ( ) ) . isDirectory ( ) ) ; } | Determine whether the file object is pointing to a symbolic link that is pointing to a directory . | 61 | 20 |
11,981 | public SftpFileAttributes get ( String remote , String local , boolean resume ) throws FileNotFoundException , SftpStatusException , SshException , TransferCancelledException { return get ( remote , local , null , resume ) ; } | Download the remote file into the local file . | 52 | 9 |
11,982 | public InputStream getInputStream ( String remotefile , long position ) throws SftpStatusException , SshException { String remotePath = resolveRemotePath ( remotefile ) ; sftp . getAttributes ( remotePath ) ; return new SftpFileInputStream ( sftp . openFile ( remotePath , SftpSubsystemChannel . OPEN_READ ) , position ) ; } | Create an InputStream for reading a remote file . | 87 | 10 |
11,983 | public SftpFileAttributes get ( String remote , OutputStream local , long position ) throws SftpStatusException , SshException , TransferCancelledException { return get ( remote , local , null , position ) ; } | Download the remote file into an OutputStream . | 48 | 9 |
11,984 | public OutputStream getOutputStream ( String remotefile ) throws SftpStatusException , SshException { String remotePath = resolveRemotePath ( remotefile ) ; return new SftpFileOutputStream ( sftp . openFile ( remotePath , SftpSubsystemChannel . OPEN_CREATE | SftpSubsystemChannel . OPEN_TRUNCATE | SftpSubsystemChannel . OPEN_WRITE ) ) ; } | Create an OutputStream for writing to a remote file . | 98 | 11 |
11,985 | public void put ( InputStream in , String remote , long position ) throws SftpStatusException , SshException , TransferCancelledException { put ( in , remote , null , position ) ; } | Upload the contents of an InputStream to the remote computer . | 43 | 12 |
11,986 | public void rm ( String path , boolean force , boolean recurse ) throws SftpStatusException , SshException { String actual = resolveRemotePath ( path ) ; SftpFileAttributes attrs = null ; attrs = sftp . getAttributes ( actual ) ; SftpFile file ; if ( attrs . isDirectory ( ) ) { SftpFile [ ] list = ls ( path ) ; if ( ! force && ( list . length > 0 ) ) { throw new SftpStatusException ( SftpStatusException . SSH_FX_FAILURE , "You cannot delete non-empty directory, use force=true to overide" ) ; } for ( int i = 0 ; i < list . length ; i ++ ) { file = list [ i ] ; if ( file . isDirectory ( ) && ! file . getFilename ( ) . equals ( "." ) && ! file . getFilename ( ) . equals ( ".." ) ) { if ( recurse ) { rm ( file . getAbsolutePath ( ) , force , recurse ) ; } else { throw new SftpStatusException ( SftpStatusException . SSH_FX_FAILURE , "Directory has contents, cannot delete without recurse=true" ) ; } } else if ( file . isFile ( ) ) { sftp . removeFile ( file . getAbsolutePath ( ) ) ; } } sftp . removeDirectory ( actual ) ; } else { sftp . removeFile ( actual ) ; } } | Remove a file or directory on the remote computer with options to force deletion of existing files and recursion . | 327 | 21 |
11,987 | public String getAbsolutePath ( String path ) throws SftpStatusException , SshException { String actual = resolveRemotePath ( path ) ; return sftp . getAbsolutePath ( actual ) ; } | Get the absolute path for a file . | 45 | 8 |
11,988 | public void putFiles ( String local , String remote , FileTransferProgress progress , boolean resume ) throws FileNotFoundException , SftpStatusException , SshException , TransferCancelledException { putFileMatches ( local , remote , progress , resume ) ; } | make local copies of some of the variables then call putfilematches which calls put on each file that matches the regexp local . | 56 | 27 |
11,989 | public int authenticate ( AuthenticationClient auth , String servicename ) throws SshException { try { auth . authenticate ( this , servicename ) ; readMessage ( ) ; transport . disconnect ( TransportProtocol . PROTOCOL_ERROR , "Unexpected response received from Authentication Protocol" ) ; throw new SshException ( "Unexpected response received from Authentication Protocol" , SshException . PROTOCOL_VIOLATION ) ; } catch ( AuthenticationResult result ) { state = result . getResult ( ) ; if ( state == SshAuthentication . COMPLETE ) transport . completedAuthentication ( ) ; return state ; } } | Authenticate using the mechanism provided . | 132 | 7 |
11,990 | public void sendRequest ( String username , String servicename , String methodname , byte [ ] requestdata ) throws SshException { ByteArrayWriter msg = new ByteArrayWriter ( ) ; try { msg . write ( SSH_MSG_USERAUTH_REQUEST ) ; msg . writeString ( username ) ; msg . writeString ( servicename ) ; msg . writeString ( methodname ) ; if ( requestdata != null ) { msg . write ( requestdata ) ; } transport . sendMessage ( msg . toByteArray ( ) , true ) ; } catch ( IOException ex ) { throw new SshException ( ex , SshException . INTERNAL_ERROR ) ; } finally { try { msg . close ( ) ; } catch ( IOException e ) { } } } | Send an authentication request . This sends an SSH_MSG_USERAUTH_REQUEST message . | 166 | 21 |
11,991 | public static UnsignedInteger32 add ( UnsignedInteger32 x , UnsignedInteger32 y ) { return new UnsignedInteger32 ( x . longValue ( ) + y . longValue ( ) ) ; } | Add two unsigned integers together . | 44 | 6 |
11,992 | public boolean setAuthenticationMethod ( int methodId , Authentication method ) { if ( methodId < 0 || methodId > 255 ) return false ; if ( method == null ) { // Want to remove a particular method return ( authMethods . remove ( new Integer ( methodId ) ) != null ) ; } else { // Add the method, or rewrite old one authMethods . put ( new Integer ( methodId ) , method ) ; } return true ; } | Adds another authentication method . | 94 | 5 |
11,993 | public Authentication getAuthenticationMethod ( int methodId ) { Object method = authMethods . get ( new Integer ( methodId ) ) ; if ( method == null ) return null ; return ( Authentication ) method ; } | Get authentication method which corresponds to given method id | 44 | 9 |
11,994 | public void installCBCCiphers ( ComponentFactory ciphers ) { if ( testJCECipher ( "3des-cbc" , TripleDesCbc . class ) ) { ciphers . add ( "3des-cbc" , TripleDesCbc . class ) ; } if ( testJCECipher ( "blowfish-cbc" , BlowfishCbc . class ) ) { ciphers . add ( "blowfish-cbc" , BlowfishCbc . class ) ; } if ( testJCECipher ( "aes128-cbc" , AES128Cbc . class ) ) { ciphers . add ( "aes128-cbc" , AES128Cbc . class ) ; } if ( testJCECipher ( "aes192-cbc" , AES192Cbc . class ) ) { ciphers . add ( "aes192-cbc" , AES192Cbc . class ) ; } if ( testJCECipher ( "aes256-cbc" , AES256Cbc . class ) ) { ciphers . add ( "aes256-cbc" , AES256Cbc . class ) ; } } | Install deprecated Counter - Block - Mode ciphers . | 257 | 11 |
11,995 | public void installArcFourCiphers ( ComponentFactory ciphers ) { if ( testJCECipher ( "arcfour" , ArcFour . class ) ) { ciphers . add ( "arcfour" , ArcFour . class ) ; } if ( testJCECipher ( "arcfour128" , ArcFour128 . class ) ) { ciphers . add ( "arcfour128" , ArcFour128 . class ) ; } if ( testJCECipher ( "arcfour256" , ArcFour256 . class ) ) { ciphers . add ( "arcfour256" , ArcFour256 . class ) ; } } | Install deprecated ArcFour ciphers | 136 | 7 |
11,996 | public Event addAttribute ( String key , Object value ) { eventAttributes . put ( key , ( value == null ? "null" : value ) ) ; return this ; } | Add an attribute to the event | 36 | 6 |
11,997 | public InetAddress getInetAddress ( ) { if ( remoteIP == null ) { try { remoteIP = InetAddress . getByName ( remoteHost ) ; } catch ( UnknownHostException e ) { return null ; } } return remoteIP ; } | Get remote host as InetAddress object might return null if addresses are resolved by proxy and it is not possible to resolve it locally | 55 | 26 |
11,998 | public void run ( Iterable < Item > items , Context cx ) { Function prepareFunc = ( Function ) indexResults . getPrototype ( ) . get ( "prepare" , indexResults ) ; prepareFunc . call ( cx , scope , indexResults , NO_ARGS ) ; Object args [ ] = new Object [ ] { null , mapFunction } ; for ( Item item : items ) { args [ 0 ] = item ; indexFunction . call ( cx , scope , indexResults , args ) ; } Function doneFunc = ( Function ) indexResults . getPrototype ( ) . get ( "setDone" , indexResults ) ; doneFunc . call ( cx , scope , indexResults , NO_ARGS ) ; } | Run the indexer on the given iterable of items . This will attempt to apply some optimizations to ensure that only items which need re - indexing are actually passed to the map function . | 157 | 38 |
11,999 | public static Indexer create ( String mapTxt ) { Context cx = Context . enter ( ) ; try { return new Indexer ( mapTxt , cx ) ; } finally { Context . exit ( ) ; } } | Create a new indexer object | 46 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.