void clSFTP::Write(const wxMemoryBuffer& fileContent, const wxString& remotePath) throw(clException) { if(!m_sftp) { throw clException("SFTP is not initialized"); } int access_type = O_WRONLY | O_CREAT | O_TRUNC; sftp_file file; wxString tmpRemoteFile = remotePath; tmpRemoteFile << ".codelitesftp"; file = sftp_open(m_sftp, tmpRemoteFile.mb_str(wxConvUTF8).data(), access_type, 0644); if(file == NULL) { throw clException(wxString() << _("Can't open file: ") << tmpRemoteFile << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } char* p = (char*)fileContent.GetData(); const int maxChunkSize = 65536; wxInt64 bytesLeft = fileContent.GetDataLen(); while(bytesLeft > 0) { wxInt64 chunkSize = bytesLeft > maxChunkSize ? maxChunkSize : bytesLeft; wxInt64 bytesWritten = sftp_write(file, p, chunkSize); if(bytesWritten < 0) { sftp_close(file); throw clException(wxString() << _("Can't write data to file: ") << tmpRemoteFile << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } bytesLeft -= bytesWritten; p += bytesWritten; } sftp_close(file); // Unlink the original file if it exists bool needUnlink = false; { // Check if the file exists sftp_attributes attr = sftp_stat(m_sftp, remotePath.mb_str(wxConvISO8859_1).data()); if(attr) { needUnlink = true; sftp_attributes_free(attr); } } if(needUnlink && sftp_unlink(m_sftp, remotePath.mb_str(wxConvUTF8).data()) < 0) { throw clException(wxString() << _("Failed to unlink file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } // Rename the file if(sftp_rename(m_sftp, tmpRemoteFile.mb_str(wxConvUTF8).data(), remotePath.mb_str(wxConvUTF8).data()) < 0) { throw clException(wxString() << _("Failed to rename file: ") << tmpRemoteFile << " -> " << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } }
static void torture_sftp_read_blocking(void **state) { struct torture_state *s = *state; struct torture_sftp *t = s->ssh.tsftp; char libssh_tmp_file[] = "/tmp/libssh_sftp_test_XXXXXX"; char buf[MAX_XFER_BUF_SIZE]; ssize_t bytesread; ssize_t byteswritten; int fd; sftp_file file; mode_t mask; file = sftp_open(t->sftp, "/usr/bin/ssh", O_RDONLY, 0); assert_non_null(file); mask = umask(S_IRWXO | S_IRWXG); fd = mkstemp(libssh_tmp_file); umask(mask); unlink(libssh_tmp_file); for (;;) { bytesread = sftp_read(file, buf, MAX_XFER_BUF_SIZE); if (bytesread == 0) { break; /* EOF */ } assert_false(bytesread < 0); byteswritten = write(fd, buf, bytesread); assert_int_equal(byteswritten, bytesread); } close(fd); sftp_close(file); }
wxString clSFTP::Read(const wxString& remotePath) throw (clException) { if ( !m_sftp ) { throw clException("SFTP is not initialized"); } sftp_file file = sftp_open(m_sftp, remotePath.mb_str(wxConvISO8859_1).data(), O_RDONLY, 0); if (file == NULL) { throw clException(wxString() << _("Failed to open remote file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } wxString content; char buffer[1024]; int nbytes = 0; memset(buffer, 0, sizeof(buffer)); nbytes = sftp_read(file, buffer, sizeof(buffer)); while (nbytes > 0) { content << wxString(buffer, nbytes); memset(buffer, 0, sizeof(buffer)); nbytes = sftp_read(file, buffer, sizeof(buffer)); } if ( nbytes < 0 ) { sftp_close(file); throw clException(wxString() << _("Failed to read remote file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } sftp_close( file ); return content; }
int FSSftp::OpenRead ( FSPath& path, int* err, FSCInfo* info ) { MutexLock lock( &mutex ); int ret = CheckSession( err, info ); if ( ret ) { return ret; } int n = 0; for ( ; n < MAX_FILES; n++ ) if ( !fileTable[n] ) { break; } if ( n >= MAX_FILES ) { if ( err ) { *err = SSH_INTERROR_OUTOF; } return -1; } sftp_file f = sftp_open( sftpSession, ( char* ) path.GetString( _operParam.charset, '/' ), O_RDONLY, 0 ); if ( !f ) { if ( err ) { *err = sftp_get_error( sftpSession ); } return -1; } fileTable[n] = f; return n; }
static void torture_sftp_fsync(void **state) { struct torture_state *s = *state; struct torture_sftp *t = s->ssh.tsftp; char libssh_tmp_file[] = "/tmp/libssh_sftp_test_XXXXXX"; char buf[MAX_XFER_BUF_SIZE] = {0}; char buf_verify[MAX_XFER_BUF_SIZE] = {0}; size_t count; size_t bytesread; ssize_t byteswritten; int fd; sftp_file file; mode_t mask; int rc; FILE *fp; struct stat sb; mask = umask(S_IRWXO | S_IRWXG); fd = mkstemp(libssh_tmp_file); umask(mask); assert_return_code(fd, errno); close(fd); unlink(libssh_tmp_file); file = sftp_open(t->sftp, libssh_tmp_file, O_WRONLY | O_CREAT, 0600); assert_non_null(file); rc = lstat(libssh_tmp_file, &sb); assert_return_code(rc, errno); snprintf(buf, sizeof(buf), "libssh fsync test\n"); count = strlen(buf) + 1; byteswritten = sftp_write(file, buf, count); assert_int_equal(byteswritten, count); rc = sftp_fsync(file); assert_return_code(rc, errno); fp = fopen(libssh_tmp_file, "r"); assert_non_null(fp); rc = fstat(fileno(fp), &sb); assert_return_code(rc, errno); bytesread = fread(buf_verify, sizeof(buf_verify), 1, fp); if (bytesread == 0) { if (!feof(fp)) { assert_int_equal(bytesread, count); } } assert_string_equal(buf, buf_verify); sftp_close(file); fclose(fp); unlink(libssh_tmp_file); }
int FSSftp::OpenCreate ( FSPath& path, bool overwrite, int mode, int* err, FSCInfo* info ) { MutexLock lock( &mutex ); int ret = CheckSession( err, info ); if ( ret ) { return ret; } if ( !overwrite ) { /* заебался выяснять почему sftp_open с O_EXCL выдает "generc error" при наличии файла, а не EEXIST какой нибудь поэтому встанил эту дурацкую проверку на наличие */ sftp_attributes a = sftp_lstat( sftpSession, ( char* ) path.GetString( _operParam.charset, '/' ) ); if ( a ) { sftp_attributes_free( a ); //!!! if ( err ) { *err = SSH_FX_FILE_ALREADY_EXISTS; } return -1; } } int n = 0; for ( ; n < MAX_FILES; n++ ) if ( !fileTable[n] ) { break; } if ( n >= MAX_FILES ) { if ( err ) { *err = SSH_INTERROR_OUTOF; } return -1; } sftp_file f = sftp_open( sftpSession, ( char* ) path.GetString( _operParam.charset, '/' ), O_CREAT | O_WRONLY | ( overwrite ? O_TRUNC : O_EXCL ), mode ); if ( !f ) { //printf("ssh-err:'%s'\n",ssh_get_error(sshSession)); if ( err ) { *err = sftp_get_error( sftpSession ); } return -1; } fileTable[n] = f; return n; }
SFTPInputStream::SFTPInputStream(sftp_session sftp, ssh_session ssh, std::string filename) { this->sftp = sftp; this->ssh = ssh; this->filename = filename; int access_type = O_RDONLY; this->file = sftp_open(sftp, filename.c_str(), access_type, 0); if (!file) { std::cerr << "Error opening file for reading: " << strerror(errno) << std::endl; throw std::runtime_error("can't open file"); } sftp_attributes attr = sftp_fstat(file); this->total_size = attr->size; this->index = 0; }
uint8_t* sn_sftp_load_file(ssh_session ssh, sftp_session sftp, std::string path) { uint8_t *data; int access_type, fd, nbytes, index, rc; char buffer[SFTP_MAX_XFER_BUFFER]; index = 0; sftp_file file; access_type = O_RDONLY; file = sftp_open(sftp, path.c_str(), access_type, 0); if (file == NULL) { std::cerr << "Can't open file for reading: " << strerror(errno) << std::endl; return NULL; } sftp_attributes attr = sftp_fstat(file); data = new uint8_t[attr->size + 1]; for(;;) { nbytes = sftp_read(file, buffer, sizeof(buffer)); if (nbytes == 0) { break; } else if (nbytes < 0) { std::cerr << "Error while reading file: " << ssh_get_error(ssh) << std::endl; sftp_close(file); delete[] data; return NULL; } memcpy(data + index, buffer, nbytes); index += nbytes; } rc = sftp_close(file); assert(rc == SSH_OK); data[attr->size] = '\0'; sftp_attributes_free(attr); return data; }
int main() { // INIT ssh_session sshsession = ssh_new(); ssh_options_set(sshsession, SSH_OPTIONS_HOST, "192.168.1.117"); if (ssh_connect(sshsession) == 0) { if (ssh_userauth_password(sshsession, "root", "password") == 0) { sftp_session sftpsession = sftp_new(sshsession); if (sftp_init(sftpsession) == 0) { // DIR READ sftp_dir dir = sftp_opendir(sftpsession, "/root/"); sftp_attributes file; while((file = sftp_readdir(sftpsession, dir))) { if (file->type == 1) // 1 == file; 2 == dir { // todo.. } } sftp_closedir(dir); // FILE READ sftp_file l_file = sftp_open(sftpsession, "/root/test.txt", O_RDONLY, 0); sftp_attributes attr = sftp_fstat(l_file); QByteArray l_ba; l_ba.resize(attr->size); sftp_read(l_file, l_ba.data(), attr->size); // Returns readed sftp_close(l_file); } } ssh_disconnect(sshsession); } return 0; }
void clSFTP::Read(const wxString& remotePath, wxMemoryBuffer& buffer) throw(clException) { if(!m_sftp) { throw clException("SFTP is not initialized"); } sftp_file file = sftp_open(m_sftp, remotePath.mb_str(wxConvUTF8).data(), O_RDONLY, 0); if(file == NULL) { throw clException(wxString() << _("Failed to open remote file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } SFTPAttribute::Ptr_t fileAttr = Stat(remotePath); if(!fileAttr) { throw clException(wxString() << _("Could not stat file:") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } wxInt64 fileSize = fileAttr->GetSize(); if(fileSize == 0) return; // Allocate buffer for the file content char pBuffer[65536]; // buffer // Read the entire file content wxInt64 bytesLeft = fileSize; wxInt64 bytesRead = 0; while(bytesLeft > 0) { wxInt64 nbytes = sftp_read(file, pBuffer, sizeof(pBuffer)); bytesRead += nbytes; bytesLeft -= nbytes; buffer.AppendData(pBuffer, nbytes); } if(bytesRead != fileSize) { sftp_close(file); buffer.Clear(); throw clException(wxString() << _("Could not read file:") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } sftp_close(file); }
sftp_file CSFTPSession::CreateFileHande(const std::string& file) { if (m_connected) { P8PLATFORM::CLockObject lock(m_lock); m_LastActive = P8PLATFORM::GetTimeMs(); sftp_file handle = sftp_open(m_sftp_session, CorrectPath(file).c_str(), O_RDONLY, 0); if (handle) { sftp_file_set_blocking(handle); return handle; } else kodi::Log(ADDON_LOG_ERROR, "SFTPSession: Was connected but couldn't create filehandle for '%s'", file.c_str()); } else kodi::Log(ADDON_LOG_ERROR, "SFTPSession: Not connected and can't create file handle for '%s'", file.c_str()); return NULL; }
static csync_vio_method_handle_t *_sftp_creat(const char *uri, mode_t mode) { csync_vio_method_handle_t *mh = NULL; char *path = NULL; if (_sftp_connect(uri) < 0) { return NULL; } if (c_parse_uri(uri, NULL, NULL, NULL, NULL, NULL, &path) < 0) { return NULL; } mh = (csync_vio_method_handle_t *) sftp_open(_sftp_session, path, O_CREAT|O_WRONLY|O_TRUNC, mode); if (mh == NULL) { errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session)); } SAFE_FREE(path); return mh; }
int sftp_test(SSH_SESSION *session, int test){ SFTP_SESSION *sftp=sftp_new(session); SFTP_FILE *file; int wrote=0; char name[128]; if(sftp == NULL) return SSH_ERROR; if(sftp_init(sftp)<0){ printf("problem initializing sftp : %s\n",ssh_get_error(session)); return SSH_ERROR; } if(test==TEST_WRITE){ snprintf(name,sizeof(name),"/tmp/libsshstress%d",rand()); file=sftp_open(sftp,name,O_RDWR|O_CREAT,0777); if(!file){ printf("Failed to open file : %s\n",ssh_get_error(session)); sftp_free(sftp); return SSH_ERROR; } while(wrote<FILESIZE){ int max=FILESIZE-wrote; int towrite=rand()%max + 1; int ret=sftp_write(file,&samplefile[wrote],towrite); if(ret<=0){ printf("Problem while writing : %s\n",ssh_get_error(session)); sftp_free(sftp); return SSH_ERROR; } if(ret != towrite){ printf("Asked to write %d, wrote %d\n",towrite,ret); } wrote += ret; } sftp_close(file); } sftp_free(sftp); return SSH_OK; }
void clSFTP::Write(const wxString& fileContent, const wxString& remotePath) throw (clException) { if ( !m_sftp ) { throw clException("SFTP is not initialized"); } int access_type = O_WRONLY | O_CREAT | O_TRUNC; sftp_file file; std::string str = fileContent.mb_str(wxConvUTF8).data(); file = sftp_open(m_sftp, remotePath.mb_str(wxConvUTF8).data(), access_type, 0644); if (file == NULL) { throw clException(wxString() << _("Can't open file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } size_t nbytes = sftp_write(file, str.c_str(), str.length()); if (nbytes != str.length()) { sftp_close(file); throw clException(wxString() << _("Can't write data to file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } sftp_close(file); }
static int do_write(const char* path, FILE* fp, ftp_transfer_func hookf, uint64_t offset) { /* try to set up a scp connection */ if (gvSSHTrySCP && !offset) { ssh_scp scp = ssh_scp_new(ftp->session, SSH_SCP_WRITE, path); if (scp != NULL) { int rc = ssh_scp_init(scp); if (rc == SSH_OK) return do_scp_write(scp, path, fp, hookf); ssh_scp_free(scp); } } time_t then = time(NULL) - 1; ftp_set_close_handler(); if (hookf) hookf(&ftp->ti); ftp->ti.begin = false; struct stat sb; errno = 0; if (fstat(fileno(fp), &sb) == -1) { ftp_err(_("Couldn't fstat local file: %s\n"), strerror(errno)); return -1; } /* open remote file */ sftp_file file = sftp_open(ftp->sftp_session, path, O_WRONLY | O_CREAT | (offset == 0u ? O_TRUNC : 0), sb.st_mode); if (!file) { ftp_err(_("Cannot open file for writing: %s\n"), ssh_get_error(ftp->session)); return -1; } /* seek to offset */ int r = sftp_seek64(file, offset); if (r != SSH_OK) { ftp_err(_("Failed to seek: %s\n"), ssh_get_error(ftp->session)); sftp_close(file); return -1; } /* read file */ char buffer[SSH_BUFSIZ]; ssize_t nbytes = 0; errno = 0; while ((nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp)) > 0) { if (ftp_sigints() > 0) { ftp_trace("break due to sigint\n"); break; } ssize_t nwritten = sftp_write(file, buffer, nbytes); if (nwritten != nbytes) { ftp_err(_("Error while writing to file: %s\n"), ssh_get_error(ftp->session)); sftp_close(file); return -1; } ftp->ti.size += nbytes; if (hookf) { time_t now = time(NULL); if (now > then) { hookf(&ftp->ti); then = now; } } errno = 0; } if (ferror(fp)) { ftp_err(_("Failed to read from file: %s\n"), strerror(errno)); r = -1; } sftp_close(file); return r; }
void SSH::getFileSftp(const std::string& filePath, sftp_file& handle) { if (!sftp_) openSftp(); handle = sftp_open(sftp_, ("/"+filePath).c_str(), 0x0000, 0); // read only }
local_file = g_fopen (local_path, "wb"); if (!local_file) { remmina_sftp_client_thread_set_error (client, task, _("Error creating file %s."), local_path); return FALSE; } size = 0; break; case GTK_RESPONSE_APPLY: break; } } tmp = remmina_ssh_unconvert (REMMINA_SSH (sftp), remote_path); remote_file = sftp_open (sftp->sftp_sess, tmp, O_RDONLY, 0); g_free(tmp); if (!remote_file) { fclose (local_file); remmina_sftp_client_thread_set_error (client, task, _("Error opening file %s on server. %s"), remote_path, ssh_get_error (REMMINA_SSH (client->sftp)->session)); return FALSE; } if (size > 0) { if (sftp_seek64 (remote_file, size) < 0) { sftp_close (remote_file);
static void do_sftp(ssh_session session){ sftp_session sftp=sftp_new(session); sftp_dir dir; sftp_attributes file; sftp_statvfs_t sftpstatvfs; struct statvfs sysstatvfs; sftp_file fichier; sftp_file to; int len=1; unsigned int i; char data[DATALEN]={0}; char *lnk; unsigned int count; if(!sftp){ fprintf(stderr, "sftp error initialising channel: %s\n", ssh_get_error(session)); return; } if(sftp_init(sftp)){ fprintf(stderr, "error initialising sftp: %s\n", ssh_get_error(session)); return; } printf("Additional SFTP extensions provided by the server:\n"); count = sftp_extensions_get_count(sftp); for (i = 0; i < count; i++) { printf("\t%s, version: %s\n", sftp_extensions_get_name(sftp, i), sftp_extensions_get_data(sftp, i)); } /* test symlink and readlink */ if (sftp_symlink(sftp, "/tmp/this_is_the_link", "/tmp/sftp_symlink_test") < 0) { fprintf(stderr, "Could not create link (%s)\n", ssh_get_error(session)); return; } lnk = sftp_readlink(sftp, "/tmp/sftp_symlink_test"); if (lnk == NULL) { fprintf(stderr, "Could not read link (%s)\n", ssh_get_error(session)); return; } printf("readlink /tmp/sftp_symlink_test: %s\n", lnk); sftp_unlink(sftp, "/tmp/sftp_symlink_test"); if (sftp_extension_supported(sftp, "*****@*****.**", "2")) { sftpstatvfs = sftp_statvfs(sftp, "/tmp"); if (sftpstatvfs == NULL) { fprintf(stderr, "statvfs failed (%s)\n", ssh_get_error(session)); return; } printf("sftp statvfs:\n" "\tfile system block size: %llu\n" "\tfundamental fs block size: %llu\n" "\tnumber of blocks (unit f_frsize): %llu\n" "\tfree blocks in file system: %llu\n" "\tfree blocks for non-root: %llu\n" "\ttotal file inodes: %llu\n" "\tfree file inodes: %llu\n" "\tfree file inodes for to non-root: %llu\n" "\tfile system id: %llu\n" "\tbit mask of f_flag values: %llu\n" "\tmaximum filename length: %llu\n", (unsigned long long) sftpstatvfs->f_bsize, (unsigned long long) sftpstatvfs->f_frsize, (unsigned long long) sftpstatvfs->f_blocks, (unsigned long long) sftpstatvfs->f_bfree, (unsigned long long) sftpstatvfs->f_bavail, (unsigned long long) sftpstatvfs->f_files, (unsigned long long) sftpstatvfs->f_ffree, (unsigned long long) sftpstatvfs->f_favail, (unsigned long long) sftpstatvfs->f_fsid, (unsigned long long) sftpstatvfs->f_flag, (unsigned long long) sftpstatvfs->f_namemax); sftp_statvfs_free(sftpstatvfs); if (statvfs("/tmp", &sysstatvfs) < 0) { fprintf(stderr, "statvfs failed (%s)\n", strerror(errno)); return; } printf("sys statvfs:\n" "\tfile system block size: %llu\n" "\tfundamental fs block size: %llu\n" "\tnumber of blocks (unit f_frsize): %llu\n" "\tfree blocks in file system: %llu\n" "\tfree blocks for non-root: %llu\n" "\ttotal file inodes: %llu\n" "\tfree file inodes: %llu\n" "\tfree file inodes for to non-root: %llu\n" "\tfile system id: %llu\n" "\tbit mask of f_flag values: %llu\n" "\tmaximum filename length: %llu\n", (unsigned long long) sysstatvfs.f_bsize, (unsigned long long) sysstatvfs.f_frsize, (unsigned long long) sysstatvfs.f_blocks, (unsigned long long) sysstatvfs.f_bfree, (unsigned long long) sysstatvfs.f_bavail, (unsigned long long) sysstatvfs.f_files, (unsigned long long) sysstatvfs.f_ffree, (unsigned long long) sysstatvfs.f_favail, (unsigned long long) sysstatvfs.f_fsid, (unsigned long long) sysstatvfs.f_flag, (unsigned long long) sysstatvfs.f_namemax); } /* the connection is made */ /* opening a directory */ dir=sftp_opendir(sftp,"./"); if(!dir) { fprintf(stderr, "Directory not opened(%s)\n", ssh_get_error(session)); return ; } /* reading the whole directory, file by file */ while((file=sftp_readdir(sftp,dir))){ fprintf(stderr, "%30s(%.8o) : %s(%.5d) %s(%.5d) : %.10llu bytes\n", file->name, file->permissions, file->owner, file->uid, file->group, file->gid, (long long unsigned int) file->size); sftp_attributes_free(file); } /* when file=NULL, an error has occured OR the directory listing is end of file */ if(!sftp_dir_eof(dir)){ fprintf(stderr, "Error: %s\n", ssh_get_error(session)); return; } if(sftp_closedir(dir)){ fprintf(stderr, "Error: %s\n", ssh_get_error(session)); return; } /* this will open a file and copy it into your /home directory */ /* the small buffer size was intended to stress the library. of course, you can use a buffer till 20kbytes without problem */ fichier=sftp_open(sftp,"/usr/bin/ssh",O_RDONLY, 0); if(!fichier){ fprintf(stderr, "Error opening /usr/bin/ssh: %s\n", ssh_get_error(session)); return; } /* open a file for writing... */ to=sftp_open(sftp,"ssh-copy",O_WRONLY | O_CREAT, 0700); if(!to){ fprintf(stderr, "Error opening ssh-copy for writing: %s\n", ssh_get_error(session)); return; } while((len=sftp_read(fichier,data,4096)) > 0){ if(sftp_write(to,data,len)!=len){ fprintf(stderr, "Error writing %d bytes: %s\n", len, ssh_get_error(session)); return; } } printf("finished\n"); if(len<0) fprintf(stderr, "Error reading file: %s\n", ssh_get_error(session)); sftp_close(fichier); sftp_close(to); printf("fichiers ferm\n"); to=sftp_open(sftp,"/tmp/grosfichier",O_WRONLY|O_CREAT, 0644); for(i=0;i<1000;++i){ len=sftp_write(to,data,DATALEN); printf("wrote %d bytes\n",len); if(len != DATALEN){ printf("chunk %d : %d (%s)\n",i,len,ssh_get_error(session)); } } sftp_close(to); /* close the sftp session */ sftp_free(sftp); printf("sftp session terminated\n"); }
static int ggnfs_open(const char *fileName, struct fuse_file_info *fi) { fprintf(stderr, "inside sftp_read_sync\n"); int access_type; sftp_file file; char buffer[MAX_XFER_BUF_SIZE]; int nbytes, nwritten, rc; int fd; access_type = O_RDONLY; char filePath[PATH_MAX]; strcpy(filePath, remotePath); //strcat(filePath,"/"); strcat(filePath,fileName); fprintf(stderr, "filePath : %s\n", filePath); file = sftp_open(ggnfs_data.sftp, filePath, access_type, 0); if (file == NULL) { fprintf(stderr, "Can't open file for reading: %s\n", ssh_get_error(ggnfs_data.session)); return SSH_ERROR; } char localFilePath[PATH_MAX] ; strcpy(localFilePath, tmp_dir); strcat(localFilePath, fileName); fprintf(stderr, "local file path NOW NOW-> : %s\n", localFilePath); fd = open(localFilePath, O_CREAT | O_RDWR,0644); if (fd < 0) { fprintf(stderr, "Can't open file for writing: %s\n", strerror(errno)); return SSH_ERROR; } fprintf(stderr, "before for loop to read -> : %s\n", localFilePath); for (;;) { nbytes = sftp_read(file, buffer, sizeof(buffer)); if (nbytes == 0) { break; // EOF } else if (nbytes < 0) { fprintf(stderr, "Error while reading file: %s\n", ssh_get_error(ggnfs_data.session)); sftp_close(file); return SSH_ERROR; } nwritten = write(fd, buffer, nbytes); if (nwritten != nbytes) { fprintf(stderr, "Error writing: %s\n", strerror(errno)); sftp_close(file); return SSH_ERROR; } } fprintf(stderr, "AFTER for loop to read -> : %s\n", localFilePath); rc = sftp_close(file); if (rc != SSH_OK) { fprintf(stderr, "Can't close the read file: %s\n", ssh_get_error(ggnfs_data.session)); return rc; } fi->fh = fd; return EXIT_SUCCESS; }
static int do_read(const char* infile, FILE* fp, getmode_t mode, ftp_transfer_func hookf, uint64_t offset) { if (gvSSHTrySCP && !offset) { char* escaped = bash_backslash_quote(infile); /* try to set up a scp connection */ ssh_scp scp = ssh_scp_new(ftp->session, SSH_SCP_READ, escaped); free(escaped); if (scp != NULL) { int rc = ssh_scp_init(scp); if (rc == SSH_OK) return do_scp_read(scp, infile, fp, mode, hookf); ssh_scp_free(scp); } } time_t then = time(NULL) - 1; ftp_set_close_handler(); if (hookf) hookf(&ftp->ti); ftp->ti.begin = false; /* check if remote file is not a directory */ sftp_attributes attrib = sftp_stat(ftp->sftp_session, infile); if (!attrib) return -1; if (S_ISDIR(attrib->permissions)) { ftp_err(_("Cannot download a directory: %s\n"), infile); sftp_attributes_free(attrib); return -1; } sftp_attributes_free(attrib); /* open remote file */ sftp_file file = sftp_open(ftp->sftp_session, infile, O_RDONLY, 0); if (!file) { ftp_err(_("Cannot open file for reading: %s\n"), ssh_get_error(ftp->session)); return -1; } /* seek to offset */ int r = sftp_seek64(file, offset); if (r != SSH_OK) { ftp_err(_("Failed to seek: %s\n"), ssh_get_error(ftp->session)); sftp_close(file); return -1; } /* read file */ char buffer[SSH_BUFSIZ]; ssize_t nbytes = 0; while ((nbytes = sftp_read(file, buffer, sizeof(buffer))) > 0) { if (ftp_sigints() > 0) { ftp_trace("break due to sigint\n"); break; } errno = 0; if (fwrite(buffer, nbytes, 1, fp) != 1) { ftp_err(_("Error while writing to file: %s\n"), strerror(errno)); ftp->ti.ioerror = true; sftp_close(file); return -1; } ftp->ti.size += nbytes; if (hookf) { time_t now = time(NULL); if (now > then) { hookf(&ftp->ti); then = now; } } } if (nbytes < 0) { ftp_err(_("Error while reading from file: %s\n"), ssh_get_error(ftp->session)); r = -1; } sftp_close(file); return r; }
int ggnfs_flush(const char *path, struct fuse_file_info *fi) { int retstat = 0; int nbytes; /* open the local version to read and update the remorte file */ char localFilePath[PATH_MAX] ; ggnfs_fullLocalpath(localFilePath, path); fprintf(stderr, "localPath : %s\n", localFilePath); char buffer[MAX_XFER_BUF_SIZE]; int access_type = O_WRONLY | O_CREAT | O_TRUNC; sftp_file file; int rc, nwritten; fprintf(stderr, "localPath : %s\n", localFilePath); char filePath[PATH_MAX]; ggnfs_fullRemotepath(filePath, path); fprintf(stderr, "REMOTE localPath : %s\n", filePath); mode_t mode = fi->flags; file = sftp_open(ggnfs_data.sftp, filePath, access_type, mode);// S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); if (file == NULL) { fprintf(stderr, "Can't open file for writing: %s\n", ssh_get_error(ggnfs_data.session)); return SSH_ERROR; } fprintf(stderr, "before for loop localPath : %s\n", localFilePath); lseek(fi->fh, 0L, SEEK_SET); for (;;) { fprintf(stderr, "inside loop: \n"); nbytes = read(fi->fh, buffer, sizeof(buffer)); fprintf(stderr, "after reading: size : %d \n", nbytes); //retstat += nbytes; if (nbytes == 0) { break; // EOF } else if (nbytes < 0) { fprintf(stderr, "Error while reading file: %s\n", strerror(errno)); close(file); return SSH_ERROR; } fprintf(stderr, "before sfpt_write: \n"); nwritten = sftp_write(file, buffer, nbytes); fprintf(stderr, "after sfpt_write: \n"); if (nwritten != nbytes) { fprintf(stderr, "Error writing: %s\n", strerror(errno)); sftp_close(file); return SSH_ERROR; } } rc = sftp_close(file); if (rc != SSH_OK) { fprintf(stderr, "Can't close the written file: %s\n", ssh_get_error(ggnfs_data.session)); return rc; } //close(fi->fh); fprintf(stderr, "localPath : %s\n", localFilePath); return EXIT_SUCCESS; }
/* it's just a proof of concept code for sftp, till i write a real documentation about it */ void do_sftp(SSH_SESSION *session){ SFTP_SESSION *sftp=sftp_new(session); SFTP_DIR *dir; SFTP_ATTRIBUTES *file; SFTP_FILE *fichier; SFTP_FILE *to; int len=1; int i; char data[8000]; if(!sftp){ ssh_say(0,"sftp error initialising channel : %s\n",ssh_get_error(session)); return; } if(sftp_init(sftp)){ ssh_say(0,"error initialising sftp : %s\n",ssh_get_error(session)); return; } /* the connection is made */ /* opening a directory */ dir=sftp_opendir(sftp,"./"); if(!dir) { ssh_say(0,"Directory not opened(%s)\n",ssh_get_error(session)); return ; } /* reading the whole directory, file by file */ while((file=sftp_readdir(sftp,dir))){ ssh_say(0,"%30s(%.8lo) : %.5d.%.5d : %.10lld bytes\n",file->name,file->permissions,file->uid,file->gid,file->size); sftp_attributes_free(file); } /* when file=NULL, an error has occured OR the directory listing is end of file */ if(!sftp_dir_eof(dir)){ ssh_say(0,"error : %s\n",ssh_get_error(session)); return; } if(sftp_dir_close(dir)){ ssh_say(0,"Error : %s\n",ssh_get_error(session)); return; } /* this will open a file and copy it into your /home directory */ /* the small buffer size was intended to stress the library. of course, you can use a buffer till 20kbytes without problem */ fichier=sftp_open(sftp,"/usr/bin/ssh",O_RDONLY,NULL); if(!fichier){ ssh_say(0,"Error opening /usr/bin/ssh : %s\n",ssh_get_error(session)); return; } /* open a file for writing... */ to=sftp_open(sftp,"ssh-copy",O_WRONLY | O_CREAT,NULL); if(!to){ ssh_say(0,"Error opening ssh-copy for writing : %s\n",ssh_get_error(session)); return; } while((len=sftp_read(fichier,data,4096)) > 0){ if(sftp_write(to,data,len)!=len){ ssh_say(0,"error writing %d bytes : %s\n",len,ssh_get_error(session)); return; } } printf("finished\n"); if(len<0) ssh_say(0,"Error reading file : %s\n",ssh_get_error(session)); sftp_file_close(fichier); sftp_file_close(to); printf("fichiers ferm�\n"); to=sftp_open(sftp,"/tmp/grosfichier",O_WRONLY|O_CREAT,NULL); for(i=0;i<1000;++i){ len=sftp_write(to,data,8000); printf("wrote %d bytes\n",len); if(len != 8000){ printf("chunk %d : %d (%s)\n",i,len,ssh_get_error(session)); } } sftp_file_close(to); /* close the sftp session */ sftp_free(sftp); printf("session sftp termin�\n"); }