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); }
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); }
static void freeConnection(const SFtpConnectionCache::SFtpConnection *conn) { libssh2_sftp_shutdown(conn->sftp_session); libssh2_session_disconnect(conn->session, "Normal Shutdown"); libssh2_session_free(conn->session); closesocket(conn->sock); delete(conn); }
/* sftp协议断开连接 */ static void sftp_disconnect(protocol_data_t *protocol) { if (protocol == NULL || protocol->protocol_data == NULL) { return; } sftp_data_t *data = (sftp_data_t *)protocol->protocol_data; libssh2_sftp_shutdown(data->sftp_session); libssh2_session_disconnect(data->session, "Normal Shutdown"); libssh2_session_free(data->session); close(data->sock); }
void php_ssh2_sftp_dtor(zend_resource *rsrc) { php_ssh2_sftp_data *data = (php_ssh2_sftp_data*)rsrc->ptr; if (!data) { return; } libssh2_sftp_shutdown(data->sftp); // TODO Sean-Der //zend_list_delete(data->session_rsrcid); efree(data); }
/** * @function SFTP.close * * ### Synopsis * * SFTP.close(handle); * * Close an SFTP connection and free up any resources used. * * @param {object} handle - handle to open connect returned by SFTP.connect(). */ JSVAL sftp_close (JSARGS args) { HandleScope scope; SFTP *handle = HANDLE(args[0]); if (handle->sftp_session) { libssh2_sftp_shutdown(handle->sftp_session); } if (handle->session) { libssh2_session_disconnect(handle->session, "SilkJS SFTP Disconnecting"); libssh2_session_free(handle->session); } if (handle->sock > 0) { close(handle->sock); } delete handle; return Undefined(); }
int ssh_guac_client_free_handler(guac_client* client) { ssh_guac_client_data* guac_client_data = (ssh_guac_client_data*) client->data; /* Close SSH channel */ if (guac_client_data->term_channel != NULL) { libssh2_channel_send_eof(guac_client_data->term_channel); libssh2_channel_close(guac_client_data->term_channel); } /* Free terminal */ guac_terminal_free(guac_client_data->term); pthread_join(guac_client_data->client_thread, NULL); /* Free channels */ libssh2_channel_free(guac_client_data->term_channel); /* Clean up SFTP */ if (guac_client_data->sftp_session) libssh2_sftp_shutdown(guac_client_data->sftp_session); if (guac_client_data->sftp_ssh_session) { libssh2_session_disconnect(guac_client_data->sftp_ssh_session, "Bye"); libssh2_session_free(guac_client_data->sftp_ssh_session); } /* Free session */ if (guac_client_data->session != NULL) libssh2_session_free(guac_client_data->session); /* Free auth key */ if (guac_client_data->key != NULL) ssh_key_free(guac_client_data->key); /* Free clipboard */ guac_common_clipboard_free(guac_client_data->clipboard); /* Free cursors */ guac_ssh_cursor_free(client, guac_client_data->ibar_cursor); guac_ssh_cursor_free(client, guac_client_data->blank_cursor); /* Free generic data struct */ free(client->data); return 0; }
static void ssh_state_free(BDRVSSHState *s) { if (s->sftp_handle) { libssh2_sftp_close(s->sftp_handle); } if (s->sftp) { libssh2_sftp_shutdown(s->sftp); } if (s->session) { libssh2_session_disconnect(s->session, "from qemu ssh client: " "user closed the connection"); libssh2_session_free(s->session); } if (s->sock >= 0) { close(s->sock); } }
CURLcode Curl_sftp_done(struct connectdata *conn, CURLcode status, bool premature) { struct SSHPROTO *sftp = conn->data->reqdata.proto.ssh; (void)premature; /* not used */ Curl_safefree(sftp->path); sftp->path = NULL; Curl_safefree(sftp->homedir); sftp->homedir = NULL; if (sftp->sftp_handle) { if (libssh2_sftp_close(sftp->sftp_handle) < 0) { infof(conn->data, "Failed to close libssh2 file\n"); } } if (sftp->sftp_session) { if (libssh2_sftp_shutdown(sftp->sftp_session) < 0) { infof(conn->data, "Failed to stop libssh2 sftp subsystem\n"); } } if (sftp->ssh_channel) { if (libssh2_channel_close(sftp->ssh_channel) < 0) { infof(conn->data, "Failed to stop libssh2 channel subsystem\n"); } } if (sftp->ssh_session) { libssh2_session_disconnect(sftp->ssh_session, "Shutdown"); libssh2_session_free(sftp->ssh_session); sftp->ssh_session = NULL; } free(conn->data->reqdata.proto.ssh); conn->data->reqdata.proto.ssh = NULL; Curl_pgrsDone(conn); (void)status; /* unused */ return CURLE_OK; }
int UnMount( struct FHandler *s, void *f ) { if( f != NULL ) { File *lf = (File *)f; if( lf->f_SpecialData ) { SpecialData *sdat = (SpecialData *) lf->f_SpecialData; libssh2_sftp_shutdown( sdat->sftp_session); libssh2_session_disconnect( sdat->session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(sdat->session); close( sdat->sock); DEBUG("all done!\n"); libssh2_exit(); if( sdat->sd_Host ) { free( sdat->sd_Host ); } if( sdat->sd_LoginUser ) { free( sdat->sd_LoginUser ); } if( sdat->sd_LoginPass ) { free( sdat->sd_LoginPass ); } free( lf->f_SpecialData ); } if( lf->f_Name ) { free( lf->f_Name ); } if( lf->f_Path ) { free( lf->f_Path ); } //free( f ); } return 0; }
void sftpfs_close_connection (struct vfs_s_super *super, const char *shutdown_message, GError ** error) { sftpfs_super_data_t *super_data; (void) error; super_data = (sftpfs_super_data_t *) super->data; if (super_data == NULL) return; vfs_path_element_free (super_data->original_connection_info); super_data->original_connection_info = NULL; if (super_data->agent != NULL) { libssh2_agent_disconnect (super_data->agent); libssh2_agent_free (super_data->agent); super_data->agent = NULL; } if (super_data->sftp_session != NULL) { libssh2_sftp_shutdown (super_data->sftp_session); super_data->sftp_session = NULL; } if (super_data->session != NULL) { libssh2_session_disconnect (super_data->session, shutdown_message); super_data->session = NULL; } super_data->fingerprint = NULL; if (super_data->socket_handle != -1) { close (super_data->socket_handle); super_data->socket_handle = -1; } }
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; }
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; }
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; }
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 = 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; }
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); }
/* * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. */ CURLcode Curl_ssh_connect(struct connectdata *conn, bool *done) { int i; struct SSHPROTO *ssh; const char *fingerprint; const char *authlist; char *home; char rsa_pub[PATH_MAX]; char rsa[PATH_MAX]; char tempHome[PATH_MAX]; curl_socket_t sock; char *real_path; char *working_path; int working_path_len; bool authed = FALSE; CURLcode result; struct SessionHandle *data = conn->data; rsa_pub[0] = rsa[0] = '\0'; result = ssh_init(conn); if (result) return result; ssh = data->reqdata.proto.ssh; working_path = curl_easy_unescape(data, data->reqdata.path, 0, &working_path_len); if (!working_path) return CURLE_OUT_OF_MEMORY; #ifdef CURL_LIBSSH2_DEBUG if (ssh->user) { infof(data, "User: %s\n", ssh->user); } if (ssh->passwd) { infof(data, "Password: %s\n", ssh->passwd); } #endif /* CURL_LIBSSH2_DEBUG */ sock = conn->sock[FIRSTSOCKET]; ssh->ssh_session = libssh2_session_init_ex(libssh2_malloc, libssh2_free, libssh2_realloc, ssh); if (ssh->ssh_session == NULL) { failf(data, "Failure initialising ssh session\n"); Curl_safefree(ssh->path); return CURLE_FAILED_INIT; } #ifdef CURL_LIBSSH2_DEBUG infof(data, "SSH socket: %d\n", sock); #endif /* CURL_LIBSSH2_DEBUG */ if (libssh2_session_startup(ssh->ssh_session, sock)) { failf(data, "Failure establishing ssh session\n"); libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(ssh->path); return CURLE_FAILED_INIT; } /* * Before we authenticate we should check the hostkey's fingerprint against * our known hosts. How that is handled (reading from file, whatever) is * up to us. As for know not much is implemented, besides showing how to * get the fingerprint. */ fingerprint = libssh2_hostkey_hash(ssh->ssh_session, LIBSSH2_HOSTKEY_HASH_MD5); #ifdef CURL_LIBSSH2_DEBUG /* The fingerprint points to static storage (!), don't free() it. */ infof(data, "Fingerprint: "); for (i = 0; i < 16; i++) { infof(data, "%02X ", (unsigned char) fingerprint[i]); } infof(data, "\n"); #endif /* CURL_LIBSSH2_DEBUG */ /* TBD - methods to check the host keys need to be done */ /* * Figure out authentication methods * NB: As soon as we have provided a username to an openssh server we must * never change it later. Thus, always specify the correct username here, * even though the libssh2 docs kind of indicate that it should be possible * to get a 'generic' list (not user-specific) of authentication methods, * presumably with a blank username. That won't work in my experience. * So always specify it here. */ authlist = libssh2_userauth_list(ssh->ssh_session, ssh->user, strlen(ssh->user)); /* * Check the supported auth types in the order I feel is most secure with the * requested type of authentication */ if ((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) && (strstr(authlist, "publickey") != NULL)) { /* To ponder about: should really the lib be messing about with the HOME environment variable etc? */ home = curl_getenv("HOME"); if (data->set.ssh_public_key) snprintf(rsa_pub, sizeof(rsa_pub), "%s", data->set.ssh_public_key); else if (home) snprintf(rsa_pub, sizeof(rsa_pub), "%s/.ssh/id_dsa.pub", home); if (data->set.ssh_private_key) snprintf(rsa, sizeof(rsa), "%s", data->set.ssh_private_key); else if (home) snprintf(rsa, sizeof(rsa), "%s/.ssh/id_dsa", home); curl_free(home); if (rsa_pub[0]) { /* The function below checks if the files exists, no need to stat() here. */ if (libssh2_userauth_publickey_fromfile(ssh->ssh_session, ssh->user, rsa_pub, rsa, "") == 0) { authed = TRUE; } } } if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) && (strstr(authlist, "password") != NULL)) { if (!libssh2_userauth_password(ssh->ssh_session, ssh->user, ssh->passwd)) authed = TRUE; } if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_HOST) && (strstr(authlist, "hostbased") != NULL)) { } if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) && (strstr(authlist, "keyboard-interactive") != NULL)) { /* Authentication failed. Continue with keyboard-interactive now. */ if (libssh2_userauth_keyboard_interactive_ex(ssh->ssh_session, ssh->user, strlen(ssh->user), &kbd_callback) == 0) { authed = TRUE; } } if (!authed) { failf(data, "Authentication failure\n"); libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(ssh->path); return CURLE_FAILED_INIT; } /* * At this point we have an authenticated ssh session. */ conn->sockfd = sock; conn->writesockfd = CURL_SOCKET_BAD; if (conn->protocol == PROT_SFTP) { /* * Start the libssh2 sftp session */ ssh->sftp_session = libssh2_sftp_init(ssh->ssh_session); if (ssh->sftp_session == NULL) { failf(data, "Failure initialising sftp session\n"); libssh2_sftp_shutdown(ssh->sftp_session); ssh->sftp_session = NULL; libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; return CURLE_FAILED_INIT; } /* * Get the "home" directory */ i = libssh2_sftp_realpath(ssh->sftp_session, ".", tempHome, PATH_MAX-1); if (i > 0) { /* It seems that this string is not always NULL terminated */ tempHome[i] = '\0'; ssh->homedir = (char *)strdup(tempHome); if (!ssh->homedir) { libssh2_sftp_shutdown(ssh->sftp_session); ssh->sftp_session = NULL; libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; return CURLE_OUT_OF_MEMORY; } } else { /* Return the error type */ i = libssh2_sftp_last_error(ssh->sftp_session); DEBUGF(infof(data, "error = %d\n", i)); } } /* Check for /~/ , indicating realative to the users home directory */ if (conn->protocol == PROT_SCP) { real_path = (char *)malloc(working_path_len+1); if (real_path == NULL) { Curl_safefree(working_path); libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; return CURLE_OUT_OF_MEMORY; } if (working_path[1] == '~') /* It is referenced to the home directory, so strip the leading '/' */ memcpy(real_path, working_path+1, 1 + working_path_len-1); else memcpy(real_path, working_path, 1 + working_path_len); } else if (conn->protocol == PROT_SFTP) { if (working_path[1] == '~') { real_path = (char *)malloc(strlen(ssh->homedir) + working_path_len + 1); if (real_path == NULL) { libssh2_sftp_shutdown(ssh->sftp_session); ssh->sftp_session = NULL; libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(working_path); return CURLE_OUT_OF_MEMORY; } /* It is referenced to the home directory, so strip the leading '/' */ memcpy(real_path, ssh->homedir, strlen(ssh->homedir)); real_path[strlen(ssh->homedir)] = '/'; real_path[strlen(ssh->homedir)+1] = '\0'; if (working_path_len > 3) { memcpy(real_path+strlen(ssh->homedir)+1, working_path + 3, 1 + working_path_len -3); } } else { real_path = (char *)malloc(working_path_len+1); if (real_path == NULL) { libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(working_path); return CURLE_OUT_OF_MEMORY; } memcpy(real_path, working_path, 1+working_path_len); } } else return CURLE_FAILED_INIT; Curl_safefree(working_path); ssh->path = real_path; *done = TRUE; return CURLE_OK; }
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/secretdir"; 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]; } /* * 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; /* ... 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_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 */ if ((i = 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; } /* Since we have not set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); fprintf(stderr, "libssh2_sftp_opendir()!\n"); /* Request a dir listing via SFTP */ sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath); if (!sftp_handle) { fprintf(stderr, "Unable to open dir with SFTP\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_opendir() is done, now receive listing!\n"); do { char mem[512]; char longentry[512]; LIBSSH2_SFTP_ATTRIBUTES attrs; /* loop until we fail */ rc = libssh2_sftp_readdir_ex(sftp_handle, mem, sizeof(mem), longentry, sizeof(longentry), &attrs); if(rc > 0) { /* rc is the length of the file name in the mem buffer */ if (longentry[0] != '\0') { printf("%s\n", longentry); } else { if(attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) { /* this should check what permissions it is and print the output accordingly */ printf("--fix----- "); } else { printf("---------- "); } if(attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID) { printf("%4ld %4ld ", attrs.uid, attrs.gid); } else { printf(" - - "); } if(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) { /* attrs.filesize is an uint64_t according to the docs but there is no really good and portable 64bit type for C before C99, and correspondingly there was no good printf() option for it... */ printf("%8lld ", attrs.filesize); } printf("%s\n", mem); } } else break; } while (1); libssh2_sftp_closedir(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); 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_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; }
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 = 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; }
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; }
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/sftp_mkdir_nonblock"; int rc; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif LIBSSH2_SFTP *sftp_session; #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; /* ... 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; } /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); fprintf(stderr, "libssh2_sftp_mkdirnb()!\n"); /* Make a directory via SFTP */ while (libssh2_sftp_mkdir(sftp_session, sftppath, LIBSSH2_SFTP_S_IRWXU| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IXGRP| LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH) == LIBSSH2_ERROR_EAGAIN); 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 printf("all done\n"); libssh2_exit(); return 0; }