[Libssh] sftp_read() Trouble

Chris Backas chb at infoplusonline.com
Thu Aug 2 20:04:26 CEST 2007


Greeting all,

I'm trying to use libssh to automate some file transfers and  
deletions from an SFTP server, and I'm currently trying to proof-of- 
concept the code. Following sample.c, I have a reliable login/ 
authentication procedure working and everything, and I can read a  
directory list and open the file I want to transfer. However, when I  
actually start using sftp_read(), I get some strange behavior from it.

Namely, the first call succeeds and fills by buffer with the expected  
data. The second call, however, fails. And how it fails varies by  
what host I connect to.  IE:

MacOS X 10.4.10 (PPC) -> Red Hat Enterprise Linux 4 (Intel, OpenSSH)  
= I get an error on my second call to sftp_read(), the server returns  
"bad message"
MacOS X 10.4.10 (PPC) -> Mac OS X 10.4.10 (PPC, OpenSSH) = I get what  
appears to be a normal EOF from the server, even though the file is  
much larger than the single fetch I've gotten so far.

I'll paste the code in below. It's a method of an Objective C class  
wrapper I'm using, but it should be clear enough what I'm doing.

Thanks for any insight/help!
Chris Backas


-(void)fetchFile:(NSString*)remoteFileName toLocalFile:(NSString*) 
localFilePath
{
	// Setup a buffer
	char data[8192];

	// Fixup the remote filepath with the last directory we've changed  
to - unless it looks like an absolute path.
	// (We won't concern ourselves with Windows paths)
	if (![remoteFileName hasPrefix:@"/"])
	{
		remoteFileName = [currentDirectoryString  
stringByAppendingPathComponent:remoteFileName];
	}

	// Try to open the remote file, ensuring it exists
	char* remoteFileCString = [self cStringForString:remoteFileName];
	SFTP_FILE* remoteFile = sftp_open 
(sftpSession,remoteFileCString,O_RDONLY,NULL);
	free(remoteFileCString);
	if(!remoteFile)
	{
		[NSException raise:@"SFTP Failure" format:@"Couldn't open remote  
file: %@",remoteFileName];
	}

	// Get ready to fetch the data.
	NSMutableData* fileData = [NSMutableData data];
	int len = 1;
	while((len=sftp_read(remoteFile,data,8192)) > 0)
	{
		[fileData appendBytes:data length:len];
     }
	if (len == -1)
		[NSException raise:@"SFTP Failure" format:@"Transfer error: %@", 
[self lastError]];
	[fileData writeToFile:localFilePath atomically:YES];

	// Close the remote file
	sftp_file_close(remoteFile);

}




More information about the Libssh mailing list