0

I'm trying to download a file over sftp and so far I've connected to a server via ssh session then opened an sftp session using the ssh session and everything seems fine. I have opened a file on the server and I'm using sftp_read() to get block of bytes from the file. My code is:

char buffer[16384] = {};
ssize_t nbytes;
ssize_t ntotal = 0;
for (;;) {
    nbytes = sftp_read(file, buffer, sizeof(buffer));

    if (nbytes == 0) {
        break; // EOF
    }

    localFile << buffer;
    ntotal += nbytes;
    //sftp_seek(file, ntotal);
}

But for some reason, when the blocks are being read, the first 20 bytes are correct but the 21st up till the 16384th byte are wrong. It turns out that after reading 20 bytes, the reader jumps to the 16384th byte of the file and continues reading like nothing happened.

I did some testing and if I changed the buffer to any size whether it was 16384, 21, 22, 50 etc, it still jumped to the 16384th byte after reading 20 bytes correctly.

Is there a reason for this? Is there a better library than libssh and sftp that I can use without errors?

Stapps
  • 13
  • 4
  • 1
    you're not writing to the stream correctly, use `localFile.write(buffer, nbytes)` – programmerjake Nov 17 '14 at 00:24
  • I'm using a std::ofstream to write to a local file. I've done it before so that syntax is fine. – Stapps Nov 17 '14 at 01:11
  • 1
    Well the issue is. localFile << buffer; This will always write 16384 bytes to the file, even if you got only 2 bytes fromt he sftp. So you write random data to the file. programmerjake is right! – asn Nov 17 '14 at 06:24
  • @asn actually `localFile << buffer` writes until it hits a null character, so it could actually write much more than 16kB. – programmerjake Nov 17 '14 at 08:32
  • one detail I missed out is that if I debug and place a break point after it fills the buffer, I can see it's filled the entire buffer with characters, characters that are from the original file (I've use a hex editor to view the bytes of both local and server files). The sftp_read only returns 20 bytes and then jumps the other 16364 bytes. Even the written file output is significantly smaller than the original file's size. – Stapps Nov 17 '14 at 19:41
  • If you think there is a bug in sftp. Please create a reproducer written in C. There are several thousand people using the sftp subsystem using libssh which did not notice an issue! – asn Dec 05 '14 at 08:43

1 Answers1

-1

I didn't need to use libssh after all. For anybody wanting another way of copying files over sftp, just use:

system("scp -i private_key user@server.com:directory_to_file/file.txt path_to_local_dir/file.txt");
Stapps
  • 13
  • 4
  • hey man, just another problem that I have, could you send me the code snippet that you used to connect to the remote server – Kimutai Mar 14 '15 at 12:42