Search code examples
javatcpscpjsch

Jsch ScpTo example clarification


I have been reading the Jsch ScpTo Example, but am having trouble understanding part of what they are doing. More specifically, I am having trouble understanding how the checkAck method works.

checkAck method:

static int checkAck(InputStream in) throws IOException{
    int b=in.read();
    // b may be 0 for success,
    //          1 for error,
    //          2 for fatal error,
    //          -1
    if(b==0) return b;
    if(b==-1) return b;

    if(b==1 || b==2){
        StringBuffer sb=new StringBuffer();
        int c;
        do {
            c=in.read();
            sb.append((char)c);
        }
        while(c!='\n');
        if(b==1){ // error
            System.out.print(sb.toString());
        }
        if(b==2){ // fatal error
            System.out.print(sb.toString());
        }
    }
    return b;
}

It appears that this is referencing the ACK flag in the TCP protocol. However, reading up on the TCP protocol, there appears to be a fairly large amount of stuff sent in the TCP header. When the method is invoked however it doesn't have to sort through all of this and extract the flag. It simply assumes that the ACK flag will be the next integer in the stream.

Could someone explain to me whichever of the following is applicable:

  1. why this assumption is valid,
  2. the proper way to extract the flag,
  3. how they make sure that the input stream is always on the correct flag before calling the method, or
  4. if this doesn't relate to the TCP ACK flag, what does it relate to?

Solution

  • The ScpTo.java is an implementation of SCP protocol.

    The flag, the checkAck method reads, is an SCP protocol response from the server (ack).

    It has nothing to do with TCP, which is two layers below on a protocol stack, hidden away from you, not only by SSH layer in JSch, but mainly by the Java and OS.

    I believe that unfortunately, there's no specification for SCP protocol. You can only refer to a canonical implementation of SCP in OpenSSH scp code, to understand the protocol.

    Just shortly: To every command sent by the client, the server responds with a single-byte "ack", where:

    • 0x00 is success
    • 0x01 is error
    • 0x02 is fatal error

    I'd strongly advise you against using the SCP, if possible. Use an SFTP, which is natively supported by JSch (and other SSH implementations)