166 changes: 105 additions & 61 deletions acinclude.m4
Original file line number Diff line number Diff line change
Expand Up @@ -382,86 +382,130 @@ AC_DEFUN([CURL_CONFIGURE_REENTRANT], [
#
])

AC_DEFUN([LIBSSH2_CHECKFOR_MBEDTLS], [
old_LDFLAGS=$LDFLAGS
old_CFLAGS=$CFLAGS
if test -n "$use_mbedtls" && test "$use_mbedtls" != "no"; then
LDFLAGS="$LDFLAGS -L$use_mbedtls/lib"
CFLAGS="$CFLAGS -I$use_mbedtls/include"
fi
dnl LIBSSH2_LIB_HAVE_LINKFLAGS
dnl --------------------------
dnl Wrapper around AC_LIB_HAVE_LINKFLAGS to also check $prefix/lib, if set.
dnl
dnl autoconf only checks $prefix/lib64 if gcc -print-search-dirs output
dnl includes a directory named lib64. So, to find libraries in $prefix/lib
dnl we append -L$prefix/lib to LDFLAGS before checking.
dnl
dnl For conveniece, $4 is expanded if [lib]$1 is found.

AC_LIB_HAVE_LINKFLAGS([mbedtls], [], [
#include <mbedtls/version.h>
])
AC_DEFUN([LIBSSH2_LIB_HAVE_LINKFLAGS], [
libssh2_save_CPPFLAGS="$CPPFLAGS"
libssh2_save_LDFLAGS="$LDFLAGS"
if test "$ac_cv_libmbedtls" = "yes"; then
AC_DEFINE(LIBSSH2_MBEDTLS, 1, [Use mbedtls])
LIBSREQUIRED= # mbedtls doesn't provide a .pc file
LIBS="$LIBS -lmbedtls -lmbedcrypto"
found_crypto=libmbedtls
support_clear_memory=yes
else
# restore
LDFLAGS=$old_LDFLAGS
CFLAGS=$old_CFLAGS
if test "${with_lib$1_prefix+set}" = set; then
CPPFLAGS="$CPPFLAGS${CPPFLAGS:+ }-I${with_lib$1_prefix}/include"
LDFLAGS="$LDFLAGS${LDFLAGS:+ }-L${with_lib$1_prefix}/lib"
fi
])
AC_DEFUN([LIBSSH2_CHECKFOR_GCRYPT], [
AC_LIB_HAVE_LINKFLAGS([$1], [$2], [$3])
old_LDFLAGS=$LDFLAGS
old_CFLAGS=$CFLAGS
if test -n "$use_libgcrypt" && test "$use_libgcrypt" != "no"; then
LDFLAGS="$LDFLAGS -L$use_libgcrypt/lib"
CFLAGS="$CFLAGS -I$use_libgcrypt/include"
fi
AC_LIB_HAVE_LINKFLAGS([gcrypt], [], [
#include <gcrypt.h>
])
LDFLAGS="$libssh2_save_LDFLAGS"
if test "$ac_cv_libgcrypt" = "yes"; then
AC_DEFINE(LIBSSH2_LIBGCRYPT, 1, [Use libgcrypt])
LIBSREQUIRED= # libgcrypt doesn't provide a .pc file. sad face.
LIBS="$LIBS -lgcrypt"
found_crypto=libgcrypt
if test "$ac_cv_lib$1" = "yes"; then :
$4
else
# restore
LDFLAGS=$old_LDFLAGS
CFLAGS=$old_CFLAGS
CPPFLAGS="$libssh2_save_CPPFLAGS"
fi
])

AC_DEFUN([LIBSSH2_CHECK_CRYPTO], [
if test "$use_crypto" = "auto" && test "$found_crypto" = "none" || test "$use_crypto" = "$1"; then
m4_case([$1],
[openssl], [
LIBSSH2_LIB_HAVE_LINKFLAGS([ssl], [crypto], [#include <openssl/ssl.h>], [
AC_DEFINE(LIBSSH2_OPENSSL, 1, [Use $1])
LIBSREQUIRED="$LIBSREQUIRED${LIBSREQUIRED:+ }libssl libcrypto"
# Not all OpenSSL have AES-CTR functions.
libssh2_save_LIBS="$LIBS"
LIBS="$LIBS $LIBSSL"
AC_CHECK_FUNCS(EVP_aes_128_ctr)
LIBS="$libssh2_save_LIBS"
found_crypto="$1"
found_crypto_str="OpenSSL (AES-CTR: ${ac_cv_func_EVP_aes_128_ctr:-N/A})"
])
],
[libgcrypt], [
LIBSSH2_LIB_HAVE_LINKFLAGS([gcrypt], [], [#include <gcrypt.h>], [
AC_DEFINE(LIBSSH2_LIBGCRYPT, 1, [Use $1])
found_crypto="$1"
])
],
AC_DEFUN([LIBSSH2_CHECKFOR_WINCNG], [
[mbedtls], [
LIBSSH2_LIB_HAVE_LINKFLAGS([mbedcrypto], [], [#include <mbedtls/version.h>], [
AC_DEFINE(LIBSSH2_MBEDTLS, 1, [Use $1])
found_crypto="$1"
support_clear_memory=yes
])
],
[wincng], [
# Look for Windows Cryptography API: Next Generation
AC_LIB_HAVE_LINKFLAGS([bcrypt], [], [
#include <windows.h>
#include <bcrypt.h>
])
AC_LIB_HAVE_LINKFLAGS([crypt32], [], [
AC_CHECK_HEADERS([ntdef.h ntstatus.h], [], [], [#include <windows.h>])
AC_CHECK_DECLS([SecureZeroMemory], [], [], [#include <windows.h>])
LIBSSH2_LIB_HAVE_LINKFLAGS([crypt32], [], [
#include <windows.h>
#include <wincrypt.h>
])
AC_CHECK_HEADERS([ntdef.h ntstatus.h], [], [], [
#include <windows.h>
])
AC_CHECK_DECLS([SecureZeroMemory], [], [], [
LIBSSH2_LIB_HAVE_LINKFLAGS([bcrypt], [], [
#include <windows.h>
#include <bcrypt.h>
], [
AC_DEFINE(LIBSSH2_WINCNG, 1, [Use $1])
found_crypto="$1"
found_crypto_str="Windows Cryptography API: Next Generation"
support_clear_memory="$ac_cv_have_decl_SecureZeroMemory"
])
],
)
test "$found_crypto" = "none" &&
crypto_errors="${crypto_errors}No $1 crypto library found!
"
fi
])

if test "$ac_cv_libbcrypt" = "yes"; then
AC_DEFINE(LIBSSH2_WINCNG, 1, [Use Windows CNG])
LIBSREQUIRED= # wincng doesn't provide a .pc file. sad face.
LIBS="$LIBS -lbcrypt"
if test "$ac_cv_libcrypt32" = "yes"; then
LIBS="$LIBS -lcrypt32"
fi
found_crypto="Windows Cryptography API: Next Generation"
if test "$ac_cv_have_decl_SecureZeroMemory" = "yes"; then
support_clear_memory=yes
fi

dnl LIBSSH2_CHECK_OPTION_WERROR
dnl -------------------------------------------------
dnl Verify if configure has been invoked with option
dnl --enable-werror or --disable-werror, and set
dnl shell variable want_werror as appropriate.

AC_DEFUN([LIBSSH2_CHECK_OPTION_WERROR], [
AC_BEFORE([$0],[LIBSSH2_CHECK_COMPILER])dnl
AC_MSG_CHECKING([whether to enable compiler warnings as errors])
OPT_COMPILER_WERROR="default"
AC_ARG_ENABLE(werror,
AC_HELP_STRING([--enable-werror],[Enable compiler warnings as errors])
AC_HELP_STRING([--disable-werror],[Disable compiler warnings as errors]),
OPT_COMPILER_WERROR=$enableval)
case "$OPT_COMPILER_WERROR" in
no)
dnl --disable-werror option used
want_werror="no"
;;
default)
dnl configure option not specified
want_werror="no"
;;
*)
dnl --enable-werror option used
want_werror="yes"
;;
esac
AC_MSG_RESULT([$want_werror])
if test X"$want_werror" = Xyes; then
CFLAGS="$CFLAGS -Werror"
fi
])

23 changes: 5 additions & 18 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,6 @@ environment:
- GENERATOR: "Visual Studio 12 2013"
BUILD_SHARED_LIBS: OFF

- GENERATOR: "Visual Studio 11 2012"
BUILD_SHARED_LIBS: ON

- GENERATOR: "Visual Studio 11 2012"
BUILD_SHARED_LIBS: OFF

- GENERATOR: "Visual Studio 10 2010"
BUILD_SHARED_LIBS: ON

- GENERATOR: "Visual Studio 10 2010"
BUILD_SHARED_LIBS: OFF

- GENERATOR: "Visual Studio 9 2008"
BUILD_SHARED_LIBS: ON

- GENERATOR: "Visual Studio 9 2008"
BUILD_SHARED_LIBS: OFF

digitalocean_access_token:
secure: 8qRitvrj69Xhf0Tmu27xnz5drmL2YhmOJLGpXIkYyTCC0JNtBoXW6fMcF3u4Uj1+pIQ+TjegQOwYimlz0oivKTro3v3EXro+osAMNJG6NKc=

Expand Down Expand Up @@ -100,3 +82,8 @@ on_failure:
- ps: if($env:digitalocean_access_token) { docker-machine rm -y $($env:DOCKER_MACHINE_NAME) }
- ps: if(Test-Path _builds/CMakeFiles/CMakeOutput.log) { cat _builds/CMakeFiles/CMakeOutput.log }
- ps: if(Test-Path _builds/CMakeFiles/CMakeError.log) { cat _builds/CMakeFiles/CMakeError.log }

# whitelist branches to avoid testing feature branches twice (as branch and as pull request)
branches:
only:
- master
143 changes: 81 additions & 62 deletions configure.ac
Original file line number Diff line number Diff line change
Expand Up @@ -83,79 +83,78 @@ AC_C_BIGENDIAN
dnl check for how to do large files
AC_SYS_LARGEFILE

found_crypto=none
# Crypto backends

# Configure parameters
AC_ARG_WITH(openssl,
AC_HELP_STRING([--with-openssl],[Use OpenSSL for crypto]),
use_openssl=$withval,use_openssl=auto)
AC_ARG_WITH(libgcrypt,
AC_HELP_STRING([--with-libgcrypt],[Use libgcrypt for crypto]),
[ use_libgcrypt=$withval
LIBSSH2_CHECKFOR_GCRYPT
], use_libgcrypt=auto)
AC_ARG_WITH(wincng,
AC_HELP_STRING([--with-wincng],[Use Windows CNG for crypto]),
[ use_wincng=$withval
LIBSSH2_CHECKFOR_WINCNG
] ,use_wincng=auto)
AC_ARG_WITH([mbedtls],
AC_HELP_STRING([--with-mbedtls],[Use mbedTLS for crypto]),
[ use_mbedtls=$withval
LIBSSH2_CHECKFOR_MBEDTLS
], use_mbedtls=auto
found_crypto=none
found_crypto_str=""
support_clear_memory=no
crypto_errors=""

m4_set_add([crypto_backends], [openssl])
m4_set_add([crypto_backends], [libgcrypt])
m4_set_add([crypto_backends], [mbedtls])
m4_set_add([crypto_backends], [wincng])

AC_ARG_WITH([crypto],
AC_HELP_STRING([--with-crypto=auto|]m4_set_contents([crypto_backends], [|]),
[Select crypto backend (default: auto)]),
use_crypto=$withval,
use_crypto=auto
)
AC_ARG_WITH(libz,
AC_HELP_STRING([--with-libz],[Use zlib for compression]),
use_libz=$withval,use_libz=auto)

support_clear_memory=no
case "${use_crypto}" in
auto|m4_set_contents([crypto_backends], [|]))
m4_set_map([crypto_backends], [LIBSSH2_CHECK_CRYPTO])
;;
yes|"")
crypto_errors="No crypto backend specified!"
;;
*)
crypto_errors="Unknown crypto backend '${use_crypto}' specified!"
;;
esac

if test "$found_crypto" = "none"; then
crypto_errors="${crypto_errors}
Specify --with-crypto=\$backend and/or the neccessary library search prefix.

# Look for OpenSSL
if test "$found_crypto" = "none" && test "$use_openssl" != "no"; then
AC_LIB_HAVE_LINKFLAGS([ssl], [crypto], [#include <openssl/ssl.h>])
Known crypto backends: auto, m4_set_contents([crypto_backends], [, ])"
AS_MESSAGE([ERROR: ${crypto_errors}])
else
test "$found_crypto_str" = "" && found_crypto_str="$found_crypto"
fi
if test "$ac_cv_libssl" = "yes"; then
AC_DEFINE(LIBSSH2_OPENSSL, 1, [Use OpenSSL])
LIBSREQUIRED=libssl,libcrypto

# Not all OpenSSL have AES-CTR functions.
save_LIBS="$LIBS"
LIBS="$LIBS $LIBSSL"
AC_CHECK_FUNCS(EVP_aes_128_ctr)
LIBS="$save_LIBS"
m4_set_foreach([crypto_backends], [backend],
[AM_CONDITIONAL(m4_toupper(backend), test "$found_crypto" = "backend")]
)
m4_undefine([backend])

found_crypto="OpenSSL (AES-CTR: ${ac_cv_func_EVP_aes_128_ctr:-N/A})"
fi

AM_CONDITIONAL(OPENSSL, test "$ac_cv_libssl" = "yes")
AM_CONDITIONAL(WINCNG, test "$ac_cv_libbcrypt" = "yes")
AM_CONDITIONAL(LIBGCRYPT, test "$ac_cv_libgcrypt" = "yes")
AM_CONDITIONAL(MBEDTLS, test "$ac_cv_libmbedtls" = "yes")
AM_CONDITIONAL(OS400QC3, false)
# libz

# Check if crypto library was found
if test "$found_crypto" = "none"; then
AC_MSG_ERROR([No crypto library found!
Try --with-libssl-prefix=PATH
or --with-libgcrypt-prefix=PATH
or --with-libmbedtls-prefix=PATH
or --with-wincng on Windows\
])
fi
AC_ARG_WITH([libz],
AC_HELP_STRING([--with-libz],[Use libz for compression]),
use_libz=$withval,
use_libz=auto)

# Look for Libz
if test "$use_libz" != "no"; then
found_libz=no
libz_errors=""

if test "$use_libz" != no; then
AC_LIB_HAVE_LINKFLAGS([z], [], [#include <zlib.h>])
if test "$ac_cv_libz" != yes; then
AC_MSG_NOTICE([Cannot find zlib, disabling compression])
AC_MSG_NOTICE([Try --with-libz-prefix=PATH if you know you have it])
if test "$use_libz" = auto; then
AC_MSG_NOTICE([Cannot find libz, disabling compression])
found_libz="disabled; no libz found"
else
libz_errors="No libz found!
Try --with-libz-prefix=PATH if you know that you have it."
AS_MESSAGE([ERROR: $libz_errors])
fi
else
AC_DEFINE(LIBSSH2_HAVE_ZLIB, 1, [Compile in zlib support])
if test "${LIBSREQUIRED}" != ""; then
LIBSREQUIRED="${LIBSREQUIRED},"
fi
LIBSREQUIRED="${LIBSREQUIRED}zlib"
LIBSREQUIRED="$LIBSREQUIRED${LIBSREQUIRED:+ }zlib"
found_libz="yes"
fi
fi

Expand Down Expand Up @@ -213,6 +212,7 @@ AC_HELP_STRING([--disable-debug],[Disable debug options]),
[ case "$enable_debug" in
no)
AC_MSG_RESULT(no)
CPPFLAGS="$CPPFLAGS -DNDEBUG"
;;
*) AC_MSG_RESULT(yes)
enable_debug=yes
Expand Down Expand Up @@ -319,7 +319,7 @@ case $host in
;;
esac

AC_CHECK_FUNCS(gettimeofday select strtoll)
AC_CHECK_FUNCS(gettimeofday select strtoll memset_s)

dnl Check for select() into ws2_32 for Msys/Mingw
if test "$ac_cv_func_select" != "yes"; then
Expand Down Expand Up @@ -351,6 +351,25 @@ AC_C_INLINE

CURL_CHECK_NONBLOCKING_SOCKET

missing_required_deps=0

if test "${libz_errors}" != ""; then
AS_MESSAGE([ERROR: ${libz_errors}])
missing_required_deps=1
fi

if test "$found_crypto" = "none"; then
AS_MESSAGE([ERROR: ${crypto_errors}])
missing_required_deps=1
fi

if test $missing_required_deps = 1; then
AC_MSG_ERROR([Required dependencies are missing!])
fi

# Configure parameters
LIBSSH2_CHECK_OPTION_WERROR

AC_CONFIG_FILES([Makefile
src/Makefile
tests/Makefile
Expand All @@ -367,10 +386,10 @@ AC_MSG_NOTICE([summary of build options:
Compiler: ${CC}
Compiler flags: ${CFLAGS}
Library types: Shared=${enable_shared}, Static=${enable_static}
Crypto library: ${found_crypto}
Crypto library: ${found_crypto_str}
Clear memory: $enable_clear_memory
Debug build: $enable_debug
Build examples: $build_examples
Path to sshd: $ac_cv_path_SSHD (only for self-tests)
zlib compression: $ac_cv_libz
zlib compression: ${found_libz}
])
4 changes: 4 additions & 0 deletions docs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ set(MAN_PAGES
libssh2_agent_disconnect.3
libssh2_agent_free.3
libssh2_agent_get_identity.3
libssh2_agent_get_identity_path.3
libssh2_agent_init.3
libssh2_agent_list_identities.3
libssh2_agent_set_identity_path.3
libssh2_agent_userauth.3
libssh2_banner_set.3
libssh2_base64_decode.3
Expand Down Expand Up @@ -134,6 +136,7 @@ set(MAN_PAGES
libssh2_session_free.3
libssh2_session_get_blocking.3
libssh2_session_get_timeout.3
libssh2_session_handshake.3
libssh2_session_hostkey.3
libssh2_session_init.3
libssh2_session_init_ex.3
Expand Down Expand Up @@ -200,6 +203,7 @@ set(MAN_PAGES
libssh2_userauth_publickey.3
libssh2_userauth_publickey_fromfile.3
libssh2_userauth_publickey_fromfile_ex.3
libssh2_userauth_publickey_frommemory.3
libssh2_version.3)

include(GNUInstallDirs)
Expand Down
108 changes: 77 additions & 31 deletions docs/HACKING.CRYPTO
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,38 @@ Procedures listed as "void" may indeed have a result type: the void indication
indicates the libssh2 core modules never use the function result.


0) Build system.

Adding a crypto backend to the autotools build system (./configure) is easy:

0.1) Add one new line in configure.ac

m4_set_add([crypto_backends], [newname])

This automatically creates a --with-crypto=newname option.

0.2) Add an m4_case stanza to LIBSSH2_CRYPTO_CHECK in acinclude.m4

This must check for all required libraries, and if found set and AC_SUBST a
variable with the library linking flags. The recommended method is to use
LIBSSH2_LIB_HAVE_LINKFLAGS from LIBSSH2_CRYPTO_CHECK, which automatically
creates and handles a --with-$newname-prefix option and sets an
LTLIBNEWNAME variable on success.

0.3) Create Makefile.newname.inc in the top-level directory

This must set CRYPTO_CSOURCES, CRYPTO_HHEADERS and CRYPTO_LTLIBS.
Set CRYPTO_CSOURCES and CRYPTO_HHEADERS to the new backend source files
and set CRYPTO_LTLIBS to the required library linking parameters, e.g.
$(LTLIBNEWNAME) as generated by by LIBSSH2_LIB_HAVE_LINKFLAGS.

0.4) Add a new block in src/Makefile.am

if NEWNAME
include ../Makefile.newname.inc
endif


1) Crypto library initialization/termination.

void libssh2_crypto_init(void);
Expand Down Expand Up @@ -61,7 +93,7 @@ SHA_DIGEST_LENGTH
#define to 20, the SHA-1 digest length.

libssh2_sha1_ctx
Type of an SHA1 computation context. Generally a struct.
Type of an SHA-1 computation context. Generally a struct.

int libssh2_sha1_init(libssh2_sha1_ctx *x);
Initializes the SHA-1 computation context at x.
Expand All @@ -75,7 +107,7 @@ Note: if the ctx parameter is modified by the underlying code,
this procedure must be implemented as a macro to map ctx --> &ctx.

void libssh2_sha1_final(libssh2_sha1_ctx ctx,
unsigned char output[SHA1_DIGEST_LEN]);
unsigned char output[SHA_DIGEST_LEN]);
Get the computed SHA-1 signature from context ctx and store it into the
output buffer.
Release the context.
Expand Down Expand Up @@ -196,7 +228,7 @@ the keylen-byte key. Is invoked just after libssh2_hmac_ctx_init().
Returns 1 for success and 0 for failure.


4) Bidirectional Key ciphers.
4) Bidirectional key ciphers.

_libssh2_cipher_ctx
Type of a cipher computation context.
Expand Down Expand Up @@ -252,10 +284,6 @@ LIBSSH2_AES_CTR
#define as 1 if the crypto library supports AES in CTR mode, else 0.
If defined as 0, the rest of this section can be omitted.

void _libssh2_init_aes_ctr(void);
Initialize static AES CTR ciphers.
This procedure is already prototyped in crypto.h.

_libssh2_cipher_aes128ctr
AES-128-CTR algorithm identifier initializer.
#define with constant value of type _libssh2_cipher_type().
Expand Down Expand Up @@ -305,24 +333,56 @@ TripleDES-CBC algorithm identifier initializer.
#define with constant value of type _libssh2_cipher_type().


5) Big numbers.
5) Diffie-Hellman support.

5.1) Diffie-Hellman context.
_libssh2_dh_ctx
Type of a Diffie-Hellman computation context.
Must always be defined.

5.2) Diffie-Hellman computation procedures.
void libssh2_dh_init(_libssh2_dh_ctx *dhctx);
Initializes the Diffie-Hellman context at `dhctx'. No effective context
creation needed here.

int libssh2_dh_key_pair(_libssh2_dh_ctx *dhctx, _libssh2_bn *public,
_libssh2_bn *g, _libssh2_bn *p, int group_order,
_libssh2_bn_ctx *bnctx);
Generates a Diffie-Hellman key pair using base `g', prime `p' and the given
`group_order'. Can use the given big number context `bnctx' if needed.
The private key is stored as opaque in the Diffie-Hellman context `*dhctx' and
the public key is returned in `public'.
0 is returned upon success, else -1.

int libssh2_dh_secret(_libssh2_dh_ctx *dhctx, _libssh2_bn *secret,
_libssh2_bn *f, _libssh2_bn *p, _libssh2_bn_ctx * bnctx)
Computes the Diffie-Hellman secret from the previously created context `*dhctx',
the public key `f' from the other party and the same prime `p' used at
context creation. The result is stored in `secret'.
0 is returned upon success, else -1.

void libssh2_dh_dtor(_libssh2_dh_ctx *dhctx)
Destroys Diffie-Hellman context at `dhctx' and resets its storage.


6) Big numbers.
Positive multi-byte integers support is sufficient.

5.1) Computation contexts.
6.1) Computation contexts.
This has a real meaning if the big numbers computations need some context
storage. If not, use a dummy type and functions (macros).

_libssh2_bn_ctx
Type of multiple precision computation context. May not be empty. if not used,
#define as char, for example.

libssh2_bn_ctx _libssh2_bn_ctx_new(void);
_libssh2_bn_ctx _libssh2_bn_ctx_new(void);
Returns a new multiple precision computation context.

void _libssh2_bn_ctx_free(_libssh2_bn_ctx ctx);
Releases a multiple precision computation context.

5.2) Computation support.
6.2) Computation support.
_libssh2_bn
Type of multiple precision numbers (aka bignumbers or huge integers) for the
crypto library.
Expand All @@ -339,7 +399,7 @@ allocates the number. Returns a value of type _libssh2_bn *.
void _libssh2_bn_free(_libssh2_bn *bn);
Destroys the multiple precision number at bn.

unsigned long _libssh2_bn_bytes(libssh2_bn *bn);
unsigned long _libssh2_bn_bytes(_libssh2_bn *bn);
Get the number of bytes needed to store the bits of the multiple precision
number at bn.

Expand All @@ -362,22 +422,8 @@ Converts the absolute value of bn into big-endian form and store it at
val. val must point to _libssh2_bn_bytes(bn) bytes of memory.
Returns the length of the big-endian number.

void _libssh2_bn_rand(_libssh2_bn *bn, int bits, int top, int bottom);
Generates a cryptographically strong pseudo-random number of bits in
length and stores it in bn. If top is -1, the most significant bit of the
random number can be zero. If top is 0, it is set to 1, and if top is 1, the
two most significant bits of the number will be set to 1, so that the product
of two such random numbers will always have 2*bits length. If bottom is true,
the number will be odd.

void _libssh2_bn_mod_exp(_libssh2_bn *r, _libssh2_bn *a,
_libssh2_bn *p, _libssh2_bn *m,
_libssh2_bn_ctx *ctx);
Computes a to the p-th power modulo m and stores the result into r (r=a^p % m).
May use the given context.


6) Private key algorithms.
7) Private key algorithms.
Format of an RSA public key:
a) "ssh-rsa".
b) RSA exponent, MSB first, with high order bit = 0.
Expand Down Expand Up @@ -421,7 +467,7 @@ Both buffers have to be allocated using LIBSSH2_ALLOC().
Returns 0 if OK, else -1.
This procedure is already prototyped in crypto.h.

6.1) RSA
7.1) RSA
LIBSSH2_RSA
#define as 1 if the crypto library supports RSA, else 0.
If defined as 0, the rest of this section can be omitted.
Expand Down Expand Up @@ -515,7 +561,7 @@ void _libssh2_rsa_free(libssh2_rsa_ctx *rsactx);
Releases the RSA computation context at rsactx.


6.2) DSA
7.2) DSA
LIBSSH2_DSA
#define as 1 if the crypto library supports DSA, else 0.
If defined as 0, the rest of this section can be omitted.
Expand Down Expand Up @@ -565,7 +611,7 @@ This procedure is already prototyped in crypto.h.
int _libssh2_dsa_sha1_verify(libssh2_dsa_ctx *dsactx,
const unsigned char *sig,
const unsigned char *m, unsigned long m_len);
Verify (sig, siglen) signature of (m, m_len) using an SHA1 hash and the
Verify (sig, siglen) signature of (m, m_len) using an SHA-1 hash and the
DSA context.
Returns 0 if OK, else -1.
This procedure is already prototyped in crypto.h.
Expand All @@ -581,7 +627,7 @@ void _libssh2_dsa_free(libssh2_dsa_ctx *dsactx);
Releases the DSA computation context at dsactx.


7) Miscellaneous
8) Miscellaneous

void libssh2_prepare_iovec(struct iovec *vector, unsigned int len);
Prepare len consecutive iovec slots before using them.
Expand Down
16 changes: 16 additions & 0 deletions docs/INSTALL_AUTOTOOLS
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@ Software Foundation, Inc.
This file is free documentation; the Free Software Foundation gives
unlimited permission to copy, distribute and modify it.

When Building directly from Master
==================================

If you want to build directly from the git repository, you must first
generate the configure script and Makefile using autotools. There is
a convenience script that calls all tools in the correct order. Make
sure that autoconf, automake and libtool are installed on your system,
then execute the following script:

./buildconf

After executing this script, you can build the project as usual:

./configure
make

Basic Installation
==================

Expand Down
2 changes: 1 addition & 1 deletion docs/INSTALL_CMAKE
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,4 @@ builds your project:
[1] https://www.cmake.org/cmake/resources/software.html
[2] https://www.cmake.org/cmake/help/v3.0/manual/cmake-packages.7.html
[3] https://www.cmake.org/cmake/help/v3.0/manual/cmake-packages.7.html#package-registry
[4] http://www.kitware.com/media/html/BuildingExternalProjectsWithCMake2.8.html
[4] https://blog.kitware.com/wp-content/uploads/2016/01/kitware_quarterly1009.pdf
2 changes: 2 additions & 0 deletions docs/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ dist_man_MANS = \
libssh2_agent_disconnect.3 \
libssh2_agent_free.3 \
libssh2_agent_get_identity.3 \
libssh2_agent_get_identity_path.3 \
libssh2_agent_init.3 \
libssh2_agent_list_identities.3 \
libssh2_agent_set_identity_path.3 \
libssh2_agent_userauth.3 \
libssh2_banner_set.3 \
libssh2_base64_decode.3 \
Expand Down
4 changes: 2 additions & 2 deletions docs/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ announcement.
[distros@openwall](http://oss-security.openwall.org/wiki/mailing-lists/distros)
when also informing and preparing them for the upcoming public security
vulnerability announcement - attach the advisory draft for information. Note
that 'distros' won't accept an embargo longer than 19 days.
that 'distros' won't accept an embargo longer than 14 days.

- Update the "security advisory" with the CVE number.

Expand Down Expand Up @@ -96,5 +96,5 @@ libssh2 project and you have shown an understanding for the project and its way
of working. You must've been around for a good while and you should have no
plans in vanishing in the near future.

We do not make the list of partipants public mostly because it tends to vary
We do not make the list of participants public mostly because it tends to vary
somewhat over time and a list somewhere will only risk getting outdated.
22 changes: 22 additions & 0 deletions docs/libssh2_agent_get_identity_path.3
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.\"
.\" Copyright (c) 2019 by Will Cosgrove
.\"
.TH libssh2_agent_get_identity_path 3 "6 Mar 2019" "libssh2 1.9" "libssh2 manual"
.SH NAME
libssh2_agent_get_identity_path - gets the custom ssh-agent socket path
.SH SYNOPSIS
#include <libssh2.h>

const char *
libssh2_agent_get_identity_path(LIBSSH2_AGENT *agent);
.SH DESCRIPTION
Returns the custom agent identity socket path if set using libssh2_agent_set_identity_path()

.SH RETURN VALUE
Returns the socket path on disk.
.SH AVAILABILITY
Added in libssh2 1.9
.SH SEE ALSO
.BR libssh2_agent_init(3)
.BR libssh2_agent_set_identity_path(3)

22 changes: 22 additions & 0 deletions docs/libssh2_agent_set_identity_path.3
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.\"
.\" Copyright (c) 2019 by Will Cosgrove
.\"
.TH libssh2_agent_set_identity_path 3 "6 Mar 2019" "libssh2 1.9" "libssh2 manual"
.SH NAME
libssh2_agent_set_identity_path - set an ssh-agent socket path on disk
.SH SYNOPSIS
#include <libssh2.h>

void
libssh2_agent_set_identity_path(LIBSSH2_AGENT *agent, const char *path);
.SH DESCRIPTION
Allows a custom agent identity socket path instead of the default SSH_AUTH_SOCK env value

.SH RETURN VALUE
Returns void
.SH AVAILABILITY
Added in libssh2 1.9
.SH SEE ALSO
.BR libssh2_agent_init(3)
.BR libssh2_agent_get_identity_path(3)

2 changes: 1 addition & 1 deletion docs/libssh2_channel_wait_eof.3
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ int
libssh2_channel_wait_eof(LIBSSH2_CHANNEL *channel);

.SH DESCRIPTION
Wait for the remote end to acknowledge an EOF request.
Wait for the remote end to send EOF.

.SH RETURN VALUE
Return 0 on success or negative on failure. It returns
Expand Down
6 changes: 3 additions & 3 deletions docs/libssh2_hostkey_hash.3
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ libssh2_hostkey_hash(LIBSSH2_SESSION *session, int hash_type);
\fIsession\fP - Session instance as returned by
.BR libssh2_session_init_ex(3)

\fIhash_type\fP - One of: \fBLIBSSH2_HOSTKEY_HASH_MD5\fP or
\fBLIBSSH2_HOSTKEY_HASH_SHA1\fP.
\fIhash_type\fP - One of: \fBLIBSSH2_HOSTKEY_HASH_MD5\fP,
\fBLIBSSH2_HOSTKEY_HASH_SHA1\fP or \fBLIBSSH2_HOSTKEY_HASH_SHA256\fP.

Returns the computed digest of the remote system's hostkey. The length of
the returned string is hash_type specific (e.g. 16 bytes for MD5,
20 bytes for SHA1).
20 bytes for SHA1, 32 bytes for SHA256).
.SH RETURN VALUE
Computed hostkey hash value, or NULL if the information is not available
(either the session has not yet been started up, or the requested hash
Expand Down
10 changes: 5 additions & 5 deletions docs/libssh2_session_supported_algs.3
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ int libssh2_session_supported_algs(LIBSSH2_SESSION* session,
const char*** algs);
.SH DESCRIPTION
\fIsession\fP - An instance of initialized LIBSSH2_SESSION (the function will
use its pointer to the memory allocation function). \fImethod_type\fP - Method
type. See .BR \fIlibssh2_session_method_pref(3)\fP. \fIalgs\fP - Address of a
pointer that will point to an array of returned algorithms
use its pointer to the memory allocation function). \fImethod_type\fP -
Method type. See \fIlibssh2_session_method_pref(3)\fP. \fIalgs\fP - Address
of a pointer that will point to an array of returned algorithms

Get a list of supported algorithms for the given \fImethod_type\fP. The
method_type parameter is equivalent to method_type in
Expand Down Expand Up @@ -44,9 +44,9 @@ rc = libssh2_session_supported_algs(session,
if (rc>0) {
/* the call succeeded, do sth. with the list of algorithms
(e.g. list them)... */
printf("Supported symmetric algorithms:\n");
printf("Supported symmetric algorithms:\\n");
for ( i=0; i<rc; i++ )
printf("\t%s\n", algorithms[i]);
printf("\\t%s\\n", algorithms[i]);

/* ... and free the allocated memory when not needed anymore */
libssh2_free(session, algorithms);
Expand Down
108 changes: 57 additions & 51 deletions example/direct_tcpip.c
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
Expand All @@ -82,49 +82,50 @@ int main(int argc, char *argv[])
int listensock = -1, forwardsock = -1;
#endif

if (argc > 1)
if(argc > 1)
server_ip = argv[1];
if (argc > 2)
if(argc > 2)
username = argv[2];
if (argc > 3)
if(argc > 3)
password = argv[3];
if (argc > 4)
if(argc > 4)
local_listenip = argv[4];
if (argc > 5)
if(argc > 5)
local_listenport = atoi(argv[5]);
if (argc > 6)
if(argc > 6)
remote_desthost = argv[6];
if (argc > 7)
if(argc > 7)
remote_destport = atoi(argv[7]);

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

/* Connect to SSH server */
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
#ifdef WIN32
if (sock == INVALID_SOCKET) {
if(sock == INVALID_SOCKET) {
fprintf(stderr, "failed to open socket!\n");
return -1;
}
#else
if (sock == -1) {
if(sock == -1) {
perror("socket");
return -1;
}
#endif

sin.sin_family = AF_INET;
if (INADDR_NONE == (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) {
perror("inet_addr");
return -1;
}
sin.sin_port = htons(22);
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
Expand Down Expand Up @@ -159,63 +160,67 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist);
if (strstr(userauthlist, "password"))
if(strstr(userauthlist, "password"))
auth |= AUTH_PASSWORD;
if (strstr(userauthlist, "publickey"))
if(strstr(userauthlist, "publickey"))
auth |= AUTH_PUBLICKEY;

/* check for options */
if(argc > 8) {
if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[8], "-p"))
if((auth & AUTH_PASSWORD) && !strcasecmp(argv[8], "-p"))
auth = AUTH_PASSWORD;
if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[8], "-k"))
if((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[8], "-k"))
auth = AUTH_PUBLICKEY;
}

if (auth & AUTH_PASSWORD) {
if (libssh2_userauth_password(session, username, password)) {
if(auth & AUTH_PASSWORD) {
if(libssh2_userauth_password(session, username, password)) {
fprintf(stderr, "Authentication by password failed.\n");
goto shutdown;
}
} else if (auth & AUTH_PUBLICKEY) {
if (libssh2_userauth_publickey_fromfile(session, username, keyfile1,
keyfile2, password)) {
}
else if(auth & AUTH_PUBLICKEY) {
if(libssh2_userauth_publickey_fromfile(session, username, keyfile1,
keyfile2, password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown;
}
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
} else {
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
}

listensock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
#ifdef WIN32
if (listensock == INVALID_SOCKET) {
if(listensock == INVALID_SOCKET) {
fprintf(stderr, "failed to open listen socket!\n");
return -1;
}
#else
if (listensock == -1) {
if(listensock == -1) {
perror("socket");
return -1;
}
#endif

sin.sin_family = AF_INET;
sin.sin_port = htons(local_listenport);
if (INADDR_NONE == (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) {
perror("inet_addr");
goto shutdown;
}
sockopt = 1;
setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt));
sinlen=sizeof(sin);
if (-1 == bind(listensock, (struct sockaddr *)&sin, sinlen)) {
setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &sockopt,
sizeof(sockopt));
sinlen = sizeof(sin);
if(-1 == bind(listensock, (struct sockaddr *)&sin, sinlen)) {
perror("bind");
goto shutdown;
}
if (-1 == listen(listensock, 2)) {
if(-1 == listen(listensock, 2)) {
perror("listen");
goto shutdown;
}
Expand All @@ -225,12 +230,12 @@ int main(int argc, char *argv[])

forwardsock = accept(listensock, (struct sockaddr *)&sin, &sinlen);
#ifdef WIN32
if (forwardsock == INVALID_SOCKET) {
if(forwardsock == INVALID_SOCKET) {
fprintf(stderr, "failed to accept forward socket!\n");
goto shutdown;
}
#else
if (forwardsock == -1) {
if(forwardsock == -1) {
perror("accept");
goto shutdown;
}
Expand All @@ -244,7 +249,7 @@ int main(int argc, char *argv[])

channel = libssh2_channel_direct_tcpip_ex(session, remote_desthost,
remote_destport, shost, sport);
if (!channel) {
if(!channel) {
fprintf(stderr, "Could not open the direct-tcpip channel!\n"
"(Note that this can be a problem at the server!"
" Please review the server logs.)\n");
Expand All @@ -254,57 +259,58 @@ int main(int argc, char *argv[])
/* Must use non-blocking IO hereafter due to the current libssh2 API */
libssh2_session_set_blocking(session, 0);

while (1) {
while(1) {
FD_ZERO(&fds);
FD_SET(forwardsock, &fds);
tv.tv_sec = 0;
tv.tv_usec = 100000;
rc = select(forwardsock + 1, &fds, NULL, NULL, &tv);
if (-1 == rc) {
if(-1 == rc) {
perror("select");
goto shutdown;
}
if (rc && FD_ISSET(forwardsock, &fds)) {
if(rc && FD_ISSET(forwardsock, &fds)) {
len = recv(forwardsock, buf, sizeof(buf), 0);
if (len < 0) {
if(len < 0) {
perror("read");
goto shutdown;
} else if (0 == len) {
}
else if(0 == len) {
fprintf(stderr, "The client at %s:%d disconnected!\n", shost,
sport);
goto shutdown;
}
wr = 0;
while(wr < len) {
i = libssh2_channel_write(channel, buf + wr, len - wr);
if (LIBSSH2_ERROR_EAGAIN == i) {
if(LIBSSH2_ERROR_EAGAIN == i) {
continue;
}
if (i < 0) {
if(i < 0) {
fprintf(stderr, "libssh2_channel_write: %d\n", i);
goto shutdown;
}
wr += i;
}
}
while (1) {
while(1) {
len = libssh2_channel_read(channel, buf, sizeof(buf));
if (LIBSSH2_ERROR_EAGAIN == len)
if(LIBSSH2_ERROR_EAGAIN == len)
break;
else if (len < 0) {
else if(len < 0) {
fprintf(stderr, "libssh2_channel_read: %d", (int)len);
goto shutdown;
}
wr = 0;
while (wr < len) {
while(wr < len) {
i = send(forwardsock, buf + wr, len - wr, 0);
if (i <= 0) {
if(i <= 0) {
perror("write");
goto shutdown;
}
wr += i;
}
if (libssh2_channel_eof(channel)) {
if(libssh2_channel_eof(channel)) {
fprintf(stderr, "The server at %s:%d disconnected!\n",
remote_desthost, remote_destport);
goto shutdown;
Expand All @@ -320,7 +326,7 @@ int main(int argc, char *argv[])
close(forwardsock);
close(listensock);
#endif
if (channel)
if(channel)
libssh2_channel_free(channel);
libssh2_session_disconnect(session, "Client disconnecting normally");
libssh2_session_free(session);
Expand Down
54 changes: 29 additions & 25 deletions example/scp.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ int main(int argc, char *argv[])
const char *fingerprint;
LIBSSH2_SESSION *session;
LIBSSH2_CHANNEL *channel;
const char *username="username";
const char *password="password";
const char *scppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *scppath = "/tmp/TEST";
libssh2_struct_stat fileinfo;
int rc;
libssh2_struct_stat_size got = 0;
Expand All @@ -49,31 +49,32 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}
if (argc > 2) {
if(argc > 2) {
username = argv[2];
}
if (argc > 3) {
if(argc > 3) {
password = argv[3];
}
if (argc > 4) {
if(argc > 4) {
scppath = argv[4];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

Expand All @@ -86,8 +87,8 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
Expand Down Expand Up @@ -119,18 +120,20 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* 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");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) {
#define HOME_DIR "/home/username/"
if(libssh2_userauth_publickey_fromfile(session, username,
HOME_DIR ".ssh/id_rsa.pub",
HOME_DIR ".ssh/id_rsa",
password)) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -139,7 +142,7 @@ int main(int argc, char *argv[])
/* Request a file via SCP */
channel = libssh2_scp_recv2(session, scppath, &fileinfo);

if (!channel) {
if(!channel) {
fprintf(stderr, "Unable to open a session: %d\n",
libssh2_session_last_errno(session));
goto shutdown;
Expand All @@ -148,7 +151,7 @@ int main(int argc, char *argv[])

while(got < fileinfo.st_size) {
char mem[1024];
int amount=sizeof(mem);
int amount = sizeof(mem);

if((fileinfo.st_size -got) < amount) {
amount = (int)(fileinfo.st_size -got);
Expand All @@ -170,7 +173,8 @@ int main(int argc, char *argv[])

shutdown:

libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
libssh2_session_disconnect(session,
"Normal Shutdown, Thank you for playing");
libssh2_session_free(session);

#ifdef WIN32
Expand Down
85 changes: 44 additions & 41 deletions example/scp_nonblock.c
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ int main(int argc, char *argv[])
const char *fingerprint;
LIBSSH2_SESSION *session;
LIBSSH2_CHANNEL *channel;
const char *username="username";
const char *password="password";
const char *scppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *scppath = "/tmp/TEST";
libssh2_struct_stat fileinfo;
#ifdef HAVE_GETTIMEOFDAY
struct timeval start;
Expand All @@ -103,31 +103,32 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}
if (argc > 2) {
if(argc > 2) {
username = argv[2];
}
if (argc > 3) {
if(argc > 3) {
password = argv[3];
}
if (argc > 4) {
if(argc > 4) {
scppath = argv[4];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

Expand All @@ -140,14 +141,14 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
fprintf(stderr, "failed to connect!\n");
return -1;
}

/* Create a session instance */
session = libssh2_session_init();
if (!session)
if(!session)
return -1;

/* Since we have set non-blocking, tell libssh2 we are non-blocking */
Expand All @@ -160,9 +161,9 @@ int main(int argc, char *argv[])
/* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers
*/
while ((rc = libssh2_session_handshake(session, sock)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
while((rc = libssh2_session_handshake(session, sock)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1;
}
Expand All @@ -179,24 +180,25 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* We could authenticate via password */
while ((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "Authentication by password failed.\n");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
while ((rc = libssh2_userauth_publickey_fromfile(session, username,
"/home/username/"
".ssh/id_rsa.pub",
"/home/username/"
".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
while((rc = libssh2_userauth_publickey_fromfile(session, username,
"/home/username/"
".ssh/id_rsa.pub",
"/home/username/"
".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -211,7 +213,7 @@ int main(int argc, char *argv[])
do {
channel = libssh2_scp_recv2(session, scppath, &fileinfo);

if (!channel) {
if(!channel) {
if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
char *err_msg;

Expand All @@ -224,30 +226,30 @@ int main(int argc, char *argv[])
waitsocket(sock, session);
}
}
} while (!channel);
} while(!channel);
fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n");

while(got < fileinfo.st_size) {
char mem[1024*24];
int rc;

do {
int amount=sizeof(mem);
int amount = sizeof(mem);

if ((fileinfo.st_size -got) < amount) {
if((fileinfo.st_size -got) < amount) {
amount = (int)(fileinfo.st_size - got);
}

/* loop until we block */
rc = libssh2_channel_read(channel, mem, amount);
if (rc > 0) {
if(rc > 0) {
write(1, mem, rc);
got += rc;
total += rc;
}
} while (rc > 0);
} while(rc > 0);

if ((rc == LIBSSH2_ERROR_EAGAIN) && (got < fileinfo.st_size)) {
if((rc == LIBSSH2_ERROR_EAGAIN) && (got < fileinfo.st_size)) {
/* this is due to blocking that would occur otherwise
so we loop on this condition */

Expand All @@ -262,10 +264,11 @@ int main(int argc, char *argv[])
gettimeofday(&end, NULL);

time_ms = tvdiff(end, start);
fprintf(stderr, "Got " LIBSSH2_STRUCT_STAT_SIZE_FORMAT " bytes in %ld ms = %.1f bytes/sec spin: %d\n", total,
time_ms, total/(time_ms/1000.0), spin);
fprintf(stderr, "Got %ld bytes in %ld ms = %.1f bytes/sec spin: %d\n",
(long)total,
time_ms, total/(time_ms/1000.0), spin);
#else
fprintf(stderr, "Got " LIBSSH2_STRUCT_STAT_SIZE_FORMAT " bytes spin: %d\n", total, spin);
fprintf(stderr, "Got %ld bytes spin: %d\n", (long)total, spin);
#endif

libssh2_channel_free(channel);
Expand Down
65 changes: 34 additions & 31 deletions example/scp_write.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ int main(int argc, char *argv[])
const char *fingerprint;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel;
const char *username="username";
const char *password="password";
const char *loclfile="scp_write.c";
const char *scppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *loclfile = "scp_write.c";
const char *scppath = "/tmp/TEST";
FILE *local;
int rc;
char mem[1024];
Expand All @@ -53,39 +53,40 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}
if (argc > 2) {
if(argc > 2) {
username = argv[2];
}
if (argc > 3) {
if(argc > 3) {
password = argv[3];
}
if(argc > 4) {
loclfile = argv[4];
}
if (argc > 5) {
if(argc > 5) {
scppath = argv[5];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

local = fopen(loclfile, "rb");
if (!local) {
if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1;
}
Expand All @@ -105,8 +106,8 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
Expand Down Expand Up @@ -138,18 +139,20 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* 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");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) {
#define HOME "/home/username/"
if(libssh2_userauth_publickey_fromfile(session, username,
HOME ".ssh/id_rsa.pub",
HOME ".ssh/id_rsa",
password)) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -159,7 +162,7 @@ int main(int argc, char *argv[])
channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777,
(unsigned long)fileinfo.st_size);

if (!channel) {
if(!channel) {
char *errmsg;
int errlen;
int err = libssh2_session_last_error(session, &errmsg, &errlen, 0);
Expand All @@ -170,7 +173,7 @@ int main(int argc, char *argv[])
fprintf(stderr, "SCP session waiting to send file\n");
do {
nread = fread(mem, 1, sizeof(mem), local);
if (nread <= 0) {
if(nread <= 0) {
/* end of file */
break;
}
Expand All @@ -179,7 +182,7 @@ int main(int argc, char *argv[])
do {
/* write the same data over and over, until error or completion */
rc = libssh2_channel_write(channel, ptr, nread);
if (rc < 0) {
if(rc < 0) {
fprintf(stderr, "ERROR %d\n", rc);
break;
}
Expand All @@ -188,9 +191,9 @@ int main(int argc, char *argv[])
ptr += rc;
nread -= rc;
}
} while (nread);
} while(nread);

} while (1);
} while(1);

fprintf(stderr, "Sending EOF\n");
libssh2_channel_send_eof(channel);
Expand All @@ -207,15 +210,15 @@ int main(int argc, char *argv[])
shutdown:

if(session) {
libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);
}
#ifdef WIN32
closesocket(sock);
#else
close(sock);
#endif
if (local)
if(local)
fclose(local);
fprintf(stderr, "all done\n");

Expand Down
92 changes: 48 additions & 44 deletions example/scp_write_nonblock.c
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ int main(int argc, char *argv[])
const char *fingerprint;
LIBSSH2_SESSION *session = NULL;
LIBSSH2_CHANNEL *channel;
const char *username="username";
const char *password="password";
const char *loclfile="scp_write.c";
const char *scppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *loclfile = "scp_write.c";
const char *scppath = "/tmp/TEST";
FILE *local;
int rc;
char mem[1024*100];
Expand All @@ -92,39 +92,40 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}
if (argc > 2) {
if(argc > 2) {
username = argv[2];
}
if (argc > 3) {
if(argc > 3) {
password = argv[3];
}
if(argc > 4) {
loclfile = argv[4];
}
if (argc > 5) {
if(argc > 5) {
scppath = argv[5];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

local = fopen(loclfile, "rb");
if (!local) {
if(!local) {
fprintf(stderr, "Can't local file %s\n", loclfile);
return -1;
}
Expand All @@ -140,8 +141,8 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
Expand All @@ -158,8 +159,8 @@ int main(int argc, char *argv[])
/* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers
*/
while ((rc = libssh2_session_handshake(session, sock))
== LIBSSH2_ERROR_EAGAIN);
while((rc = libssh2_session_handshake(session, sock))
== LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1;
Expand All @@ -177,21 +178,24 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* We could authenticate via password */
while ((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
while((rc = libssh2_userauth_password(session, username, password)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "Authentication by password failed.\n");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
while ((rc = libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) == LIBSSH2_ERROR_EAGAIN);
if (rc) {
#define HOME "/home/username/"
while((rc = libssh2_userauth_publickey_fromfile(session, username,
HOME ".ssh/id_rsa.pub",
HOME ".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -202,21 +206,21 @@ int main(int argc, char *argv[])
channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777,
(unsigned long)fileinfo.st_size);

if ((!channel) && (libssh2_session_last_errno(session) !=
LIBSSH2_ERROR_EAGAIN)) {
if((!channel) && (libssh2_session_last_errno(session) !=
LIBSSH2_ERROR_EAGAIN)) {
char *err_msg;

libssh2_session_last_error(session, &err_msg, NULL, 0);
fprintf(stderr, "%s\n", err_msg);
goto shutdown;
}
} while (!channel);
} while(!channel);

fprintf(stderr, "SCP session waiting to send file\n");
start = time(NULL);
do {
nread = fread(mem, 1, sizeof(mem), local);
if (nread <= 0) {
if(nread <= 0) {
/* end of file */
break;
}
Expand All @@ -226,12 +230,12 @@ int main(int argc, char *argv[])

prev = 0;
do {
while ((rc = libssh2_channel_write(channel, ptr, nread)) ==
LIBSSH2_ERROR_EAGAIN) {
while((rc = libssh2_channel_write(channel, ptr, nread)) ==
LIBSSH2_ERROR_EAGAIN) {
waitsocket(sock, session);
prev = 0;
}
if (rc < 0) {
if(rc < 0) {
fprintf(stderr, "ERROR %d total %ld / %d prev %d\n", rc,
total, (int)nread, (int)prev);
break;
Expand All @@ -243,31 +247,31 @@ int main(int argc, char *argv[])
nread -= rc;
ptr += rc;
}
} while (nread);
} while (!nread); /* only continue if nread was drained */
} while(nread);
} while(!nread); /* only continue if nread was drained */

duration = (int)(time(NULL)-start);

fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n",
total, duration, total/(double)duration);

fprintf(stderr, "Sending EOF\n");
while (libssh2_channel_send_eof(channel) == LIBSSH2_ERROR_EAGAIN);
while(libssh2_channel_send_eof(channel) == LIBSSH2_ERROR_EAGAIN);

fprintf(stderr, "Waiting for EOF\n");
while (libssh2_channel_wait_eof(channel) == LIBSSH2_ERROR_EAGAIN);
while(libssh2_channel_wait_eof(channel) == LIBSSH2_ERROR_EAGAIN);

fprintf(stderr, "Waiting for channel to close\n");
while (libssh2_channel_wait_closed(channel) == LIBSSH2_ERROR_EAGAIN);
while(libssh2_channel_wait_closed(channel) == LIBSSH2_ERROR_EAGAIN);

libssh2_channel_free(channel);
channel = NULL;

shutdown:

while (libssh2_session_disconnect(session,
"Normal Shutdown, Thank you for playing") ==
LIBSSH2_ERROR_EAGAIN);
while(libssh2_session_disconnect(session,
"Normal Shutdown,") ==
LIBSSH2_ERROR_EAGAIN);
libssh2_session_free(session);

#ifdef WIN32
Expand Down
98 changes: 54 additions & 44 deletions example/sftp.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,19 @@
#include <ctype.h>


const char *keyfile1="~/.ssh/id_rsa.pub";
const char *keyfile2="~/.ssh/id_rsa";
const char *username="username";
const char *password="password";
const char *sftppath="/tmp/TEST";


static void kbd_callback(const char *name, int name_len,
const char *instruction, int instruction_len, int num_prompts,
const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
void **abstract)
const char *keyfile1 = "~/.ssh/id_rsa.pub";
const char *keyfile2 = "~/.ssh/id_rsa";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/TEST";


static void kbd_callback(const char *name, int name_len,
const char *instruction, int instruction_len,
int num_prompts,
const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
void **abstract)
{
int i;
size_t n;
Expand All @@ -67,15 +68,15 @@ static void kbd_callback(const char *name, int name_len,

fprintf(stderr, "Number of prompts: %d\n\n", num_prompts);

for (i = 0; i < num_prompts; i++) {
for(i = 0; i < num_prompts; i++) {
fprintf(stderr, "Prompt %d from server: '", i);
fwrite(prompts[i].text, 1, prompts[i].length, stderr);
fprintf(stderr, "'\n");

fprintf(stderr, "Please type response: ");
fgets(buf, sizeof(buf), stdin);
n = strlen(buf);
while (n > 0 && strchr("\r\n", buf[n - 1]))
while(n > 0 && strchr("\r\n", buf[n - 1]))
n--;
buf[n] = 0;

Expand Down Expand Up @@ -108,16 +109,17 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}

Expand All @@ -131,8 +133,8 @@ int main(int argc, char *argv[])
sftppath = argv[4];
}

rc = libssh2_init (0);
if (rc != 0) {
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}
Expand All @@ -146,8 +148,8 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
Expand Down Expand Up @@ -185,62 +187,69 @@ int main(int argc, char *argv[])
/* check what authentication methods are available */
userauthlist = libssh2_userauth_list(session, username, strlen(username));
fprintf(stderr, "Authentication methods: %s\n", userauthlist);
if (strstr(userauthlist, "password") != NULL) {
if(strstr(userauthlist, "password") != NULL) {
auth_pw |= 1;
}
if (strstr(userauthlist, "keyboard-interactive") != NULL) {
if(strstr(userauthlist, "keyboard-interactive") != NULL) {
auth_pw |= 2;
}
if (strstr(userauthlist, "publickey") != NULL) {
if(strstr(userauthlist, "publickey") != NULL) {
auth_pw |= 4;
}

/* if we got an 4. argument we set this option if supported */
/* if we got an 4. argument we set this option if supported */
if(argc > 5) {
if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) {
if((auth_pw & 1) && !strcasecmp(argv[5], "-p")) {
auth_pw = 1;
}
if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) {
if((auth_pw & 2) && !strcasecmp(argv[5], "-i")) {
auth_pw = 2;
}
if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) {
if((auth_pw & 4) && !strcasecmp(argv[5], "-k")) {
auth_pw = 4;
}
}

if (auth_pw & 1) {
if(auth_pw & 1) {
/* 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");
goto shutdown;
}
} else if (auth_pw & 2) {
}
else if(auth_pw & 2) {
/* Or via keyboard-interactive */
if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) {
if(libssh2_userauth_keyboard_interactive(session, username,
&kbd_callback) ) {
fprintf(stderr,
"\tAuthentication by keyboard-interactive failed!\n");
goto shutdown;
} else {
}
else {
fprintf(stderr,
"\tAuthentication by keyboard-interactive succeeded.\n");
}
} else if (auth_pw & 4) {
}
else if(auth_pw & 4) {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) {
if(libssh2_userauth_publickey_fromfile(session, username, keyfile1,
keyfile2, password)) {
fprintf(stderr, "\tAuthentication by public key failed!\n");
goto shutdown;
} else {
}
else {
fprintf(stderr, "\tAuthentication by public key succeeded.\n");
}
} else {
}
else {
fprintf(stderr, "No supported authentication methods found!\n");
goto shutdown;
}

fprintf(stderr, "libssh2_sftp_init()!\n");
sftp_session = libssh2_sftp_init(session);

if (!sftp_session) {
if(!sftp_session) {
fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown;
}
Expand All @@ -250,7 +259,7 @@ int main(int argc, char *argv[])
sftp_handle =
libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0);

if (!sftp_handle) {
if(!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP: %ld\n",
libssh2_sftp_last_error(sftp_session));
goto shutdown;
Expand All @@ -262,19 +271,20 @@ int main(int argc, char *argv[])
/* loop until we fail */
fprintf(stderr, "libssh2_sftp_read()!\n");
rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem));
if (rc > 0) {
if(rc > 0) {
write(1, mem, rc);
} else {
}
else {
break;
}
} while (1);
} while(1);

libssh2_sftp_close(sftp_handle);
libssh2_sftp_shutdown(sftp_session);

shutdown:

libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);

#ifdef WIN32
Expand Down
78 changes: 41 additions & 37 deletions example/sftp_RW_nonblock.c
Original file line number Diff line number Diff line change
Expand Up @@ -79,32 +79,33 @@ int main(int argc, char *argv[])
struct sockaddr_in sin;
const char *fingerprint;
LIBSSH2_SESSION *session;
const char *username="username";
const char *password="password";
const char *sftppath="/tmp/TEST"; /* source path */
const char *dest="/tmp/TEST2"; /* destination path */
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/TEST"; /* source path */
const char *dest = "/tmp/TEST2"; /* destination path */
int rc;
LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle;
FILE *tempstorage;
char mem[1000];
struct timeval timeout;
fd_set fd;
fd_set fd2;

#ifdef WIN32
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

Expand All @@ -117,7 +118,7 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = htonl(0x7F000001);
if (connect(sock, (struct sockaddr*)(&sin),
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
Expand Down Expand Up @@ -171,25 +172,26 @@ int main(int argc, char *argv[])
goto shutdown;
}

if (auth_pw) {
if(auth_pw) {
/* We could authenticate via password */
while ((rc = libssh2_userauth_password(session, username, password))
while((rc = libssh2_userauth_password(session, username, password))
== LIBSSH2_ERROR_EAGAIN);
if (rc) {
if(rc) {
fprintf(stderr, "Authentication by password failed.\n");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
while ((rc =
libssh2_userauth_publickey_fromfile(session, username,
"/home/username/"
".ssh/id_rsa.pub",
"/home/username/"
".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
while((rc =
libssh2_userauth_publickey_fromfile(session, username,
"/home/username/"
".ssh/id_rsa.pub",
"/home/username/"
".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -209,15 +211,15 @@ int main(int argc, char *argv[])
goto shutdown;
}
}
} while (!sftp_session);
} while(!sftp_session);

/* Request a file via SFTP */
do {
sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
LIBSSH2_FXF_READ, 0);

if (!sftp_handle) {
if (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
if(!sftp_handle) {
if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open file with SFTP\n");
goto shutdown;
}
Expand All @@ -226,7 +228,7 @@ int main(int argc, char *argv[])
waitsocket(sock, session); /* now we wait */
}
}
} while (!sftp_handle);
} while(!sftp_handle);

fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n");
do {
Expand All @@ -242,7 +244,7 @@ int main(int argc, char *argv[])
/* write to temporary storage area */
fwrite(mem, rc, 1, tempstorage);
}
} while (rc > 0);
} while(rc > 0);

if(rc != LIBSSH2_ERROR_EAGAIN) {
/* error or end of file */
Expand All @@ -253,19 +255,20 @@ int main(int argc, char *argv[])
timeout.tv_usec = 0;

FD_ZERO(&fd);

FD_ZERO(&fd2);
FD_SET(sock, &fd);
FD_SET(sock, &fd2);

/* wait for readable or writeable */
rc = select(sock+1, &fd, &fd, NULL, &timeout);
rc = select(sock + 1, &fd, &fd2, NULL, &timeout);
if(rc <= 0) {
/* negative is error
0 is timeout */
fprintf(stderr, "SFTP download timed out: %d\n", rc);
break;
}

} while (1);
} while(1);

libssh2_sftp_close(sftp_handle);
fclose(tempstorage);
Expand Down Expand Up @@ -301,7 +304,7 @@ int main(int argc, char *argv[])
nread);
ptr += rc;
nread -= nread;
} while (rc >= 0);
} while(rc >= 0);

if(rc != LIBSSH2_ERROR_EAGAIN) {
/* error or end of file */
Expand All @@ -312,19 +315,20 @@ int main(int argc, char *argv[])
timeout.tv_usec = 0;

FD_ZERO(&fd);

FD_ZERO(&fd2);
FD_SET(sock, &fd);
FD_SET(sock, &fd2);

/* wait for readable or writeable */
rc = select(sock+1, &fd, &fd, NULL, &timeout);
rc = select(sock + 1, &fd, &fd2, NULL, &timeout);
if(rc <= 0) {
/* negative is error
0 is timeout */
fprintf(stderr, "SFTP upload timed out: %d\n",
rc);
break;
}
} while (1);
} while(1);
fprintf(stderr, "SFTP upload done!\n");
}
else {
Expand All @@ -336,15 +340,15 @@ int main(int argc, char *argv[])

shutdown:

libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);

#ifdef WIN32
closesocket(sock);
#else
close(sock);
#endif
if (tempstorage)
if(tempstorage)
fclose(tempstorage);
fprintf(stderr, "all done\n");

Expand Down
59 changes: 31 additions & 28 deletions example/sftp_append.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ int main(int argc, char *argv[])
struct sockaddr_in sin;
const char *fingerprint;
LIBSSH2_SESSION *session;
const char *username="username";
const char *password="password";
const char *loclfile="sftp_write.c";
const char *sftppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *loclfile = "sftp_write.c";
const char *sftppath = "/tmp/TEST";
int rc;
FILE *local;
LIBSSH2_SFTP *sftp_session;
Expand All @@ -57,16 +57,17 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}

Expand All @@ -83,14 +84,14 @@ int main(int argc, char *argv[])
sftppath = argv[5];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

local = fopen(loclfile, "rb");
if (!local) {
if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1;
}
Expand All @@ -104,8 +105,8 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
Expand Down Expand Up @@ -140,18 +141,20 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* 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");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) {
#define HOME "/home/username/"
if(libssh2_userauth_publickey_fromfile(session, username,
HOME ".ssh/id_rsa.pub",
HOME ".ssh/id_rsa",
password)) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -160,7 +163,7 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_init()!\n");
sftp_session = libssh2_sftp_init(session);

if (!sftp_session) {
if(!sftp_session) {
fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown;
}
Expand All @@ -173,7 +176,7 @@ int main(int argc, char *argv[])
LIBSSH2_FXF_WRITE|LIBSSH2_FXF_READ,
LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR|
LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH);
if (!sftp_handle) {
if(!sftp_handle) {
fprintf(stderr, "Unable to open file with SFTP\n");
goto shutdown;
}
Expand All @@ -188,14 +191,14 @@ int main(int argc, char *argv[])

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");
goto shutdown;
}
fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");
do {
nread = fread(mem, 1, sizeof(mem), local);
if (nread <= 0) {
if(nread <= 0) {
/* end of file */
break;
}
Expand All @@ -208,9 +211,9 @@ int main(int argc, char *argv[])
break;
ptr += rc;
nread -= rc;
} while (nread);
} while(nread);

} while (rc > 0);
} while(rc > 0);

libssh2_sftp_close(sftp_handle);
libssh2_sftp_shutdown(sftp_session);
Expand All @@ -225,7 +228,7 @@ int main(int argc, char *argv[])
#else
close(sock);
#endif
if (local)
if(local)
fclose(local);
fprintf(stderr, "all done\n");

Expand Down
36 changes: 19 additions & 17 deletions example/sftp_mkdir.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,27 @@ int main(int argc, char *argv[])
struct sockaddr_in sin;
const char *fingerprint;
LIBSSH2_SESSION *session;
const char *username="username";
const char *password="password";
const char *sftppath="/tmp/sftp_mkdir";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/sftp_mkdir";
int rc;
LIBSSH2_SFTP *sftp_session;

#ifdef WIN32
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}

Expand All @@ -73,9 +74,9 @@ int main(int argc, char *argv[])
sftppath = argv[4];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

Expand All @@ -88,7 +89,7 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
Expand Down Expand Up @@ -121,15 +122,16 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* 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");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username,
if(libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) {
Expand All @@ -140,7 +142,7 @@ int main(int argc, char *argv[])

sftp_session = libssh2_sftp_init(session);

if (!sftp_session) {
if(!sftp_session) {
fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown;
}
Expand All @@ -161,7 +163,7 @@ int main(int argc, char *argv[])

shutdown:

libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);

#ifdef WIN32
Expand Down
38 changes: 20 additions & 18 deletions example/sftp_mkdir_nonblock.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,27 @@ int main(int argc, char *argv[])
struct sockaddr_in sin;
const char *fingerprint;
LIBSSH2_SESSION *session;
const char *username="username";
const char *password="password";
const char *sftppath="/tmp/sftp_mkdir_nonblock";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/sftp_mkdir_nonblock";
int rc;
LIBSSH2_SFTP *sftp_session;

#ifdef WIN32
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}

Expand All @@ -73,9 +74,9 @@ int main(int argc, char *argv[])
sftppath = argv[4];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

Expand All @@ -88,7 +89,7 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
Expand Down Expand Up @@ -121,15 +122,16 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* 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");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username,
if(libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) {
Expand All @@ -141,7 +143,7 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_init()!\n");
sftp_session = libssh2_sftp_init(session);

if (!sftp_session) {
if(!sftp_session) {
fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown;
}
Expand All @@ -151,7 +153,7 @@ int main(int argc, char *argv[])

fprintf(stderr, "libssh2_sftp_mkdirnb()!\n");
/* 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_IRGRP|LIBSSH2_SFTP_S_IXGRP|
LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH)
Expand All @@ -161,7 +163,7 @@ int main(int argc, char *argv[])

shutdown:

libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
libssh2_session_disconnect(session, "Normal Shutdown");
libssh2_session_free(session);

#ifdef WIN32
Expand Down
86 changes: 45 additions & 41 deletions example/sftp_nonblock.c
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ int main(int argc, char *argv[])
struct sockaddr_in sin;
const char *fingerprint;
LIBSSH2_SESSION *session;
const char *username="username";
const char *password="password";
const char *sftppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *sftppath = "/tmp/TEST";
#ifdef HAVE_GETTIMEOFDAY
struct timeval start;
struct timeval end;
Expand All @@ -103,32 +103,33 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}

if (argc > 2) {
if(argc > 2) {
username = argv[2];
}
if (argc > 3) {
if(argc > 3) {
password = argv[3];
}
if (argc > 4) {
if(argc > 4) {
sftppath = argv[4];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

Expand All @@ -141,15 +142,15 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}

/* Create a session instance */
session = libssh2_session_init();
if (!session)
if(!session)
return -1;

/* Since we have set non-blocking, tell libssh2 we are non-blocking */
Expand All @@ -162,9 +163,9 @@ int main(int argc, char *argv[])
/* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers
*/
while ((rc = libssh2_session_handshake(session, sock)) ==
while((rc = libssh2_session_handshake(session, sock)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
if(rc) {
fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
return -1;
}
Expand All @@ -181,25 +182,26 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* We could authenticate via password */
while ((rc = libssh2_userauth_password(session, username, password))
while((rc = libssh2_userauth_password(session, username, password))
== LIBSSH2_ERROR_EAGAIN);
if (rc) {
if(rc) {
fprintf(stderr, "Authentication by password failed.\n");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
while ((rc =
libssh2_userauth_publickey_fromfile(session, username,
"/home/username/"
".ssh/id_rsa.pub",
"/home/username/"
".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if (rc) {
while((rc =
libssh2_userauth_publickey_fromfile(session, username,
"/home/username/"
".ssh/id_rsa.pub",
"/home/username/"
".ssh/id_rsa",
password)) ==
LIBSSH2_ERROR_EAGAIN);
if(rc) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -222,16 +224,16 @@ int main(int argc, char *argv[])
goto shutdown;
}
}
} while (!sftp_session);
} while(!sftp_session);

fprintf(stderr, "libssh2_sftp_open()!\n");
/* Request a file via SFTP */
do {
sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
LIBSSH2_FXF_READ, 0);

if (!sftp_handle) {
if (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
if(!sftp_handle) {
if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
fprintf(stderr, "Unable to open file with SFTP\n");
goto shutdown;
}
Expand All @@ -240,31 +242,33 @@ int main(int argc, char *argv[])
waitsocket(sock, session); /* now we wait */
}
}
} while (!sftp_handle);
} while(!sftp_handle);

fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n");
do {
char mem[1024*24];

/* loop until we fail */
while ((rc = libssh2_sftp_read(sftp_handle, mem,
while((rc = libssh2_sftp_read(sftp_handle, mem,
sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) {
spin++;
waitsocket(sock, session); /* now we wait */
}
if (rc > 0) {
if(rc > 0) {
total += rc;
write(1, mem, rc);
} else {
}
else {
break;
}
} while (1);
} while(1);

#ifdef HAVE_GETTIMEOFDAY
gettimeofday(&end, NULL);
time_ms = tvdiff(end, start);
fprintf(stderr, "Got %d bytes in %ld ms = %.1f bytes/sec spin: %d\n", total,
time_ms, total/(time_ms/1000.0), spin );
fprintf(stderr, "Got %d bytes in %ld ms = %.1f bytes/sec spin: %d\n",
total,
time_ms, total/(time_ms/1000.0), spin);
#else
fprintf(stderr, "Got %d bytes spin: %d\n", total, spin);
#endif
Expand All @@ -275,7 +279,7 @@ int main(int argc, char *argv[])
shutdown:

fprintf(stderr, "libssh2_session_disconnect\n");
while (libssh2_session_disconnect(session,
while(libssh2_session_disconnect(session,
"Normal Shutdown, Thank you") ==
LIBSSH2_ERROR_EAGAIN);
libssh2_session_free(session);
Expand Down
55 changes: 29 additions & 26 deletions example/sftp_write.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ int main(int argc, char *argv[])
struct sockaddr_in sin;
const char *fingerprint;
LIBSSH2_SESSION *session;
const char *username="username";
const char *password="password";
const char *loclfile="sftp_write.c";
const char *sftppath="/tmp/TEST";
const char *username = "username";
const char *password = "password";
const char *loclfile = "sftp_write.c";
const char *sftppath = "/tmp/TEST";
int rc;
FILE *local;
LIBSSH2_SFTP *sftp_session;
Expand All @@ -56,16 +56,17 @@ int main(int argc, char *argv[])
WSADATA wsadata;
int err;

err = WSAStartup(MAKEWORD(2,0), &wsadata);
if (err != 0) {
err = WSAStartup(MAKEWORD(2, 0), &wsadata);
if(err != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", err);
return 1;
}
#endif

if (argc > 1) {
if(argc > 1) {
hostaddr = inet_addr(argv[1]);
} else {
}
else {
hostaddr = htonl(0x7F000001);
}

Expand All @@ -82,14 +83,14 @@ int main(int argc, char *argv[])
sftppath = argv[5];
}

rc = libssh2_init (0);
if (rc != 0) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
rc = libssh2_init(0);
if(rc != 0) {
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
return 1;
}

local = fopen(loclfile, "rb");
if (!local) {
if(!local) {
fprintf(stderr, "Can't open local file %s\n", loclfile);
return -1;
}
Expand All @@ -103,7 +104,7 @@ int main(int argc, char *argv[])
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
if(connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
Expand Down Expand Up @@ -139,18 +140,20 @@ int main(int argc, char *argv[])
}
fprintf(stderr, "\n");

if (auth_pw) {
if(auth_pw) {
/* 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");
goto shutdown;
}
} else {
}
else {
/* Or by public key */
if (libssh2_userauth_publickey_fromfile(session, username,
"/home/username/.ssh/id_rsa.pub",
"/home/username/.ssh/id_rsa",
password)) {
const char *pubkey = "/home/username/.ssh/id_rsa.pub";
const char *privkey = "/home/username/.ssh/id_rsa.pub";
if(libssh2_userauth_publickey_fromfile(session, username,
pubkey, privkey,
password)) {
fprintf(stderr, "\tAuthentication by public key failed\n");
goto shutdown;
}
Expand All @@ -159,7 +162,7 @@ int main(int argc, char *argv[])
fprintf(stderr, "libssh2_sftp_init()!\n");
sftp_session = libssh2_sftp_init(session);

if (!sftp_session) {
if(!sftp_session) {
fprintf(stderr, "Unable to init SFTP session\n");
goto shutdown;
}
Expand All @@ -172,14 +175,14 @@ int main(int argc, char *argv[])
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");
goto shutdown;
}
fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");
do {
nread = fread(mem, 1, sizeof(mem), local);
if (nread <= 0) {
if(nread <= 0) {
/* end of file */
break;
}
Expand All @@ -192,9 +195,9 @@ int main(int argc, char *argv[])
break;
ptr += rc;
nread -= rc;
} while (nread);
} while(nread);

} while (rc > 0);
} while(rc > 0);

libssh2_sftp_close(sftp_handle);
libssh2_sftp_shutdown(sftp_session);
Expand All @@ -209,7 +212,7 @@ int main(int argc, char *argv[])
#else
close(sock);
#endif
if (local)
if(local)
fclose(local);
fprintf(stderr, "all done\n");

Expand Down
Loading