1
0
mirror of https://github.com/libssh2/libssh2.git synced 2025-07-02 22:02:25 +03:00

tidy-up: example, tests continued

- fix skip auth if `userauthlist` is NULL.
  Closes #836 (Reported-by: @sudipm-mukherjee on github)
- fix most silenced `checksrc` warnings.
- sync examples/tests code between each other.
  (output messages, error handling, declaration order, comments)
- stop including unnecessary headers.
- always deinitialize in case of error.
- drop some redundant variables.
- add error handling where missing.
- show more error codes.
- switch `perror()` to `fprintf()`.
- fix some `printf()`s to be `fprintf()`.
- formatting.

Closes #960
This commit is contained in:
Viktor Szakats
2023-04-14 11:05:21 +00:00
parent 0162d1649c
commit 2efdb6747a
51 changed files with 1550 additions and 1289 deletions

View File

@ -51,18 +51,19 @@ static unsigned int remote_destport = 22;
enum { enum {
AUTH_NONE = 0, AUTH_NONE = 0,
AUTH_PASSWORD, AUTH_PASSWORD = 1,
AUTH_PUBLICKEY AUTH_PUBLICKEY = 2
}; };
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
int rc, i, auth = AUTH_NONE; int i, auth = AUTH_NONE;
struct sockaddr_in sin; struct sockaddr_in sin;
socklen_t sinlen; socklen_t sinlen;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel = NULL; LIBSSH2_CHANNEL *channel = NULL;
const char *shost; const char *shost;
unsigned int sport; unsigned int sport;
@ -70,18 +71,17 @@ int main(int argc, char *argv[])
struct timeval tv; struct timeval tv;
ssize_t len, wr; ssize_t len, wr;
char buf[16384]; char buf[16384];
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t sock;
libssh2_socket_t listensock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t listensock = LIBSSH2_INVALID_SOCKET;
libssh2_socket_t forwardsock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t forwardsock = LIBSSH2_INVALID_SOCKET;
#ifdef WIN32 #ifdef WIN32
char sockopt; char sockopt;
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#else #else
@ -113,26 +113,26 @@ int main(int argc, char *argv[])
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock == LIBSSH2_INVALID_SOCKET) { if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to open socket!\n"); fprintf(stderr, "failed to open socket!\n");
return -1; goto shutdown;
} }
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(server_ip); sin.sin_addr.s_addr = inet_addr(server_ip);
if(INADDR_NONE == sin.sin_addr.s_addr) { if(INADDR_NONE == sin.sin_addr.s_addr) {
fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip); fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip);
return -1; goto shutdown;
} }
sin.sin_port = htons(22); sin.sin_port = htons(22);
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr)); fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr));
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) { if(!session) {
fprintf(stderr, "Could not initialize SSH session!\n"); fprintf(stderr, "Could not initialize SSH session!\n");
return -1; goto shutdown;
} }
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
@ -141,7 +141,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Error when starting up SSH session: %d\n", rc); fprintf(stderr, "Error when starting up SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -158,51 +158,55 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password")) fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth |= AUTH_PASSWORD; if(strstr(userauthlist, "password"))
if(strstr(userauthlist, "publickey")) auth |= AUTH_PASSWORD;
auth |= AUTH_PUBLICKEY; if(strstr(userauthlist, "publickey"))
auth |= AUTH_PUBLICKEY;
/* check for options */ /* check for options */
if(argc > 8) { if(argc > 8) {
if((auth & AUTH_PASSWORD) && !strcmp(argv[8], "-p")) if((auth & AUTH_PASSWORD) && !strcmp(argv[8], "-p"))
auth = AUTH_PASSWORD; auth = AUTH_PASSWORD;
if((auth & AUTH_PUBLICKEY) && !strcmp(argv[8], "-k")) if((auth & AUTH_PUBLICKEY) && !strcmp(argv[8], "-k"))
auth = AUTH_PUBLICKEY; auth = AUTH_PUBLICKEY;
} }
if(auth & AUTH_PASSWORD) { if(auth & AUTH_PASSWORD) {
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown;
}
}
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown; goto shutdown;
} }
} }
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown;
}
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
}
listensock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); listensock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(listensock == LIBSSH2_INVALID_SOCKET) { if(listensock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to open listen socket!\n"); fprintf(stderr, "failed to open listen socket!\n");
return -1; goto shutdown;
} }
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons((unsigned short)local_listenport); sin.sin_port = htons((unsigned short)local_listenport);
sin.sin_addr.s_addr = inet_addr(local_listenip); sin.sin_addr.s_addr = inet_addr(local_listenip);
if(INADDR_NONE == sin.sin_addr.s_addr) { if(INADDR_NONE == sin.sin_addr.s_addr) {
perror("inet_addr"); fprintf(stderr, "failed in inet_addr()!\n");
goto shutdown; goto shutdown;
} }
sockopt = 1; sockopt = 1;
@ -210,11 +214,11 @@ int main(int argc, char *argv[])
sizeof(sockopt)); sizeof(sockopt));
sinlen = sizeof(sin); sinlen = sizeof(sin);
if(-1 == bind(listensock, (struct sockaddr *)&sin, sinlen)) { if(-1 == bind(listensock, (struct sockaddr *)&sin, sinlen)) {
perror("bind"); fprintf(stderr, "failed to bind()!\n");
goto shutdown; goto shutdown;
} }
if(-1 == listen(listensock, 2)) { if(-1 == listen(listensock, 2)) {
perror("listen"); fprintf(stderr, "failed to listen()!\n");
goto shutdown; goto shutdown;
} }
@ -237,8 +241,8 @@ int main(int argc, char *argv[])
remote_destport, shost, sport); remote_destport, shost, sport);
if(!channel) { if(!channel) {
fprintf(stderr, "Could not open the direct-tcpip channel!\n" fprintf(stderr, "Could not open the direct-tcpip channel!\n"
"(Note that this can be a problem at the server!" "(Note that this can be a problem at the server!"
" Please review the server logs.)\n"); " Please review the server logs.)\n");
goto shutdown; goto shutdown;
} }
@ -252,13 +256,13 @@ int main(int argc, char *argv[])
tv.tv_usec = 100000; tv.tv_usec = 100000;
rc = select((int)(forwardsock + 1), &fds, NULL, NULL, &tv); rc = select((int)(forwardsock + 1), &fds, NULL, NULL, &tv);
if(-1 == rc) { if(-1 == rc) {
perror("select"); fprintf(stderr, "failed to select()!\n");
goto shutdown; goto shutdown;
} }
if(rc && FD_ISSET(forwardsock, &fds)) { if(rc && FD_ISSET(forwardsock, &fds)) {
len = recv(forwardsock, buf, sizeof(buf), 0); len = recv(forwardsock, buf, sizeof(buf), 0);
if(len < 0) { if(len < 0) {
perror("read"); fprintf(stderr, "failed to recv()!\n");
goto shutdown; goto shutdown;
} }
else if(0 == len) { else if(0 == len) {
@ -293,7 +297,7 @@ int main(int argc, char *argv[])
while(wr < len) { while(wr < len) {
ssize_t nsent = send(forwardsock, buf + wr, len - wr, 0); ssize_t nsent = send(forwardsock, buf + wr, len - wr, 0);
if(nsent <= 0) { if(nsent <= 0) {
perror("write"); fprintf(stderr, "failed to send()!\n");
goto shutdown; goto shutdown;
} }
wr += nsent; wr += nsent;
@ -307,23 +311,38 @@ int main(int argc, char *argv[])
} }
shutdown: shutdown:
if(forwardsock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(forwardsock); closesocket(forwardsock);
closesocket(listensock);
#else #else
close(forwardsock); close(forwardsock);
close(listensock);
#endif #endif
}
if(listensock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32
closesocket(listensock);
#else
close(listensock);
#endif
}
if(channel) if(channel)
libssh2_channel_free(channel); libssh2_channel_free(channel);
libssh2_session_disconnect(session, "Client disconnecting normally");
libssh2_session_free(session);
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
libssh2_exit(); libssh2_exit();

View File

@ -21,9 +21,6 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -31,6 +28,12 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *scppath = "/tmp/TEST";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -38,24 +41,18 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
LIBSSH2_CHANNEL *channel;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *scppath = "/tmp/TEST";
libssh2_struct_stat fileinfo;
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel;
libssh2_struct_stat fileinfo;
libssh2_struct_stat_size got = 0; libssh2_struct_stat_size got = 0;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -82,25 +79,29 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
@ -108,7 +109,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -126,7 +127,7 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -135,7 +136,7 @@ int main(int argc, char *argv[])
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -149,7 +150,6 @@ int main(int argc, char *argv[])
goto shutdown; goto shutdown;
} }
while(got < fileinfo.st_size) { while(got < fileinfo.st_size) {
char mem[1024]; char mem[1024];
int amount = sizeof(mem); int amount = sizeof(mem);
@ -176,14 +176,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "scp_nonblock 192.168.0.1 user password /tmp/secrets" * $ ./scp_nonblock 192.168.0.1 user password /tmp/secrets
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -39,12 +39,18 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *scppath = "/tmp/TEST";
#ifdef HAVE_GETTIMEOFDAY #ifdef HAVE_GETTIMEOFDAY
/* diff in ms */ /* diff in ms */
static long tvdiff(struct timeval newer, struct timeval older) static long tvdiff(struct timeval newer, struct timeval older)
{ {
return (newer.tv_sec-older.tv_sec)*1000+ return (newer.tv_sec - older.tv_sec) * 1000 +
(newer.tv_usec-older.tv_usec)/1000; (newer.tv_usec - older.tv_usec) / 1000;
} }
#endif #endif
@ -85,31 +91,25 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *scppath = "/tmp/TEST";
libssh2_struct_stat fileinfo; libssh2_struct_stat fileinfo;
#ifdef HAVE_GETTIMEOFDAY #ifdef HAVE_GETTIMEOFDAY
struct timeval start; struct timeval start;
struct timeval end; struct timeval end;
long time_ms; long time_ms;
#endif #endif
int rc;
int spin = 0; int spin = 0;
libssh2_struct_stat_size got = 0; libssh2_struct_stat_size got = 0;
libssh2_struct_stat_size total = 0; libssh2_struct_stat_size total = 0;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -131,29 +131,34 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -169,14 +174,14 @@ int main(int argc, char *argv[])
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
* is check the hostkey's fingerprint against our known hosts Your app * 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 * may have it hard coded, may go to a file, may present it to the
* user, that's your call * user, that's your call
*/ */
fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
fprintf(stderr, "Fingerprint: "); fprintf(stderr, "Fingerprint: ");
for(i = 0; i < 20; i++) { for(i = 0; i < 20; i++) {
@ -189,7 +194,7 @@ int main(int argc, char *argv[])
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -200,7 +205,7 @@ int main(int argc, char *argv[])
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -231,13 +236,13 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n"); fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n");
while(got < fileinfo.st_size) { while(got < fileinfo.st_size) {
char mem[1024*24]; char mem[1024 * 24];
ssize_t nread; ssize_t nread;
do { do {
int amount = sizeof(mem); int amount = sizeof(mem);
if((fileinfo.st_size -got) < amount) { if((fileinfo.st_size - got) < amount) {
amount = (int)(fileinfo.st_size - got); amount = (int)(fileinfo.st_size - got);
} }
@ -250,7 +255,7 @@ int main(int argc, char *argv[])
} }
} while(nread > 0); } while(nread > 0);
if((nread == LIBSSH2_ERROR_EAGAIN) && (got < fileinfo.st_size)) { if(nread == LIBSSH2_ERROR_EAGAIN && got < fileinfo.st_size) {
/* this is due to blocking that would occur otherwise /* this is due to blocking that would occur otherwise
so we loop on this condition */ so we loop on this condition */
@ -267,7 +272,7 @@ int main(int argc, char *argv[])
time_ms = tvdiff(end, start); time_ms = tvdiff(end, start);
fprintf(stderr, "Got %ld bytes in %ld ms = %.1f bytes/sec spin: %d\n", fprintf(stderr, "Got %ld bytes in %ld ms = %.1f bytes/sec spin: %d\n",
(long)total, time_ms, (long)total, time_ms,
(double)total/((double)time_ms/1000.0), spin); (double)total / ((double)time_ms / 1000.0), spin);
#else #else
fprintf(stderr, "Got %ld bytes spin: %d\n", (long)total, spin); fprintf(stderr, "Got %ld bytes spin: %d\n", (long)total, spin);
#endif #endif
@ -277,14 +282,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -17,9 +17,6 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -27,6 +24,13 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "scp_write.c";
static const char *scppath = "/tmp/TEST";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -34,28 +38,21 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
int rc;
LIBSSH2_SESSION *session = NULL; LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *loclfile = "scp_write.c";
const char *scppath = "/tmp/TEST";
FILE *local; FILE *local;
int rc;
char mem[1024]; char mem[1024];
size_t nread; size_t nread;
char *ptr; char *ptr;
struct stat fileinfo; struct stat fileinfo;
int err;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -80,7 +77,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -88,19 +85,18 @@ int main(int argc, char *argv[])
local = fopen(loclfile, "rb"); local = fopen(loclfile, "rb");
if(!local) { if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile); fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1; return 1;
} }
stat(loclfile, &fileinfo); stat(loclfile, &fileinfo);
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) { if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n"); fprintf(stderr, "failed to create socket!\n");
return -1; goto shutdown;
} }
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
@ -108,14 +104,15 @@ int main(int argc, char *argv[])
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
@ -123,7 +120,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -141,7 +138,7 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -150,7 +147,7 @@ int main(int argc, char *argv[])
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -162,6 +159,7 @@ int main(int argc, char *argv[])
if(!channel) { if(!channel) {
char *errmsg; char *errmsg;
int errlen; int errlen;
int err;
err = libssh2_session_last_error(session, &errmsg, &errlen, 0); err = libssh2_session_last_error(session, &errmsg, &errlen, 0);
fprintf(stderr, "Unable to open a session: (%d) %s\n", err, errmsg); fprintf(stderr, "Unable to open a session: (%d) %s\n", err, errmsg);
goto shutdown; goto shutdown;
@ -211,13 +209,18 @@ shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session); libssh2_session_free(session);
} }
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
if(local) if(local)
fclose(local); fclose(local);
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -31,6 +31,13 @@
#include <ctype.h> #include <ctype.h>
#include <time.h> #include <time.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "scp_write.c";
static const char *scppath = "/tmp/TEST";
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -68,17 +75,11 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
int rc;
LIBSSH2_SESSION *session = NULL; LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *loclfile = "scp_write.c";
const char *scppath = "/tmp/TEST";
FILE *local; FILE *local;
int rc; char mem[1024 * 100];
char mem[1024*100];
size_t nread; size_t nread;
char *ptr; char *ptr;
struct stat fileinfo; struct stat fileinfo;
@ -89,11 +90,10 @@ int main(int argc, char *argv[])
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -118,38 +118,42 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
local = fopen(loclfile, "rb"); local = fopen(loclfile, "rb");
if(!local) { if(!local) {
fprintf(stderr, "Can't local file %s\n", loclfile); fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1; return 1;
} }
stat(loclfile, &fileinfo); stat(loclfile, &fileinfo);
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -157,11 +161,11 @@ int main(int argc, char *argv[])
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
*/ */
while((rc = libssh2_session_handshake(session, sock)) while((rc = libssh2_session_handshake(session, sock)) ==
== LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -181,7 +185,7 @@ int main(int argc, char *argv[])
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -192,7 +196,7 @@ int main(int argc, char *argv[])
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -202,8 +206,8 @@ int main(int argc, char *argv[])
channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777, channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777,
(size_t)fileinfo.st_size); (size_t)fileinfo.st_size);
if((!channel) && (libssh2_session_last_errno(session) != if(!channel &&
LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
char *err_msg; char *err_msg;
libssh2_session_last_error(session, &err_msg, NULL, 0); libssh2_session_last_error(session, &err_msg, NULL, 0);
@ -247,7 +251,7 @@ int main(int argc, char *argv[])
} while(nread); } while(nread);
} while(!nread); /* only continue if nread was drained */ } while(!nread); /* only continue if nread was drained */
duration = (int)(time(NULL)-start); duration = (int)(time(NULL) - start);
fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n", fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n",
(long)total, duration, (double)total / duration); (long)total, duration, (double)total / duration);
@ -266,15 +270,20 @@ int main(int argc, char *argv[])
shutdown: shutdown:
while(libssh2_session_disconnect(session, "Normal Shutdown") if(session) {
== LIBSSH2_ERROR_EAGAIN); while(libssh2_session_disconnect(session, "Normal Shutdown") ==
libssh2_session_free(session); LIBSSH2_ERROR_EAGAIN);
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp 192.168.0.1 user password /tmp/secrets -p|-i|-k" * $ ./sftp 192.168.0.1 user password /tmp/secrets -p|-i|-k
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -27,9 +27,6 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -76,7 +73,7 @@ static void kbd_callback(const char *name, int name_len,
fgets(buf, sizeof(buf), stdin); fgets(buf, sizeof(buf), stdin);
n = strlen(buf); n = strlen(buf);
while(n > 0 && strchr("\r\n", buf[n - 1])) while(n > 0 && strchr("\r\n", buf[n - 1]))
n--; n--;
buf[n] = 0; buf[n] = 0;
responses[i].text = strdup(buf); responses[i].text = strdup(buf);
@ -99,18 +96,17 @@ int main(int argc, char *argv[])
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session;
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -132,7 +128,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -142,20 +138,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are blocking */ /* Since we have set non-blocking, tell libssh2 we are blocking */
libssh2_session_set_blocking(session, 1); libssh2_session_set_blocking(session, 1);
@ -166,7 +167,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -184,65 +185,67 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password") != NULL) { fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth_pw |= 1; if(strstr(userauthlist, "password")) {
} auth_pw |= 1;
if(strstr(userauthlist, "keyboard-interactive") != NULL) { }
auth_pw |= 2; if(strstr(userauthlist, "keyboard-interactive")) {
} auth_pw |= 2;
if(strstr(userauthlist, "publickey") != NULL) { }
auth_pw |= 4; if(strstr(userauthlist, "publickey")) {
} auth_pw |= 4;
}
/* if we got an 4. argument we set this option if supported */ /* check for options */
if(argc > 5) { if(argc > 5) {
if((auth_pw & 1) && !strcmp(argv[5], "-p")) { if((auth_pw & 1) && !strcmp(argv[5], "-p")) {
auth_pw = 1; auth_pw = 1;
}
if((auth_pw & 2) && !strcmp(argv[5], "-i")) {
auth_pw = 2;
}
if((auth_pw & 4) && !strcmp(argv[5], "-k")) {
auth_pw = 4;
}
} }
if((auth_pw & 2) && !strcmp(argv[5], "-i")) {
auth_pw = 2;
}
if((auth_pw & 4) && !strcmp(argv[5], "-k")) {
auth_pw = 4;
}
}
if(auth_pw & 1) { if(auth_pw & 1) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
}
} }
} else if(auth_pw & 2) {
else if(auth_pw & 2) { /* Or via keyboard-interactive */
/* Or via keyboard-interactive */ if(libssh2_userauth_keyboard_interactive(session, username,
if(libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) {
&kbd_callback) ) { fprintf(stderr,
fprintf(stderr, "Authentication by keyboard-interactive failed!\n");
"\tAuthentication by keyboard-interactive failed!\n"); goto shutdown;
goto shutdown; }
else {
fprintf(stderr,
"Authentication by keyboard-interactive succeeded.\n");
}
}
else if(auth_pw & 4) {
/* Or by public key */
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
} }
else { else {
fprintf(stderr, fprintf(stderr, "No supported authentication methods found!\n");
"\tAuthentication by keyboard-interactive succeeded.\n");
}
}
else if(auth_pw & 4) {
/* Or by public key */
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
else {
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
}
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
} }
fprintf(stderr, "libssh2_sftp_init()!\n"); fprintf(stderr, "libssh2_sftp_init()!\n");
@ -255,14 +258,14 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_open()!\n"); fprintf(stderr, "libssh2_sftp_open()!\n");
/* Request a file via SFTP */ /* Request a file via SFTP */
sftp_handle = sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); LIBSSH2_FXF_READ, 0);
if(!sftp_handle) { if(!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP: %ld\n", fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session)); libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n");
do { do {
char mem[1024]; char mem[1024];
@ -284,14 +287,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -27,9 +27,6 @@
#ifdef HAVE_NETINET_IN_H #ifdef HAVE_NETINET_IN_H
#include <netinet/in.h> #include <netinet/in.h>
#endif #endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_TIME_H #ifdef HAVE_SYS_TIME_H
#include <sys/time.h> #include <sys/time.h>
#endif #endif
@ -44,6 +41,13 @@
example uses to store the downloaded example uses to store the downloaded
file in */ file in */
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *sftppath = "/tmp/TEST"; /* source path */
static const char *dest = "/tmp/TEST2"; /* destination path */
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -80,17 +84,11 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/TEST"; /* source path */
const char *dest = "/tmp/TEST2"; /* destination path */
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
FILE *tempstorage; FILE *tempstorage = NULL;
char mem[1000]; char mem[1000];
struct timeval timeout; struct timeval timeout;
fd_set fd; fd_set fd;
@ -98,40 +96,56 @@ int main(int argc, char *argv[])
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
if(argc > 1) {
username = argv[1];
}
if(argc > 2) {
password = argv[2];
}
if(argc > 3) {
sftppath = argv[3];
}
if(argc > 4) {
dest = argv[4];
}
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* The application is responsible for creating the socket establishing * responsible for creating the socket establishing the connection
* the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = htonl(0x7F000001); sin.sin_addr.s_addr = htonl(0x7F000001);
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
@ -139,7 +153,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -156,19 +170,6 @@ int main(int argc, char *argv[])
} }
fprintf(stderr, "\n"); fprintf(stderr, "\n");
if(argc > 1) {
username = argv[1];
}
if(argc > 2) {
password = argv[2];
}
if(argc > 3) {
sftppath = argv[3];
}
if(argc > 4) {
dest = argv[4];
}
tempstorage = fopen(STORAGE, "wb"); tempstorage = fopen(STORAGE, "wb");
if(!tempstorage) { if(!tempstorage) {
fprintf(stderr, "Can't open temp storage file %s\n", STORAGE); fprintf(stderr, "Can't open temp storage file %s\n", STORAGE);
@ -177,22 +178,22 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
while((rc = libssh2_userauth_password(session, username, password)) while((rc = libssh2_userauth_password(session, username, password)) ==
== LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
else { else {
/* Or by public key */ /* Or by public key */
while((rc = while((rc =
libssh2_userauth_publickey_fromfile(session, username, libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -201,8 +202,7 @@ int main(int argc, char *argv[])
sftp_session = libssh2_sftp_init(session); sftp_session = libssh2_sftp_init(session);
if(!sftp_session) { if(!sftp_session) {
if(libssh2_session_last_errno(session) == if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) {
LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "non-blocking init\n"); fprintf(stderr, "non-blocking init\n");
waitsocket(sock, session); /* now we wait */ waitsocket(sock, session); /* now we wait */
} }
@ -217,10 +217,10 @@ int main(int argc, char *argv[])
do { do {
sftp_handle = libssh2_sftp_open(sftp_session, sftppath, sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
LIBSSH2_FXF_READ, 0); LIBSSH2_FXF_READ, 0);
if(!sftp_handle) { if(!sftp_handle) {
if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
else { else {
@ -283,11 +283,13 @@ int main(int argc, char *argv[])
/* we're done downloading, now reverse the process and upload the /* we're done downloading, now reverse the process and upload the
temporarily stored data to the destination path */ temporarily stored data to the destination path */
sftp_handle = sftp_handle = libssh2_sftp_open(sftp_session, dest,
libssh2_sftp_open(sftp_session, dest, LIBSSH2_FXF_WRITE |
LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT, LIBSSH2_FXF_CREAT,
LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRUSR |
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); LIBSSH2_SFTP_S_IWUSR |
LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH);
if(sftp_handle) { if(sftp_handle) {
size_t nread; size_t nread;
char *ptr; char *ptr;
@ -342,16 +344,22 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
if(tempstorage) if(tempstorage)
fclose(tempstorage); fclose(tempstorage);
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* sftp_append 192.168.0.1 user password localfile /tmp/remotefile * $ ./sftp_append 192.168.0.1 user password localfile /tmp/remotefile
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -30,6 +30,13 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "sftp_write.c";
static const char *sftppath = "/tmp/TEST";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -37,30 +44,23 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *loclfile = "sftp_write.c";
const char *sftppath = "/tmp/TEST";
int rc; int rc;
FILE *local; LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
LIBSSH2_SFTP_ATTRIBUTES attrs; LIBSSH2_SFTP_ATTRIBUTES attrs;
char mem[1024*100]; char mem[1024 * 100];
FILE *local;
size_t nread; size_t nread;
ssize_t nwritten; ssize_t nwritten;
char *ptr; char *ptr;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -93,7 +93,7 @@ int main(int argc, char *argv[])
local = fopen(loclfile, "rb"); local = fopen(loclfile, "rb");
if(!local) { if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile); fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1; return 1;
} }
/* /*
@ -101,20 +101,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are blocking */ /* Since we have set non-blocking, tell libssh2 we are blocking */
libssh2_session_set_blocking(session, 1); libssh2_session_set_blocking(session, 1);
@ -125,7 +130,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -143,7 +148,7 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -152,7 +157,7 @@ int main(int argc, char *argv[])
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -167,14 +172,16 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_open() for READ and WRITE!\n"); fprintf(stderr, "libssh2_sftp_open() for READ and WRITE!\n");
/* Request a file via SFTP */ /* Request a file via SFTP */
sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
sftp_handle = LIBSSH2_FXF_WRITE |
libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ,
LIBSSH2_FXF_WRITE|LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR |
LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IWUSR |
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH);
if(!sftp_handle) { if(!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
@ -187,11 +194,12 @@ int main(int argc, char *argv[])
fprintf(stderr, "Did a seek to position %ld\n", (long) attrs.filesize); fprintf(stderr, "Did a seek to position %ld\n", (long) attrs.filesize);
fprintf(stderr, "libssh2_sftp_open() a handle for APPEND\n"); fprintf(stderr, "libssh2_sftp_open() a handle for APPEND\n");
if(!sftp_handle) { if(!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");
do { do {
nread = fread(mem, 1, sizeof(mem), local); nread = fread(mem, 1, sizeof(mem), local);
@ -216,16 +224,23 @@ int main(int argc, char *argv[])
libssh2_sftp_shutdown(sftp_session); libssh2_sftp_shutdown(sftp_session);
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
if(local) if(local)
fclose(local); fclose(local);
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp 192.168.0.1 user password /tmp/sftp_mkdir" * $ ./sftp_mkdir 192.168.0.1 user password /tmp/sftp_mkdir
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -30,6 +30,12 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *sftppath = "/tmp/sftp_mkdir";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -37,22 +43,16 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/sftp_mkdir";
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -74,7 +74,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -84,20 +84,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
@ -105,7 +110,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -123,7 +128,7 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -132,7 +137,7 @@ int main(int argc, char *argv[])
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -149,10 +154,11 @@ int main(int argc, char *argv[])
/* Make a directory via SFTP */ /* Make a directory via SFTP */
rc = libssh2_sftp_mkdir(sftp_session, sftppath, rc = libssh2_sftp_mkdir(sftp_session, sftppath,
LIBSSH2_SFTP_S_IRWXU| LIBSSH2_SFTP_S_IRWXU |
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IXGRP| LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH); LIBSSH2_SFTP_S_IXGRP |
LIBSSH2_SFTP_S_IROTH |
LIBSSH2_SFTP_S_IXOTH);
if(rc) if(rc)
fprintf(stderr, "libssh2_sftp_mkdir failed: %d\n", rc); fprintf(stderr, "libssh2_sftp_mkdir failed: %d\n", rc);
@ -160,14 +166,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp 192.168.0.1 user password /tmp/sftp_write_nonblock.c" * $ ./sftp_mkdir_nonblock 192.168.0.1 user password /tmp/sftp_write_nonblock.c
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -30,6 +30,12 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *sftppath = "/tmp/sftp_mkdir_nonblock";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -37,22 +43,16 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/sftp_mkdir_nonblock";
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -74,7 +74,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -84,20 +84,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
@ -105,7 +110,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -123,7 +128,7 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -132,12 +137,11 @@ int main(int argc, char *argv[])
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
fprintf(stderr, "libssh2_sftp_init()!\n");
sftp_session = libssh2_sftp_init(session); sftp_session = libssh2_sftp_init(session);
if(!sftp_session) { if(!sftp_session) {
@ -148,26 +152,32 @@ int main(int argc, char *argv[])
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
fprintf(stderr, "libssh2_sftp_mkdirnb()!\n");
/* Make a directory via SFTP */ /* Make a directory via SFTP */
while(libssh2_sftp_mkdir(sftp_session, sftppath, while(libssh2_sftp_mkdir(sftp_session, sftppath,
LIBSSH2_SFTP_S_IRWXU| LIBSSH2_SFTP_S_IRWXU |
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IXGRP| LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH) LIBSSH2_SFTP_S_IXGRP |
== LIBSSH2_ERROR_EAGAIN); LIBSSH2_SFTP_S_IROTH |
LIBSSH2_SFTP_S_IXOTH) ==
LIBSSH2_ERROR_EAGAIN);
libssh2_sftp_shutdown(sftp_session); libssh2_sftp_shutdown(sftp_session);
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp_nonblock 192.168.0.1 user password /tmp/secrets" * $ ./sftp_nonblock 192.168.0.1 user password /tmp/secrets
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -40,12 +40,18 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *sftppath = "/tmp/TEST";
#ifdef HAVE_GETTIMEOFDAY #ifdef HAVE_GETTIMEOFDAY
/* diff in ms */ /* diff in ms */
static long tvdiff(struct timeval newer, struct timeval older) static long tvdiff(struct timeval newer, struct timeval older)
{ {
return (newer.tv_sec-older.tv_sec)*1000+ return (newer.tv_sec - older.tv_sec) * 1000 +
(newer.tv_usec-older.tv_usec)/1000; (newer.tv_usec - older.tv_usec) / 1000;
} }
#endif #endif
@ -86,30 +92,24 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session; int rc;
const char *pubkey = "/home/username/.ssh/id_rsa.pub"; LIBSSH2_SESSION *session = NULL;
const char *privkey = "/home/username/.ssh/id_rsa"; LIBSSH2_SFTP *sftp_session;
const char *username = "username"; LIBSSH2_SFTP_HANDLE *sftp_handle;
const char *password = "password";
const char *sftppath = "/tmp/TEST";
#ifdef HAVE_GETTIMEOFDAY #ifdef HAVE_GETTIMEOFDAY
struct timeval start; struct timeval start;
struct timeval end; struct timeval end;
long time_ms; long time_ms;
#endif #endif
int rc;
libssh2_struct_stat_size total = 0; libssh2_struct_stat_size total = 0;
int spin = 0; int spin = 0;
LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -131,7 +131,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -141,19 +141,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -166,10 +172,10 @@ int main(int argc, char *argv[])
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
*/ */
while((rc = libssh2_session_handshake(session, sock)) == while((rc = libssh2_session_handshake(session, sock)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -186,22 +192,22 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
while((rc = libssh2_userauth_password(session, username, password)) while((rc = libssh2_userauth_password(session, username, password)) ==
== LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
else { else {
/* Or by public key */ /* Or by public key */
while((rc = while((rc =
libssh2_userauth_publickey_fromfile(session, username, libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -213,8 +219,7 @@ int main(int argc, char *argv[])
sftp_session = libssh2_sftp_init(session); sftp_session = libssh2_sftp_init(session);
if(!sftp_session) { if(!sftp_session) {
if(libssh2_session_last_errno(session) == if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) {
LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "non-blocking init\n"); fprintf(stderr, "non-blocking init\n");
waitsocket(sock, session); /* now we wait */ waitsocket(sock, session); /* now we wait */
} }
@ -230,10 +235,10 @@ int main(int argc, char *argv[])
do { do {
sftp_handle = libssh2_sftp_open(sftp_session, sftppath, sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
LIBSSH2_FXF_READ, 0); LIBSSH2_FXF_READ, 0);
if(!sftp_handle) { if(!sftp_handle) {
if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
else { else {
@ -245,12 +250,12 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n");
do { do {
char mem[1024*24]; char mem[1024 * 24];
ssize_t nread; ssize_t nread;
/* loop until we fail */ /* loop until we fail */
while((nread = libssh2_sftp_read(sftp_handle, mem, while((nread = libssh2_sftp_read(sftp_handle, mem, sizeof(mem))) ==
sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) { LIBSSH2_ERROR_EAGAIN) {
spin++; spin++;
waitsocket(sock, session); /* now we wait */ waitsocket(sock, session); /* now we wait */
} }
@ -268,7 +273,7 @@ int main(int argc, char *argv[])
time_ms = tvdiff(end, start); time_ms = tvdiff(end, start);
fprintf(stderr, "Got %ld bytes in %ld ms = %.1f bytes/sec spin: %d\n", fprintf(stderr, "Got %ld bytes in %ld ms = %.1f bytes/sec spin: %d\n",
(long)total, time_ms, (long)total, time_ms,
(double)total/((double)time_ms/1000.0), spin); (double)total / ((double)time_ms / 1000.0), spin);
#else #else
fprintf(stderr, "Got %ld bytes spin: %d\n", (long)total, spin); fprintf(stderr, "Got %ld bytes spin: %d\n", (long)total, spin);
#endif #endif
@ -278,16 +283,21 @@ int main(int argc, char *argv[])
shutdown: shutdown:
fprintf(stderr, "libssh2_session_disconnect\n"); if(session) {
while(libssh2_session_disconnect(session, "Normal Shutdown") fprintf(stderr, "libssh2_session_disconnect\n");
== LIBSSH2_ERROR_EAGAIN); while(libssh2_session_disconnect(session, "Normal Shutdown") ==
libssh2_session_free(session); LIBSSH2_ERROR_EAGAIN);
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp 192.168.0.1 user password sftp_write.c /tmp/secrets" * $ ./sftp_write 192.168.0.1 user password sftp_write.c /tmp/secrets
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -30,6 +30,13 @@
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "sftp_write.c";
static const char *sftppath = "/tmp/TEST";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -37,29 +44,22 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *loclfile = "sftp_write.c";
const char *sftppath = "/tmp/TEST";
int rc; int rc;
FILE *local; LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
char mem[1024*100]; FILE *local;
char mem[1024 * 100];
size_t nread; size_t nread;
ssize_t nwritten; ssize_t nwritten;
char *ptr; char *ptr;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -84,7 +84,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -92,7 +92,7 @@ int main(int argc, char *argv[])
local = fopen(loclfile, "rb"); local = fopen(loclfile, "rb");
if(!local) { if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile); fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1; return 1;
} }
/* /*
@ -100,20 +100,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are blocking */ /* Since we have set non-blocking, tell libssh2 we are blocking */
libssh2_session_set_blocking(session, 1); libssh2_session_set_blocking(session, 1);
@ -124,7 +129,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -142,7 +147,7 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -151,7 +156,7 @@ int main(int argc, char *argv[])
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -166,16 +171,20 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_open()!\n"); fprintf(stderr, "libssh2_sftp_open()!\n");
/* Request a file via SFTP */ /* Request a file via SFTP */
sftp_handle = sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE |
LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_FXF_CREAT |
LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_FXF_TRUNC,
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); LIBSSH2_SFTP_S_IRUSR |
LIBSSH2_SFTP_S_IWUSR |
LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH);
if(!sftp_handle) { if(!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");
do { do {
nread = fread(mem, 1, sizeof(mem), local); nread = fread(mem, 1, sizeof(mem), local);
@ -193,23 +202,29 @@ int main(int argc, char *argv[])
ptr += nwritten; ptr += nwritten;
nread -= nwritten; nread -= nwritten;
} while(nread); } while(nread);
} while(nwritten > 0); } while(nwritten > 0);
libssh2_sftp_close(sftp_handle); libssh2_sftp_close(sftp_handle);
libssh2_sftp_shutdown(sftp_session); libssh2_sftp_shutdown(sftp_session);
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
if(local) if(local)
fclose(local); fclose(local);
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp 192.168.0.1 user password thisfile /tmp/storehere" * $ ./sftp_write_nonblock 192.168.0.1 user password thisfile /tmp/storehere
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -37,6 +37,13 @@
#include <ctype.h> #include <ctype.h>
#include <time.h> #include <time.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "sftp_write_nonblock.c";
static const char *sftppath = "/tmp/sftp_write_nonblock.c";
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -74,17 +81,11 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *loclfile = "sftp_write_nonblock.c";
const char *sftppath = "/tmp/sftp_write_nonblock.c";
int rc; int rc;
FILE *local; LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
FILE *local;
char mem[1024 * 100]; char mem[1024 * 100];
size_t nread; size_t nread;
ssize_t nwritten; ssize_t nwritten;
@ -95,11 +96,10 @@ int main(int argc, char *argv[])
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -124,7 +124,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -132,7 +132,7 @@ int main(int argc, char *argv[])
local = fopen(loclfile, "rb"); local = fopen(loclfile, "rb");
if(!local) { if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile); fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1; return 1;
} }
/* /*
@ -140,20 +140,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -161,17 +166,17 @@ int main(int argc, char *argv[])
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
*/ */
while((rc = libssh2_session_handshake(session, sock)) while((rc = libssh2_session_handshake(session, sock)) ==
== LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do is /* At this point we have not yet authenticated. The first thing to do
* check the hostkey's fingerprint against our known hosts Your app may * is check the hostkey's fingerprint against our known hosts Your app
* have it hard coded, may go to a file, may present it to the user, * may have it hard coded, may go to a file, may present it to the
* that's your call * user, that's your call
*/ */
fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
fprintf(stderr, "Fingerprint: "); fprintf(stderr, "Fingerprint: ");
@ -183,9 +188,9 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -196,7 +201,7 @@ int main(int argc, char *argv[])
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -206,7 +211,7 @@ int main(int argc, char *argv[])
sftp_session = libssh2_sftp_init(session); sftp_session = libssh2_sftp_init(session);
if(!sftp_session && if(!sftp_session &&
(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to init SFTP session\n"); fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown; goto shutdown;
} }
@ -215,23 +220,24 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_open()!\n"); fprintf(stderr, "libssh2_sftp_open()!\n");
/* Request a file via SFTP */ /* Request a file via SFTP */
do { do {
sftp_handle = sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE |
LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT| LIBSSH2_FXF_CREAT |
LIBSSH2_FXF_TRUNC, LIBSSH2_FXF_TRUNC,
LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRUSR |
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); LIBSSH2_SFTP_S_IWUSR |
LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH);
if(!sftp_handle && if(!sftp_handle &&
(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
} while(!sftp_handle); } while(!sftp_handle);
fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");
start = time(NULL); start = time(NULL);
do { do {
nread = fread(mem, 1, sizeof(mem), local); nread = fread(mem, 1, sizeof(mem), local);
if(nread <= 0) { if(nread <= 0) {
@ -245,18 +251,17 @@ int main(int argc, char *argv[])
do { do {
/* write data in a loop until we block */ /* write data in a loop until we block */
while((nwritten = libssh2_sftp_write(sftp_handle, ptr, nread)) == while((nwritten = libssh2_sftp_write(sftp_handle, ptr, nread)) ==
LIBSSH2_ERROR_EAGAIN) { LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session); waitsocket(sock, session);
} }
if(nwritten < 0) if(nwritten < 0)
break; break;
ptr += nwritten; ptr += nwritten;
nread -= nwritten; nread -= nwritten;
} while(nread); } while(nread);
} while(nwritten > 0); } while(nwritten > 0);
duration = (int)(time(NULL)-start); duration = (int)(time(NULL) - start);
fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n", fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n",
(long)total, duration, (double)total / duration); (long)total, duration, (double)total / duration);
@ -267,15 +272,20 @@ int main(int argc, char *argv[])
shutdown: shutdown:
while(libssh2_session_disconnect(session, "Normal Shutdown") if(session) {
== LIBSSH2_ERROR_EAGAIN); while(libssh2_session_disconnect(session, "Normal Shutdown") ==
libssh2_session_free(session); LIBSSH2_ERROR_EAGAIN);
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* "sftp 192.168.0.1 user password file /tmp/storehere" * $ ./sftp_write_sliding 192.168.0.1 user password thisfile /tmp/storehere
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -37,6 +37,13 @@
#include <ctype.h> #include <ctype.h>
#include <time.h> #include <time.h>
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "sftp_write_nonblock.c";
static const char *sftppath = "/tmp/sftp_write_nonblock.c";
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -74,32 +81,25 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *loclfile = "sftp_write_nonblock.c";
const char *sftppath = "/tmp/sftp_write_nonblock.c";
int rc; int rc;
FILE *local; LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
FILE *local;
char mem[1024 * 1000]; char mem[1024 * 1000];
size_t nread; size_t nread;
size_t memuse;
ssize_t nwritten; ssize_t nwritten;
size_t memuse;
time_t start; time_t start;
libssh2_struct_stat_size total = 0; libssh2_struct_stat_size total = 0;
int duration; int duration;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -124,7 +124,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -132,7 +132,7 @@ int main(int argc, char *argv[])
local = fopen(loclfile, "rb"); local = fopen(loclfile, "rb");
if(!local) { if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile); fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1; return 1;
} }
/* /*
@ -140,20 +140,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -161,11 +166,11 @@ int main(int argc, char *argv[])
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
*/ */
while((rc = libssh2_session_handshake(session, sock)) while((rc = libssh2_session_handshake(session, sock)) ==
== LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -183,9 +188,9 @@ int main(int argc, char *argv[])
if(auth_pw) { if(auth_pw) {
/* We could authenticate via password */ /* We could authenticate via password */
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -196,7 +201,7 @@ int main(int argc, char *argv[])
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -206,7 +211,7 @@ int main(int argc, char *argv[])
sftp_session = libssh2_sftp_init(session); sftp_session = libssh2_sftp_init(session);
if(!sftp_session && if(!sftp_session &&
(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to init SFTP session\n"); fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown; goto shutdown;
} }
@ -215,26 +220,27 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_open()!\n"); fprintf(stderr, "libssh2_sftp_open()!\n");
/* Request a file via SFTP */ /* Request a file via SFTP */
do { do {
sftp_handle = sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE |
LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT| LIBSSH2_FXF_CREAT |
LIBSSH2_FXF_TRUNC, LIBSSH2_FXF_TRUNC,
LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRUSR |
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); LIBSSH2_SFTP_S_IWUSR |
LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IROTH);
if(!sftp_handle && if(!sftp_handle &&
(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open file with SFTP\n"); fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown; goto shutdown;
} }
} while(!sftp_handle); } while(!sftp_handle);
fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");
start = time(NULL); start = time(NULL);
memuse = 0; /* it starts blank */
memuse = 0; /* it starts blank */
do { do {
nread = fread(&mem[memuse], 1, sizeof(mem)-memuse, local); nread = fread(&mem[memuse], 1, sizeof(mem) - memuse, local);
if(nread <= 0) { if(nread <= 0) {
/* end of file */ /* end of file */
if(memuse > 0) if(memuse > 0)
@ -248,7 +254,7 @@ int main(int argc, char *argv[])
/* write data in a loop until we block */ /* write data in a loop until we block */
while((nwritten = libssh2_sftp_write(sftp_handle, mem, memuse)) == while((nwritten = libssh2_sftp_write(sftp_handle, mem, memuse)) ==
LIBSSH2_ERROR_EAGAIN) { LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session); waitsocket(sock, session);
} }
if(nwritten < 0) if(nwritten < 0)
@ -265,7 +271,7 @@ int main(int argc, char *argv[])
} while(nwritten > 0); } while(nwritten > 0);
duration = (int)(time(NULL)-start); duration = (int)(time(NULL) - start);
fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n", fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n",
(long)total, duration, (double)total / duration); (long)total, duration, (double)total / duration);
@ -276,15 +282,20 @@ int main(int argc, char *argv[])
shutdown: shutdown:
while(libssh2_session_disconnect(session, "Normal Shutdown") if(session) {
== LIBSSH2_ERROR_EAGAIN); while(libssh2_session_disconnect(session, "Normal Shutdown") ==
libssh2_session_free(session); LIBSSH2_ERROR_EAGAIN);
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password and * The sample code has default values for host name, user name, password and
* path, but you can specify them on the command line like: * path, but you can specify them on the command line like:
* *
* "sftpdir 192.168.0.1 user password /tmp/secretdir" * $ ./sftpdir 192.168.0.1 user password /tmp/secretdir
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -23,9 +23,6 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -43,6 +40,7 @@ static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa"; static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username"; static const char *username = "username";
static const char *password = "password"; static const char *password = "password";
static const char *sftppath = "/tmp/secretdir";
static void kbd_callback(const char *name, int name_len, static void kbd_callback(const char *name, int name_len,
const char *instruction, int instruction_len, const char *instruction, int instruction_len,
@ -67,22 +65,21 @@ int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
libssh2_socket_t sock; libssh2_socket_t sock;
int rc, i, auth_pw = 0; int i, auth_pw = 0;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session; int rc;
const char *sftppath = "/tmp/secretdir"; LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -104,7 +101,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -114,20 +111,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers * and setup crypto, compression, and MAC layers
@ -135,7 +137,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -153,68 +155,67 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password") != NULL) { fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth_pw |= 1; if(strstr(userauthlist, "password")) {
} auth_pw |= 1;
if(strstr(userauthlist, "keyboard-interactive") != NULL) { }
auth_pw |= 2; if(strstr(userauthlist, "keyboard-interactive")) {
} auth_pw |= 2;
if(strstr(userauthlist, "publickey") != NULL) { }
auth_pw |= 4; if(strstr(userauthlist, "publickey")) {
} auth_pw |= 4;
}
/* if we got an 5. argument we set this option if supported */ /* check for options */
if(argc > 5) { if(argc > 5) {
if((auth_pw & 1) && !strcmp(argv[5], "-p")) { if((auth_pw & 1) && !strcmp(argv[5], "-p")) {
auth_pw = 1; auth_pw = 1;
}
if((auth_pw & 2) && !strcmp(argv[5], "-i")) {
auth_pw = 2;
}
if((auth_pw & 4) && !strcmp(argv[5], "-k")) {
auth_pw = 4;
}
} }
if((auth_pw & 2) && !strcmp(argv[5], "-i")) {
auth_pw = 2;
}
if((auth_pw & 4) && !strcmp(argv[5], "-k")) {
auth_pw = 4;
}
}
if(auth_pw & 1) { if(auth_pw & 1) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "\tAuthentication by password failed!\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
}
}
else if(auth_pw & 2) {
/* Or via keyboard-interactive */
if(libssh2_userauth_keyboard_interactive(session, username,
&kbd_callback) ) {
fprintf(stderr,
"Authentication by keyboard-interactive failed!\n");
goto shutdown;
}
else {
fprintf(stderr,
"Authentication by keyboard-interactive succeeded.\n");
}
}
else if(auth_pw & 4) {
/* Or by public key */
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
} }
else { else {
fprintf(stderr, "\tAuthentication by password succeeded.\n"); fprintf(stderr, "No supported authentication methods found!\n");
}
}
else if(auth_pw & 2) {
/* Or via keyboard-interactive */
if(libssh2_userauth_keyboard_interactive(session, username,
&kbd_callback) ) {
fprintf(stderr,
"\tAuthentication by keyboard-interactive failed!\n");
goto shutdown; goto shutdown;
} }
else {
fprintf(stderr,
"\tAuthentication by keyboard-interactive succeeded.\n");
}
}
else if(auth_pw & 4) {
/* Or by public key */
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown;
}
else {
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
}
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
} }
fprintf(stderr, "libssh2_sftp_init()!\n"); fprintf(stderr, "libssh2_sftp_init()!\n");
@ -231,11 +232,11 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_opendir()!\n"); fprintf(stderr, "libssh2_sftp_opendir()!\n");
/* Request a dir listing via SFTP */ /* Request a dir listing via SFTP */
sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath); sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath);
if(!sftp_handle) { if(!sftp_handle) {
fprintf(stderr, "Unable to open dir with SFTP\n"); fprintf(stderr, "Unable to open dir with SFTP\n");
goto shutdown; goto shutdown;
} }
fprintf(stderr, "libssh2_sftp_opendir() is done, now receive listing!\n"); fprintf(stderr, "libssh2_sftp_opendir() is done, now receive listing!\n");
do { do {
char mem[512]; char mem[512];
@ -287,14 +288,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,7 @@
* The sample code has default values for host name, user name, password and * The sample code has default values for host name, user name, password and
* path, but you can specify them on the command line like: * path, but you can specify them on the command line like:
* *
* "sftpdir 192.168.0.1 user password /tmp/secretdir" * $ ./sftpdir_nonblock 192.168.0.1 user password /tmp/secretdir
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -23,9 +23,6 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -39,6 +36,12 @@
#define __FILESIZE "llu" #define __FILESIZE "llu"
#endif #endif
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *sftppath = "/tmp/secretdir";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -46,23 +49,17 @@ int main(int argc, char *argv[])
int i, auth_pw = 1; int i, auth_pw = 1;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/secretdir";
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_HANDLE *sftp_handle;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -84,7 +81,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -94,20 +91,25 @@ int main(int argc, char *argv[])
* and establishing the connection * and establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance /* Create a session instance */
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* Since we have set non-blocking, tell libssh2 we are non-blocking */ /* Since we have set non-blocking, tell libssh2 we are non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -119,7 +121,7 @@ int main(int argc, char *argv[])
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -139,7 +141,7 @@ int main(int argc, char *argv[])
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -150,7 +152,7 @@ int main(int argc, char *argv[])
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -159,8 +161,8 @@ int main(int argc, char *argv[])
do { do {
sftp_session = libssh2_sftp_init(session); sftp_session = libssh2_sftp_init(session);
if((!sftp_session) && (libssh2_session_last_errno(session) != if(!sftp_session &&
LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to init SFTP session\n"); fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown; goto shutdown;
} }
@ -171,8 +173,8 @@ int main(int argc, char *argv[])
do { do {
sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath); sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath);
if((!sftp_handle) && (libssh2_session_last_errno(session) != if(!sftp_handle &&
LIBSSH2_ERROR_EAGAIN)) { libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open dir with SFTP\n"); fprintf(stderr, "Unable to open dir with SFTP\n");
goto shutdown; goto shutdown;
} }
@ -227,14 +229,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,7 +4,8 @@
* The sample code has default values for host name, user name, password * The sample code has default values for host name, user name, password
* and path to copy, but you can specify them on the command line like: * and path to copy, but you can specify them on the command line like:
* *
* Usage: ssh2 hostip user password [[-p|-i|-k] [command]] * $ ./ssh2 hostip user password [[-p|-i|-k] [command]]
*
* -p authenticate using password * -p authenticate using password
* -i authenticate using keyboard-interactive * -i authenticate using keyboard-interactive
* -k authenticate using public key (password argument decrypts keyfile) * -k authenticate using public key (password argument decrypts keyfile)
@ -13,7 +14,6 @@
#include "libssh2_setup.h" #include "libssh2_setup.h"
#include <libssh2.h> #include <libssh2.h>
#include <libssh2_sftp.h>
#ifdef HAVE_SYS_SOCKET_H #ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h> #include <sys/socket.h>
@ -67,18 +67,19 @@ int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
libssh2_socket_t sock; libssh2_socket_t sock;
int rc, i, auth_pw = 0; int i, auth_pw = 0;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
rc = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(rc != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", rc); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
@ -98,7 +99,7 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -107,6 +108,11 @@ int main(int argc, char *argv[])
* responsible for creating the socket establishing the connection * responsible for creating the socket establishing the connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
rc = 1;
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
@ -117,29 +123,25 @@ int main(int argc, char *argv[])
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance and start it up. This will trade welcome /* Create a session instance and start it up. This will trade welcome
* banners, exchange keys, and setup crypto, compression, and MAC layers * banners, exchange keys, and setup crypto, compression, and MAC layers
*/ */
session = libssh2_session_init(); session = libssh2_session_init();
/* Enable all debugging when libssh2 was built with debugging enabled */ if(!session) {
libssh2_trace(session, fprintf(stderr, "Could not initialize SSH session!\n");
LIBSSH2_TRACE_TRANS | goto shutdown;
LIBSSH2_TRACE_KEX | }
LIBSSH2_TRACE_AUTH |
LIBSSH2_TRACE_CONN |
LIBSSH2_TRACE_SCP |
LIBSSH2_TRACE_SFTP |
LIBSSH2_TRACE_ERROR |
LIBSSH2_TRACE_PUBLICKEY |
LIBSSH2_TRACE_SOCKET
);
if(libssh2_session_handshake(session, sock)) { /* Enable all debugging when libssh2 was built with debugging enabled */
fprintf(stderr, "Failure establishing SSH session\n"); libssh2_trace(session, ~0);
return -1;
rc = libssh2_session_handshake(session, sock);
if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -157,91 +159,94 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password") != NULL) { fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth_pw |= 1; if(strstr(userauthlist, "password")) {
} auth_pw |= 1;
if(strstr(userauthlist, "keyboard-interactive") != NULL) { }
auth_pw |= 2; if(strstr(userauthlist, "keyboard-interactive")) {
} auth_pw |= 2;
if(strstr(userauthlist, "publickey") != NULL) { }
auth_pw |= 4; if(strstr(userauthlist, "publickey")) {
} auth_pw |= 4;
}
/* if we got an 4. argument we set this option if supported */ /* check for options */
if(argc > 4) { if(argc > 4) {
if((auth_pw & 1) && !strcmp(argv[4], "-p")) { if((auth_pw & 1) && !strcmp(argv[4], "-p")) {
auth_pw = 1; auth_pw = 1;
}
if((auth_pw & 2) && !strcmp(argv[4], "-i")) {
auth_pw = 2;
}
if((auth_pw & 4) && !strcmp(argv[4], "-k")) {
auth_pw = 4;
}
} }
if((auth_pw & 2) && !strcmp(argv[4], "-i")) {
auth_pw = 2;
}
if((auth_pw & 4) && !strcmp(argv[4], "-k")) {
auth_pw = 4;
}
}
if(auth_pw & 1) { if(auth_pw & 1) {
/* We could authenticate via password */ /* We could authenticate via password */
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "\tAuthentication by password failed!\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
}
else {
fprintf(stderr, "Authentication by password succeeded.\n");
}
} }
else { else if(auth_pw & 2) {
fprintf(stderr, "\tAuthentication by password succeeded.\n"); /* Or via keyboard-interactive */
if(libssh2_userauth_keyboard_interactive(session, username,
&kbd_callback) ) {
fprintf(stderr,
"Authentication by keyboard-interactive failed!\n");
goto shutdown;
}
else {
fprintf(stderr,
"Authentication by keyboard-interactive succeeded.\n");
}
} }
} else if(auth_pw & 4) {
else if(auth_pw & 2) { /* Or by public key */
/* Or via keyboard-interactive */ size_t fn1sz, fn2sz;
if(libssh2_userauth_keyboard_interactive(session, username, char *fn1, *fn2;
&kbd_callback) ) { char const *h = getenv("HOME");
fprintf(stderr, if(!h || !*h)
"\tAuthentication by keyboard-interactive failed!\n"); h = ".";
goto shutdown; fn1sz = strlen(h) + strlen(pubkey) + 2;
} fn2sz = strlen(h) + strlen(privkey) + 2;
else { fn1 = malloc(fn1sz);
fprintf(stderr, fn2 = malloc(fn2sz);
"\tAuthentication by keyboard-interactive succeeded.\n"); if(!fn1 || !fn2) {
} free(fn2);
} free(fn1);
else if(auth_pw & 4) { fprintf(stderr, "out of memory\n");
/* Or by public key */ goto shutdown;
size_t fn1sz, fn2sz; }
char *fn1, *fn2; /* Using asprintf() here would be much cleaner,
char const *h = getenv("HOME"); but less portable */
if(!h || !*h) snprintf(fn1, fn1sz, "%s/%s", h, pubkey);
h = "."; snprintf(fn2, fn2sz, "%s/%s", h, privkey);
fn1sz = strlen(h) + strlen(pubkey) + 2;
fn2sz = strlen(h) + strlen(privkey) + 2; if(libssh2_userauth_publickey_fromfile(session, username,
fn1 = malloc(fn1sz); fn1, fn2,
fn2 = malloc(fn2sz); password)) {
if(!fn1 || !fn2) { fprintf(stderr, "Authentication by public key failed!\n");
free(fn2);
free(fn1);
goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
free(fn2); free(fn2);
free(fn1); free(fn1);
fprintf(stderr, "out of memory\n");
goto shutdown;
}
/* Using asprintf() here would be much cleaner, but less portable */
snprintf(fn1, fn1sz, "%s/%s", h, pubkey);
snprintf(fn2, fn2sz, "%s/%s", h, privkey);
if(libssh2_userauth_publickey_fromfile(session, username,
fn1, fn2,
password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
free(fn2);
free(fn1);
goto shutdown;
} }
else { else {
fprintf(stderr, "\tAuthentication by public key succeeded.\n"); fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
} }
free(fn2);
free(fn1);
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
} }
/* Request a session channel on which to run a shell */ /* Request a session channel on which to run a shell */
@ -331,14 +336,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -3,12 +3,11 @@
* *
* The sample code has default values for host name, user name: * The sample code has default values for host name, user name:
* *
* "ssh2_agent host user" * $ ./ssh2_agent host user
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
#include <libssh2.h> #include <libssh2.h>
#include <libssh2_sftp.h>
#ifdef HAVE_SYS_SOCKET_H #ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h> #include <sys/socket.h>
@ -35,11 +34,12 @@ static const char *username = "username";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t sock;
int i, rc; int i;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
int rc;
LIBSSH2_SESSION *session = NULL; LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
LIBSSH2_AGENT *agent = NULL; LIBSSH2_AGENT *agent = NULL;
@ -47,11 +47,10 @@ int main(int argc, char *argv[])
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -62,13 +61,12 @@ int main(int argc, char *argv[])
else { else {
hostaddr = htonl(0x7F000001); hostaddr = htonl(0x7F000001);
} }
if(argc > 2) { if(argc > 2) {
username = argv[2]; username = argv[2];
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -91,13 +89,17 @@ int main(int argc, char *argv[])
goto shutdown; goto shutdown;
} }
/* Create a session instance and start it up. This will trade welcome /* Create a session instance */
* banners, exchange keys, and setup crypto, compression, and MAC layers
*/
session = libssh2_session_init(); session = libssh2_session_init();
if(libssh2_session_handshake(session, sock)) { if(!session) {
fprintf(stderr, "Failure establishing SSH session\n"); fprintf(stderr, "Could not initialize SSH session!\n");
return 1; goto shutdown;
}
rc = libssh2_session_handshake(session, sock);
if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -115,55 +117,57 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "publickey") == NULL) { fprintf(stderr, "Authentication methods: %s\n", userauthlist);
fprintf(stderr, "\"publickey\" authentication is not supported\n"); if(!strstr(userauthlist, "publickey")) {
goto shutdown; fprintf(stderr, "\"publickey\" authentication is not supported\n");
} goto shutdown;
}
/* Connect to the ssh-agent */ /* Connect to the ssh-agent */
agent = libssh2_agent_init(session); agent = libssh2_agent_init(session);
if(!agent) { if(!agent) {
fprintf(stderr, "Failure initializing ssh-agent support\n"); fprintf(stderr, "Failure initializing ssh-agent support\n");
rc = 1;
goto shutdown;
}
if(libssh2_agent_connect(agent)) {
fprintf(stderr, "Failure connecting to ssh-agent\n");
rc = 1;
goto shutdown;
}
if(libssh2_agent_list_identities(agent)) {
fprintf(stderr, "Failure requesting identities to ssh-agent\n");
rc = 1;
goto shutdown;
}
for(;;) {
rc = libssh2_agent_get_identity(agent, &identity, prev_identity);
if(rc == 1)
break;
if(rc < 0) {
fprintf(stderr,
"Failure obtaining identity from ssh-agent support\n");
rc = 1; rc = 1;
goto shutdown; goto shutdown;
} }
if(libssh2_agent_userauth(agent, username, identity)) { if(libssh2_agent_connect(agent)) {
fprintf(stderr, "\tAuthentication with username %s and " fprintf(stderr, "Failure connecting to ssh-agent\n");
"public key %s failed!\n", rc = 1;
username, identity->comment); goto shutdown;
} }
else { if(libssh2_agent_list_identities(agent)) {
fprintf(stderr, "\tAuthentication with username %s and " fprintf(stderr, "Failure requesting identities to ssh-agent\n");
"public key %s succeeded!\n", rc = 1;
username, identity->comment); goto shutdown;
break; }
for(;;) {
rc = libssh2_agent_get_identity(agent, &identity, prev_identity);
if(rc == 1)
break;
if(rc < 0) {
fprintf(stderr,
"Failure obtaining identity from ssh-agent support\n");
rc = 1;
goto shutdown;
}
if(libssh2_agent_userauth(agent, username, identity)) {
fprintf(stderr, "Authentication with username %s and "
"public key %s failed!\n",
username, identity->comment);
}
else {
fprintf(stderr, "Authentication with username %s and "
"public key %s succeeded.\n",
username, identity->comment);
break;
}
prev_identity = identity;
}
if(rc) {
fprintf(stderr, "Couldn't continue authentication\n");
goto shutdown;
} }
prev_identity = identity;
}
if(rc) {
fprintf(stderr, "Couldn't continue authentication\n");
goto shutdown;
} }
/* We're authenticated now. */ /* We're authenticated now. */
@ -181,7 +185,8 @@ int main(int argc, char *argv[])
libssh2_channel_setenv(channel, "FOO", "bar"); libssh2_channel_setenv(channel, "FOO", "bar");
/* Request a terminal with 'vanilla' terminal emulation /* Request a terminal with 'vanilla' terminal emulation
* See /etc/termcap for more options * See /etc/termcap for more options. This is useful when opening
* an interactive shell.
*/ */
if(libssh2_channel_request_pty(channel, "vanilla")) { if(libssh2_channel_request_pty(channel, "vanilla")) {
fprintf(stderr, "Failed requesting pty\n"); fprintf(stderr, "Failed requesting pty\n");
@ -208,6 +213,7 @@ int main(int argc, char *argv[])
*/ */
skip_shell: skip_shell:
if(channel) { if(channel) {
libssh2_channel_free(channel); libssh2_channel_free(channel);
channel = NULL; channel = NULL;

View File

@ -7,8 +7,6 @@
* The example uses agent authentication to ensure an agent to forward * The example uses agent authentication to ensure an agent to forward
* is running. * is running.
* *
* Run it like this:
*
* $ ./ssh2_agent_forwarding 127.0.0.1 user "uptime" * $ ./ssh2_agent_forwarding 127.0.0.1 user "uptime"
* *
*/ */
@ -42,6 +40,10 @@
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
static const char *hostname = "127.0.0.1";
static const char *commandline = "uptime";
static const char *username;
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -74,25 +76,28 @@ static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
const char *hostname = "127.0.0.1";
const char *commandline = "uptime";
const char *username = NULL;
uint32_t hostaddr; uint32_t hostaddr;
libssh2_socket_t sock; libssh2_socket_t sock;
struct sockaddr_in sin; struct sockaddr_in sin;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
LIBSSH2_AGENT *agent = NULL; LIBSSH2_AGENT *agent = NULL;
struct libssh2_agent_publickey *identity, *prev_identity = NULL; struct libssh2_agent_publickey *identity, *prev_identity = NULL;
int rc;
int exitcode; int exitcode;
char *exitsignal = (char *)"none"; char *exitsignal = (char *)"none";
ssize_t bytecount = 0; ssize_t bytecount = 0;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
WSAStartup(MAKEWORD(2, 0), &wsadata);
rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1;
}
#endif #endif
if(argc < 2) { if(argc < 2) {
fprintf(stderr, "At least IP and username arguments are required.\n"); fprintf(stderr, "At least IP and username arguments are required.\n");
return 1; return 1;
@ -106,35 +111,40 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
hostaddr = inet_addr(hostname); hostaddr = inet_addr(hostname);
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
if(libssh2_session_handshake(session, sock) != 0) { if(libssh2_session_handshake(session, sock) != 0) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* Connect to the ssh-agent */ /* Connect to the ssh-agent */
@ -165,14 +175,14 @@ int main(int argc, char *argv[])
goto shutdown; goto shutdown;
} }
if(libssh2_agent_userauth(agent, username, identity)) { if(libssh2_agent_userauth(agent, username, identity)) {
fprintf(stderr, "\tAuthentication with username %s and " fprintf(stderr, "Authentication with username %s and "
"public key %s failed!\n", "public key %s failed!\n",
username, identity->comment); username, identity->comment);
} }
else { else {
fprintf(stderr, "\tAuthentication with username %s and " fprintf(stderr, "Authentication with username %s and "
"public key %s succeeded!\n", "public key %s succeeded.\n",
username, identity->comment); username, identity->comment);
break; break;
} }
prev_identity = identity; prev_identity = identity;
@ -189,13 +199,16 @@ int main(int argc, char *argv[])
/* Set session to non-blocking */ /* Set session to non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
/* Exec non-blocking on the remove host */ /* Exec non-blocking on the remote host */
while((channel = libssh2_channel_open_session(session)) == NULL && do {
libssh2_session_last_error(session, NULL, NULL, 0) == channel = libssh2_channel_open_session(session);
LIBSSH2_ERROR_EAGAIN) { if(channel ||
libssh2_session_last_error(session, NULL, NULL, 0) !=
LIBSSH2_ERROR_EAGAIN)
break;
waitsocket(sock, session); waitsocket(sock, session);
} } while(1);
if(channel == NULL) { if(!channel) {
fprintf(stderr, "Error\n"); fprintf(stderr, "Error\n");
exit(1); exit(1);
} }
@ -203,19 +216,19 @@ int main(int argc, char *argv[])
LIBSSH2_ERROR_EAGAIN) { LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session); waitsocket(sock, session);
} }
if(rc != 0) { if(rc) {
fprintf(stderr, "Error, couldn't request auth agent, error code %d.\n", fprintf(stderr, "Error, couldn't request auth agent, error code %d.\n",
rc); rc);
exit(1); exit(1);
} }
else { else {
fprintf(stdout, "\tAgent forwarding request succeeded!\n"); fprintf(stdout, "Agent forwarding request succeeded!\n");
} }
while((rc = libssh2_channel_exec(channel, commandline)) == while((rc = libssh2_channel_exec(channel, commandline)) ==
LIBSSH2_ERROR_EAGAIN) { LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session); waitsocket(sock, session);
} }
if(rc != 0) { if(rc) {
fprintf(stderr, "Error\n"); fprintf(stderr, "Error\n");
exit(1); exit(1);
} }
@ -261,10 +274,11 @@ int main(int argc, char *argv[])
} }
if(exitsignal) { if(exitsignal) {
printf("\nGot signal: %s\n", exitsignal); fprintf(stderr, "\nGot signal: %s\n", exitsignal);
} }
else { else {
printf("\nEXIT: %d bytecount: %d\n", exitcode, (int)bytecount); fprintf(stderr, "\nEXIT: %d bytecount: %d\n",
exitcode, (int)bytecount);
} }
libssh2_channel_free(channel); libssh2_channel_free(channel);
@ -272,14 +286,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -1,11 +1,9 @@
/* /*
* Run it like this:
*
* $ ./ssh2_echo 127.0.0.1 user password
*
* The code sends a 'cat' command, and then writes a lot of data to it only to * The code sends a 'cat' command, and then writes a lot of data to it only to
* check that reading the returned data sums up to the same amount. * check that reading the returned data sums up to the same amount.
* *
* $ ./ssh2_echo 127.0.0.1 user password
*
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -37,6 +35,11 @@
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
static const char *hostname = "127.0.0.1";
static const char *commandline = "cat";
static const char *username = "user";
static const char *password = "password";
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -71,17 +74,13 @@ static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
const char *hostname = "127.0.0.1";
const char *commandline = "cat";
const char *username = "user";
const char *password = "password";
uint32_t hostaddr; uint32_t hostaddr;
libssh2_socket_t sock; libssh2_socket_t sock;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
LIBSSH2_CHANNEL *channel;
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel;
int exitcode = 0; int exitcode = 0;
char *exitsignal = (char *)"none"; char *exitsignal = (char *)"none";
size_t len; size_t len;
@ -90,11 +89,10 @@ int main(int argc, char *argv[])
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -110,31 +108,36 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
hostaddr = inet_addr(hostname); hostaddr = inet_addr(hostname);
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* tell libssh2 we want it all done non-blocking */ /* tell libssh2 we want it all done non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -146,7 +149,7 @@ int main(int argc, char *argv[])
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
nh = libssh2_knownhost_init(session); nh = libssh2_knownhost_init(session);
@ -173,8 +176,8 @@ int main(int argc, char *argv[])
&host); &host);
fprintf(stderr, "Host check: %d, key: %s\n", check, fprintf(stderr, "Host check: %d, key: %s\n", check,
(check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)? (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) ?
host->key:"<none>"); host->key : "<none>");
/***** /*****
* At this point, we could verify that 'check' tells us the key is * At this point, we could verify that 'check' tells us the key is
@ -192,28 +195,31 @@ int main(int argc, char *argv[])
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
exit(1); exit(1);
} }
} }
libssh2_trace(session, LIBSSH2_TRACE_SOCKET); libssh2_trace(session, LIBSSH2_TRACE_SOCKET);
/* Exec non-blocking on the remove host */ /* Exec non-blocking on the remote host */
while((channel = libssh2_channel_open_session(session)) == NULL && do {
libssh2_session_last_error(session, NULL, NULL, 0) == channel = libssh2_channel_open_session(session);
LIBSSH2_ERROR_EAGAIN) { if(channel ||
libssh2_session_last_error(session, NULL, NULL, 0) !=
LIBSSH2_ERROR_EAGAIN)
break;
waitsocket(sock, session); waitsocket(sock, session);
} } while(1);
if(channel == NULL) { if(!channel) {
fprintf(stderr, "Error\n"); fprintf(stderr, "Error\n");
exit(1); exit(1);
} }
while((rc = libssh2_channel_exec(channel, commandline)) == while((rc = libssh2_channel_exec(channel, commandline)) ==
LIBSSH2_ERROR_EAGAIN) LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session); waitsocket(sock, session);
}
if(rc != 0) { if(rc) {
fprintf(stderr, "exec error\n"); fprintf(stderr, "exec error\n");
exit(1); exit(1);
} }
@ -244,7 +250,7 @@ int main(int argc, char *argv[])
do { do {
int act = 0; int act = 0;
rc = (libssh2_poll(fds, 1, 10)); rc = libssh2_poll(fds, 1, 10);
if(rc < 1) if(rc < 1)
continue; continue;
@ -348,14 +354,21 @@ int main(int argc, char *argv[])
} }
} }
libssh2_session_disconnect(session, "Normal Shutdown"); shutdown:
libssh2_session_free(session);
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,8 +4,6 @@
* The sample code has fixed values for host name, user name, password * The sample code has fixed values for host name, user name, password
* and command to run. * and command to run.
* *
* Run it like this:
*
* $ ./ssh2_exec 127.0.0.1 user password "uptime" * $ ./ssh2_exec 127.0.0.1 user password "uptime"
* *
*/ */
@ -39,6 +37,13 @@
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
static const char *hostname = "127.0.0.1";
static const char *commandline = "uptime";
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "user";
static const char *password = "password";
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session) static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
{ {
struct timeval timeout; struct timeval timeout;
@ -71,19 +76,13 @@ static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
const char *hostname = "127.0.0.1";
const char *commandline = "uptime";
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa";
const char *username = "user";
const char *password = "password";
uint32_t hostaddr; uint32_t hostaddr;
libssh2_socket_t sock; libssh2_socket_t sock;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
LIBSSH2_SESSION *session;
LIBSSH2_CHANNEL *channel;
int rc; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel;
int exitcode; int exitcode;
char *exitsignal = (char *)"none"; char *exitsignal = (char *)"none";
ssize_t bytecount = 0; ssize_t bytecount = 0;
@ -93,11 +92,10 @@ int main(int argc, char *argv[])
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -116,31 +114,36 @@ int main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
hostaddr = inet_addr(hostname); hostaddr = inet_addr(hostname);
/* Ultra basic "connect to port 22 on localhost" /* Ultra basic "connect to port 22 on localhost". Your code is
* Your code is responsible for creating the socket establishing the * responsible for creating the socket establishing the connection
* connection
*/ */
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_port = htons(22); sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) if(!session) {
return -1; fprintf(stderr, "Could not initialize SSH session!\n");
goto shutdown;
}
/* tell libssh2 we want it all done non-blocking */ /* tell libssh2 we want it all done non-blocking */
libssh2_session_set_blocking(session, 0); libssh2_session_set_blocking(session, 0);
@ -152,7 +155,7 @@ int main(int argc, char *argv[])
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc); fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1; goto shutdown;
} }
nh = libssh2_knownhost_init(session); nh = libssh2_knownhost_init(session);
@ -177,9 +180,10 @@ int main(int argc, char *argv[])
LIBSSH2_KNOWNHOST_TYPE_PLAIN| LIBSSH2_KNOWNHOST_TYPE_PLAIN|
LIBSSH2_KNOWNHOST_KEYENC_RAW, LIBSSH2_KNOWNHOST_KEYENC_RAW,
&host); &host);
fprintf(stderr, "Host check: %d, key: %s\n", check, fprintf(stderr, "Host check: %d, key: %s\n", check,
(check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)? (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) ?
host->key:"<none>"); host->key : "<none>");
/***** /*****
* At this point, we could verify that 'check' tells us the key is * At this point, we could verify that 'check' tells us the key is
@ -195,9 +199,9 @@ int main(int argc, char *argv[])
if(strlen(password) != 0) { if(strlen(password) != 0) {
/* We could authenticate via password */ /* We could authenticate via password */
while((rc = libssh2_userauth_password(session, username, password)) == while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -206,9 +210,9 @@ int main(int argc, char *argv[])
while((rc = libssh2_userauth_publickey_fromfile(session, username, while((rc = libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) == password)) ==
LIBSSH2_ERROR_EAGAIN); LIBSSH2_ERROR_EAGAIN);
if(rc) { if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
} }
} }
@ -217,13 +221,16 @@ int main(int argc, char *argv[])
libssh2_trace(session, ~0); libssh2_trace(session, ~0);
#endif #endif
/* Exec non-blocking on the remove host */ /* Exec non-blocking on the remote host */
while((channel = libssh2_channel_open_session(session)) == NULL && do {
libssh2_session_last_error(session, NULL, NULL, 0) == channel = libssh2_channel_open_session(session);
LIBSSH2_ERROR_EAGAIN) { if(channel ||
libssh2_session_last_error(session, NULL, NULL, 0) !=
LIBSSH2_ERROR_EAGAIN)
break;
waitsocket(sock, session); waitsocket(sock, session);
} } while(1);
if(channel == NULL) { if(!channel) {
fprintf(stderr, "Error\n"); fprintf(stderr, "Error\n");
exit(1); exit(1);
} }
@ -231,7 +238,7 @@ int main(int argc, char *argv[])
LIBSSH2_ERROR_EAGAIN) { LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session); waitsocket(sock, session);
} }
if(rc != 0) { if(rc) {
fprintf(stderr, "exec error\n"); fprintf(stderr, "exec error\n");
exit(1); exit(1);
} }
@ -287,14 +294,19 @@ int main(int argc, char *argv[])
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
fprintf(stderr, "all done\n"); fprintf(stderr, "all done\n");
libssh2_exit(); libssh2_exit();

View File

@ -4,9 +4,6 @@
#ifdef HAVE_SYS_SOCKET_H #ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h> #include <sys/socket.h>
#endif #endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#ifdef HAVE_UNISTD_H #ifdef HAVE_UNISTD_H
#include <unistd.h> #include <unistd.h>
#endif #endif
@ -16,9 +13,6 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -44,8 +38,8 @@ static const char *server_ip = "127.0.0.1";
enum { enum {
AUTH_NONE = 0, AUTH_NONE = 0,
AUTH_PASSWORD, AUTH_PASSWORD = 1,
AUTH_PUBLICKEY AUTH_PUBLICKEY = 2
}; };
static int netconf_write(LIBSSH2_CHANNEL *channel, const char *buf, size_t len) static int netconf_write(LIBSSH2_CHANNEL *channel, const char *buf, size_t len)
@ -110,23 +104,23 @@ static ssize_t netconf_read_until(LIBSSH2_CHANNEL *channel, const char *endtag,
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
int rc, i, auth = AUTH_NONE; int i, auth = AUTH_NONE;
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel = NULL; LIBSSH2_CHANNEL *channel = NULL;
char buf[1048576]; /* avoid any buffer reallocation for simplicity */ char buf[1048576]; /* avoid any buffer reallocation for simplicity */
ssize_t len; ssize_t len;
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t sock;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -139,7 +133,7 @@ int main(int argc, char *argv[])
password = argv[3]; password = argv[3];
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -148,26 +142,26 @@ int main(int argc, char *argv[])
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock == LIBSSH2_INVALID_SOCKET) { if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to open socket!\n"); fprintf(stderr, "failed to open socket!\n");
return -1; goto shutdown;
} }
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(server_ip); sin.sin_addr.s_addr = inet_addr(server_ip);
if(INADDR_NONE == sin.sin_addr.s_addr) { if(INADDR_NONE == sin.sin_addr.s_addr) {
fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip); fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip);
return -1; goto shutdown;
} }
sin.sin_port = htons(830); sin.sin_port = htons(830);
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr)); fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr));
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) { if(!session) {
fprintf(stderr, "Could not initialize SSH session!\n"); fprintf(stderr, "Could not initialize SSH session!\n");
return -1; goto shutdown;
} }
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
@ -176,7 +170,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Error when starting up SSH session: %d\n", rc); fprintf(stderr, "Error when starting up SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -193,54 +187,58 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password")) fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth |= AUTH_PASSWORD; if(strstr(userauthlist, "password"))
if(strstr(userauthlist, "publickey")) auth |= AUTH_PASSWORD;
auth |= AUTH_PUBLICKEY; if(strstr(userauthlist, "publickey"))
auth |= AUTH_PUBLICKEY;
/* check for options */ /* check for options */
if(argc > 4) { if(argc > 4) {
if((auth & AUTH_PASSWORD) && !strcmp(argv[4], "-p")) if((auth & AUTH_PASSWORD) && !strcmp(argv[4], "-p"))
auth = AUTH_PASSWORD; auth = AUTH_PASSWORD;
if((auth & AUTH_PUBLICKEY) && !strcmp(argv[4], "-k")) if((auth & AUTH_PUBLICKEY) && !strcmp(argv[4], "-k"))
auth = AUTH_PUBLICKEY; auth = AUTH_PUBLICKEY;
} }
if(auth & AUTH_PASSWORD) { if(auth & AUTH_PASSWORD) {
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown;
}
}
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown; goto shutdown;
} }
} }
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown;
}
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
}
/* open a channel */ /* open a channel */
channel = libssh2_channel_open_session(session); channel = libssh2_channel_open_session(session);
if(!channel) { if(!channel) {
fprintf(stderr, "Could not open the channel!\n" fprintf(stderr, "Could not open the channel!\n"
"(Note that this can be a problem at the server!" "(Note that this can be a problem at the server!"
" Please review the server logs.)\n"); " Please review the server logs.)\n");
goto shutdown; goto shutdown;
} }
/* execute the subsystem on our channel */ /* execute the subsystem on our channel */
if(libssh2_channel_subsystem(channel, "netconf")) { if(libssh2_channel_subsystem(channel, "netconf")) {
fprintf(stderr, "Could not execute the \"netconf\" subsystem!\n" fprintf(stderr, "Could not execute the \"netconf\" subsystem!\n"
"(Note that this can be a problem at the server!" "(Note that this can be a problem at the server!"
" Please review the server logs.)\n"); " Please review the server logs.)\n");
goto shutdown; goto shutdown;
} }
@ -285,16 +283,22 @@ int main(int argc, char *argv[])
(int)len, buf); (int)len, buf);
shutdown: shutdown:
if(channel) if(channel)
libssh2_channel_free(channel); libssh2_channel_free(channel);
libssh2_session_disconnect(session, "Client disconnecting normally");
libssh2_session_free(session);
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
libssh2_exit(); libssh2_exit();

View File

@ -54,34 +54,34 @@ static int local_destport = 22;
enum { enum {
AUTH_NONE = 0, AUTH_NONE = 0,
AUTH_PASSWORD, AUTH_PASSWORD = 1,
AUTH_PUBLICKEY AUTH_PUBLICKEY = 2
}; };
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
int rc, i, auth = AUTH_NONE; int i, auth = AUTH_NONE;
struct sockaddr_in sin; struct sockaddr_in sin;
socklen_t sinlen = sizeof(sin); socklen_t sinlen = sizeof(sin);
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_LISTENER *listener = NULL; LIBSSH2_LISTENER *listener = NULL;
LIBSSH2_CHANNEL *channel = NULL; LIBSSH2_CHANNEL *channel = NULL;
fd_set fds; fd_set fds;
struct timeval tv; struct timeval tv;
ssize_t len, wr; ssize_t len, wr;
char buf[16384]; char buf[16384];
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t sock;
libssh2_socket_t forwardsock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t forwardsock = LIBSSH2_INVALID_SOCKET;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return 1; return 1;
} }
#endif #endif
@ -102,7 +102,7 @@ int main(int argc, char *argv[])
local_destport = atoi(argv[7]); local_destport = atoi(argv[7]);
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
@ -111,26 +111,26 @@ int main(int argc, char *argv[])
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock == LIBSSH2_INVALID_SOCKET) { if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to open socket!\n"); fprintf(stderr, "failed to open socket!\n");
return -1; goto shutdown;
} }
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(server_ip); sin.sin_addr.s_addr = inet_addr(server_ip);
if(INADDR_NONE == sin.sin_addr.s_addr) { if(INADDR_NONE == sin.sin_addr.s_addr) {
fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip); fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip);
return -1; goto shutdown;
} }
sin.sin_port = htons(22); sin.sin_port = htons(22);
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr)); fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr));
return -1; goto shutdown;
} }
/* Create a session instance */ /* Create a session instance */
session = libssh2_session_init(); session = libssh2_session_init();
if(!session) { if(!session) {
fprintf(stderr, "Could not initialize SSH session!\n"); fprintf(stderr, "Could not initialize SSH session!\n");
return -1; goto shutdown;
} }
/* ... start it up. This will trade welcome banners, exchange keys, /* ... start it up. This will trade welcome banners, exchange keys,
@ -139,7 +139,7 @@ int main(int argc, char *argv[])
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc) { if(rc) {
fprintf(stderr, "Error when starting up SSH session: %d\n", rc); fprintf(stderr, "Error when starting up SSH session: %d\n", rc);
return -1; goto shutdown;
} }
/* At this point we have not yet authenticated. The first thing to do /* At this point we have not yet authenticated. The first thing to do
@ -156,39 +156,43 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password")) fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth |= AUTH_PASSWORD; if(strstr(userauthlist, "password"))
if(strstr(userauthlist, "publickey")) auth |= AUTH_PASSWORD;
auth |= AUTH_PUBLICKEY; if(strstr(userauthlist, "publickey"))
auth |= AUTH_PUBLICKEY;
/* check for options */ /* check for options */
if(argc > 8) { if(argc > 8) {
if((auth & AUTH_PASSWORD) && !strcmp(argv[8], "-p")) if((auth & AUTH_PASSWORD) && !strcmp(argv[8], "-p"))
auth = AUTH_PASSWORD; auth = AUTH_PASSWORD;
if((auth & AUTH_PUBLICKEY) && !strcmp(argv[8], "-k")) if((auth & AUTH_PUBLICKEY) && !strcmp(argv[8], "-k"))
auth = AUTH_PUBLICKEY; auth = AUTH_PUBLICKEY;
} }
if(auth & AUTH_PASSWORD) { if(auth & AUTH_PASSWORD) {
if(libssh2_userauth_password(session, username, password)) { if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n"); fprintf(stderr, "Authentication by password failed!\n");
goto shutdown;
}
}
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown; goto shutdown;
} }
} }
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown;
}
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
}
fprintf(stderr, "Asking server to listen on remote %s:%d\n", fprintf(stderr, "Asking server to listen on remote %s:%d\n",
remote_listenhost, remote_wantport); remote_listenhost, remote_wantport);
@ -197,8 +201,8 @@ int main(int argc, char *argv[])
remote_wantport, &remote_listenport, 1); remote_wantport, &remote_listenport, 1);
if(!listener) { if(!listener) {
fprintf(stderr, "Could not start the tcpip-forward listener!\n" fprintf(stderr, "Could not start the tcpip-forward listener!\n"
"(Note that this can be a problem at the server!" "(Note that this can be a problem at the server!"
" Please review the server logs.)\n"); " Please review the server logs.)\n");
goto shutdown; goto shutdown;
} }
@ -209,8 +213,8 @@ int main(int argc, char *argv[])
channel = libssh2_channel_forward_accept(listener); channel = libssh2_channel_forward_accept(listener);
if(!channel) { if(!channel) {
fprintf(stderr, "Could not accept connection!\n" fprintf(stderr, "Could not accept connection!\n"
"(Note that this can be a problem at the server!" "(Note that this can be a problem at the server!"
" Please review the server logs.)\n"); " Please review the server logs.)\n");
goto shutdown; goto shutdown;
} }
@ -227,11 +231,11 @@ int main(int argc, char *argv[])
sin.sin_port = htons((unsigned short)local_destport); sin.sin_port = htons((unsigned short)local_destport);
sin.sin_addr.s_addr = inet_addr(local_destip); sin.sin_addr.s_addr = inet_addr(local_destip);
if(INADDR_NONE == sin.sin_addr.s_addr) { if(INADDR_NONE == sin.sin_addr.s_addr) {
perror("inet_addr"); fprintf(stderr, "failed in inet_addr()!\n");
goto shutdown; goto shutdown;
} }
if(-1 == connect(forwardsock, (struct sockaddr *)&sin, sinlen)) { if(-1 == connect(forwardsock, (struct sockaddr *)&sin, sinlen)) {
perror("connect"); fprintf(stderr, "failed to connect()!\n");
goto shutdown; goto shutdown;
} }
@ -248,14 +252,14 @@ int main(int argc, char *argv[])
tv.tv_usec = 100000; tv.tv_usec = 100000;
rc = select((int)(forwardsock + 1), &fds, NULL, NULL, &tv); rc = select((int)(forwardsock + 1), &fds, NULL, NULL, &tv);
if(-1 == rc) { if(-1 == rc) {
perror("select"); fprintf(stderr, "failed to select()!\n");
goto shutdown; goto shutdown;
} }
if(rc && FD_ISSET(forwardsock, &fds)) { if(rc && FD_ISSET(forwardsock, &fds)) {
ssize_t nwritten; ssize_t nwritten;
len = recv(forwardsock, buf, sizeof(buf), 0); len = recv(forwardsock, buf, sizeof(buf), 0);
if(len < 0) { if(len < 0) {
perror("read"); fprintf(stderr, "failed to recv()!\n");
goto shutdown; goto shutdown;
} }
else if(0 == len) { else if(0 == len) {
@ -288,7 +292,7 @@ int main(int argc, char *argv[])
while(wr < len) { while(wr < len) {
nsent = send(forwardsock, buf + wr, len - wr, 0); nsent = send(forwardsock, buf + wr, len - wr, 0);
if(nsent <= 0) { if(nsent <= 0) {
perror("write"); fprintf(stderr, "failed to send()!\n");
goto shutdown; goto shutdown;
} }
wr += nsent; wr += nsent;
@ -302,23 +306,33 @@ int main(int argc, char *argv[])
} }
shutdown: shutdown:
if(forwardsock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(forwardsock); closesocket(forwardsock);
#else #else
close(forwardsock); close(forwardsock);
#endif #endif
}
if(channel) if(channel)
libssh2_channel_free(channel); libssh2_channel_free(channel);
if(listener) if(listener)
libssh2_channel_forward_cancel(listener); libssh2_channel_forward_cancel(listener);
libssh2_session_disconnect(session, "Client disconnecting normally");
libssh2_session_free(session);
if(session) {
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
closesocket(sock); closesocket(sock);
#else #else
close(sock); close(sock);
#endif #endif
}
libssh2_exit(); libssh2_exit();

View File

@ -1,8 +1,7 @@
/* /*
* Sample showing how to makes SSH2 with X11 Forwarding works. * Sample showing how to makes SSH2 with X11 Forwarding works.
* *
* Usage: * $ ./x11 host user password [DEBUG]
* "ssh2 host user password [DEBUG]"
*/ */
#include "libssh2_setup.h" #include "libssh2_setup.h"
@ -30,6 +29,9 @@
#ifdef HAVE_ARPA_INET_H #ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_UN_H #ifdef HAVE_SYS_UN_H
#include <sys/un.h> #include <sys/un.h>
#endif #endif
@ -73,7 +75,7 @@ static void remove_node(struct chan_X11_list *elem)
return; return;
} }
while(current_node->next != NULL) { while(current_node->next) {
if(current_node->next == elem) { if(current_node->next == elem) {
current_node->next = current_node->next->next; current_node->next = current_node->next->next;
current_node = current_node->next; current_node = current_node->next;
@ -86,7 +88,7 @@ static void remove_node(struct chan_X11_list *elem)
static void session_shutdown(LIBSSH2_SESSION *session) static void session_shutdown(LIBSSH2_SESSION *session)
{ {
libssh2_session_disconnect(session, "Session Shutdown"); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session); libssh2_session_free(session);
} }
@ -124,11 +126,11 @@ static int _normal_mode(void)
static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel, static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel,
char *shost, int sport, void **abstract) char *shost, int sport, void **abstract)
{ {
const char *display = NULL; const char *display;
char *ptr = NULL; char *ptr;
char *temp_buff = NULL; char *temp_buff;
int display_port = 0; int display_port;
int rc = 0; int rc;
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET;
struct sockaddr_un addr; struct sockaddr_un addr;
struct chan_X11_list *new; struct chan_X11_list *new;
@ -142,14 +144,14 @@ static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel,
* Inspired by x11_connect_display in openssh * Inspired by x11_connect_display in openssh
*/ */
display = getenv("DISPLAY"); display = getenv("DISPLAY");
if(display != NULL) { if(display) {
if(strncmp(display, "unix:", 5) == 0 || if(strncmp(display, "unix:", 5) == 0 ||
display[0] == ':') { display[0] == ':') {
/* Connect to the local unix domain */ /* Connect to the local unix domain */
ptr = strrchr(display, ':'); ptr = strrchr(display, ':');
temp_buff = (char *) calloc(strlen(ptr + 1) + 1, sizeof(char)); temp_buff = (char *)calloc(strlen(ptr + 1) + 1, sizeof(char));
if(!temp_buff) { if(!temp_buff) {
perror("calloc"); fprintf(stderr, "failed to calloc()!\n");
return; return;
} }
memcpy(temp_buff, ptr + 1, strlen(ptr + 1)); memcpy(temp_buff, ptr + 1, strlen(ptr + 1));
@ -167,7 +169,7 @@ static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel,
if(rc != -1) { if(rc != -1) {
/* Connection Successful */ /* Connection Successful */
if(gp_x11_chan == NULL) { if(!gp_x11_chan) {
/* Calloc ensure that gp_X11_chan is full of 0 */ /* Calloc ensure that gp_X11_chan is full of 0 */
gp_x11_chan = (struct chan_X11_list *) gp_x11_chan = (struct chan_X11_list *)
calloc(1, sizeof(struct chan_X11_list)); calloc(1, sizeof(struct chan_X11_list));
@ -177,7 +179,7 @@ static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel,
} }
else { else {
chan_iter = gp_x11_chan; chan_iter = gp_x11_chan;
while(chan_iter->next != NULL) while(chan_iter->next)
chan_iter = chan_iter->next; chan_iter = chan_iter->next;
/* Create the new Node */ /* Create the new Node */
new = (struct chan_X11_list *) new = (struct chan_X11_list *)
@ -201,10 +203,10 @@ static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel,
*/ */
static int x11_send_receive(LIBSSH2_CHANNEL *channel, int sock) static int x11_send_receive(LIBSSH2_CHANNEL *channel, int sock)
{ {
char *buf = NULL; char *buf;
int bufsize = 8192; int bufsize = 8192;
int rc = 0; int rc;
int nfds = 1; int nfds = 1;
LIBSSH2_POLLFD *fds = NULL; LIBSSH2_POLLFD *fds = NULL;
fd_set set; fd_set set;
struct timeval timeval_out; struct timeval timeval_out;
@ -240,7 +242,7 @@ static int x11_send_receive(LIBSSH2_CHANNEL *channel, int sock)
if(rc > 0) { if(rc > 0) {
ssize_t nread; ssize_t nread;
memset((void *)buf, 0, bufsize); memset(buf, 0, bufsize);
/* Data in sock */ /* Data in sock */
nread = read(sock, buf, bufsize); nread = read(sock, buf, bufsize);
@ -264,14 +266,13 @@ static int x11_send_receive(LIBSSH2_CHANNEL *channel, int sock)
/* /*
* Main, more than inspired by ssh2.c by Bagder * Main, more than inspired by ssh2.c by Bagder
*/ */
int int main(int argc, char *argv[])
main(int argc, char *argv[])
{ {
uint32_t hostaddr = 0; uint32_t hostaddr = 0;
int rc = 0; int rc;
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET; libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET;
struct sockaddr_in sin; struct sockaddr_in sin;
LIBSSH2_SESSION *session; LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
char *username = NULL; char *username = NULL;
char *password = NULL; char *password = NULL;
@ -311,14 +312,14 @@ main(int argc, char *argv[])
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1; return 1;
} }
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) { if(sock == LIBSSH2_INVALID_SOCKET) {
perror("socket"); fprintf(stderr, "failed to open socket!\n");
return -1; return -1;
} }
@ -333,7 +334,7 @@ main(int argc, char *argv[])
/* Open a session */ /* Open a session */
session = libssh2_session_init(); session = libssh2_session_init();
rc = libssh2_session_handshake(session, sock); rc = libssh2_session_handshake(session, sock);
if(rc != 0) { if(rc) {
fprintf(stderr, "Failed Start the SSH session\n"); fprintf(stderr, "Failed Start the SSH session\n");
return -1; return -1;
} }
@ -351,7 +352,7 @@ main(int argc, char *argv[])
/* Authenticate via password */ /* Authenticate via password */
rc = libssh2_userauth_password(session, username, password); rc = libssh2_userauth_password(session, username, password);
if(rc != 0) { if(rc) {
fprintf(stderr, "Failed to authenticate\n"); fprintf(stderr, "Failed to authenticate\n");
session_shutdown(session); session_shutdown(session);
close(sock); close(sock);
@ -359,8 +360,8 @@ main(int argc, char *argv[])
} }
/* Open a channel */ /* Open a channel */
channel = libssh2_channel_open_session(session); channel = libssh2_channel_open_session(session);
if(channel == NULL) { if(!channel) {
fprintf(stderr, "Failed to open a new channel\n"); fprintf(stderr, "Failed to open a new channel\n");
session_shutdown(session); session_shutdown(session);
close(sock); close(sock);
@ -369,7 +370,7 @@ main(int argc, char *argv[])
/* Request a PTY */ /* Request a PTY */
rc = libssh2_channel_request_pty(channel, "xterm"); rc = libssh2_channel_request_pty(channel, "xterm");
if(rc != 0) { if(rc) {
fprintf(stderr, "Failed to request a pty\n"); fprintf(stderr, "Failed to request a pty\n");
session_shutdown(session); session_shutdown(session);
close(sock); close(sock);
@ -378,7 +379,7 @@ main(int argc, char *argv[])
/* Request X11 */ /* Request X11 */
rc = libssh2_channel_x11_req(channel, 0); rc = libssh2_channel_x11_req(channel, 0);
if(rc != 0) { if(rc) {
fprintf(stderr, "Failed to request X11 forwarding\n"); fprintf(stderr, "Failed to request X11 forwarding\n");
session_shutdown(session); session_shutdown(session);
close(sock); close(sock);
@ -387,7 +388,7 @@ main(int argc, char *argv[])
/* Request a shell */ /* Request a shell */
rc = libssh2_channel_shell(channel); rc = libssh2_channel_shell(channel);
if(rc != 0) { if(rc) {
fprintf(stderr, "Failed to open a shell\n"); fprintf(stderr, "Failed to open a shell\n");
session_shutdown(session); session_shutdown(session);
close(sock); close(sock);
@ -395,7 +396,7 @@ main(int argc, char *argv[])
} }
rc = _raw_mode(); rc = _raw_mode();
if(rc != 0) { if(rc) {
fprintf(stderr, "Failed to entered in raw mode\n"); fprintf(stderr, "Failed to entered in raw mode\n");
session_shutdown(session); session_shutdown(session);
close(sock); close(sock);
@ -422,11 +423,11 @@ main(int argc, char *argv[])
} }
buf = calloc(bufsiz, sizeof(char)); buf = calloc(bufsiz, sizeof(char));
if(buf == NULL) if(!buf)
break; break;
fds = malloc(sizeof(LIBSSH2_POLLFD)); fds = malloc(sizeof(LIBSSH2_POLLFD));
if(fds == NULL) { if(!fds) {
free(buf); free(buf);
break; break;
} }
@ -444,13 +445,13 @@ main(int argc, char *argv[])
} }
/* Looping on X clients */ /* Looping on X clients */
if(gp_x11_chan != NULL) { if(gp_x11_chan) {
current_node = gp_x11_chan; current_node = gp_x11_chan;
} }
else else
current_node = NULL; current_node = NULL;
while(current_node != NULL) { while(current_node) {
struct chan_X11_list *next_node; struct chan_X11_list *next_node;
rc = x11_send_receive(current_node->chan, current_node->sock); rc = x11_send_receive(current_node->chan, current_node->sock);
next_node = current_node->next; next_node = current_node->next;
@ -494,10 +495,9 @@ main(int argc, char *argv[])
#else #else
int int main(void)
main(void)
{ {
printf("Sorry, this platform is not supported."); fprintf(stderr, "Sorry, this platform is not supported.");
return 1; return 1;
} }

View File

@ -110,7 +110,7 @@ static int run_command_varg(char **output, const char *command, va_list args)
buf[0] = 0; buf[0] = 0;
buf_len = 0; buf_len = 0;
while(buf_len < (sizeof(buf) - 1) && while(buf_len < (sizeof(buf) - 1) &&
fgets(&buf[buf_len], (int)(sizeof(buf) - buf_len), pipe) != NULL) { fgets(&buf[buf_len], (int)(sizeof(buf) - buf_len), pipe)) {
buf_len = strlen(buf); buf_len = strlen(buf);
} }
@ -119,7 +119,7 @@ static int run_command_varg(char **output, const char *command, va_list args)
#else #else
ret = pclose(pipe); ret = pclose(pipe);
#endif #endif
if(ret != 0) { if(ret) {
fprintf(stderr, "Error running command '%s' (exit %d): %s\n", fprintf(stderr, "Error running command '%s' (exit %d): %s\n",
command, ret, buf); command, ret, buf);
} }
@ -159,7 +159,7 @@ static int build_openssh_server_docker_image(void)
if(have_docker) { if(have_docker) {
char buildcmd[1024]; char buildcmd[1024];
const char *container_image_name = openssh_server_image(); const char *container_image_name = openssh_server_image();
if(container_image_name != NULL) { if(container_image_name) {
int ret = run_command(NULL, "docker pull --quiet %s", int ret = run_command(NULL, "docker pull --quiet %s",
container_image_name); container_image_name);
if(ret == 0) { if(ret == 0) {
@ -191,7 +191,7 @@ static int start_openssh_server(char **container_id_out)
{ {
if(have_docker) { if(have_docker) {
const char *container_host_port = openssh_server_port(); const char *container_host_port = openssh_server_port();
if(container_host_port != NULL) { if(container_host_port) {
return run_command(container_id_out, return run_command(container_id_out,
"docker run --rm -d -p %s:22 " "docker run --rm -d -p %s:22 "
"libssh2/openssh_server", "libssh2/openssh_server",
@ -235,12 +235,12 @@ static int is_running_inside_a_container(void)
ssize_t read = 0; ssize_t read = 0;
int found = 0; int found = 0;
f = fopen(cgroup_filename, "r"); f = fopen(cgroup_filename, "r");
if(f == NULL) { if(!f) {
/* Don't go further, we are not in a container */ /* Don't go further, we are not in a container */
return 0; return 0;
} }
while((read = getline(&line, &len, f)) != -1) { while((read = getline(&line, &len, f)) != -1) {
if(strstr(line, "docker") != NULL) { if(strstr(line, "docker")) {
found = 1; found = 1;
break; break;
} }
@ -263,7 +263,7 @@ static void portable_sleep(unsigned int seconds)
static int ip_address_from_container(char *container_id, char **ip_address_out) static int ip_address_from_container(char *container_id, char **ip_address_out)
{ {
const char *active_docker_machine = docker_machine_name(); const char *active_docker_machine = docker_machine_name();
if(active_docker_machine != NULL) { if(active_docker_machine) {
/* This can be flaky when tests run in parallel (see /* This can be flaky when tests run in parallel (see
https://github.com/docker/machine/issues/2612), so we retry a few https://github.com/docker/machine/issues/2612), so we retry a few
@ -337,14 +337,14 @@ static libssh2_socket_t open_socket_to_container(char *container_id)
if(have_docker) { if(have_docker) {
int res; int res;
res = ip_address_from_container(container_id, &ip_address); res = ip_address_from_container(container_id, &ip_address);
if(res != 0) { if(res) {
fprintf(stderr, "Failed to get IP address for container %s\n", fprintf(stderr, "Failed to get IP address for container %s\n",
container_id); container_id);
goto cleanup; goto cleanup;
} }
res = port_from_container(container_id, &port_string); res = port_from_container(container_id, &port_string);
if(res != 0) { if(res) {
fprintf(stderr, "Failed to get port for container %s\n", fprintf(stderr, "Failed to get port for container %s\n",
container_id); container_id);
goto cleanup; goto cleanup;
@ -424,7 +424,7 @@ int start_openssh_fixture(void)
WSADATA wsadata; WSADATA wsadata;
ret = WSAStartup(MAKEWORD(2, 0), &wsadata); ret = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(ret != 0) { if(ret) {
fprintf(stderr, "WSAStartup failed with error: %d\n", ret); fprintf(stderr, "WSAStartup failed with error: %d\n", ret);
return 1; return 1;
} }
@ -433,7 +433,7 @@ int start_openssh_fixture(void)
have_docker = (getenv("OPENSSH_NO_DOCKER") == NULL); have_docker = (getenv("OPENSSH_NO_DOCKER") == NULL);
ret = build_openssh_server_docker_image(); ret = build_openssh_server_docker_image();
if(ret == 0) { if(!ret) {
return start_openssh_server(&running_container_id); return start_openssh_server(&running_container_id);
} }
else { else {

View File

@ -10,12 +10,12 @@
#include "testinput.h" #include "testinput.h"
#define FUZZ_ASSERT(COND) \ #define FUZZ_ASSERT(COND) \
if(!(COND)) \ if(!(COND)) \
{ \ { \
fprintf(stderr, "Assertion failed: " #COND "\n%s", \ fprintf(stderr, "Assertion failed: " #COND "\n%s", \
strerror(errno)); \ strerror(errno)); \
assert((COND)); \ assert((COND)); \
} }
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{ {
@ -27,7 +27,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
goto EXIT_LABEL; goto EXIT_LABEL;
} }
@ -38,7 +38,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
written = send(socket_fds[1], data, size, 0); written = send(socket_fds[1], data, size, 0);
if (written != size) if(written != size)
{ {
// Handle whatever error case we're in. // Handle whatever error case we're in.
fprintf(stderr, "send() of %zu bytes returned %zu (%d)\n", fprintf(stderr, "send() of %zu bytes returned %zu (%d)\n",
@ -49,7 +49,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
} }
rc = shutdown(socket_fds[1], SHUT_WR); rc = shutdown(socket_fds[1], SHUT_WR);
if (rc != 0) if(rc)
{ {
fprintf(stderr, "socket shutdown failed (%d)\n", rc); fprintf(stderr, "socket shutdown failed (%d)\n", rc);
goto EXIT_LABEL; goto EXIT_LABEL;
@ -61,7 +61,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
libssh2_session_set_blocking(session, 1); libssh2_session_set_blocking(session, 1);
} }
else { else {
goto EXIT_LABEL; goto EXIT_LABEL;
} }
if(libssh2_session_handshake(session, socket_fds[0])) { if(libssh2_session_handshake(session, socket_fds[0])) {
@ -73,9 +73,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
EXIT_LABEL: EXIT_LABEL:
if (session != NULL) if(session)
{ {
if (handshake_completed) if(handshake_completed)
{ {
libssh2_session_disconnect(session, libssh2_session_disconnect(session,
"Normal Shutdown, Thank you for playing"); "Normal Shutdown, Thank you for playing");

View File

@ -41,7 +41,7 @@ int main(void)
{ {
int exit_code = 1; int exit_code = 1;
LIBSSH2_SESSION *session = start_session_fixture(); LIBSSH2_SESSION *session = start_session_fixture();
if(session != NULL) { if(session) {
exit_code = (test(session) == 0) ? 0 : 1; exit_code = (test(session) == 0) ? 0 : 1;
} }
stop_session_fixture(); stop_session_fixture();

View File

@ -70,7 +70,7 @@ static int connect_to_server(void)
} }
rc = libssh2_session_handshake(connected_session, connected_socket); rc = libssh2_session_handshake(connected_session, connected_socket);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_session_handshake"); print_last_session_error("libssh2_session_handshake");
return -1; return -1;
} }
@ -107,11 +107,11 @@ LIBSSH2_SESSION *start_session_fixture(void)
setup_fixture_workdir(); setup_fixture_workdir();
rc = start_openssh_fixture(); rc = start_openssh_fixture();
if(rc != 0) { if(rc) {
return NULL; return NULL;
} }
rc = libssh2_init(0); rc = libssh2_init(0);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2_init failed (%d)\n", rc); fprintf(stderr, "libssh2_init failed (%d)\n", rc);
return NULL; return NULL;
} }
@ -120,7 +120,7 @@ LIBSSH2_SESSION *start_session_fixture(void)
if(getenv("FIXTURE_TRACE_ALL")) { if(getenv("FIXTURE_TRACE_ALL")) {
libssh2_trace(connected_session, ~0); libssh2_trace(connected_session, ~0);
} }
if(connected_session == NULL) { if(!connected_session) {
fprintf(stderr, "libssh2_session_init_ex failed\n"); fprintf(stderr, "libssh2_session_init_ex failed\n");
return NULL; return NULL;
} }
@ -153,7 +153,7 @@ LIBSSH2_SESSION *start_session_fixture(void)
libssh2_session_set_blocking(connected_session, 1); libssh2_session_set_blocking(connected_session, 1);
rc = connect_to_server(); rc = connect_to_server();
if(rc != 0) { if(rc) {
return NULL; return NULL;
} }

View File

@ -74,7 +74,7 @@ int main(int argc, char *argv[])
(void)argc; (void)argc;
rc = libssh2_init(LIBSSH2_INIT_NO_CRYPTO); rc = libssh2_init(LIBSSH2_INIT_NO_CRYPTO);
if(rc != 0) { if(rc) {
fprintf(stderr, "libssh2_init() failed: %d\n", rc); fprintf(stderr, "libssh2_init() failed: %d\n", rc);
return 1; return 1;
} }

View File

@ -2,7 +2,6 @@
#include "libssh2_setup.h" #include "libssh2_setup.h"
#include <libssh2.h> #include <libssh2.h>
#include <libssh2_sftp.h>
#ifdef HAVE_SYS_SOCKET_H #ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h> #include <sys/socket.h>
@ -24,6 +23,11 @@
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
static const char *pubkey = "etc/user.pub";
static const char *privkey = "etc/user";
static const char *username = "username";
static const char *password = "password";
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
uint32_t hostaddr; uint32_t hostaddr;
@ -32,22 +36,17 @@ int main(int argc, char *argv[])
struct sockaddr_in sin; struct sockaddr_in sin;
const char *fingerprint; const char *fingerprint;
char *userauthlist; char *userauthlist;
LIBSSH2_SESSION *session; int rc;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel; LIBSSH2_CHANNEL *channel;
const char *pubkey = "etc/user.pub";
const char *privkey = "etc/user";
const char *username = "username";
const char *password = "password";
int ec = 1;
#ifdef WIN32 #ifdef WIN32
WSADATA wsadata; WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2, 0), &wsadata); rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) { if(rc) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err); fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
return -1; return 1;
} }
#endif #endif
@ -55,17 +54,30 @@ int main(int argc, char *argv[])
(void)argv; (void)argv;
if(getenv("USER")) if(getenv("USER"))
username = getenv("USER"); username = getenv("USER");
if(getenv("PRIVKEY")) if(getenv("PRIVKEY"))
privkey = getenv("PRIVKEY"); privkey = getenv("PRIVKEY");
if(getenv("PUBKEY")) if(getenv("PUBKEY"))
pubkey = getenv("PUBKEY"); pubkey = getenv("PUBKEY");
hostaddr = htonl(0x7F000001); hostaddr = htonl(0x7F000001);
rc = libssh2_init(0);
if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}
rc = 1;
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == LIBSSH2_INVALID_SOCKET) {
fprintf(stderr, "failed to create socket!\n");
goto shutdown;
}
#ifndef WIN32 #ifndef WIN32
fcntl(sock, F_SETFL, 0); fcntl(sock, F_SETFL, 0);
#endif #endif
@ -74,64 +86,70 @@ int main(int argc, char *argv[])
sin.sin_addr.s_addr = hostaddr; sin.sin_addr.s_addr = hostaddr;
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) { if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n"); fprintf(stderr, "failed to connect!\n");
return 1; goto shutdown;
} }
/* Create a session instance and start it up /* Create a session instance and start it up. This will trade welcome
* This will trade welcome banners, exchange keys, * banners, exchange keys, and setup crypto, compression, and MAC layers
* and setup crypto, compression, and MAC layers
*/ */
session = libssh2_session_init(); session = libssh2_session_init();
if(libssh2_session_handshake(session, sock)) { if(!session) {
fprintf(stderr, "Failure establishing SSH session\n"); fprintf(stderr, "Could not initialize SSH session!\n");
return 1; goto shutdown;
} }
/* At this point we haven't authenticated, rc = libssh2_session_handshake(session, sock);
* The first thing to do is check the hostkey's if(rc) {
* fingerprint against our known hosts fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
* Your app may have it hard coded, may go to a file, goto shutdown;
* may present it to the user, that's your call }
/* At this point we have not 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); fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
printf("Fingerprint: "); fprintf(stderr, "Fingerprint: ");
for(i = 0; i < 20; i++) { for(i = 0; i < 20; i++) {
printf("%02X ", (unsigned char)fingerprint[i]); fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
} }
printf("\n"); fprintf(stderr, "\n");
/* check what authentication methods are available */ /* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, userauthlist = libssh2_userauth_list(session, username,
(unsigned int)strlen(username)); (unsigned int)strlen(username));
printf("Authentication methods: %s\n", userauthlist); if(userauthlist) {
if(strstr(userauthlist, "password") != NULL) { fprintf(stderr, "Authentication methods: %s\n", userauthlist);
auth_pw |= 1; if(strstr(userauthlist, "password")) {
} auth_pw |= 1;
if(strstr(userauthlist, "keyboard-interactive") != NULL) { }
auth_pw |= 2; if(strstr(userauthlist, "keyboard-interactive")) {
} auth_pw |= 2;
if(strstr(userauthlist, "publickey") != NULL) { }
auth_pw |= 4; if(strstr(userauthlist, "publickey")) {
} auth_pw |= 4;
}
if(auth_pw & 4) { if(auth_pw & 4) {
/* Authenticate by public key */ /* Authenticate by public key */
if(libssh2_userauth_publickey_fromfile(session, username, if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey, pubkey, privkey,
password)) { password)) {
printf("\tAuthentication by public key failed!\n"); fprintf(stderr, "Authentication by public key failed!\n");
goto shutdown; goto shutdown;
}
else {
fprintf(stderr, "Authentication by public key succeeded.\n");
}
} }
else { else {
printf("\tAuthentication by public key succeeded.\n"); fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
} }
} }
else {
printf("No supported authentication methods found!\n");
goto shutdown;
}
/* Request a shell */ /* Request a session channel on which to run a shell */
channel = libssh2_channel_open_session(session); channel = libssh2_channel_open_session(session);
if(!channel) { if(!channel) {
fprintf(stderr, "Unable to open a session\n"); fprintf(stderr, "Unable to open a session\n");
@ -144,7 +162,8 @@ int main(int argc, char *argv[])
libssh2_channel_setenv(channel, "FOO", "bar"); libssh2_channel_setenv(channel, "FOO", "bar");
/* Request a terminal with 'vanilla' terminal emulation /* Request a terminal with 'vanilla' terminal emulation
* See /etc/termcap for more options * See /etc/termcap for more options. This is useful when opening
* an interactive shell.
*/ */
if(libssh2_channel_request_pty(channel, "vanilla")) { if(libssh2_channel_request_pty(channel, "vanilla")) {
fprintf(stderr, "Failed requesting pty\n"); fprintf(stderr, "Failed requesting pty\n");
@ -157,9 +176,10 @@ int main(int argc, char *argv[])
goto shutdown; goto shutdown;
} }
ec = 0; rc = 0;
skip_shell: skip_shell:
if(channel) { if(channel) {
libssh2_channel_free(channel); libssh2_channel_free(channel);
channel = NULL; channel = NULL;
@ -167,16 +187,22 @@ skip_shell:
shutdown: shutdown:
libssh2_session_disconnect(session, "Normal Shutdown"); if(session) {
libssh2_session_free(session); libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
if(sock != LIBSSH2_INVALID_SOCKET) {
#ifdef WIN32 #ifdef WIN32
Sleep(1000); closesocket(sock);
closesocket(sock);
#else #else
sleep(1); close(sock);
close(sock);
#endif #endif
}
return ec; fprintf(stderr, "all done\n");
libssh2_exit();
return rc;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }
@ -39,7 +39,7 @@ int test(LIBSSH2_SESSION *session)
/* } */ /* } */
rc = libssh2_channel_request_auth_agent(channel); rc = libssh2_channel_request_auth_agent(channel);
if(rc != 0) { if(rc) {
fprintf(stderr, "Auth agent request for agent forwarding failed, " fprintf(stderr, "Auth agent request for agent forwarding failed, "
"error code %d\n", rc); "error code %d\n", rc);
return 1; return 1;

View File

@ -21,7 +21,7 @@ int test(LIBSSH2_SESSION *session)
char *expected_hostkey = NULL; char *expected_hostkey = NULL;
const char *hostkey = libssh2_session_hostkey(session, &len, &type); const char *hostkey = libssh2_session_hostkey(session, &len, &type);
if(hostkey == NULL) { if(!hostkey) {
print_last_session_error("libssh2_session_hostkey"); print_last_session_error("libssh2_session_hostkey");
return 1; return 1;
} }
@ -41,7 +41,7 @@ int test(LIBSSH2_SESSION *session)
return 1; return 1;
} }
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_base64_decode"); print_last_session_error("libssh2_base64_decode");
return 1; return 1;
} }

View File

@ -62,7 +62,7 @@ int test(LIBSSH2_SESSION *session)
(void)EXPECTED_ECDSA_HOSTKEY; (void)EXPECTED_ECDSA_HOSTKEY;
hostkey = libssh2_session_hostkey(session, &len, &type); hostkey = libssh2_session_hostkey(session, &len, &type);
if(hostkey == NULL) { if(!hostkey) {
print_last_session_error("libssh2_session_hostkey"); print_last_session_error("libssh2_session_hostkey");
return 1; return 1;
} }
@ -70,7 +70,7 @@ int test(LIBSSH2_SESSION *session)
if(type == LIBSSH2_HOSTKEY_TYPE_ECDSA_256) { if(type == LIBSSH2_HOSTKEY_TYPE_ECDSA_256) {
md5_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); md5_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5);
if(md5_hash == NULL) { if(!md5_hash) {
print_last_session_error( print_last_session_error(
"libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_MD5)"); "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_MD5)");
return 1; return 1;
@ -86,7 +86,7 @@ int test(LIBSSH2_SESSION *session)
} }
sha1_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); sha1_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
if(sha1_hash == NULL) { if(!sha1_hash) {
print_last_session_error( print_last_session_error(
"libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA1)"); "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA1)");
return 1; return 1;
@ -103,7 +103,7 @@ int test(LIBSSH2_SESSION *session)
sha256_hash = libssh2_hostkey_hash(session, sha256_hash = libssh2_hostkey_hash(session,
LIBSSH2_HOSTKEY_HASH_SHA256); LIBSSH2_HOSTKEY_HASH_SHA256);
if(sha256_hash == NULL) { if(!sha256_hash) {
print_last_session_error( print_last_session_error(
"libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA256)"); "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA256)");
return 1; return 1;
@ -122,7 +122,7 @@ int test(LIBSSH2_SESSION *session)
else if(type == LIBSSH2_HOSTKEY_TYPE_RSA) { else if(type == LIBSSH2_HOSTKEY_TYPE_RSA) {
md5_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); md5_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5);
if(md5_hash == NULL) { if(!md5_hash) {
print_last_session_error( print_last_session_error(
"libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_MD5)"); "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_MD5)");
return 1; return 1;
@ -138,7 +138,7 @@ int test(LIBSSH2_SESSION *session)
} }
sha1_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); sha1_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
if(sha1_hash == NULL) { if(!sha1_hash) {
print_last_session_error( print_last_session_error(
"libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA1)"); "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA1)");
return 1; return 1;
@ -155,7 +155,7 @@ int test(LIBSSH2_SESSION *session)
sha256_hash = libssh2_hostkey_hash(session, sha256_hash = libssh2_hostkey_hash(session,
LIBSSH2_HOSTKEY_HASH_SHA256); LIBSSH2_HOSTKEY_HASH_SHA256);
if(sha256_hash == NULL) { if(!sha256_hash) {
print_last_session_error( print_last_session_error(
"libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA256)"); "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA256)");
return 1; return 1;

View File

@ -32,12 +32,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "keyboard-interactive") == NULL) { if(!strstr(userauth_list, "keyboard-interactive")) {
fprintf(stderr, fprintf(stderr,
"'keyboard-interactive' was expected in userauth list: %s\n", "'keyboard-interactive' was expected in userauth list: %s\n",
userauth_list); userauth_list);

View File

@ -223,7 +223,7 @@ LIBSSH2_ALLOC_FUNC(test_alloc)
{ {
int *threshold_int_ptr = *abstract; int *threshold_int_ptr = *abstract;
alloc_count++; alloc_count++;
if(*abstract != NULL && *threshold_int_ptr == alloc_count) { if(*abstract && *threshold_int_ptr == alloc_count) {
return NULL; return NULL;
} }
@ -252,7 +252,7 @@ int test_case(int num,
alloc_count = 0; alloc_count = 0;
free_count = 0; free_count = 0;
session = libssh2_session_init_ex(test_alloc, test_free, NULL, abstract); session = libssh2_session_init_ex(test_alloc, test_free, NULL, abstract);
if(session == NULL) { if(!session) {
fprintf(stderr, "libssh2_session_init_ex failed\n"); fprintf(stderr, "libssh2_session_init_ex failed\n");
return 1; return 1;
} }

View File

@ -34,12 +34,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "keyboard-interactive") == NULL) { if(!strstr(userauth_list, "keyboard-interactive")) {
fprintf(stderr, fprintf(stderr,
"'keyboard-interactive' was expected in userauth list: %s\n", "'keyboard-interactive' was expected in userauth list: %s\n",
userauth_list); userauth_list);
@ -48,7 +48,7 @@ int test(LIBSSH2_SESSION *session)
rc = libssh2_userauth_keyboard_interactive_ex( rc = libssh2_userauth_keyboard_interactive_ex(
session, USERNAME, (unsigned int)strlen(USERNAME), kbd_callback); session, USERNAME, (unsigned int)strlen(USERNAME), kbd_callback);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_keyboard_interactive_ex"); print_last_session_error("libssh2_userauth_keyboard_interactive_ex");
return 1; return 1;
} }

View File

@ -10,12 +10,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "password") == NULL) { if(!strstr(userauth_list, "password")) {
fprintf(stderr, "'password' was expected in userauth list: %s\n", fprintf(stderr, "'password' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;

View File

@ -11,12 +11,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, WRONG_USERNAME, libssh2_userauth_list(session, WRONG_USERNAME,
(unsigned int)strlen(WRONG_USERNAME)); (unsigned int)strlen(WRONG_USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "password") == NULL) { if(!strstr(userauth_list, "password")) {
fprintf(stderr, "'password' was expected in userauth list: %s\n", fprintf(stderr, "'password' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;

View File

@ -11,12 +11,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "password") == NULL) { if(!strstr(userauth_list, "password")) {
fprintf(stderr, "'password' was expected in userauth list: %s\n", fprintf(stderr, "'password' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -26,7 +26,7 @@ int test(LIBSSH2_SESSION *session)
(unsigned int)strlen(USERNAME), (unsigned int)strlen(USERNAME),
PASSWORD, PASSWORD,
(unsigned int)strlen(PASSWORD), NULL); (unsigned int)strlen(PASSWORD), NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_password_ex"); print_last_session_error("libssh2_userauth_password_ex");
return 1; return 1;
} }

View File

@ -11,12 +11,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -26,7 +26,7 @@ int test(LIBSSH2_SESSION *session)
rc = libssh2_userauth_publickey_fromfile_ex( rc = libssh2_userauth_publickey_fromfile_ex(
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), NULL); srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
userauth_list = libssh2_userauth_list(session, USERNAME, userauth_list = libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
userauth_list = libssh2_userauth_list(session, USERNAME, userauth_list = libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -16,12 +16,12 @@ int test(LIBSSH2_SESSION *session)
userauth_list = libssh2_userauth_list(session, USERNAME, userauth_list = libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -40,7 +40,7 @@ int test(LIBSSH2_SESSION *session)
free(buffer); free(buffer);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }
@ -54,7 +54,7 @@ static int read_file(const char *path, char **out_buffer, size_t *out_len)
char *buffer = NULL; char *buffer = NULL;
size_t len = 0; size_t len = 0;
if(out_buffer == NULL || out_len == NULL || path == NULL) { if(!out_buffer || !out_len || !path) {
fprintf(stderr, "invalid params."); fprintf(stderr, "invalid params.");
return 1; return 1;
} }

View File

@ -13,12 +13,12 @@ int test(LIBSSH2_SESSION *session)
userauth_list = libssh2_userauth_list(session, USERNAME, userauth_list = libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -28,7 +28,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
PASSWORD); PASSWORD);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -13,12 +13,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -28,7 +28,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
PASSWORD); PASSWORD);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
userauth_list = libssh2_userauth_list(session, USERNAME, userauth_list = libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -12,12 +12,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -27,7 +27,7 @@ int test(LIBSSH2_SESSION *session)
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE),
NULL); NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }

View File

@ -32,12 +32,12 @@ int test(LIBSSH2_SESSION *session)
const char *userauth_list = const char *userauth_list =
libssh2_userauth_list(session, USERNAME, libssh2_userauth_list(session, USERNAME,
(unsigned int)strlen(USERNAME)); (unsigned int)strlen(USERNAME));
if(userauth_list == NULL) { if(!userauth_list) {
print_last_session_error("libssh2_userauth_list"); print_last_session_error("libssh2_userauth_list");
return 1; return 1;
} }
if(strstr(userauth_list, "publickey") == NULL) { if(!strstr(userauth_list, "publickey")) {
fprintf(stderr, "'publickey' was expected in userauth list: %s\n", fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
userauth_list); userauth_list);
return 1; return 1;
@ -46,7 +46,7 @@ int test(LIBSSH2_SESSION *session)
rc = libssh2_userauth_publickey_fromfile_ex( rc = libssh2_userauth_publickey_fromfile_ex(
session, USERNAME, (unsigned int)strlen(USERNAME), session, USERNAME, (unsigned int)strlen(USERNAME),
srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), NULL); srcdir_path(KEY_FILE_PUBLIC), srcdir_path(KEY_FILE_PRIVATE), NULL);
if(rc != 0) { if(rc) {
print_last_session_error("libssh2_userauth_publickey_fromfile_ex"); print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
return 1; return 1;
} }