예제 #1
0
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));
    }
}
예제 #2
0
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);
}
예제 #3
0
int FSSftp::Write ( int fd, void* buf, int size, int* err, FSCInfo* info )
{
	MutexLock lock( &mutex );

	int ret = CheckSession( err, info ); //???

	if ( ret ) { return ret; }

	if ( fd < 0 || fd >= MAX_FILES || !fileTable[fd] )
	{
		if ( err ) { *err = EINVAL; }

		return -1;
	}


	/*
	   Бля, libssh похоже какие-то уроды пишут
	   при size 65536 портит данные, если 16к то нормально, пришлось уменьшить,
	   а вот читать такие блоки - читает.
	   хотя надо и там уменьшить, кто этих пидоров знает

	   а было - так
	   int bytes = sftp_write(fileTable[fd], buf, size);
	*/

	int bytes = 0;
	char* s = ( char* )buf;

	while ( size > 0 )
	{
		int n = size;

		if ( n > 0x4000 )
		{
			n = 0x4000;
		}

		int ret = sftp_write( fileTable[fd], s, n );

		if ( ret < 0 )
		{
			if ( err ) { *err = sftp_get_error( sftpSession ); }

			return -1;
		}

		if ( !ret ) { break; }

		s += ret;
		size -= ret;
		bytes += ret;
	}

	return bytes;
}
예제 #4
0
static ssize_t _sftp_write(csync_vio_method_handle_t *fhandle, const void *buf, size_t count) {
  int rc = -1;

  rc = sftp_write(fhandle, (void *) buf, count);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  return rc;
}
예제 #5
0
파일: main.c 프로젝트: Paxxi/libssh
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;
}
예제 #6
0
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);
}
예제 #7
0
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; 

}
예제 #8
0
/* 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");
}
예제 #9
0
파일: ssh_cmd.c 프로젝트: casualuser/yafc
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;

}
예제 #10
0
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");
}