void PJSSH::GetFile(const char* aRemoteFileName, std::ostream& aStream) const { LIBSSH2_SFTP* sftp = libssh2_sftp_init(mSession); if( NULL == sftp ) { throw std::runtime_error("Failed to open a sftp session."); } LIBSSH2_SFTP_HANDLE* file_handle = libssh2_sftp_open(sftp,aRemoteFileName,LIBSSH2_FXF_READ,0); if( NULL == file_handle ) { std::ostringstream o; o<<"Failed to open remote file for reading. Last error code=" <<libssh2_sftp_last_error(sftp); throw std::runtime_error(o.str()); } // Read the whole file and write the read data on the supplied stream. char buffer[1024]; size_t num_of_read_bytes(0); do { num_of_read_bytes = libssh2_sftp_read(file_handle,buffer,1024); aStream.write(buffer,num_of_read_bytes); } while( num_of_read_bytes == 1024 ); // Close sftp file handle and end SFTP session. libssh2_sftp_close_handle(file_handle); libssh2_sftp_shutdown(sftp); }
guac_stream* guac_sftp_download_file(guac_client* client, char* filename) { ssh_guac_client_data* client_data = (ssh_guac_client_data*) client->data; guac_stream* stream; LIBSSH2_SFTP_HANDLE* file; /* Attempt to open file for reading */ file = libssh2_sftp_open(client_data->sftp_session, filename, LIBSSH2_FXF_READ, 0); if (file == NULL) { guac_client_log_error(client, "Unable to read file \"%s\": %s", filename, libssh2_sftp_last_error(client_data->sftp_session)); return NULL; } /* Allocate stream */ stream = guac_client_alloc_stream(client); stream->ack_handler = guac_sftp_ack_handler; stream->data = file; /* Send stream start, strip name */ filename = basename(filename); guac_protocol_send_file(client->socket, stream, "application/octet-stream", filename); guac_socket_flush(client->socket); return stream; }
void getClient(char * serverAddress) { int sockFd = makeSocketOrDie(); struct addrinfo * serverInfo = getServerInfo(serverAddress); printf("Connecting to server\n"); connectOrDie(sockFd, serverInfo); printf("Connected to server. Making LIBSSH2 session\n"); LIBSSH2_SESSION * session = makeSession(); libssh2_session_set_blocking(session, 1); libssh2_session_set_timeout(session, 5000); printf("Made session, handshaking\n"); int result = libssh2_session_handshake(session, sockFd); //const char * fingerprint = libssh2_hostkey_hash(session, LIBSSH_HOSTKEY_HASH_SHA1); //TODO: Match the fingerprint against something. if (result) { char * errorMessage; libssh2_session_last_error(session, &errorMessage, NULL, 0); fprintf(stderr, "Error %s handshaking\n", errorMessage); exit(EXIT_FAILURE); } printf("Handshake completed, making SFTP Session\n"); libssh2_userauth_password(session, NETID, PWD); LIBSSH2_SFTP * sftpSession = makeSFTPSession(session); printf("Started SFTP - Downloading file\n"); LIBSSH2_SFTP_HANDLE * fileHandle = libssh2_sftp_open(sftpSession, serverFilePath, LIBSSH2_FXF_READ, 0); readFile(session, sftpSession, fileHandle); libssh2_sftp_shutdown(sftpSession); libssh2_session_disconnect(session, "Done.\n"); libssh2_session_free(session); freeaddrinfo(serverInfo); close(sockFd); }
int SyncTransferThread::do_download(QString remote_path, QString local_path) { qDebug() <<__FUNCTION__<<": "<<__LINE__<<":"<< __FILE__; qDebug()<< "remote_path = "<< remote_path << " , local_path = " << local_path ; int pcnt = 0 ; int rlen , wlen ; int file_size , tran_len = 0 ; LIBSSH2_SFTP_HANDLE * sftp_handle ; LIBSSH2_SFTP_ATTRIBUTES ssh2_sftp_attrib; char buff[8192] = {0}; QString currFile; sftp_handle = libssh2_sftp_open(this->ssh2_sftp, GlobalOption::instance()->remote_codec->fromUnicode(remote_path), LIBSSH2_FXF_READ, 0); if (sftp_handle == NULL) { //TODO 错误消息通知用户。 qDebug()<<"open sftp file error :"<< libssh2_sftp_last_error(this->ssh2_sftp); return -1 ; } memset(&ssh2_sftp_attrib,0,sizeof(ssh2_sftp_attrib)); libssh2_sftp_fstat(sftp_handle,&ssh2_sftp_attrib); file_size = ssh2_sftp_attrib.filesize; qDebug()<<" remote file size :"<< file_size ; currFile = local_path.right(local_path.length() - this->local_base_path.length() - 1); emit this->syncFileStarted(currFile, file_size); // 本地编码 --> Qt 内部编码 QFile q_file(local_path); if (!q_file.open(QIODevice::ReadWrite|QIODevice::Truncate)) { //TODO 错误消息通知用户。 qDebug()<<"open local file error:"<< q_file.errorString() ; } else { //read remote file and then write to local file while ((rlen = libssh2_sftp_read(sftp_handle, buff, sizeof(buff))) > 0) { wlen = q_file.write( buff, rlen ); tran_len += wlen ; qDebug()<<"Read len :"<<rlen <<" , write len: "<<wlen <<" tran len: "<<tran_len ; //my progress signal if (file_size == 0) { emit this->transfer_percent_changed(currFile, 100, tran_len, wlen); } else { pcnt = 100.0 *((double)tran_len / (double)file_size); emit this->transfer_percent_changed(currFile, pcnt, tran_len, wlen); } } q_file.flush(); q_file.close(); } libssh2_sftp_close(sftp_handle); q_debug()<<"syncDownload done."; this->do_touch_local_file_with_time(local_path, SSHFileInfo(ssh2_sftp_attrib).lastModified()); emit this->syncFileStopped(currFile, 0); return 0; }
/* sftp打开文件接口(读) */ static int sftp_open_file_for_read(protocol_data_t *protocol, char *filepath) { if (protocol == NULL || protocol->protocol_data == NULL || filepath == NULL) { return -1; } sftp_data_t *data = (sftp_data_t *)protocol->protocol_data; data->file_handle = libssh2_sftp_open(data->sftp_session, filepath, LIBSSH2_FXF_READ, 0); return 0; }
/* sftp打开文件接口(写) */ static int sftp_open_file_for_write(protocol_data_t *protocol, char *filepath) { if (protocol == NULL || protocol->protocol_data == NULL || filepath == NULL) { return -1; } sftp_data_t *data = (sftp_data_t *)protocol->protocol_data; data->file_handle = libssh2_sftp_open(data->sftp_session, filepath, LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT| LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH); return 0; }
int FSSftp::OpenRead ( FSPath& path, int flags, 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; } try { LIBSSH2_SFTP_HANDLE* fd = 0; while ( true ) { fd = libssh2_sftp_open( sftpSession, ( char* )path.GetString( _operParam.charset, '/' ), LIBSSH2_FXF_READ, 0 ); if ( fd ) { break; } CheckSFTPEagain(); WaitSocket( info ); } fileTable[n] = fd; } catch ( int e ) { if ( err ) { *err = e; } return ( e == -2 ) ? -2 : -1; } return n; }
/** * @function SFTP.writeFile * * ### Synopsis * * var status = SFTP.writeFile(handle, srcPath, dstPath); * var status = SFTP.writeFile(handle, srcPath, dstPath, mode); * * Write file to remote server via SFTP. * * @param {object} handle - opaque handle to already open SFTP connection. * @param {string} srcPath - path to file in local file system to send. * @param {string} dstPath - path to file in remote file system to create. * @param {int} mode - desired resulting file permissions of file on remote end. * @return {boolean} success - true if the transfer succeeded. * * ### Note * If mode is not provided, the file mode of the file being sent will be used. */ static JSVAL sftp_writeFile (JSARGS args) { HandleScope scope; SFTP *handle = HANDLE(args[0]); String::Utf8Value srcPath(args[1]); String::Utf8Value dstPath(args[2]); int mode; struct stat fileinfo; if (stat(*srcPath, &fileinfo) != 0) { return scope.Close(String::New(strerror(errno))); } if (args.Length() > 3) { mode = args[3]->IntegerValue(); } else { mode = fileinfo.st_mode; } mode &= 0777; int fd = open(*srcPath, O_RDONLY); if (fd < 0) { return scope.Close(String::New(strerror(errno))); } LIBSSH2_SFTP_HANDLE *sftp_handle = libssh2_sftp_open(handle->sftp_session, *dstPath, LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC, mode); char mem[1024]; ssize_t toWrite = fileinfo.st_size; while (toWrite > 0) { ssize_t nRead = read(fd, mem, 1024); if (nRead < 0) { int eNum = errno; libssh2_sftp_close(sftp_handle); close(fd); errno = eNum; return scope.Close(False()); } int rc = libssh2_sftp_write(sftp_handle, mem, nRead); if (rc < 0) { libssh2_sftp_close(sftp_handle); close(fd); return scope.Close(False()); } toWrite -= nRead; } close(fd); libssh2_sftp_close(sftp_handle); return scope.Close(True()); }
/** * @function SFTP.stat * * ### Synopsis * * var stat = SFTP.stat(handle, path); * * Get attributes of a remote file. * * The returned object will be of the form: * * + size: size of file in bytes. * + permissions: file permissions. * + uid: uid of owner of file. * + gid: gid of owner of file. * + mtime: modification time (timestamp) of file. * + atime: access time (timestamp) of file * * @param {object} handle - opaque handle to existing SFTP connection (already connected). * @param {string} path - path on remote server to directory to get status of. * @returns {object} stat - object of the form described above. */ JSVAL sftp_stat (JSARGS args) { HandleScope scope; SFTP *handle = HANDLE(args[0]); String::Utf8Value path(args[1]); LIBSSH2_SFTP_HANDLE *sftp_handle = libssh2_sftp_open(handle->sftp_session, *path, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { return scope.Close(String::New("Could not get status for remote file")); } LIBSSH2_SFTP_ATTRIBUTES attrs; if (libssh2_sftp_fstat_ex(sftp_handle, &attrs, 0) < 0) { libssh2_sftp_close(sftp_handle); return scope.Close(String::New("Could not get status for remote file")); } Handle<String> _permissions = String::New("permissions"); Handle<String> _uid = String::New("uid"); Handle<String> _gid = String::New("gid"); Handle<String> _size = String::New("size"); Handle<String> _mtime = String::New("mtime"); Handle<String> _atime = String::New("atime"); JSOBJ o = Object::New(); if (attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) { o->Set(_size, Integer::New(attrs.filesize)); } if (attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) { o->Set(_permissions, Integer::New(attrs.permissions)); } if (attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID) { o->Set(_uid, Integer::New(attrs.uid)); o->Set(_gid, Integer::New(attrs.gid)); } if (attrs.flags & LIBSSH2_SFTP_ATTR_ACMODTIME) { o->Set(_mtime, Integer::New(attrs.mtime)); o->Set(_atime, Integer::New(attrs.atime)); } libssh2_sftp_close(sftp_handle); return scope.Close(o); }
bool SFtpFileEngine::open(QIODevice::OpenMode openMode) { qDebug() << "open()" << _fileName << openMode; if (_fileFlags & QAbstractFileEngine::DirectoryType) return false; if (!(openMode & (QIODevice::ReadOnly | QIODevice::WriteOnly))) return false; if ((openMode & QIODevice::ReadOnly) && (!(_fileFlags & QAbstractFileEngine::ExistsFlag))) return false; if (!sftpConnect()) return false; int flags = 0; int mode = 0; if (openMode & QIODevice::ReadOnly) flags |= LIBSSH2_FXF_READ; if (openMode & QIODevice::WriteOnly) { flags |= LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT; mode |= LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH; } _sftp_handle = libssh2_sftp_open(_sftp_session, _textCodec->fromUnicode(_path).data(), flags, mode); return _sftp_handle; }
CURLcode Curl_sftp_do(struct connectdata *conn, bool *done) { LIBSSH2_SFTP_ATTRIBUTES attrs; struct SSHPROTO *sftp = conn->data->reqdata.proto.ssh; CURLcode res = CURLE_OK; struct SessionHandle *data = conn->data; curl_off_t bytecount = 0; char *buf = data->state.buffer; *done = TRUE; /* unconditionally */ if (data->set.upload) { /* * NOTE!!! libssh2 requires that the destination path is a full path * that includes the destination file and name OR ends in a "/" . * If this is not done the destination file will be named the * same name as the last directory in the path. */ sftp->sftp_handle = libssh2_sftp_open(sftp->sftp_session, sftp->path, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp->sftp_handle) return CURLE_FAILED_INIT; /* upload data */ res = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL); } else { if (sftp->path[strlen(sftp->path)-1] == '/') { /* * This is a directory that we are trying to get, so produce a * directory listing * * **BLOCKING behaviour** This should be made into a state machine and * get a separate function called from Curl_sftp_recv() when there is * data to read from the network, instead of "hanging" here. */ char filename[PATH_MAX+1]; int len, totalLen, currLen; char *line; sftp->sftp_handle = libssh2_sftp_opendir(sftp->sftp_session, sftp->path); if (!sftp->sftp_handle) return CURLE_SSH; while ((len = libssh2_sftp_readdir(sftp->sftp_handle, filename, PATH_MAX, &attrs)) > 0) { filename[len] = '\0'; if (data->set.ftp_list_only) { if ((attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) && ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFDIR)) { infof(data, "%s\n", filename); } } else { totalLen = 80 + len; line = (char *)malloc(totalLen); if (!line) return CURLE_OUT_OF_MEMORY; if (!(attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID)) attrs.uid = attrs.gid =0; currLen = snprintf(line, totalLen, "---------- 1 %5d %5d", attrs.uid, attrs.gid); if (attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) { if ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFDIR) { line[0] = 'd'; } else if ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFLNK) { line[0] = 'l'; } else if ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFSOCK) { line[0] = 's'; } else if ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFCHR) { line[0] = 'c'; } else if ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFBLK) { line[0] = 'b'; } if (attrs.permissions & LIBSSH2_SFTP_S_IRUSR) { line[1] = 'r'; } if (attrs.permissions & LIBSSH2_SFTP_S_IWUSR) { line[2] = 'w'; } if (attrs.permissions & LIBSSH2_SFTP_S_IXUSR) { line[3] = 'x'; } if (attrs.permissions & LIBSSH2_SFTP_S_IRGRP) { line[4] = 'r'; } if (attrs.permissions & LIBSSH2_SFTP_S_IWGRP) { line[5] = 'w'; } if (attrs.permissions & LIBSSH2_SFTP_S_IXGRP) { line[6] = 'x'; } if (attrs.permissions & LIBSSH2_SFTP_S_IROTH) { line[7] = 'r'; } if (attrs.permissions & LIBSSH2_SFTP_S_IWOTH) { line[8] = 'w'; } if (attrs.permissions & LIBSSH2_SFTP_S_IXOTH) { line[9] = 'x'; } } if (attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) { currLen += snprintf(line+currLen, totalLen-currLen, "%11lld", attrs.filesize); } if (attrs.flags & LIBSSH2_SFTP_ATTR_ACMODTIME) { const char *months[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm *nowParts; time_t now, remoteTime; now = time(NULL); remoteTime = (time_t)attrs.mtime; nowParts = localtime(&remoteTime); if ((time_t)attrs.mtime > (now - (3600 * 24 * 180))) { currLen += snprintf(line+currLen, totalLen-currLen, " %s %2d %2d:%02d", months[nowParts->tm_mon], nowParts->tm_mday, nowParts->tm_hour, nowParts->tm_min); } else { currLen += snprintf(line+currLen, totalLen-currLen, " %s %2d %5d", months[nowParts->tm_mon], nowParts->tm_mday, 1900+nowParts->tm_year); } } currLen += snprintf(line+currLen, totalLen-currLen, " %s", filename); if ((attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) && ((attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFLNK)) { char linkPath[PATH_MAX + 1]; snprintf(linkPath, PATH_MAX, "%s%s", sftp->path, filename); len = libssh2_sftp_readlink(sftp->sftp_session, linkPath, filename, PATH_MAX); line = realloc(line, totalLen + 4 + len); if (!line) return CURLE_OUT_OF_MEMORY; currLen += snprintf(line+currLen, totalLen-currLen, " -> %s", filename); } currLen += snprintf(line+currLen, totalLen-currLen, "\n"); res = Curl_client_write(conn, CLIENTWRITE_BODY, line, 0); free(line); } } libssh2_sftp_closedir(sftp->sftp_handle); sftp->sftp_handle = NULL; /* no data to transfer */ res = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); } else { /* * Work on getting the specified file */ sftp->sftp_handle = libssh2_sftp_open(sftp->sftp_session, sftp->path, LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp->sftp_handle) return CURLE_SSH; if (libssh2_sftp_stat(sftp->sftp_session, sftp->path, &attrs)) { /* * libssh2_sftp_open() didn't return an error, so maybe the server * just doesn't support stat() */ data->reqdata.size = -1; data->reqdata.maxdownload = -1; } else { data->reqdata.size = attrs.filesize; data->reqdata.maxdownload = attrs.filesize; Curl_pgrsSetDownloadSize(data, attrs.filesize); } Curl_pgrsTime(data, TIMER_STARTTRANSFER); /* Now download data. The libssh2 0.14 doesn't offer any way to do this without using this BLOCKING approach, so here's room for improvement once libssh2 can return EWOULDBLOCK to us. */ #if 0 /* code left here just because this is what this function will use the day libssh2 is improved */ res = Curl_setup_transfer(conn, FIRSTSOCKET, bytecount, FALSE, NULL, -1, NULL); #endif while (res == CURLE_OK) { size_t nread; /* NOTE: most *read() functions return ssize_t but this returns size_t which normally is unsigned! */ nread = libssh2_sftp_read(data->reqdata.proto.ssh->sftp_handle, buf, BUFSIZE-1); if (nread > 0) buf[nread] = 0; /* this check can be changed to a <= 0 when nread is changed to a signed variable type */ if ((nread == 0) || (nread == (size_t)~0)) break; bytecount += nread; res = Curl_client_write(conn, CLIENTWRITE_BODY, buf, nread); if(res) return res; Curl_pgrsSetDownloadCounter(data, bytecount); if(Curl_pgrsUpdate(conn)) res = CURLE_ABORTED_BY_CALLBACK; else { struct timeval now = Curl_tvnow(); res = Curl_speedcheck(data, now); } } if(Curl_pgrsUpdate(conn)) res = CURLE_ABORTED_BY_CALLBACK; /* no (more) data to transfer */ res = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); } } return res; }
int main(int argc, char *argv[]) { unsigned long hostaddr = inet_addr("128.83.120.177"); int sock, rc; struct sockaddr_in sin; LIBSSH2_SFTP_HANDLE *sftp_handle; rc = libssh2_init (0); if (rc != 0) { fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } session = libssh2_session_init(); if (!session) return -1; /* Tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if (libssh2_userauth_publickey_fromfile(session, username, "/home/ethan/.ssh/id_rsa.pub", "/home/ethan/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } else { fprintf(stderr, "\tAuthentication by public key succeeded.\n"); } fprintf(stderr, "calling libssh2_sftp_init()...\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "calling libssh2_sftp_open()...\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); get_file_stat_struct(); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session)); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now receiving data...\n"); do { char mem[1024]; fprintf(stderr, "calling libssh2_sftp_read()...\n"); rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { write(1, mem, rc); } else { break; } } while (1); // continue until it fails libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); close(sock); fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
static int uwsgi_ssh_request_file( struct wsgi_request *wsgi_req, char* filepath, struct uwsgi_ssh_mountpoint *usm ) { int sock = -1; int return_status = 0; LIBSSH2_SESSION *session = NULL; if (uwsgi_init_ssh_session(usm, &sock, &session)) { uwsgi_log("[SSH] session initialization failed. Is the SSH server up?\n"); return_status = 500; goto shutdown; } LIBSSH2_SFTP *sftp_session = NULL; do { sftp_session = libssh2_sftp_init(session); if (!sftp_session) { if ((libssh2_session_last_errno(session)) == LIBSSH2_ERROR_EAGAIN) { if (uwsgi_ssh_waitsocket(sock, session)) { return_status = 500; goto shutdown; } } else { uwsgi_error("uwsgi_ssh_request_file()/libssh2_sftp_init()"); return_status = 500; goto shutdown; } } } while (!sftp_session); // Request file stats via SFTP LIBSSH2_SFTP_ATTRIBUTES file_attrs; int rc; while ((rc = libssh2_sftp_stat(sftp_session, filepath, &file_attrs)) == LIBSSH2_ERROR_EAGAIN) { if (uwsgi_ssh_waitsocket(sock, session)) { return_status = 500; goto shutdown; } } if (rc < 0) { // If it fails, requested file could not exist. if (rc == LIBSSH2_ERROR_SFTP_PROTOCOL && libssh2_sftp_last_error(sftp_session) == LIBSSH2_FX_NO_SUCH_FILE) { return_status = 404; } else { uwsgi_error("uwsgi_ssh_request_file()/libssh2_sftp_stat()"); return_status = 500; } goto sftp_shutdown; } if (wsgi_req->if_modified_since_len) { time_t ims = uwsgi_parse_http_date(wsgi_req->if_modified_since, wsgi_req->if_modified_since_len); if (file_attrs.mtime <= (unsigned long)ims) { if (uwsgi_response_prepare_headers(wsgi_req, "304 Not Modified", 16) || uwsgi_response_write_headers_do(wsgi_req)) { uwsgi_error("uwsgi_parse_http_date()/uwsgi_response_prepare_headers(do)()"); } return_status = 500; goto sftp_shutdown; } } if (uwsgi_response_prepare_headers(wsgi_req, "200", 3)) { uwsgi_error("uwsgi_ssh_request_file()/uwsgi_response_prepare_headers()"); return_status = 500; goto sftp_shutdown; } if (uwsgi_response_add_content_length(wsgi_req, file_attrs.filesize)) { uwsgi_error("uwsgi_ssh_request_file()/uwsgi_response_add_content_length()"); return_status = 500; goto sftp_shutdown; } if (uwsgi_response_add_last_modified(wsgi_req, file_attrs.mtime)) { uwsgi_error("uwsgi_ssh_request_file()/uwsgi_response_add_last_modified()"); return_status = 500; goto sftp_shutdown; } size_t mime_type_len = 0; char *mime_type = uwsgi_get_mime_type(filepath, strlen(filepath), &mime_type_len); if (mime_type) { if (uwsgi_response_add_content_type(wsgi_req, mime_type, mime_type_len)) { uwsgi_error("uwsgi_ssh_request_file()/uwsgi_response_add_content_type()"); // goto sftp_shutdown; } } // Request a file via SFTP LIBSSH2_SFTP_HANDLE *sftp_handle = NULL; do { sftp_handle = libssh2_sftp_open(sftp_session, filepath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { if (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { uwsgi_error("uwsgi_ssh_request_file()/libssh2_sftp_open()"); return_status = 500; goto sftp_shutdown; } else { if (uwsgi_ssh_waitsocket(sock, session)) { return_status = 500; goto sftp_shutdown; } } } } while (!sftp_handle); size_t buffer_size = uwsgi.page_size; void *buffer = alloca(buffer_size); libssh2_uint64_t read_size = 0; while (read_size < file_attrs.filesize) { rc = libssh2_sftp_read(sftp_handle, buffer, buffer_size); if (rc == LIBSSH2_ERROR_EAGAIN) { if (uwsgi_ssh_waitsocket(sock, session)) { return_status = 500; goto sftp_shutdown; } } else if (rc < 0) { uwsgi_error("uwsgi_ssh_request_file()/libssh2_sftp_read()"); break; } else { read_size += rc; if (uwsgi_response_write_body_do(wsgi_req, buffer, rc)) { uwsgi_error("uwsgi_ssh_request_file()/uwsgi_response_write_body_do()"); break; } } } while ((rc = libssh2_sftp_close(sftp_handle)) == LIBSSH2_ERROR_EAGAIN) { if (uwsgi_ssh_waitsocket(sock, session)) { return_status = 500; goto sftp_shutdown; } }; if (rc < 0) { uwsgi_error("uwsgi_ssh_request_file()/libssh2_sftp_close()"); } sftp_shutdown: while ((rc = libssh2_sftp_shutdown(sftp_session)) == LIBSSH2_ERROR_EAGAIN) { uwsgi_ssh_waitsocket(sock, session); } if (rc < 0) { uwsgi_error("uwsgi_ssh_request_file()/libssh2_sftp_shutdown()"); } shutdown: while (libssh2_session_disconnect(session, "Normal Shutdown, thank you!") == LIBSSH2_ERROR_EAGAIN) { uwsgi_ssh_waitsocket(sock, session); } libssh2_session_free(session); close(sock); libssh2_exit(); return return_status; }
static int connect_to_ssh(BDRVSSHState *s, QDict *options, int ssh_flags, int creat_mode, Error **errp) { int r, ret; QemuOpts *opts = NULL; Error *local_err = NULL; const char *user, *path, *host_key_check; long port = 0; opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(opts, options, &local_err); if (local_err) { ret = -EINVAL; error_propagate(errp, local_err); goto err; } if (!ssh_process_legacy_socket_options(options, opts, errp)) { ret = -EINVAL; goto err; } path = qemu_opt_get(opts, "path"); if (!path) { ret = -EINVAL; error_setg(errp, "No path was specified"); goto err; } user = qemu_opt_get(opts, "user"); if (!user) { user = g_get_user_name(); if (!user) { error_setg_errno(errp, errno, "Can't get user name"); ret = -errno; goto err; } } host_key_check = qemu_opt_get(opts, "host_key_check"); if (!host_key_check) { host_key_check = "yes"; } /* Pop the config into our state object, Exit if invalid */ s->inet = ssh_config(s, options, errp); if (!s->inet) { ret = -EINVAL; goto err; } if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) { error_setg(errp, "Use only numeric port value"); ret = -EINVAL; goto err; } /* Open the socket and connect. */ s->sock = inet_connect_saddr(s->inet, errp, NULL, NULL); if (s->sock < 0) { ret = -EIO; goto err; } /* Create SSH session. */ s->session = libssh2_session_init(); if (!s->session) { ret = -EINVAL; session_error_setg(errp, s, "failed to initialize libssh2 session"); goto err; } #if TRACE_LIBSSH2 != 0 libssh2_trace(s->session, TRACE_LIBSSH2); #endif r = libssh2_session_handshake(s->session, s->sock); if (r != 0) { ret = -EINVAL; session_error_setg(errp, s, "failed to establish SSH session"); goto err; } /* Check the remote host's key against known_hosts. */ ret = check_host_key(s, s->inet->host, port, host_key_check, errp); if (ret < 0) { goto err; } /* Authenticate. */ ret = authenticate(s, user, errp); if (ret < 0) { goto err; } /* Start SFTP. */ s->sftp = libssh2_sftp_init(s->session); if (!s->sftp) { session_error_setg(errp, s, "failed to initialize sftp handle"); ret = -EINVAL; goto err; } /* Open the remote file. */ DPRINTF("opening file %s flags=0x%x creat_mode=0%o", path, ssh_flags, creat_mode); s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode); if (!s->sftp_handle) { session_error_setg(errp, s, "failed to open remote file '%s'", path); ret = -EINVAL; goto err; } qemu_opts_del(opts); r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs); if (r < 0) { sftp_error_setg(errp, s, "failed to read file attributes"); return -EINVAL; } return 0; err: if (s->sftp_handle) { libssh2_sftp_close(s->sftp_handle); } s->sftp_handle = NULL; if (s->sftp) { libssh2_sftp_shutdown(s->sftp); } s->sftp = NULL; if (s->session) { libssh2_session_disconnect(s->session, "from qemu ssh client: " "error opening connection"); libssh2_session_free(s->session); } s->session = NULL; qemu_opts_del(opts); return ret; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write_nonblock.c"; const char *sftppath="/tmp/sftp_write_nonblock.c"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; char mem[1024]; size_t nread; char *ptr; #ifdef WIN32 WSADATA wsadata; WSAStartup(WINSOCK_VERSION, &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { loclfile = argv[4]; } if (argc > 5) { sftppath = argv[5]; } local = fopen(loclfile, "rb"); if (!local) { printf("Can't local file %s\n", loclfile); goto shutdown; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* We set the socket non-blocking. We do it after the connect just to simplify the example code. */ #ifdef F_SETFL /* FIXME: this can/should be done in a more portable manner */ rc = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, rc | O_NONBLOCK); #else #error "add support for setting the socket non-blocking here" #endif /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); printf("Fingerprint: "); for(i = 0; i < 16; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if ((!sftp_session) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } while (!sftp_session); /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if ((!sftp_handle) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write data in a loop until we block */ while ((rc = libssh2_sftp_write(sftp_handle, ptr, nread)) == LIBSSH2_ERROR_EAGAIN) { ; } ptr += rc; nread -= nread; } while (rc > 0); } while (1); fclose(local); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: while ((rc = libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing")) == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 Sleep(1000); closesocket(sock); #else sleep(1); close(sock); #endif printf("all done\n"); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write.c"; const char *sftppath="/tmp/TEST"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_ATTRIBUTES attrs; char mem[1024*100]; size_t nread; char *ptr; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } if(argc > 4) { loclfile = argv[4]; } if(argc > 5) { sftppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { printf("Can't local file %s\n", loclfile); return -1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* Since we have set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() for READ and WRITE!\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } if(libssh2_sftp_fstat_ex(sftp_handle, &attrs, 0) < 0) { printf("libssh2_sftp_fstat_ex failed\n"); goto shutdown; } else libssh2_sftp_seek64(sftp_handle, attrs.filesize); printf("Did a seek to position %ld\n", (long) attrs.filesize); fprintf(stderr, "libssh2_sftp_open() a handle for APPEND\n"); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write data in a loop until we block */ rc = libssh2_sftp_write(sftp_handle, ptr, nread); if(rc < 0) break; ptr += rc; nread -= rc; } while (nread); } while (rc > 0); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif if (local) fclose(local); printf("all done\n"); libssh2_exit(); return 0; }
void PJSSH::PutStream(std::istream & aStream, const char* aRemoteFileName) const { //Check if local file exists if(!aStream) { std::string error("The local file does not exist"); throw std::runtime_error(error); } LIBSSH2_SFTP* sftp = libssh2_sftp_init(mSession); if( NULL == sftp ) { throw std::runtime_error("Failed to open a sftp session."); } //Check if remote file exitst LIBSSH2_SFTP_ATTRIBUTES fileinfo; int status = libssh2_sftp_stat(sftp, aRemoteFileName , &fileinfo); if(status == 0) { //File exitsts std::string error("The file " + std::string(aRemoteFileName) + " alerady exists"); throw std::runtime_error(error); } LIBSSH2_SFTP_HANDLE* file_handle = libssh2_sftp_open(sftp,aRemoteFileName, LIBSSH2_FXF_TRUNC | LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT,0); if( NULL == file_handle ) { std::ostringstream o; o<<"Failed to write on remote file. Last error code=" <<libssh2_sftp_last_error(sftp); throw std::runtime_error(o.str()); } char buffer[1024]; do { aStream.read(buffer,1024); const std::streamsize num_of_read_characters(aStream.gcount()); if( num_of_read_characters > 0 ) { const size_t num_of_bytes_written = libssh2_sftp_write( file_handle, buffer, num_of_read_characters); if( num_of_bytes_written == ((size_t)-1) ) { throw std::runtime_error("Failed to write to the remote file."); } else if( static_cast<std::streamsize>(num_of_bytes_written) != num_of_read_characters ) { throw std::runtime_error("Failed to write all bytes to remote file."); } else if(num_of_read_characters <= 0) { throw std::runtime_error("Failed to read characters from the input " "stream to be written to the remote file."); } } } while( aStream ); // Close sftp file handle and end SFTP session. libssh2_sftp_close_handle(file_handle); libssh2_sftp_shutdown(sftp); }
int main(int argc, char *argv[]) { int sock , i, auth_pw = 0, port = 22; struct sockaddr_in6 sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; int rc; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; struct hostent *server; if (!strcmp(argv[1], "--help")) usage(); if (argc > 1) { inet_pton(AF_INET6,argv[1],sin.sin6_addr.s6_addr); } if (argc > 2) { port = atoi(argv[2]); } if (argc > 3) { username = argv[3]; } if (argc > 4) { password = argv[4]; } if (argc > 5) { sftppath = argv[5]; } if (argc > 6) { localpath = argv[6]; } sock = socket(AF_INET6, SOCK_STREAM, 0); server = gethostbyname2(argv[1],AF_INET6); if (server == NULL) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } memset((char *) &sin, 0, sizeof(sin)); sin.sin6_flowinfo = 0; sin.sin6_family = AF_INET6; memmove((char *) &sin.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length); sin.sin6_port = htons(port); if (connect(sock, (struct sockaddr *)(&sin), sizeof(struct sockaddr_in6)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } session = libssh2_session_init(); if (!session) return -1; libssh2_session_set_blocking(session, 1); rc = libssh2_session_startup(session, sock); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); userauthlist = libssh2_userauth_list(session, username, strlen(username)); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if (argc > 5) { if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { if (libssh2_userauth_password(session, username, password)) { return 1; goto shutdown; } } else if (auth_pw & 2) { if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback)) { return 1; goto shutdown; } } else if (auth_pw & 4) { if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); return 1; goto shutdown; } } else { printf("No supported authentication methods found!\n"); return 1; goto shutdown; } sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); return 1; goto shutdown; } sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { return 2; goto shutdown; } FILE *fp = fopen(localpath, "w"); if (fp) { char mem [1024]; do { rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { fwrite(mem, rc, 1, fp); } else { break; } } while (1); fclose(fp); } libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write_nonblock.c"; const char *sftppath="/tmp/sftp_write_nonblock.c"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; char mem[1024 * 1000]; size_t nread; size_t memuse; time_t start; long total = 0; int duration; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { loclfile = argv[4]; } if (argc > 5) { sftppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { printf("Can't local file %s\n", loclfile); return -1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_handshake(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do is * check the hostkey's fingerprint against our known hosts Your app may * have it hard coded, may go to a file, may present it to the user, * that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if (!sftp_session && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } while (!sftp_session); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp_handle && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); start = time(NULL); memuse = 0; /* it starts blank */ do { nread = fread(&mem[memuse], 1, sizeof(mem)-memuse, local); if (nread <= 0) { /* end of file */ if (memuse > 0) /* the previous sending is not finished */ nread = 0; else break; } memuse += nread; total += nread; /* write data in a loop until we block */ while ((rc = libssh2_sftp_write(sftp_handle, mem, memuse)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, session); } if(rc < 0) break; if(memuse - rc) { /* make room for more data at the end of the buffer */ memmove(&mem[0], &mem[rc], memuse - rc); memuse -= rc; } else /* 'mem' was consumed fully */ memuse = 0; } while (rc > 0); duration = (int)(time(NULL)-start); printf("%ld bytes in %d seconds makes %.1f bytes/sec\n", total, duration, total/(double)duration); fclose(local); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif printf("all done\n"); libssh2_exit(); return 0; }
static int connect_to_ssh(BDRVSSHState *s, QDict *options, int ssh_flags, int creat_mode, Error **errp) { int r, ret; const char *host, *user, *path, *host_key_check; int port; if (!qdict_haskey(options, "host")) { ret = -EINVAL; error_setg(errp, "No hostname was specified"); goto err; } host = qdict_get_str(options, "host"); if (qdict_haskey(options, "port")) { port = qdict_get_int(options, "port"); } else { port = 22; } if (!qdict_haskey(options, "path")) { ret = -EINVAL; error_setg(errp, "No path was specified"); goto err; } path = qdict_get_str(options, "path"); if (qdict_haskey(options, "user")) { user = qdict_get_str(options, "user"); } else { user = g_get_user_name(); if (!user) { error_setg_errno(errp, errno, "Can't get user name"); ret = -errno; goto err; } } if (qdict_haskey(options, "host_key_check")) { host_key_check = qdict_get_str(options, "host_key_check"); } else { host_key_check = "yes"; } /* Construct the host:port name for inet_connect. */ g_free(s->hostport); s->hostport = g_strdup_printf("%s:%d", host, port); /* Open the socket and connect. */ s->sock = inet_connect(s->hostport, errp); if (s->sock < 0) { ret = -errno; goto err; } /* Create SSH session. */ s->session = libssh2_session_init(); if (!s->session) { ret = -EINVAL; session_error_setg(errp, s, "failed to initialize libssh2 session"); goto err; } #if TRACE_LIBSSH2 != 0 libssh2_trace(s->session, TRACE_LIBSSH2); #endif r = libssh2_session_handshake(s->session, s->sock); if (r != 0) { ret = -EINVAL; session_error_setg(errp, s, "failed to establish SSH session"); goto err; } /* Check the remote host's key against known_hosts. */ ret = check_host_key(s, host, port, host_key_check, errp); if (ret < 0) { goto err; } /* Authenticate. */ ret = authenticate(s, user, errp); if (ret < 0) { goto err; } /* Start SFTP. */ s->sftp = libssh2_sftp_init(s->session); if (!s->sftp) { session_error_setg(errp, s, "failed to initialize sftp handle"); ret = -EINVAL; goto err; } /* Open the remote file. */ DPRINTF("opening file %s flags=0x%x creat_mode=0%o", path, ssh_flags, creat_mode); s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode); if (!s->sftp_handle) { session_error_setg(errp, s, "failed to open remote file '%s'", path); ret = -EINVAL; goto err; } r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs); if (r < 0) { sftp_error_setg(errp, s, "failed to read file attributes"); return -EINVAL; } /* Delete the options we've used; any not deleted will cause the * block layer to give an error about unused options. */ qdict_del(options, "host"); qdict_del(options, "port"); qdict_del(options, "user"); qdict_del(options, "path"); qdict_del(options, "host_key_check"); return 0; err: if (s->sftp_handle) { libssh2_sftp_close(s->sftp_handle); } s->sftp_handle = NULL; if (s->sftp) { libssh2_sftp_shutdown(s->sftp); } s->sftp = NULL; if (s->session) { libssh2_session_disconnect(s->session, "from qemu ssh client: " "error opening connection"); libssh2_session_free(s->session); } s->session = NULL; return ret; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; int rc; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } if(argc > 4) { sftppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* Since we have set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if(argc > 5) { if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { printf("\tAuthentication by keyboard-interactive failed!\n"); goto shutdown; } else { printf("\tAuthentication by keyboard-interactive succeeded.\n"); } } else if (auth_pw & 4) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session)); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); do { char mem[1024]; /* loop until we fail */ fprintf(stderr, "libssh2_sftp_read()!\n"); rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { write(1, mem, rc); } else { break; } } while (1); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
QString SshSFtp::send(const QString &source, QString dest) { QFile s(source); QFileInfo src(source); QByteArray buffer(1024 * 100, 0); size_t nread; char *ptr; long total = 0; FILE *local; int rc; LIBSSH2_SFTP_HANDLE *sftpfile; if(dest.endsWith("/")) { if(!isDir(dest)) { mkpath(dest); } dest += src.fileName(); } local = fopen(qPrintable(source), "rb"); if (!local) { qDebug() << "ERROR : Can't open file "<< source; return ""; } do { sftpfile = libssh2_sftp_open(m_sftpSession, qPrintable(dest), LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); rc = libssh2_session_last_errno(sshClient->session()); if (!sftpfile && (rc == LIBSSH2_ERROR_EAGAIN)) { m_waitData(2000); } else { if(!sftpfile) { qDebug() << "ERROR : SSH error " << rc; fclose(local); return ""; } } } while (!sftpfile); do { nread = fread(buffer.data(), 1, buffer.size(), local); if (nread <= 0) { /* end of file */ break; } ptr = buffer.data(); total += nread; do { while ((rc = libssh2_sftp_write(sftpfile, ptr, nread)) == LIBSSH2_ERROR_EAGAIN) { m_waitData(2000); } if(rc < 0) { qDebug() << "ERROR : Write error send(" << source << "," << dest << ") = " << rc; break; } ptr += rc; nread -= rc; } while (nread); } while (rc > 0); fclose(local); libssh2_sftp_close(sftpfile); return dest; }
gboolean sftpfs_open_file (vfs_file_handler_t * file_handler, int flags, mode_t mode, GError ** error) { unsigned long sftp_open_flags = 0; int sftp_open_mode = 0; gboolean do_append = FALSE; sftpfs_file_handler_data_t *file_handler_data; sftpfs_super_data_t *super_data; char *name; (void) mode; name = vfs_s_fullpath (&sftpfs_class, file_handler->ino); if (name == NULL) return FALSE; super_data = (sftpfs_super_data_t *) file_handler->ino->super->data; file_handler_data = g_new0 (sftpfs_file_handler_data_t, 1); if ((flags & O_CREAT) != 0 || (flags & O_WRONLY) != 0) { sftp_open_flags = (flags & O_WRONLY) != 0 ? LIBSSH2_FXF_WRITE : 0; sftp_open_flags |= (flags & O_CREAT) != 0 ? LIBSSH2_FXF_CREAT : 0; if ((flags & O_APPEND) != 0) { sftp_open_flags |= LIBSSH2_FXF_APPEND; do_append = TRUE; } sftp_open_flags |= (flags & O_TRUNC) != 0 ? LIBSSH2_FXF_TRUNC : 0; sftp_open_mode = LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH; } else sftp_open_flags = LIBSSH2_FXF_READ; while (TRUE) { int libssh_errno; file_handler_data->handle = libssh2_sftp_open (super_data->sftp_session, sftpfs_fix_filename (name), sftp_open_flags, sftp_open_mode); if (file_handler_data->handle != NULL) break; libssh_errno = libssh2_session_last_errno (super_data->session); if (libssh_errno != LIBSSH2_ERROR_EAGAIN) { sftpfs_ssherror_to_gliberror (super_data, libssh_errno, error); g_free (name); g_free (file_handler_data); return FALSE; } } g_free (name); file_handler_data->flags = flags; file_handler_data->mode = mode; file_handler->data = file_handler_data; if (do_append) { struct stat file_info; if (sftpfs_fstat (file_handler, &file_info, error) == 0) libssh2_sftp_seek64 (file_handler_data->handle, file_info.st_size); } return TRUE; }
int FSSftp::OpenCreate ( FSPath& path, bool overwrite, int mode, int flags, int* err, FSCInfo* info ) { MutexLock lock( &mutex ); int ret = CheckSession( err, info ); if ( ret ) { return ret; } int n = 0; try { if ( !overwrite ) { /* странная херня, при наличии файла с O_EXCL, выдает не EEXIST, а "прерван системный вызов" поэтому встанил эту дурацкую проверку на наличие */ LIBSSH2_SFTP_ATTRIBUTES attr; int ret; WHILE_EAGAIN_( ret, libssh2_sftp_lstat( sftpSession, ( char* )path.GetString( _operParam.charset, '/' ), &attr ) ); if ( !ret ) { if ( err ) { *err = EEXIST; } return -1; } } for ( n = 0; n < MAX_FILES; n++ ) if ( !fileTable[n] ) { break; } if ( n >= MAX_FILES ) { if ( err ) { *err = SSH_INTERROR_OUTOF; } return -1; } LIBSSH2_SFTP_HANDLE* fd = 0; while ( true ) { fd = libssh2_sftp_open( sftpSession, ( char* )path.GetString( _operParam.charset, '/' ), LIBSSH2_FXF_CREAT | LIBSSH2_FXF_WRITE | ( overwrite ? LIBSSH2_FXF_TRUNC : LIBSSH2_FXF_EXCL ), mode ); if ( fd ) { break; } CheckSFTPEagain(); WaitSocket( info ); } fileTable[n] = fd; } catch ( int e ) { if ( err ) { *err = e; } return ( e == -2 ) ? -2 : -1; } return n; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *sftppath="/tmp/TEST"; struct timeval start; struct timeval end; int rc; int total = 0; long time_ms; int spin = 0; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { sftppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); gettimeofday(&start, NULL); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/" ".ssh/id_rsa.pub", "/home/username/" ".ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } #if 0 libssh2_trace(session, LIBSSH2_TRACE_CONN); #endif fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if(!sftp_session) { if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) { fprintf(stderr, "non-blocking init\n"); waitsocket(sock, session); /* now we wait */ } else { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } } while (!sftp_session); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { if (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } else { fprintf(stderr, "non-blocking open\n"); waitsocket(sock, session); /* now we wait */ } } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); do { char mem[1024*24]; /* loop until we fail */ while ((rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) { spin++; waitsocket(sock, session); /* now we wait */ } if (rc > 0) { total += rc; write(1, mem, rc); } else { break; } } while (1); gettimeofday(&end, NULL); time_ms = tvdiff(end, start); printf("Got %d bytes in %ld ms = %.1f bytes/sec spin: %d\n", total, time_ms, total/(time_ms/1000.0), spin ); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: printf("libssh2_session_disconnect\n"); while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int guac_sftp_file_handler(guac_client* client, guac_stream* stream, char* mimetype, char* filename) { ssh_guac_client_data* client_data = (ssh_guac_client_data*) client->data; char fullpath[GUAC_SFTP_MAX_PATH]; LIBSSH2_SFTP_HANDLE* file; int i; /* Ensure filename is a valid filename and not a path */ if (!__ssh_guac_valid_filename(filename)) { guac_protocol_send_ack(client->socket, stream, "SFTP: Illegal filename", GUAC_PROTOCOL_STATUS_CLIENT_BAD_REQUEST); guac_socket_flush(client->socket); return 0; } /* Copy upload path, append trailing slash */ for (i=0; i<GUAC_SFTP_MAX_PATH; i++) { char c = client_data->sftp_upload_path[i]; if (c == '\0') { fullpath[i++] = '/'; break; } fullpath[i] = c; } /* Append filename */ for (; i<GUAC_SFTP_MAX_PATH; i++) { char c = *(filename++); if (c == '\0') break; fullpath[i] = c; } /* If path + filename exceeds max length, abort */ if (i == GUAC_SFTP_MAX_PATH) { guac_protocol_send_ack(client->socket, stream, "SFTP: Name too long", GUAC_PROTOCOL_STATUS_CLIENT_OVERRUN); guac_socket_flush(client->socket); return 0; } /* Terminate path string */ fullpath[i] = '\0'; /* Open file via SFTP */ file = libssh2_sftp_open(client_data->sftp_session, fullpath, LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC, S_IRUSR | S_IWUSR); /* Inform of status */ if (file != NULL) { guac_protocol_send_ack(client->socket, stream, "SFTP: File opened", GUAC_PROTOCOL_STATUS_SUCCESS); guac_socket_flush(client->socket); } else { guac_client_log_error(client, "Unable to open file \"%s\": %s", fullpath, libssh2_sftp_last_error(client_data->sftp_session)); guac_protocol_send_ack(client->socket, stream, "SFTP: Open failed", GUAC_PROTOCOL_STATUS_RESOURCE_NOT_FOUND); guac_socket_flush(client->socket); } /* Set handlers for file stream */ stream->blob_handler = guac_sftp_blob_handler; stream->end_handler = guac_sftp_end_handler; /* Store file within stream */ stream->data = file; return 0; }
int SyncTransferThread::do_upload(QString local_path, QString remote_path) { qDebug() <<__FUNCTION__<<": "<<__LINE__<<":"<< __FILE__; qDebug()<< "remote_path = "<< remote_path << " , local_path = " << local_path ; int pcnt = 0 ; int rlen , wlen ; int file_size , tran_len = 0 ; LIBSSH2_SFTP_HANDLE * sftp_handle ; LIBSSH2_SFTP_ATTRIBUTES ssh2_sftp_attrib; char buff[5120] = {0}; QString currFile; //TODO 检查文件可写属性 sftp_handle = libssh2_sftp_open(this->ssh2_sftp, GlobalOption::instance()->remote_codec->fromUnicode(remote_path), LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, 0666); if (sftp_handle == NULL) { //TODO 错误消息通知用户。 char errmsg[200] = {0}; int emlen = 0; libssh2_session_last_error(this->ssh2_sess, (char **)&errmsg, &emlen, 0); qDebug()<<"open sftp file error :"<< libssh2_sftp_last_error(this->ssh2_sftp) <<QString(errmsg); if (libssh2_sftp_last_error(this->ssh2_sftp) == LIBSSH2_FX_PERMISSION_DENIED) { // this->errorString = QString(tr("Open file faild, Permission denied")); // qDebug()<<this->errorString; } // this->error_code = ERRNO_BASE + libssh2_sftp_last_error(this->ssh2_sftp); emit this->syncFileStopped(currFile, -1); return -1 ; } memset(&ssh2_sftp_attrib,0,sizeof(ssh2_sftp_attrib)); QFileInfo local_fi(local_path); file_size = local_fi.size(); qDebug()<<"local file size:" << file_size ; currFile = local_path.right(local_path.length() - this->local_base_path.length() - 1); emit this->syncFileStarted(currFile, file_size); // 本地编码 --> Qt 内部编码 QFile q_file(local_path); if (!q_file.open( QIODevice::ReadOnly)) { //TODO 错误消息通知用户。 qDebug()<<"open local file error:"<< q_file.errorString() ; //printf("open local file error:%s\n", strerror( errno ) ); } else { //read local file and then write to remote file while (!q_file.atEnd()) { qDebug()<<"Read local ... "; rlen = q_file.read(buff, sizeof(buff)); qDebug()<<"Read local done "; if (rlen <= 0) { //qDebug()<<"errno: "<<errno<<" err msg:"<< strerror( errno) << ftell( local_handle) ; break ; } qDebug()<<"write to sftp ... "; wlen = libssh2_sftp_write(sftp_handle, buff, rlen); qDebug()<<"write to sftp done "; Q_ASSERT(wlen == rlen); tran_len += wlen ; //qDebug()<<" local read : "<< rlen << " sftp write :"<<wlen <<" up len :"<< tran_len ; // qDebug() <<" read len :"<< rlen <<" , write len: "<< wlen // << " tran len: "<< tran_len ; if (file_size == 0 ) { emit this->transfer_percent_changed(currFile, 100, tran_len, wlen); } else { pcnt = 100.0 *((double)tran_len / (double)file_size); // qDebug()<< QString("100.0 *((double)%1 / (double)%2)").arg(tran_len).arg(file_size)<<" = "<<pcnt ; emit this->transfer_percent_changed(currFile, pcnt, tran_len, wlen); } } q_file.close(); } // qDebug()<<"out cycle, close sftp..."; libssh2_sftp_close(sftp_handle); q_debug()<<"syncUpload done."; this->do_touch_sftp_file_with_time(remote_path, QFileInfo(local_path).lastModified()); emit this->syncFileStopped(currFile, 0); return 0; }