Пример #1
0
SshFsModel::SshFsModel(QSharedPointer<ssh_session_struct> ssh, QObject *parent) :
    QAbstractItemModel(parent), _ssh(ssh)
{
    _sftp = QSharedPointer<sftp_session_struct>(sftp_new(ssh.data()), sftp_free);

    if (sftp_init(_sftp.data()) != SSH_OK)
    {
        fprintf(stderr, "Error initializing SFTP session: %s.\n", sftp_get_error(_sftp.data()));
    }
}
Пример #2
0
    void SSH::openSftp() {
        if (sftp_) return;

        sftp_ = sftp_new(session_);
        if (sftp_ == NULL) {
            throw Error(1, "Unable to create the the sftp session");
        }
        if (sftp_init(sftp_) != SSH_OK) {
            sftp_free(sftp_);
            throw Error(1, "Error initializing SFTP session");
        }
    }
Пример #3
0
gboolean
remmina_sftp_open (RemminaSFTP *sftp)
{
	sftp->sftp_sess = sftp_new (sftp->ssh.session);
	if (!sftp->sftp_sess)
	{
		remmina_ssh_set_error (REMMINA_SSH (sftp), _("Failed to create sftp session: %s"));
		return FALSE;
	}
	if (sftp_init (sftp->sftp_sess))
	{
		remmina_ssh_set_error (REMMINA_SSH (sftp), _("Failed to initialize sftp session: %s"));
		return FALSE;
	}
	return TRUE;
}
Пример #4
0
void clSFTP::Initialize() throw(clException)
{
    if(m_sftp) return;

    m_sftp = sftp_new(m_ssh->GetSession());
    if(m_sftp == NULL) {
        throw clException(wxString() << "Error allocating SFTP session: " << ssh_get_error(m_ssh->GetSession()));
    }

    int rc = sftp_init(m_sftp);
    if(rc != SSH_OK) {
        throw clException(wxString() << "Error initializing SFTP session: " << ssh_get_error(m_ssh->GetSession()),
                          sftp_get_error(m_sftp));
    }
    m_connected = true;
}
Пример #5
0
sftp_session sn_sftp_get_session(ssh_session session) {
	sftp_session s = sftp_new(session);

	if (!s) {
		std::cerr << "[sftp\tfail] Error allocating SFTP session: " << ssh_get_error(session)
			<< std::endl;
		exit(ERR_SFTP_ALLOC_SESSION);
	}

	int rc = sftp_init(s);
	if (rc != SSH_OK) {
		std::cerr << "Error initializing SFTP session: " << sftp_get_error(s) << std::endl;
		sftp_free(s);
		exit(ERR_SFTP_INIT_SESSION);
	}

	return s;
}
Пример #6
0
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;
}
Пример #7
0
static sftp_session create_sftp_session(){
       perror("Inside getattr");
        sftp_session sftp = sftp_new(con.my_ssh_session);
        if (sftp == NULL)
            {
                fprintf(stderr, "Error allocating SFTP session: %s\n",
                ssh_get_error(con.my_ssh_session));
                return NULL;
             }
        perror("sftp established");

        int rc = sftp_init(sftp);
        perror("after init");
        if (rc != SSH_OK)
        {
                fprintf(stderr, "Error initializing SFTP session: %s.\n",
                sftp_get_error(sftp));
                sftp_free(sftp);
                return NULL;
        }
	return sftp;
}
Пример #8
0
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;
}
Пример #9
0
int main(int argc, char *argv[])
{
    int fuse_stat;
    ggnfs_data.remoteHost =argv[1];
    ggnfs_data.rootdir = realpath(argv[2], NULL);
    
    printf("hostname -> %s\n", ggnfs_data.remoteHost);
    printf("rootdir -> %s\n", ggnfs_data.rootdir);
    /* start new ssh session */
    int rc;
    ggnfs_data.session = ssh_new();
    if (ggnfs_data.session == NULL)
        exit(-1);
        
     ssh_options_set(ggnfs_data.session, SSH_OPTIONS_HOST, ggnfs_data.remoteHost);   
     rc = ssh_connect(ggnfs_data.session);
     if (rc != SSH_OK)
        {
            fprintf(stderr, "Error connecting to remoteHost: %s\n",
            ssh_get_error(ggnfs_data.session));
            ssh_free(ggnfs_data.session);
            exit(-1);
        }
        // Verify the server's identity
        // For the source code of verify_knowhost(), check previous example
        if (verify_knownhost(ggnfs_data.session) < 0)
        {
            ssh_disconnect(ggnfs_data.session);
            ssh_free(ggnfs_data.session);
            exit(-1);
        }
        // Authenticate ourselves
        //char * password = "******";// getpass("Password: "******"Error authenticating with password: %s\n",
            ssh_get_error(ggnfs_data.session));
            ssh_disconnect(ggnfs_data.session);
            ssh_free(ggnfs_data.session);
            exit(-1);
        }
     

    /** making sftp session **/
    int rc_sftp;
    ggnfs_data.sftp = sftp_new(ggnfs_data.session);
    if (ggnfs_data.sftp == NULL)
    {
         fprintf(stderr, "Error allocating SFTP session: %s\n",
         ssh_get_error(ggnfs_data.session));
     //    return SSH_ERROR;
     }

    rc_sftp = sftp_init(ggnfs_data.sftp);
    if (rc_sftp != SSH_OK)
    {
         fprintf(stderr, "Error initializing SFTP session: %s.\n",
         sftp_get_error(ggnfs_data.sftp));
         sftp_free(ggnfs_data.sftp);
      //   return rc;
    }

	 
    /* Adjusting agruments to pass to FUSE mount function*/
    int i = 1;
    for(; i < argc; ++i) {
      argv[i] = argv[i+1];
    }
      argv[argc-1] = NULL;
      argc--;

    /*** TESTING: status working ***/
    //printf("show_remote_ls\n");
    //show_remote_ls(ggnfs_data->session);
    sftp_list_dir(ggnfs_data.session, ggnfs_data.sftp);


    printf("about to call fuse_main\n");
    fuse_stat = fuse_main(argc, argv, &ggnfs_oper, NULL);
    printf("fuse_main returned %d\n", fuse_stat);

    ssh_disconnect(ggnfs_data.session);
    ssh_free(ggnfs_data.session);
    sftp_free(ggnfs_data.sftp);
    return fuse_stat;

}
Пример #10
0
static int _sftp_connect(const char *uri) {
  char *scheme = NULL;
  char *user = NULL;
  char *passwd = NULL;
  char *host = NULL;
  unsigned int port = 0;
  char *path = NULL;
  unsigned char *hash = NULL;
  int hlen;
  int rc = -1;
  int state = SSH_SERVER_ERROR;
  int timeout = 10;
  int method;
  char *verbosity;

  if (_connected) {
    return 0;
  }

  rc = c_parse_uri(uri, &scheme, &user, &passwd, &host, &port, &path);
  if (rc < 0) {
    goto out;
  }

  DEBUG_SFTP(("csync_sftp - conntecting to: %s\n", host));

  /* create the session */
  _ssh_session = ssh_new();
  if (_ssh_session == NULL) {
    fprintf(stderr, "csync_sftp - error creating new connection: %s\n",
        strerror(errno));
    rc = -1;
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_TIMEOUT, &timeout);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_COMPRESSION_C_S, "none");
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_COMPRESSION_S_C, "none");
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  ssh_options_set(_ssh_session, SSH_OPTIONS_HOST, host);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  if (port) {
    ssh_options_set(_ssh_session, SSH_OPTIONS_PORT, &port);
    if (rc < 0) {
      fprintf(stderr, "csync_sftp - error setting options: %s\n",
          strerror(errno));
      goto out;
    }
    DEBUG_SFTP(("csync_sftp - port set to: %d\n", port));
  }

  if (user && *user) {
    ssh_options_set(_ssh_session, SSH_OPTIONS_USER, user);
    if (rc < 0) {
      fprintf(stderr, "csync_sftp - error setting options: %s\n",
          strerror(errno));
      goto out;
    }
    DEBUG_SFTP(("csync_sftp - username set to: %s\n", user));
  }

  verbosity = getenv("CSYNC_SFTP_LOG_VERBOSITY");
  if (verbosity) {
    rc = ssh_options_set(_ssh_session, SSH_OPTIONS_LOG_VERBOSITY_STR, verbosity);
    if (rc < 0) {
      goto out;
    }
  }

  /* read ~/.ssh/config */
  rc = ssh_options_parse_config(_ssh_session, NULL);
  if (rc < 0) {
    goto out;
  }

  _ssh_callbacks = (ssh_callbacks) c_malloc(sizeof(struct ssh_callbacks_struct));
  if (_ssh_callbacks == NULL) {
    rc = -1;
    goto out;
  }
  ZERO_STRUCTP(_ssh_callbacks);

  _ssh_callbacks->userdata = _userdata;
  _ssh_callbacks->auth_function = _ssh_auth_callback;

  ssh_callbacks_init(_ssh_callbacks);

  ssh_set_callbacks(_ssh_session, _ssh_callbacks);

  rc = ssh_connect(_ssh_session);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n", ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  hlen = ssh_get_pubkey_hash(_ssh_session, &hash);
  if (hlen < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n",
        ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  /* check the server public key hash */
  state = ssh_is_server_known(_ssh_session);
  switch (state) {
    case SSH_SERVER_KNOWN_OK:
      break;
    case SSH_SERVER_KNOWN_CHANGED:
      fprintf(stderr, "csync_sftp - The host key for this server was "
            "not found, but another type of key exists.\n"
            "An attacker might change the default server key to confuse your "
            "client into thinking the key does not exist.\n"
            "Please contact your system administrator.\n"
            "%s\n", ssh_get_error(_ssh_session));
      ssh_print_hexa("csync_sftp - public key hash", hash, hlen);

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_FOUND_OTHER:
      fprintf(stderr, "csync_sftp - the host key for this server was not "
          "found but an other type of key exists.\n");
      fprintf(stderr, "csync_sftp - an attacker might change the default "
          "server key to confuse your client into thinking the key does not "
          "exist\n");
      fprintf(stderr, "The host key for the server %s has changed.\n"
          "This could either mean that DNS SPOOFING is happening or the IP "
          "address for the host and its host key have changed at the same time.\n"
          "The fingerprint for the key sent by the remote host is:\n", host);
          ssh_print_hexa("", hash, hlen);
          fprintf(stderr, "Please contact your system administrator.\n"
          "%s\n", ssh_get_error(_ssh_session));

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_NOT_KNOWN:
      if (_authcb) {
        char *hexa;
        char *prompt;
        char buf[4] = {0};

        hexa = ssh_get_hexa(hash, hlen);
        if (hexa == NULL) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        if (asprintf(&prompt,
              "The authenticity of host '%s' can't be established.\n"
              "RSA key fingerprint is %s.\n"
              "Are you sure you want to continue connecting (yes/no)?",
              host, hexa) < 0 ) {
          free(hexa);
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        free(hexa);

        if ((*_authcb)(prompt, buf, sizeof(buf), 1, 0, _userdata) < 0) {
          free(prompt);
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        free(prompt);

        if (strncasecmp(buf, "yes", 3) != 0) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        if (ssh_write_knownhost(_ssh_session) < 0) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }
      } else {
        fprintf(stderr,"csync_sftp - the server is unknown. Connect manually to "
            "the host to retrieve the public key hash, then try again.\n");
      }
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_ERROR:
      fprintf(stderr, "%s\n", ssh_get_error(_ssh_session));

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    default:
      break;
  }

  /* Try to authenticate */
  rc = ssh_userauth_none(_ssh_session, NULL);
  if (rc == SSH_AUTH_ERROR) {
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
  }

#if 0
  /* authenticate with the server */
  if (passwd && *passwd) {
    DEBUG_SFTP(("csync_sftp - authenticating with user/password\n"));
    /*
     * This is tunneled cleartext password authentication and possibly needs
     * to be allowed by the ssh server. Set 'PasswordAuthentication yes'
     */
    auth = ssh_userauth_password(_ssh_session, user, passwd);
  } else {
    DEBUG_SFTP(("csync_sftp - authenticating with pubkey\n"));
    auth = ssh_userauth_autopubkey(_ssh_session, NULL);
  }

  if (auth == SSH_AUTH_ERROR) {
    fprintf(stderr, "csync_sftp - authenticating with pubkey: %s\n",
        ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    rc = -1;
    goto out;
  }

  if (auth != SSH_AUTH_SUCCESS) {
    if (_authcb != NULL) {
      auth = auth_kbdint(_ssh_session);
      if (auth == SSH_AUTH_ERROR) {
        fprintf(stderr,"csync_sftp - authentication failed: %s\n",
            ssh_get_error(_ssh_session));
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      }
    } else {
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
    }
  }


#endif
  method = ssh_auth_list(_ssh_session);

  while (rc != SSH_AUTH_SUCCESS) {
    /* Try to authenticate with public key first */
    if (method & SSH_AUTH_METHOD_PUBLICKEY) {
      rc = ssh_userauth_autopubkey(_ssh_session, NULL);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }

    /* Try to authenticate with keyboard interactive */
    if (method & SSH_AUTH_METHOD_INTERACTIVE) {
      rc = auth_kbdint(_ssh_session, user, passwd);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }

    /* Try to authenticate with password */
    if ((method & SSH_AUTH_METHOD_PASSWORD) && passwd && *passwd) {
      rc = ssh_userauth_password(_ssh_session, user, passwd);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }
  }

  DEBUG_SFTP(("csync_sftp - creating sftp channel...\n"));
  /* start the sftp session */
  _sftp_session = sftp_new(_ssh_session);
  if (_sftp_session == NULL) {
    fprintf(stderr, "csync_sftp - sftp error initialising channel: %s\n", ssh_get_error(_ssh_session));
    rc = -1;
    goto out;
  }

  rc = sftp_init(_sftp_session);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error initialising sftp: %s\n", ssh_get_error(_ssh_session));
    goto out;
  }

  DEBUG_SFTP(("csync_sftp - connection established...\n"));
  _connected = 1;
  rc = 0;
out:
  SAFE_FREE(scheme);
  SAFE_FREE(user);
  SAFE_FREE(passwd);
  SAFE_FREE(host);
  SAFE_FREE(path);
  SAFE_FREE(hash);

  return rc;
}
Пример #11
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");
}
Пример #12
0
int ssh_open_url(url_t* urlp)
{
  ftp->session = ssh_new();
  if (!ftp->session)
    return -1;

  /* set log level */
  if (ftp_get_verbosity() == vbDebug)
  {
    int verbosity = SSH_LOG_PROTOCOL;
    ssh_options_set(ftp->session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
  }

  /* If we have ssh options from yafcrc, load them */
  if (gvSSHOptions) {
    args_t *args = args_create();
    args_init(args, 0, NULL);
    args_push_back(args, gvSSHOptions);
    int argc = 0;
    if (ssh_options_getopt(ftp->session, &argc, args->argv) != SSH_OK) {
      ftp_err(_("Failed to load SSH options from yafcrc config (ssh_options = '%s')\n"), gvSSHOptions);
      ssh_free(ftp->session);
      ftp->session = NULL;
      return -1;
    }
    args->argc = argc;
    args_destroy(args);
  }

  /* set host name */
  ssh_options_set(ftp->session, SSH_OPTIONS_HOST, urlp->hostname);
  /* if we have port use that one */
  if (urlp->port > 0)
    ssh_options_set(ftp->session, SSH_OPTIONS_PORT, &urlp->port);

  /* parse .ssh/config */
  int r = ssh_options_parse_config(ftp->session, NULL);
  if (r != SSH_OK)
  {
    ftp_err(_("Failed to parse ssh config: %s\n"), ssh_get_error(ftp->session));
    ssh_free(ftp->session);
    ftp->session = NULL;
    return r;
  }

  /* if we have username use that one */
  if (urlp->username)
    ssh_options_set(ftp->session, SSH_OPTIONS_USER, urlp->username);

  /* connect to server */
  r = ssh_connect(ftp->session);
  if (r != SSH_OK)
  {
    ftp_err(_("Couldn't initialise connection to server: %s\n"), ssh_get_error(ftp->session));
    ssh_free(ftp->session);
    ftp->session = NULL;
    return r;
  }

  /* verify server */
  if (verify_knownhost(ftp->session))
  {
    ssh_disconnect(ftp->session);
    ssh_free(ftp->session);
    ftp->session = NULL;
    return -1;
  }

  /* authenticate user */
  r = test_several_auth_methods(ftp->session, urlp);
  if (r != SSH_OK)
  {
    ftp_err(_("Authentication failed: %s\n"), ssh_get_error(ftp->session));
    ssh_disconnect(ftp->session);
    ssh_free(ftp->session);
    ftp->session = NULL;
    return -1;
  }

  ftp->ssh_version = ssh_get_version(ftp->session);
  if (!ftp->ssh_version) {
    ftp_err(_("Couldn't initialise connection to server\n"));
    return -1;
  }

  ftp->sftp_session = sftp_new(ftp->session);
  if (!ftp->sftp_session)
  {
    ftp_err(_("Couldn't initialise ftp subsystem: %s\n"), ssh_get_error(ftp->session));
    ssh_disconnect(ftp->session);
    ssh_free(ftp->session);
    ftp->session = NULL;
    return -1;
  }

  r = sftp_init(ftp->sftp_session);
  if (r != SSH_OK)
  {
    ftp_err(_("Couldn't initialise ftp subsystem: %s\n"), ssh_get_error(ftp->sftp_session));
    sftp_free(ftp->sftp_session);
    ftp->sftp_session = NULL;
    ssh_disconnect(ftp->session);
    ssh_free(ftp->session);
    ftp->session = NULL;
    return r;
  }

  ftp->connected = true;
  ftp->loggedin = true;

  free(ftp->homedir);
  ftp->homedir = ftp_getcurdir();

  url_destroy(ftp->url);
  ftp->url = url_clone(urlp);

  free(ftp->curdir);
  ftp->curdir = xstrdup(ftp->homedir);
  free(ftp->prevdir);
  ftp->prevdir = xstrdup(ftp->homedir);
  if (ftp->url->directory)
    ftp_chdir(ftp->url->directory);

  ftp_get_feat();
  return 0;
}
Пример #13
0
static void do_sftp(ssh_session session)
{
	sftp_session sftp=sftp_new(session);
	sftp_dir dir;
	sftp_attributes file;
	char datex[11];
	time_t atime=0;
#ifdef WIN32
	struct tm *mytime=NULL;
	int x=0;
#endif

	if(!sftp)
	{
		prterr("sftp error initialising channel: %s\n",ssh_get_error(session));
		return;
	}
	if(sftp_init(sftp))
	{
        	prterr("error initializing sftp: %s\n",ssh_get_error(session));
		return;
	}
	dir=sftp_opendir(sftp,docfolder);
	if(!dir) 
	{
		prterr("Directory not opened(%s)\n", ssh_get_error(session));
		return;
	}
/* reading the whole directory, file by file */
	while((file=sftp_readdir(sftp,dir)))
	{
		if(strncmp(file->name,".",1))
		{
			if(details==FALSE)
			{
				fprintf(stdout,"%s\r\n",file->name);
			} else {
#ifndef WIN32
#ifdef _POSIX_SOURCE
				atime=file->atime;
				strftime(datex,11,"%m/%d/%Y",localtime(&atime));
#else
				ascftime(datex,"%m/%d/%Y",localtime(&file->atime));
#endif /* _POSIX_SOURCE */
#else /* WIN32 */
				mytime=localctime(&file->atime);
				x=mytime->tm_year;
				while(x>=200) x-=100;
				sprintf(datex,"%02d/%02d/%04d",mytime->tm_mon+1,mytime->tm_mday,1900+my_time->tm_year);
#endif
				fprintf(stdout,"%s\t%llu\t%s\r\n",file->name,(long long unsigned int) file->size,datex);
			}
		}
		if(diagapps)
		{
		prterr("%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))
	{
		prterr("Error: %s\n", ssh_get_error(session));
		return;
	}
	if(sftp_closedir(dir))
	{
		prterr("Error: %s\n", ssh_get_error(session));
		return;
	}
	sftp_free(sftp);
}
Пример #14
0
static int sftp_list_file(ssh_session session,char *remote_dir,char *remote_file)
{
	sftp_attributes file;
	char datex[22];
	char mtemp[1024];
	time_t mtime=0;
#ifdef WIN32
	struct tm *mytime=NULL;
	int x=0;
#endif
	sftp_session sftp=sftp_new(session);

	if(!sftp)
	{
		prterr("sftp error initialising channel: %s\n",ssh_get_error(session));
		return(1);
	}
	if(sftp_init(sftp))
	{
        	prterr("error initializing sftp: %s\n",ssh_get_error(session));
		return(1);
	}
	
	memset(datex,0,22);
	memset(mtemp,0,1024);
	if(isEMPTY(remote_dir) || !RDAstrcmp(remote_dir,"\"\""))
	{
		sprintf(mtemp,"%s",remote_file);
	} else {
		sprintf(mtemp,"%s/%s",remote_dir,remote_file);
	}
	file=sftp_stat(sftp,mtemp);
	if(file==NULL)
	{
		/* when file=NULL, an error has occured OR the directory listing is end of file */
		prterr("Error getting file info for [%s]",mtemp);
		sftp_free(sftp);
		return(1);
	}else{
	

#ifndef WIN32
#ifdef _POSIX_SOURCE
		mtime=file->mtime;
		//strftime(datex,22,"%b %d %Y %l:%M %p",localtime(&file->mtime));
		strftime(datex,22,"%b %d %Y %l:%M %p",localtime(&mtime));
#else
		TRACE;
		ascftime(datex,"%b %d %Y %l:%M %p",localtime(&file->mtime));
#endif /* _POSIX_SOURCE */
#else /* WIN32 */
		TRACE;
		mytime=localctime(&file->mtime);
		x=mytime->tm_year;
		while(x>=200) x-=100;
		sprintf(datex,"%02d/%02d/%04d  ",mytime->tm_mon+1,mytime->tm_mday,1900+my_time->tm_year);
#endif
		fprintf(stdout,"%s\t\t%llu\t\t%s\r\n",remote_file,(long long unsigned int) file->size,datex);

		if(diagapps)
		{
		prterr("\"%30s\"(%.8o) : %s(%.5d) %s(%.5d) : %.10llu bytes  %.10llu\n",
			file->name,
			file->permissions,
			file->owner,
			file->uid,
			file->group,
			file->gid,
			(long long unsigned int) file->size,
			(long long unsigned int) file->mtime);
		}
		sftp_attributes_free(file);
	}
	sftp_free(sftp);
	return(0);
}
Пример #15
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");
}
Пример #16
0
int FSSftp::CheckSession( int* err, FSCInfo* info )
{
	if ( sshSession ) { return 0; }

	try
	{
		sshSession = ssh_new();

		if ( !sshSession ) { throw int( SSH_INTERROR_X3 ); }

		if ( ssh_options_set( sshSession, SSH_OPTIONS_HOST, unicode_to_utf8( _operParam.server.Data() ).ptr() ) )
		{
			throw int( SSH_INTERROR_X3 );
		}

		int port = _operParam.port;

		if ( ssh_options_set( sshSession, SSH_OPTIONS_PORT, &port ) )
		{
			throw int( SSH_INTERROR_X3 );
		}


		FSString userName = "";

		if ( _operParam.user.Data()[0] )
		{
			userName = _operParam.user.Data();
		}
		else
		{
			char* ret = getenv( "LOGNAME" );

			if ( ret )
			{
				userName = FSString( sys_charset_id, ret );
				_operParam.user = userName.GetUnicode();

				MutexLock infoLock( &infoMutex );
				_infoParam.user = userName.GetUnicode();
			}
		};

		if ( ssh_options_set( sshSession, SSH_OPTIONS_USER, ( char* )userName.Get( _operParam.charset ) ) ) //есть сомнения, что надо все таки в utf8
		{
			throw int( SSH_INTERROR_X3 );
		}

		if ( ssh_connect( sshSession ) != SSH_OK )
		{
			throw int( SSH_INTERROR_CONNECT );
		}


		int method = ssh_userauth_list( sshSession, 0 );

		int ret;


		static unicode_t userSymbol = '@';

		if ( method & SSH_AUTH_METHOD_PASSWORD )
		{
			FSPromptData data;
			data.visible = false;
			data.prompt = utf8_to_unicode( "Password:"******"SFTP_" ).ptr(),
			        carray_cat<unicode_t>( userName.GetUnicode(), &userSymbol, _operParam.server.Data() ).ptr(),
			        &data, 1 ) ) { throw int( SSH_INTERROR_STOPPED ); }

			ret = ssh_userauth_password( sshSession,
			                             ( char* )FSString( _operParam.user.Data() ).Get( _operParam.charset ),
			                             ( char* )FSString( data.prompt.Data() ).Get( _operParam.charset ) );
		}

		if ( ret != SSH_AUTH_SUCCESS &&
		     ( method & SSH_AUTH_METHOD_INTERACTIVE ) != 0 )
		{
			while ( true )
			{
				ret = ssh_userauth_kbdint( sshSession, 0, 0 );

				if ( ret != SSH_AUTH_INFO ) { break; }

				const char* instruction = ssh_userauth_kbdint_getinstruction( sshSession );

				if ( !instruction ) { instruction = ""; }

				int n = ssh_userauth_kbdint_getnprompts( sshSession );

				if ( n <= 0 ) { continue; }

				std::vector<FSPromptData> pData( n );
				int i;

				for ( i = 0; i < n; i++ )
				{
					char echo;
					const char* prompt = ssh_userauth_kbdint_getprompt( sshSession, i, &echo );

					if ( !prompt ) { break; }

					pData[i].visible = echo != 0;
					pData[i].prompt = utf8_to_unicode( prompt ).ptr();
				}

				if ( !info ) { throw int( SSH_INTERROR_AUTH ); }

				if ( !info->Prompt(
				        utf8_to_unicode( "SFTP" ).ptr(),
				        carray_cat<unicode_t>( userName.GetUnicode(), &userSymbol, _operParam.server.Data() ).ptr(),
				        pData.ptr(), n ) ) { throw int( SSH_INTERROR_STOPPED ); }

				for ( i = 0; i < n; i++ )
				{
					if ( ssh_userauth_kbdint_setanswer( sshSession, i, ( char* )FSString( pData[i].prompt.Data() ).Get( _operParam.charset ) ) < 0 )
					{
						throw int( SSH_INTERROR_AUTH );
					}
				}
			}
		}

		if ( ret != SSH_AUTH_SUCCESS )
		{
			if ( ret == SSH_AUTH_PARTIAL )
			{
				throw int( SSH_INTERROR_UNSUPPORTED_AUTH );
			}
			else
			{
				throw int( SSH_INTERROR_AUTH );
			}
		}

		sftpSession = sftp_new( sshSession );

		if ( !sftpSession ) { throw int( SSH_INTERROR_FATAL ); }

		if ( sftp_init( sftpSession ) != SSH_OK ) { throw int( SSH_INTERROR_FATAL ); }

	}
	catch ( int e )
	{
		if ( err ) { *err = e; }

		if ( sftpSession ) { sftp_free( sftpSession ); }

		if ( sshSession ) { ssh_free( sshSession ); }

		sshSession = 0;
		sftpSession = 0;
		return ( e == SSH_INTERROR_STOPPED ) ? -2 : -1;
	}

	return 0;
}