diff --git a/acinclude-ssh2.m4 b/acinclude-ssh2.m4
index 14b4736..71860d6 100644
--- a/acinclude-ssh2.m4
+++ b/acinclude-ssh2.m4
@@ -1,3 +1,153 @@
+
+dnl **********************************************************************
+dnl CURL_DETECT_ICC ([ACTION-IF-YES])
+dnl
+dnl check if this is the Intel ICC compiler, and if so run the ACTION-IF-YES
+dnl sets the $ICC variable to "yes" or "no"
+dnl **********************************************************************
+AC_DEFUN([CURL_DETECT_ICC],
+[
+    ICC="no"
+    AC_MSG_CHECKING([for icc in use])
+    if test "$GCC" = "yes"; then
+       dnl check if this is icc acting as gcc in disguise
+       AC_EGREP_CPP([^__INTEL_COMPILER], [__INTEL_COMPILER],
+         dnl action if the text is found, this it has not been replaced by the
+         dnl cpp
+         ICC="no",
+         dnl the text was not found, it was replaced by the cpp
+         ICC="yes"
+         AC_MSG_RESULT([yes])
+         [$1]
+       )
+    fi
+    if test "$ICC" = "no"; then
+        # this is not ICC
+        AC_MSG_RESULT([no])
+    fi
+])
+
+dnl We create a function for detecting which compiler we use and then set as
+dnl pendantic compiler options as possible for that particular compiler. The
+dnl options are only used for debug-builds.
+
+AC_DEFUN([CURL_CC_DEBUG_OPTS],
+[
+    if test "z$ICC" = "z"; then
+      CURL_DETECT_ICC
+    fi
+
+    if test "$GCC" = "yes"; then
+
+       dnl figure out gcc version!
+       AC_MSG_CHECKING([gcc version])
+       gccver=`$CC -dumpversion`
+       num1=`echo $gccver | cut -d . -f1`
+       num2=`echo $gccver | cut -d . -f2`
+       gccnum=`(expr $num1 "*" 100 + $num2) 2>/dev/null`
+       AC_MSG_RESULT($gccver)
+
+       if test "$ICC" = "yes"; then
+         dnl this is icc, not gcc.
+
+         dnl ICC warnings we ignore:
+         dnl * 269 warns on our "%Od" printf formatters for curl_off_t output:
+         dnl   "invalid format string conversion"
+         dnl * 279 warns on static conditions in while expressions
+         dnl * 981 warns on "operands are evaluated in unspecified order"
+         dnl * 1418 "external definition with no prior declaration"
+         dnl * 1419 warns on "external declaration in primary source file"
+         dnl   which we know and do on purpose.
+
+         WARN="-wd279,269,981,1418,1419"
+
+         if test "$gccnum" -gt "600"; then
+            dnl icc 6.0 and older doesn't have the -Wall flag
+            WARN="-Wall $WARN"
+         fi
+       else dnl $ICC = yes
+         dnl this is a set of options we believe *ALL* gcc versions support:
+         WARN="-W -Wall -Wwrite-strings -pedantic -Wpointer-arith -Wnested-externs -Winline -Wmissing-prototypes"
+
+         dnl -Wcast-align is a bit too annoying on all gcc versions ;-)
+
+         if test "$gccnum" -ge "207"; then
+           dnl gcc 2.7 or later
+           WARN="$WARN -Wmissing-declarations"
+         fi
+
+         if test "$gccnum" -gt "295"; then
+           dnl only if the compiler is newer than 2.95 since we got lots of
+           dnl "`_POSIX_C_SOURCE' is not defined" in system headers with
+           dnl gcc 2.95.4 on FreeBSD 4.9!
+           WARN="$WARN -Wundef -Wno-long-long -Wsign-compare"
+         fi
+
+         if test "$gccnum" -ge "296"; then
+           dnl gcc 2.96 or later
+           WARN="$WARN -Wfloat-equal"
+         fi
+
+         if test "$gccnum" -gt "296"; then
+           dnl this option does not exist in 2.96
+           WARN="$WARN -Wno-format-nonliteral"
+         fi
+
+         dnl -Wunreachable-code seems totally unreliable on my gcc 3.3.2 on
+         dnl on i686-Linux as it gives us heaps with false positives.
+         dnl Also, on gcc 4.0.X it is totally unbearable and complains all
+         dnl over making it unusable for generic purposes. Let's not use it.
+
+         if test "$gccnum" -ge "303"; then
+           dnl gcc 3.3 and later
+           WARN="$WARN -Wendif-labels -Wstrict-prototypes"
+         fi
+
+         if test "$gccnum" -ge "304"; then
+           # try these on gcc 3.4
+           WARN="$WARN -Wdeclaration-after-statement"
+         fi
+
+         for flag in $CPPFLAGS; do
+           case "$flag" in
+            -I*)
+              dnl Include path, provide a -isystem option for the same dir
+              dnl to prevent warnings in those dirs. The -isystem was not very
+              dnl reliable on earlier gcc versions.
+              add=`echo $flag | sed 's/^-I/-isystem /g'`
+              WARN="$WARN $add"
+              ;;
+           esac
+         done
+
+       fi dnl $ICC = no
+
+       CFLAGS="$CFLAGS $WARN"
+
+      AC_MSG_NOTICE([Added this set of compiler options: $WARN])
+
+    else dnl $GCC = yes
+
+      AC_MSG_NOTICE([Added no extra compiler options])
+
+    fi dnl $GCC = yes
+
+    dnl strip off optimizer flags
+    NEWFLAGS=""
+    for flag in $CFLAGS; do
+      case "$flag" in
+      -O*)
+        dnl echo "cut off $flag"
+        ;;
+      *)
+        NEWFLAGS="$NEWFLAGS $flag"
+        ;;
+      esac
+    done
+    CFLAGS=$NEWFLAGS
+
+]) dnl end of AC_DEFUN()
+
 dnl CURL_CHECK_NONBLOCKING_SOCKET
 dnl -------------------------------------------------
 dnl Check for how to set a socket to non-blocking state. There seems to exist
@@ -11,124 +161,224 @@ dnl to get caught in this script by using an excessive number of #ifdefs...
 dnl
 AC_DEFUN([CURL_CHECK_NONBLOCKING_SOCKET],
 [
-	AC_MSG_CHECKING([non-blocking sockets style])
-	AC_TRY_COMPILE([
-		/* headers for O_NONBLOCK test */
-		#include <sys/types.h>
-		#include <unistd.h>
-		#include <fcntl.h>
-	],[
-		/* try to compile O_NONBLOCK */
-
-		#if defined(sun) || defined(__sun__) || defined(__SUNPRO_C) || defined(__SUNPRO_CC)
-			# if defined(__SVR4) || defined(__srv4__)
-				#  define PLATFORM_SOLARIS
-			# else
-				#  define PLATFORM_SUNOS4
-			# endif
-		#endif
-		#if (defined(_AIX) || defined(__xlC__)) && !defined(_AIX41)
-			# define PLATFORM_AIX_V3
-		#endif
-
-		#if defined(PLATFORM_SUNOS4) || defined(PLATFORM_AIX_V3) || defined(__BEOS__)
-			#error "O_NONBLOCK does not work on this platform"
-		#endif
-		int socket;
-		int flags = fcntl(socket, F_SETFL, flags | O_NONBLOCK);
-	],[
-		dnl the O_NONBLOCK test was fine
-		nonblock="O_NONBLOCK"
-		AC_DEFINE(HAVE_O_NONBLOCK, 1, [use O_NONBLOCK for non-blocking sockets])
-	],[
-		dnl the code was bad, try a different program now, test 2
-
-		AC_TRY_COMPILE([
-			/* headers for FIONBIO test */
-			#include <unistd.h>
-			#include <stropts.h>
-		],[
-			/* FIONBIO source test (old-style unix) */
-			int socket;
-			int flags = ioctl(socket, FIONBIO, &flags);
-		],[
-			dnl FIONBIO test was good
-			nonblock="FIONBIO"
-			AC_DEFINE(HAVE_FIONBIO, 1, [use FIONBIO for non-blocking sockets])
-		],[
-			dnl FIONBIO test was also bad
-			dnl the code was bad, try a different program now, test 3
-
-			AC_TRY_COMPILE([
-				/* headers for ioctlsocket test (Windows) */
-				#undef inline
-				#ifdef HAVE_WINDOWS_H
-					#ifndef WIN32_LEAN_AND_MEAN
-						#define WIN32_LEAN_AND_MEAN
-					#endif
-					#include <windows.h>
-					#ifdef HAVE_WINSOCK2_H
-						#include <winsock2.h>
-					#else
-						#ifdef HAVE_WINSOCK_H
-							#include <winsock.h>
-						#endif
-					#endif
-				#endif
-			],[
-				/* ioctlsocket source code */
-				SOCKET sd;
-				unsigned long flags = 0;
-				sd = socket(0, 0, 0);
-				ioctlsocket(sd, FIONBIO, &flags);
-			],[
-				dnl ioctlsocket test was good
-				nonblock="ioctlsocket"
-				AC_DEFINE(HAVE_IOCTLSOCKET, 1, [use ioctlsocket() for non-blocking sockets])
-			],[
-				dnl ioctlsocket didnt compile!, go to test 4
-				AC_TRY_LINK([
-					/* headers for IoctlSocket test (Amiga?) */
-					#include <sys/ioctl.h>
-				],[
-					/* IoctlSocket source code */
-					int socket;
-					int flags = IoctlSocket(socket, FIONBIO, (long)1);
-				],[
-					dnl ioctlsocket test was good
-					nonblock="IoctlSocket"
-					AC_DEFINE(HAVE_IOCTLSOCKET_CASE, 1, [use Ioctlsocket() for non-blocking sockets])
-				],[
-					dnl Ioctlsocket didnt compile, do test 5!
-					AC_TRY_COMPILE([
-						/* headers for SO_NONBLOCK test (BeOS) */
-						#include <socket.h>
-					],[
-						/* SO_NONBLOCK source code */
-						long b = 1;
-						int socket;
-						int flags = setsockopt(socket, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
-					],[
-						dnl the SO_NONBLOCK test was good
-						nonblock="SO_NONBLOCK"
-						AC_DEFINE(HAVE_SO_NONBLOCK, 1, [use SO_NONBLOCK for non-blocking sockets])
-					],[
-						dnl test 5 didnt compile!
-						nonblock="nada"
-						AC_DEFINE(HAVE_DISABLED_NONBLOCKING, 1, [disabled non-blocking sockets])
-					])
-					dnl end of fifth test
-				])
-				dnl end of forth test
-			])
-			dnl end of third test
-		])
-		dnl end of second test
-	])
-	dnl end of non-blocking try-compile test
-	AC_MSG_RESULT($nonblock)
-
-	if test "$nonblock" = "nada"; then
-		AC_MSG_WARN([non-block sockets disabled])
-	fi
+  AC_MSG_CHECKING([non-blocking sockets style])
+
+  AC_TRY_COMPILE([
+/* headers for O_NONBLOCK test */
+#include <sys/types.h>
+#include <unistd.h>
+#include <fcntl.h>
+],[
+/* try to compile O_NONBLOCK */
+
+#if defined(sun) || defined(__sun__) || defined(__SUNPRO_C) || defined(__SUNPRO_CC)
+# if defined(__SVR4) || defined(__srv4__)
+#  define PLATFORM_SOLARIS
+# else
+#  define PLATFORM_SUNOS4
+# endif
+#endif
+#if (defined(_AIX) || defined(__xlC__)) && !defined(_AIX41)
+# define PLATFORM_AIX_V3
+#endif
+
+#if defined(PLATFORM_SUNOS4) || defined(PLATFORM_AIX_V3) || defined(__BEOS__)
+#error "O_NONBLOCK does not work on this platform"
+#endif
+  int socket;
+  int flags = fcntl(socket, F_SETFL, flags | O_NONBLOCK);
+],[
+dnl the O_NONBLOCK test was fine
+nonblock="O_NONBLOCK"
+AC_DEFINE(HAVE_O_NONBLOCK, 1, [use O_NONBLOCK for non-blocking sockets])
+],[
+dnl the code was bad, try a different program now, test 2
+
+  AC_TRY_COMPILE([
+/* headers for FIONBIO test */
+#include <unistd.h>
+#include <stropts.h>
+],[
+/* FIONBIO source test (old-style unix) */
+ int socket;
+ int flags = ioctl(socket, FIONBIO, &flags);
+],[
+dnl FIONBIO test was good
+nonblock="FIONBIO"
+AC_DEFINE(HAVE_FIONBIO, 1, [use FIONBIO for non-blocking sockets])
+],[
+dnl FIONBIO test was also bad
+dnl the code was bad, try a different program now, test 3
+
+  AC_TRY_COMPILE([
+/* headers for ioctlsocket test (Windows) */
+#undef inline
+#ifdef HAVE_WINDOWS_H
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <windows.h>
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#else
+#ifdef HAVE_WINSOCK_H
+#include <winsock.h>
+#endif
+#endif
+#endif
+],[
+/* ioctlsocket source code */
+ SOCKET sd;
+ unsigned long flags = 0;
+ sd = socket(0, 0, 0);
+ ioctlsocket(sd, FIONBIO, &flags);
+],[
+dnl ioctlsocket test was good
+nonblock="ioctlsocket"
+AC_DEFINE(HAVE_IOCTLSOCKET, 1, [use ioctlsocket() for non-blocking sockets])
+],[
+dnl ioctlsocket didnt compile!, go to test 4
+
+  AC_TRY_LINK([
+/* headers for IoctlSocket test (Amiga?) */
+#include <sys/ioctl.h>
+],[
+/* IoctlSocket source code */
+ int socket;
+ int flags = IoctlSocket(socket, FIONBIO, (long)1);
+],[
+dnl ioctlsocket test was good
+nonblock="IoctlSocket"
+AC_DEFINE(HAVE_IOCTLSOCKET_CASE, 1, [use Ioctlsocket() for non-blocking sockets])
+],[
+dnl Ioctlsocket didnt compile, do test 5!
+  AC_TRY_COMPILE([
+/* headers for SO_NONBLOCK test (BeOS) */
+#include <socket.h>
+],[
+/* SO_NONBLOCK source code */
+ long b = 1;
+ int socket;
+ int flags = setsockopt(socket, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
+],[
+dnl the SO_NONBLOCK test was good
+nonblock="SO_NONBLOCK"
+AC_DEFINE(HAVE_SO_NONBLOCK, 1, [use SO_NONBLOCK for non-blocking sockets])
+],[
+dnl test 5 didnt compile!
+nonblock="nada"
+AC_DEFINE(HAVE_DISABLED_NONBLOCKING, 1, [disabled non-blocking sockets])
+])
+dnl end of fifth test
+
+])
+dnl end of forth test
+
+])
+dnl end of third test
+
+])
+dnl end of second test
+
+])
+dnl end of non-blocking try-compile test
+  AC_MSG_RESULT($nonblock)
+
+  if test "$nonblock" = "nada"; then
+    AC_MSG_WARN([non-block sockets disabled])
+  fi
 ])
+
+dnl CURL_CHECK_NEED_REENTRANT_SYSTEM
+dnl -------------------------------------------------
+dnl Checks if the preprocessor _REENTRANT definition
+dnl must be unconditionally done for this platform.
+dnl Internal macro for CURL_CONFIGURE_REENTRANT.
+
+AC_DEFUN([CURL_CHECK_NEED_REENTRANT_SYSTEM], [
+  case $host in
+    *-*-solaris* | *-*-hpux*)
+      tmp_need_reentrant="yes"
+      ;;
+    *)
+      tmp_need_reentrant="no"
+      ;;
+  esac
+])
+
+
+dnl CURL_CONFIGURE_FROM_NOW_ON_WITH_REENTRANT
+dnl -------------------------------------------------
+dnl This macro ensures that configuration tests done
+dnl after this will execute with preprocessor symbol
+dnl _REENTRANT defined. This macro also ensures that
+dnl the generated config file defines NEED_REENTRANT
+dnl and that in turn setup.h will define _REENTRANT.
+dnl Internal macro for CURL_CONFIGURE_REENTRANT.
+
+AC_DEFUN([CURL_CONFIGURE_FROM_NOW_ON_WITH_REENTRANT], [
+AC_DEFINE(NEED_REENTRANT, 1,
+  [Define to 1 if _REENTRANT preprocessor symbol must be defined.])
+cat >>confdefs.h <<_EOF
+#ifndef _REENTRANT
+#  define _REENTRANT
+#endif
+_EOF
+])
+
+
+dnl CURL_CONFIGURE_REENTRANT
+dnl -------------------------------------------------
+dnl This first checks if the preprocessor _REENTRANT
+dnl symbol is already defined. If it isn't currently
+dnl defined a set of checks are performed to verify
+dnl if its definition is required to make visible to
+dnl the compiler a set of *_r functions. Finally, if
+dnl _REENTRANT is already defined or needed it takes
+dnl care of making adjustments necessary to ensure
+dnl that it is defined equally for further configure
+dnl tests and generated config file.
+
+AC_DEFUN([CURL_CONFIGURE_REENTRANT], [
+  AC_PREREQ([2.50])dnl
+  #
+  AC_MSG_CHECKING([if _REENTRANT is already defined])
+  AC_COMPILE_IFELSE([
+    AC_LANG_PROGRAM([[
+    ]],[[
+#ifdef _REENTRANT
+      int dummy=1;
+#else
+      force compilation error
+#endif
+    ]])
+  ],[
+    AC_MSG_RESULT([yes])
+    tmp_reentrant_initially_defined="yes"
+  ],[
+    AC_MSG_RESULT([no])
+    tmp_reentrant_initially_defined="no"
+  ])
+  #
+  if test "$tmp_reentrant_initially_defined" = "no"; then
+    AC_MSG_CHECKING([if _REENTRANT is actually needed])
+    CURL_CHECK_NEED_REENTRANT_SYSTEM
+
+    if test "$tmp_need_reentrant" = "yes"; then
+      AC_MSG_RESULT([yes])
+    else
+      AC_MSG_RESULT([no])
+    fi
+  fi
+  #
+  AC_MSG_CHECKING([if _REENTRANT is onwards defined])
+  if test "$tmp_reentrant_initially_defined" = "yes" ||
+    test "$tmp_need_reentrant" = "yes"; then
+    CURL_CONFIGURE_FROM_NOW_ON_WITH_REENTRANT
+    AC_MSG_RESULT([yes])
+  else
+    AC_MSG_RESULT([no])
+  fi
+  #
+])
+
diff --git a/configure.ac.in b/configure.ac.in
index 5505c77..1919919 100644
--- a/configure.ac.in
+++ b/configure.ac.in
@@ -104,7 +104,7 @@ fi
 AM_CONDITIONAL([BUILD_SSH_TUNNEL], [test x$BUILD_SSH_TUNNEL = xyes])
 
 if test "$ac_cv_libssl" = "yes"; then
-	CPPFLAGS="$CPPFLAGS -DHAVE_OPENSSL_CRYPTO"
+	CPPFLAGS="$CPPFLAGS -DHAVE_OPENSSL_CRYPTO -DLIBSSH2_OPENSSL"
 	LIBS="$LIBS $LIBSSL"
 fi
 
diff --git a/lib-ld.m4 b/lib-ld.m4
index 4e1374d..96c4e2c 100644
--- a/lib-ld.m4
+++ b/lib-ld.m4
@@ -1,5 +1,5 @@
-# lib-ld.m4 serial 5 (gettext-0.18.2)
-dnl Copyright (C) 1996-2003, 2009-2012 Free Software Foundation, Inc.
+# lib-ld.m4 serial 3 (gettext-0.13)
+dnl Copyright (C) 1996-2003 Free Software Foundation, Inc.
 dnl This file is free software; the Free Software Foundation
 dnl gives unlimited permission to copy and/or distribute it,
 dnl with or without modifications, as long as this notice is preserved.
@@ -10,7 +10,7 @@ dnl with libtool.m4.
 
 dnl From libtool-1.4. Sets the variable with_gnu_ld to yes or no.
 AC_DEFUN([AC_LIB_PROG_LD_GNU],
-[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], [acl_cv_prog_gnu_ld],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], acl_cv_prog_gnu_ld,
 [# I'd rather use --version here, but apparently some GNU ld's only accept -v.
 case `$LD -v 2>&1 </dev/null` in
 *GNU* | *'with BFD'*)
@@ -23,7 +23,7 @@ with_gnu_ld=$acl_cv_prog_gnu_ld
 
 dnl From libtool-1.4. Sets the variable LD.
 AC_DEFUN([AC_LIB_PROG_LD],
-[AC_ARG_WITH([gnu-ld],
+[AC_ARG_WITH(gnu-ld,
 [  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]],
 test "$withval" = no || with_gnu_ld=yes, with_gnu_ld=no)
 AC_REQUIRE([AC_PROG_CC])dnl
@@ -31,14 +31,15 @@ AC_REQUIRE([AC_CANONICAL_HOST])dnl
 # Prepare PATH_SEPARATOR.
 # The user is always right.
 if test "${PATH_SEPARATOR+set}" != set; then
-  # Determine PATH_SEPARATOR by trying to find /bin/sh in a PATH which
-  # contains only /bin. Note that ksh looks also at the FPATH variable,
-  # so we have to set that as well for the test.
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 \
-    && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 \
-           || PATH_SEPARATOR=';'
-       }
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
 fi
 ac_prog=ld
 if test "$GCC" = yes; then
@@ -58,7 +59,7 @@ if test "$GCC" = yes; then
       # Canonicalize the path of ld
       ac_prog=`echo $ac_prog| sed 's%\\\\%/%g'`
       while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
-        ac_prog=`echo $ac_prog| sed "s%$re_direlt%/%"`
+	ac_prog=`echo $ac_prog| sed "s%$re_direlt%/%"`
       done
       test -z "$LD" && LD="$ac_prog"
       ;;
@@ -76,7 +77,7 @@ elif test "$with_gnu_ld" = yes; then
 else
   AC_MSG_CHECKING([for non-GNU ld])
 fi
-AC_CACHE_VAL([acl_cv_path_LD],
+AC_CACHE_VAL(acl_cv_path_LD,
 [if test -z "$LD"; then
   IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}${PATH_SEPARATOR-:}"
   for ac_dir in $PATH; do
@@ -88,9 +89,9 @@ AC_CACHE_VAL([acl_cv_path_LD],
       # Break only if it was the GNU/non-GNU ld that we prefer.
       case `"$acl_cv_path_LD" -v 2>&1 < /dev/null` in
       *GNU* | *'with BFD'*)
-        test "$with_gnu_ld" != no && break ;;
+	test "$with_gnu_ld" != no && break ;;
       *)
-        test "$with_gnu_ld" != yes && break ;;
+	test "$with_gnu_ld" != yes && break ;;
       esac
     fi
   done
@@ -100,9 +101,9 @@ else
 fi])
 LD="$acl_cv_path_LD"
 if test -n "$LD"; then
-  AC_MSG_RESULT([$LD])
+  AC_MSG_RESULT($LD)
 else
-  AC_MSG_RESULT([no])
+  AC_MSG_RESULT(no)
 fi
 test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
 AC_LIB_PROG_LD_GNU
diff --git a/lib-link.m4 b/lib-link.m4
index d11b4b4..f157d98 100644
--- a/lib-link.m4
+++ b/lib-link.m4
@@ -1,12 +1,12 @@
-# lib-link.m4 serial 26 (gettext-0.18.2)
-dnl Copyright (C) 2001-2012 Free Software Foundation, Inc.
+# lib-link.m4 serial 13 (gettext-0.16.2)
+dnl Copyright (C) 2001-2007 Free Software Foundation, Inc.
 dnl This file is free software; the Free Software Foundation
 dnl gives unlimited permission to copy and/or distribute it,
 dnl with or without modifications, as long as this notice is preserved.
 
 dnl From Bruno Haible.
 
-AC_PREREQ([2.54])
+AC_PREREQ(2.54)
 
 dnl AC_LIB_LINKFLAGS(name [, dependencies]) searches for libname and
 dnl the libraries corresponding to explicit and implicit dependencies.
@@ -18,9 +18,9 @@ AC_DEFUN([AC_LIB_LINKFLAGS],
 [
   AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
   AC_REQUIRE([AC_LIB_RPATH])
-  pushdef([Name],[m4_translit([$1],[./+-], [____])])
-  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
-                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  define([Name],[translit([$1],[./-], [___])])
+  define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+                               [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
   AC_CACHE_CHECK([how to link with lib[]$1], [ac_cv_lib[]Name[]_libs], [
     AC_LIB_LINKFLAGS_BODY([$1], [$2])
     ac_cv_lib[]Name[]_libs="$LIB[]NAME"
@@ -39,17 +39,16 @@ AC_DEFUN([AC_LIB_LINKFLAGS],
   dnl Also set HAVE_LIB[]NAME so that AC_LIB_HAVE_LINKFLAGS can reuse the
   dnl results of this search when this library appears as a dependency.
   HAVE_LIB[]NAME=yes
-  popdef([NAME])
-  popdef([Name])
+  undefine([Name])
+  undefine([NAME])
 ])
 
-dnl AC_LIB_HAVE_LINKFLAGS(name, dependencies, includes, testcode, [missing-message])
+dnl AC_LIB_HAVE_LINKFLAGS(name, dependencies, includes, testcode)
 dnl searches for libname and the libraries corresponding to explicit and
 dnl implicit dependencies, together with the specified include files and
-dnl the ability to compile and link the specified testcode. The missing-message
-dnl defaults to 'no' and may contain additional hints for the user.
-dnl If found, it sets and AC_SUBSTs HAVE_LIB${NAME}=yes and the LIB${NAME}
-dnl and LTLIB${NAME} variables and augments the CPPFLAGS variable, and
+dnl the ability to compile and link the specified testcode. If found, it
+dnl sets and AC_SUBSTs HAVE_LIB${NAME}=yes and the LIB${NAME} and
+dnl LTLIB${NAME} variables and augments the CPPFLAGS variable, and
 dnl #defines HAVE_LIB${NAME} to 1. Otherwise, it sets and AC_SUBSTs
 dnl HAVE_LIB${NAME}=no and LIB${NAME} and LTLIB${NAME} to empty.
 dnl Sets and AC_SUBSTs the LIB${NAME}_PREFIX variable to nonempty if libname
@@ -58,9 +57,9 @@ AC_DEFUN([AC_LIB_HAVE_LINKFLAGS],
 [
   AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
   AC_REQUIRE([AC_LIB_RPATH])
-  pushdef([Name],[m4_translit([$1],[./+-], [____])])
-  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
-                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  define([Name],[translit([$1],[./-], [___])])
+  define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+                               [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
 
   dnl Search for lib[]Name and define LIB[]NAME, LTLIB[]NAME and INC[]NAME
   dnl accordingly.
@@ -74,26 +73,13 @@ AC_DEFUN([AC_LIB_HAVE_LINKFLAGS],
 
   AC_CACHE_CHECK([for lib[]$1], [ac_cv_lib[]Name], [
     ac_save_LIBS="$LIBS"
-    dnl If $LIB[]NAME contains some -l options, add it to the end of LIBS,
-    dnl because these -l options might require -L options that are present in
-    dnl LIBS. -l options benefit only from the -L options listed before it.
-    dnl Otherwise, add it to the front of LIBS, because it may be a static
-    dnl library that depends on another static library that is present in LIBS.
-    dnl Static libraries benefit only from the static libraries listed after
-    dnl it.
-    case " $LIB[]NAME" in
-      *" -l"*) LIBS="$LIBS $LIB[]NAME" ;;
-      *)       LIBS="$LIB[]NAME $LIBS" ;;
-    esac
-    AC_LINK_IFELSE(
-      [AC_LANG_PROGRAM([[$3]], [[$4]])],
-      [ac_cv_lib[]Name=yes],
-      [ac_cv_lib[]Name='m4_if([$5], [], [no], [[$5]])'])
+    LIBS="$LIBS $LIB[]NAME"
+    AC_TRY_LINK([$3], [$4], [ac_cv_lib[]Name=yes], [ac_cv_lib[]Name=no])
     LIBS="$ac_save_LIBS"
   ])
   if test "$ac_cv_lib[]Name" = yes; then
     HAVE_LIB[]NAME=yes
-    AC_DEFINE([HAVE_LIB]NAME, 1, [Define if you have the lib][$1 library.])
+    AC_DEFINE([HAVE_LIB]NAME, 1, [Define if you have the $1 library.])
     AC_MSG_CHECKING([how to link with lib[]$1])
     AC_MSG_RESULT([$LIB[]NAME])
   else
@@ -109,15 +95,13 @@ AC_DEFUN([AC_LIB_HAVE_LINKFLAGS],
   AC_SUBST([LIB]NAME)
   AC_SUBST([LTLIB]NAME)
   AC_SUBST([LIB]NAME[_PREFIX])
-  popdef([NAME])
-  popdef([Name])
+  undefine([Name])
+  undefine([NAME])
 ])
 
 dnl Determine the platform dependent parameters needed to use rpath:
 dnl   acl_libext,
 dnl   acl_shlibext,
-dnl   acl_libname_spec,
-dnl   acl_library_names_spec,
 dnl   acl_hardcode_libdir_flag_spec,
 dnl   acl_hardcode_libdir_separator,
 dnl   acl_hardcode_direct,
@@ -130,7 +114,7 @@ AC_DEFUN([AC_LIB_RPATH],
   AC_REQUIRE([AC_LIB_PROG_LD])            dnl we use $LD, $with_gnu_ld
   AC_REQUIRE([AC_CANONICAL_HOST])         dnl we use $host
   AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT]) dnl we use $ac_aux_dir
-  AC_CACHE_CHECK([for shared library run path origin], [acl_cv_rpath], [
+  AC_CACHE_CHECK([for shared library run path origin], acl_cv_rpath, [
     CC="$CC" GCC="$GCC" LDFLAGS="$LDFLAGS" LD="$LD" with_gnu_ld="$with_gnu_ld" \
     ${CONFIG_SHELL-/bin/sh} "$ac_aux_dir/config.rpath" "$host" > conftest.sh
     . ./conftest.sh
@@ -147,32 +131,11 @@ AC_DEFUN([AC_LIB_RPATH],
   acl_hardcode_direct="$acl_cv_hardcode_direct"
   acl_hardcode_minus_L="$acl_cv_hardcode_minus_L"
   dnl Determine whether the user wants rpath handling at all.
-  AC_ARG_ENABLE([rpath],
+  AC_ARG_ENABLE(rpath,
     [  --disable-rpath         do not hardcode runtime library paths],
     :, enable_rpath=yes)
 ])
 
-dnl AC_LIB_FROMPACKAGE(name, package)
-dnl declares that libname comes from the given package. The configure file
-dnl will then not have a --with-libname-prefix option but a
-dnl --with-package-prefix option. Several libraries can come from the same
-dnl package. This declaration must occur before an AC_LIB_LINKFLAGS or similar
-dnl macro call that searches for libname.
-AC_DEFUN([AC_LIB_FROMPACKAGE],
-[
-  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
-                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
-  define([acl_frompackage_]NAME, [$2])
-  popdef([NAME])
-  pushdef([PACK],[$2])
-  pushdef([PACKUP],[m4_translit(PACK,[abcdefghijklmnopqrstuvwxyz./+-],
-                                     [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
-  define([acl_libsinpackage_]PACKUP,
-    m4_ifdef([acl_libsinpackage_]PACKUP, [m4_defn([acl_libsinpackage_]PACKUP)[, ]],)[lib$1])
-  popdef([PACKUP])
-  popdef([PACK])
-])
-
 dnl AC_LIB_LINKFLAGS_BODY(name [, dependencies]) searches for libname and
 dnl the libraries corresponding to explicit and implicit dependencies.
 dnl Sets the LIB${NAME}, LTLIB${NAME} and INC${NAME} variables.
@@ -181,23 +144,19 @@ dnl in ${LIB${NAME}_PREFIX}/$acl_libdirstem.
 AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
 [
   AC_REQUIRE([AC_LIB_PREPARE_MULTILIB])
-  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
-                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
-  pushdef([PACK],[m4_ifdef([acl_frompackage_]NAME, [acl_frompackage_]NAME, lib[$1])])
-  pushdef([PACKUP],[m4_translit(PACK,[abcdefghijklmnopqrstuvwxyz./+-],
-                                     [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
-  pushdef([PACKLIBS],[m4_ifdef([acl_frompackage_]NAME, [acl_libsinpackage_]PACKUP, lib[$1])])
+  define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+                               [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
   dnl Autoconf >= 2.61 supports dots in --with options.
-  pushdef([P_A_C_K],[m4_if(m4_version_compare(m4_defn([m4_PACKAGE_VERSION]),[2.61]),[-1],[m4_translit(PACK,[.],[_])],PACK)])
+  define([N_A_M_E],[m4_if(m4_version_compare(m4_defn([m4_PACKAGE_VERSION]),[2.61]),[-1],[translit([$1],[.],[_])],[$1])])
   dnl By default, look in $includedir and $libdir.
   use_additional=yes
   AC_LIB_WITH_FINAL_PREFIX([
     eval additional_includedir=\"$includedir\"
     eval additional_libdir=\"$libdir\"
   ])
-  AC_ARG_WITH(P_A_C_K[-prefix],
-[[  --with-]]P_A_C_K[[-prefix[=DIR]  search for ]PACKLIBS[ in DIR/include and DIR/lib
-  --without-]]P_A_C_K[[-prefix     don't search for ]PACKLIBS[ in includedir and libdir]],
+  AC_LIB_ARG_WITH([lib]N_A_M_E[-prefix],
+[  --with-lib]N_A_M_E[-prefix[=DIR]  search for lib$1 in DIR/include and DIR/lib
+  --without-lib]N_A_M_E[-prefix     don't search for lib$1 in includedir and libdir],
 [
     if test "X$withval" = "Xno"; then
       use_additional=no
@@ -210,10 +169,6 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
       else
         additional_includedir="$withval/include"
         additional_libdir="$withval/$acl_libdirstem"
-        if test "$acl_libdirstem2" != "$acl_libdirstem" \
-           && ! test -d "$withval/$acl_libdirstem"; then
-          additional_libdir="$withval/$acl_libdirstem2"
-        fi
       fi
     fi
 ])
@@ -223,9 +178,6 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
   LTLIB[]NAME=
   INC[]NAME=
   LIB[]NAME[]_PREFIX=
-  dnl HAVE_LIB${NAME} is an indicator that LIB${NAME}, LTLIB${NAME} have been
-  dnl computed. So it has to be reset here.
-  HAVE_LIB[]NAME=
   rpathdirs=
   ltrpathdirs=
   names_already_handled=
@@ -245,7 +197,7 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
         names_already_handled="$names_already_handled $name"
         dnl See if it was already located by an earlier AC_LIB_LINKFLAGS
         dnl or AC_LIB_HAVE_LINKFLAGS call.
-        uppername=`echo "$name" | sed -e 'y|abcdefghijklmnopqrstuvwxyz./+-|ABCDEFGHIJKLMNOPQRSTUVWXYZ____|'`
+        uppername=`echo "$name" | sed -e 'y|abcdefghijklmnopqrstuvwxyz./-|ABCDEFGHIJKLMNOPQRSTUVWXYZ___|'`
         eval value=\"\$HAVE_LIB$uppername\"
         if test -n "$value"; then
           if test "$value" = yes; then
@@ -375,9 +327,7 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
               dnl Linking with a shared library. We attempt to hardcode its
               dnl directory into the executable's runpath, unless it's the
               dnl standard /usr/lib.
-              if test "$enable_rpath" = no \
-                 || test "X$found_dir" = "X/usr/$acl_libdirstem" \
-                 || test "X$found_dir" = "X/usr/$acl_libdirstem2"; then
+              if test "$enable_rpath" = no || test "X$found_dir" = "X/usr/$acl_libdirstem"; then
                 dnl No hardcoding is needed.
                 LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
               else
@@ -465,16 +415,7 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
             case "$found_dir" in
               */$acl_libdirstem | */$acl_libdirstem/)
                 basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e "s,/$acl_libdirstem/"'*$,,'`
-                if test "$name" = '$1'; then
-                  LIB[]NAME[]_PREFIX="$basedir"
-                fi
-                additional_includedir="$basedir/include"
-                ;;
-              */$acl_libdirstem2 | */$acl_libdirstem2/)
-                basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e "s,/$acl_libdirstem2/"'*$,,'`
-                if test "$name" = '$1'; then
-                  LIB[]NAME[]_PREFIX="$basedir"
-                fi
+                LIB[]NAME[]_PREFIX="$basedir"
                 additional_includedir="$basedir/include"
                 ;;
             esac
@@ -535,11 +476,9 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
                     dnl   3. if it's already present in $LDFLAGS or the already
                     dnl      constructed $LIBNAME,
                     dnl   4. if it doesn't exist as a directory.
-                    if test "X$additional_libdir" != "X/usr/$acl_libdirstem" \
-                       && test "X$additional_libdir" != "X/usr/$acl_libdirstem2"; then
+                    if test "X$additional_libdir" != "X/usr/$acl_libdirstem"; then
                       haveit=
-                      if test "X$additional_libdir" = "X/usr/local/$acl_libdirstem" \
-                         || test "X$additional_libdir" = "X/usr/local/$acl_libdirstem2"; then
+                      if test "X$additional_libdir" = "X/usr/local/$acl_libdirstem"; then
                         if test -n "$GCC"; then
                           case $host_os in
                             linux* | gnu* | k*bsd*-gnu) haveit=yes;;
@@ -670,11 +609,6 @@ AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
       LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-R$found_dir"
     done
   fi
-  popdef([P_A_C_K])
-  popdef([PACKLIBS])
-  popdef([PACKUP])
-  popdef([PACK])
-  popdef([NAME])
 ])
 
 dnl AC_LIB_APPENDTOVAR(VAR, CONTENTS) appends the elements of CONTENTS to VAR,
@@ -720,8 +654,7 @@ AC_DEFUN([AC_LIB_LINKFLAGS_FROM_LIBS],
         if test -n "$next"; then
           dir="$next"
           dnl No need to hardcode the standard /usr/lib.
-          if test "X$dir" != "X/usr/$acl_libdirstem" \
-             && test "X$dir" != "X/usr/$acl_libdirstem2"; then
+          if test "X$dir" != "X/usr/$acl_libdirstem"; then
             rpathdirs="$rpathdirs $dir"
           fi
           next=
@@ -730,8 +663,7 @@ AC_DEFUN([AC_LIB_LINKFLAGS_FROM_LIBS],
             -L) next=yes ;;
             -L*) dir=`echo "X$opt" | sed -e 's,^X-L,,'`
                  dnl No need to hardcode the standard /usr/lib.
-                 if test "X$dir" != "X/usr/$acl_libdirstem" \
-                    && test "X$dir" != "X/usr/$acl_libdirstem2"; then
+                 if test "X$dir" != "X/usr/$acl_libdirstem"; then
                    rpathdirs="$rpathdirs $dir"
                  fi
                  next= ;;
diff --git a/lib-prefix.m4 b/lib-prefix.m4
index 007aa05..a8684e1 100644
--- a/lib-prefix.m4
+++ b/lib-prefix.m4
@@ -1,5 +1,5 @@
-# lib-prefix.m4 serial 7 (gettext-0.18)
-dnl Copyright (C) 2001-2005, 2008-2012 Free Software Foundation, Inc.
+# lib-prefix.m4 serial 5 (gettext-0.15)
+dnl Copyright (C) 2001-2005 Free Software Foundation, Inc.
 dnl This file is free software; the Free Software Foundation
 dnl gives unlimited permission to copy and/or distribute it,
 dnl with or without modifications, as long as this notice is preserved.
@@ -153,72 +153,33 @@ AC_DEFUN([AC_LIB_WITH_FINAL_PREFIX],
   prefix="$acl_save_prefix"
 ])
 
-dnl AC_LIB_PREPARE_MULTILIB creates
-dnl - a variable acl_libdirstem, containing the basename of the libdir, either
-dnl   "lib" or "lib64" or "lib/64",
-dnl - a variable acl_libdirstem2, as a secondary possible value for
-dnl   acl_libdirstem, either the same as acl_libdirstem or "lib/sparcv9" or
-dnl   "lib/amd64".
+dnl AC_LIB_PREPARE_MULTILIB creates a variable acl_libdirstem, containing
+dnl the basename of the libdir, either "lib" or "lib64".
 AC_DEFUN([AC_LIB_PREPARE_MULTILIB],
 [
-  dnl There is no formal standard regarding lib and lib64.
-  dnl On glibc systems, the current practice is that on a system supporting
-  dnl 32-bit and 64-bit instruction sets or ABIs, 64-bit libraries go under
-  dnl $prefix/lib64 and 32-bit libraries go under $prefix/lib. We determine
-  dnl the compiler's default mode by looking at the compiler's library search
-  dnl path. If at least one of its elements ends in /lib64 or points to a
-  dnl directory whose absolute pathname ends in /lib64, we assume a 64-bit ABI.
-  dnl Otherwise we use the default, namely "lib".
-  dnl On Solaris systems, the current practice is that on a system supporting
-  dnl 32-bit and 64-bit instruction sets or ABIs, 64-bit libraries go under
-  dnl $prefix/lib/64 (which is a symlink to either $prefix/lib/sparcv9 or
-  dnl $prefix/lib/amd64) and 32-bit libraries go under $prefix/lib.
-  AC_REQUIRE([AC_CANONICAL_HOST])
+  dnl There is no formal standard regarding lib and lib64. The current
+  dnl practice is that on a system supporting 32-bit and 64-bit instruction
+  dnl sets or ABIs, 64-bit libraries go under $prefix/lib64 and 32-bit
+  dnl libraries go under $prefix/lib. We determine the compiler's default
+  dnl mode by looking at the compiler's library search path. If at least
+  dnl of its elements ends in /lib64 or points to a directory whose absolute
+  dnl pathname ends in /lib64, we assume a 64-bit ABI. Otherwise we use the
+  dnl default, namely "lib".
   acl_libdirstem=lib
-  acl_libdirstem2=
-  case "$host_os" in
-    solaris*)
-      dnl See Solaris 10 Software Developer Collection > Solaris 64-bit Developer's Guide > The Development Environment
-      dnl <http://docs.sun.com/app/docs/doc/816-5138/dev-env?l=en&a=view>.
-      dnl "Portable Makefiles should refer to any library directories using the 64 symbolic link."
-      dnl But we want to recognize the sparcv9 or amd64 subdirectory also if the
-      dnl symlink is missing, so we set acl_libdirstem2 too.
-      AC_CACHE_CHECK([for 64-bit host], [gl_cv_solaris_64bit],
-        [AC_EGREP_CPP([sixtyfour bits], [
-#ifdef _LP64
-sixtyfour bits
-#endif
-           ], [gl_cv_solaris_64bit=yes], [gl_cv_solaris_64bit=no])
-        ])
-      if test $gl_cv_solaris_64bit = yes; then
-        acl_libdirstem=lib/64
-        case "$host_cpu" in
-          sparc*)        acl_libdirstem2=lib/sparcv9 ;;
-          i*86 | x86_64) acl_libdirstem2=lib/amd64 ;;
+  searchpath=`(LC_ALL=C $CC -print-search-dirs) 2>/dev/null | sed -n -e 's,^libraries: ,,p' | sed -e 's,^=,,'`
+  if test -n "$searchpath"; then
+    acl_save_IFS="${IFS= 	}"; IFS=":"
+    for searchdir in $searchpath; do
+      if test -d "$searchdir"; then
+        case "$searchdir" in
+          */lib64/ | */lib64 ) acl_libdirstem=lib64 ;;
+          *) searchdir=`cd "$searchdir" && pwd`
+             case "$searchdir" in
+               */lib64 ) acl_libdirstem=lib64 ;;
+             esac ;;
         esac
       fi
-      ;;
-    *)
-      searchpath=`(LC_ALL=C $CC -print-search-dirs) 2>/dev/null | sed -n -e 's,^libraries: ,,p' | sed -e 's,^=,,'`
-      if test -n "$searchpath"; then
-        acl_save_IFS="${IFS= 	}"; IFS=":"
-        for searchdir in $searchpath; do
-          if test -d "$searchdir"; then
-            case "$searchdir" in
-              */lib64/ | */lib64 ) acl_libdirstem=lib64 ;;
-              */../ | */.. )
-                # Better ignore directories of this form. They are misleading.
-                ;;
-              *) searchdir=`cd "$searchdir" && pwd`
-                 case "$searchdir" in
-                   */lib64 ) acl_libdirstem=lib64 ;;
-                 esac ;;
-            esac
-          fi
-        done
-        IFS="$acl_save_IFS"
-      fi
-      ;;
-  esac
-  test -n "$acl_libdirstem2" || acl_libdirstem2="$acl_libdirstem"
+    done
+    IFS="$acl_save_IFS"
+  fi
 ])
diff --git a/pgadmin/include/libssh2/Win32/libssh2_config.h b/pgadmin/include/libssh2/Win32/libssh2_config.h
index 4e2ae29..3e3caf4 100644
--- a/pgadmin/include/libssh2/Win32/libssh2_config.h
+++ b/pgadmin/include/libssh2/Win32/libssh2_config.h
@@ -16,8 +16,9 @@
 #define HAVE_INTTYPES_H
 #define HAVE_SYS_TIME_H
 #define HAVE_GETTIMEOFDAY
-#endif
+#endif /* __MINGW32__ */
 
+#define HAVE_LIBCRYPT32
 #define HAVE_WINSOCK2_H
 #define HAVE_IOCTLSOCKET
 #define HAVE_SELECT
@@ -31,8 +32,10 @@
 #define strncasecmp _strnicmp
 #define strcasecmp _stricmp
 #else
+#ifndef __MINGW32__
 #define strncasecmp strnicmp
 #define strcasecmp stricmp
+#endif /* __MINGW32__ */
 #endif /* _MSC_VER */
 
 /* Enable newer diffie-hellman-group-exchange-sha1 syntax */
diff --git a/pgadmin/include/libssh2/crypto.h b/pgadmin/include/libssh2/crypto.h
index fb576b6..05f5a5c 100644
--- a/pgadmin/include/libssh2/crypto.h
+++ b/pgadmin/include/libssh2/crypto.h
@@ -38,10 +38,16 @@
 #ifndef LIBSSH2_CRYPTO_H
 #define LIBSSH2_CRYPTO_H
 
+#ifdef LIBSSH2_OPENSSL
+#include "openssl.h"
+#endif
+
 #ifdef LIBSSH2_LIBGCRYPT
 #include "libgcrypt.h"
-#else
-#include "openssl.h"
+#endif
+
+#ifdef LIBSSH2_WINCNG
+#include "wincng.h"
 #endif
 
 int _libssh2_rsa_new(libssh2_rsa_ctx ** rsa,
@@ -74,6 +80,10 @@ int _libssh2_rsa_sha1_sign(LIBSSH2_SESSION * session,
                            size_t hash_len,
                            unsigned char **signature,
                            size_t *signature_len);
+int _libssh2_rsa_new_private_frommemory(libssh2_rsa_ctx ** rsa,
+                                        LIBSSH2_SESSION * session,
+                                        const char *filedata, size_t filedata_len,
+                                        unsigned const char *passphrase);
 
 #if LIBSSH2_DSA
 int _libssh2_dsa_new(libssh2_dsa_ctx ** dsa,
@@ -96,6 +106,10 @@ int _libssh2_dsa_sha1_verify(libssh2_dsa_ctx * dsactx,
 int _libssh2_dsa_sha1_sign(libssh2_dsa_ctx * dsactx,
                            const unsigned char *hash,
                            unsigned long hash_len, unsigned char *sig);
+int _libssh2_dsa_new_private_frommemory(libssh2_dsa_ctx ** dsa,
+                                        LIBSSH2_SESSION * session,
+                                        const char *filedata, size_t filedata_len,
+                                        unsigned const char *passphrase);
 #endif
 
 int _libssh2_cipher_init(_libssh2_cipher_ctx * h,
@@ -114,6 +128,14 @@ int _libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session,
                               size_t *pubkeydata_len,
                               const char *privatekey,
                               const char *passphrase);
+int _libssh2_pub_priv_keyfilememory(LIBSSH2_SESSION *session,
+                                    unsigned char **method,
+                                    size_t *method_len,
+                                    unsigned char **pubkeydata,
+                                    size_t *pubkeydata_len,
+                                    const char *privatekeydata,
+                                    size_t privatekeydata_len,
+                                    const char *passphrase);
 
 void _libssh2_init_aes_ctr(void);
 
diff --git a/pgadmin/include/libssh2/libgcrypt.h b/pgadmin/include/libssh2/libgcrypt.h
index 1f0276e..20062ed 100644
--- a/pgadmin/include/libssh2/libgcrypt.h
+++ b/pgadmin/include/libssh2/libgcrypt.h
@@ -42,6 +42,8 @@
 #define LIBSSH2_MD5 1
 
 #define LIBSSH2_HMAC_RIPEMD 1
+#define LIBSSH2_HMAC_SHA256 1
+#define LIBSSH2_HMAC_SHA512 1
 
 #define LIBSSH2_AES 1
 #define LIBSSH2_AES_CTR 1
@@ -55,31 +57,49 @@
 
 #define MD5_DIGEST_LENGTH 16
 #define SHA_DIGEST_LENGTH 20
+#define SHA256_DIGEST_LENGTH 32
 
 #define _libssh2_random(buf, len)                \
   (gcry_randomize ((buf), (len), GCRY_STRONG_RANDOM), 1)
 
 #define libssh2_sha1_ctx gcry_md_hd_t
-#define libssh2_sha1_init(ctx) gcry_md_open (ctx,  GCRY_MD_SHA1, 0);
-#define libssh2_sha1_update(ctx, data, len) gcry_md_write (ctx, data, len)
+
+/* returns 0 in case of failure */
+#define libssh2_sha1_init(ctx) \
+  (GPG_ERR_NO_ERROR == gcry_md_open (ctx,  GCRY_MD_SHA1, 0))
+#define libssh2_sha1_update(ctx, data, len) \
+  gcry_md_write (ctx, (unsigned char *) data, len)
 #define libssh2_sha1_final(ctx, out) \
   memcpy (out, gcry_md_read (ctx, 0), SHA_DIGEST_LENGTH), gcry_md_close (ctx)
 #define libssh2_sha1(message, len, out) \
   gcry_md_hash_buffer (GCRY_MD_SHA1, out, message, len)
 
+#define libssh2_sha256_ctx gcry_md_hd_t
+
+#define libssh2_sha256_init(ctx) \
+  (GPG_ERR_NO_ERROR == gcry_md_open (ctx,  GCRY_MD_SHA256, 0))
+#define libssh2_sha256_update(ctx, data, len) \
+  gcry_md_write (ctx, (unsigned char *) data, len)
+#define libssh2_sha256_final(ctx, out) \
+  memcpy (out, gcry_md_read (ctx, 0), SHA256_DIGEST_LENGTH), gcry_md_close (ctx)
+#define libssh2_sha256(message, len, out) \
+  gcry_md_hash_buffer (GCRY_MD_SHA256, out, message, len)
+
 #define libssh2_md5_ctx gcry_md_hd_t
 
 /* returns 0 in case of failure */
 #define libssh2_md5_init(ctx) \
   (GPG_ERR_NO_ERROR == gcry_md_open (ctx,  GCRY_MD_MD5, 0))
 
-#define libssh2_md5_update(ctx, data, len) gcry_md_write (ctx, data, len)
+#define libssh2_md5_update(ctx, data, len) \
+  gcry_md_write (ctx, (unsigned char *) data, len)
 #define libssh2_md5_final(ctx, out) \
   memcpy (out, gcry_md_read (ctx, 0), MD5_DIGEST_LENGTH), gcry_md_close (ctx)
 #define libssh2_md5(message, len, out) \
   gcry_md_hash_buffer (GCRY_MD_MD5, out, message, len)
 
 #define libssh2_hmac_ctx gcry_md_hd_t
+#define libssh2_hmac_ctx_init(ctx)
 #define libssh2_hmac_sha1_init(ctx, key, keylen) \
   gcry_md_open (ctx, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC), \
     gcry_md_setkey (*ctx, key, keylen)
@@ -89,8 +109,14 @@
 #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \
   gcry_md_open (ctx, GCRY_MD_RMD160, GCRY_MD_FLAG_HMAC), \
     gcry_md_setkey (*ctx, key, keylen)
+#define libssh2_hmac_sha256_init(ctx, key, keylen) \
+  gcry_md_open (ctx, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC), \
+    gcry_md_setkey (*ctx, key, keylen)
+#define libssh2_hmac_sha512_init(ctx, key, keylen) \
+  gcry_md_open (ctx, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC), \
+    gcry_md_setkey (*ctx, key, keylen)
 #define libssh2_hmac_update(ctx, data, datalen) \
-  gcry_md_write (ctx, data, datalen)
+  gcry_md_write (ctx, (unsigned char *) data, datalen)
 #define libssh2_hmac_final(ctx, data) \
   memcpy (data, gcry_md_read (ctx, 0), \
       gcry_md_get_algo_dlen (gcry_md_get_algo (ctx)))
@@ -143,6 +169,7 @@
 #define _libssh2_bn_ctx_new() 0
 #define _libssh2_bn_ctx_free(bnctx) ((void)0)
 #define _libssh2_bn_init() gcry_mpi_new(0)
+#define _libssh2_bn_init_from_bin() NULL /* because gcry_mpi_scan() creates a new bignum */
 #define _libssh2_bn_rand(bn, bits, top, bottom) gcry_mpi_randomize (bn, bits, GCRY_WEAK_RANDOM)
 #define _libssh2_bn_mod_exp(r, a, p, m, ctx) gcry_mpi_powm (r, a, p, m)
 #define _libssh2_bn_set_word(bn, val) gcry_mpi_set_ui(bn, val)
diff --git a/pgadmin/include/libssh2/libssh2.h b/pgadmin/include/libssh2/libssh2.h
index 9b1a6e1..f3d976c 100644
--- a/pgadmin/include/libssh2/libssh2.h
+++ b/pgadmin/include/libssh2/libssh2.h
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2009, Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2009-2012 Daniel Stenberg
+ * Copyright (c) 2009-2015 Daniel Stenberg
  * Copyright (c) 2010 Simon Josefsson <simon@josefsson.org>
  * All rights reserved.
  *
@@ -40,19 +40,19 @@
 #ifndef LIBSSH2_H
 #define LIBSSH2_H 1
 
-#define LIBSSH2_COPYRIGHT "2004-2012 The libssh2 project and its contributors."
+#define LIBSSH2_COPYRIGHT "2004-2015 The libssh2 project and its contributors."
 
 /* We use underscore instead of dash when appending DEV in dev versions just
    to make the BANNER define (used by src/session.c) be a valid SSH
    banner. Release versions have no appended strings and may of course not
    have dashes either. */
-#define LIBSSH2_VERSION "1.4.3"
+#define LIBSSH2_VERSION                             "1.6.1_DEV"
 
 /* The numeric version number is also available "in parts" by using these
    defines: */
-#define LIBSSH2_VERSION_MAJOR 1
-#define LIBSSH2_VERSION_MINOR 4
-#define LIBSSH2_VERSION_PATCH 3
+#define LIBSSH2_VERSION_MAJOR                       1
+#define LIBSSH2_VERSION_MINOR                       6
+#define LIBSSH2_VERSION_PATCH                       1
 
 /* This is the numeric version of the libssh2 version number, meant for easier
    parsing and comparions by programs. The LIBSSH2_VERSION_NUM define will
@@ -69,7 +69,7 @@
    and it is always a greater number in a more recent release. It makes
    comparisons with greater than and less than work.
 */
-#define LIBSSH2_VERSION_NUM 0x010403
+#define LIBSSH2_VERSION_NUM                         0x010601
 
 /*
  * This is the date and time when the full source package was created. The
@@ -80,7 +80,7 @@
  *
  * "Mon Feb 12 11:35:33 UTC 2007"
  */
-#define LIBSSH2_TIMESTAMP "Tue Nov 27 21:45:20 UTC 2012"
+#define LIBSSH2_TIMESTAMP "DEV"
 
 #ifndef RC_INVOKED
 
@@ -100,17 +100,21 @@ extern "C" {
 /* Allow alternate API prefix from CFLAGS or calling app */
 #ifndef LIBSSH2_API
 # ifdef LIBSSH2_WIN32
-#  ifdef LIBSSH2_LIBRARY
-#   define LIBSSH2_API __declspec(dllexport)
+#  ifdef _WINDLL
+#   ifdef LIBSSH2_LIBRARY
+#    define LIBSSH2_API __declspec(dllexport)
+#   else
+#    define LIBSSH2_API __declspec(dllimport)
+#   endif /* LIBSSH2_LIBRARY */
 #  else
-#   define LIBSSH2_API __declspec(dllimport)
-#  endif /* LIBSSH2_LIBRARY */
+#   define LIBSSH2_API
+#  endif
 # else /* !LIBSSH2_WIN32 */
 #  define LIBSSH2_API
 # endif /* LIBSSH2_WIN32 */
 #endif /* LIBSSH2_API */
 
-#if defined(LIBSSH2_DARWIN)
+#ifdef HAVE_SYS_UIO_H
 # include <sys/uio.h>
 #endif
 
@@ -141,6 +145,67 @@ typedef int libssh2_socket_t;
 #define LIBSSH2_INVALID_SOCKET -1
 #endif /* WIN32 */
 
+/*
+ * Determine whether there is small or large file support on windows.
+ */
+
+#if defined(_MSC_VER) && !defined(_WIN32_WCE)
+#  if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
+#    define LIBSSH2_USE_WIN32_LARGE_FILES
+#  else
+#    define LIBSSH2_USE_WIN32_SMALL_FILES
+#  endif
+#endif
+
+#if defined(__MINGW32__) && !defined(LIBSSH2_USE_WIN32_LARGE_FILES)
+#  define LIBSSH2_USE_WIN32_LARGE_FILES
+#endif
+
+#if defined(__WATCOMC__) && !defined(LIBSSH2_USE_WIN32_LARGE_FILES)
+#  define LIBSSH2_USE_WIN32_LARGE_FILES
+#endif
+
+#if defined(__POCC__)
+#  undef LIBSSH2_USE_WIN32_LARGE_FILES
+#endif
+
+#if defined(_WIN32) && !defined(LIBSSH2_USE_WIN32_LARGE_FILES) && !defined(LIBSSH2_USE_WIN32_SMALL_FILES)
+#  define LIBSSH2_USE_WIN32_SMALL_FILES
+#endif
+
+/*
+ * Large file (>2Gb) support using WIN32 functions.
+ */
+
+#ifdef LIBSSH2_USE_WIN32_LARGE_FILES
+#  include <io.h>
+#  include <sys/types.h>
+#  include <sys/stat.h>
+#  define LIBSSH2_STRUCT_STAT_SIZE_FORMAT    "%I64d"
+typedef struct _stati64 libssh2_struct_stat;
+typedef __int64 libssh2_struct_stat_size;
+#endif
+
+/*
+ * Small file (<2Gb) support using WIN32 functions.
+ */
+
+#ifdef LIBSSH2_USE_WIN32_SMALL_FILES
+#  include <sys/types.h>
+#  include <sys/stat.h>
+#  ifndef _WIN32_WCE
+#    define LIBSSH2_STRUCT_STAT_SIZE_FORMAT    "%d"
+typedef struct _stat libssh2_struct_stat;
+typedef off_t libssh2_struct_stat_size;
+#  endif
+#endif
+
+#ifndef LIBSSH2_STRUCT_STAT_SIZE_FORMAT
+#  define LIBSSH2_STRUCT_STAT_SIZE_FORMAT      "%zd"
+typedef struct stat libssh2_struct_stat;
+typedef off_t libssh2_struct_stat_size;
+#endif
+
 /* Part of every banner, user specified or not */
 #define LIBSSH2_SSH_BANNER                  "SSH-2.0-libssh2_" LIBSSH2_VERSION
 
@@ -281,7 +346,8 @@ typedef struct _LIBSSH2_POLLFD {
     unsigned char type; /* LIBSSH2_POLLFD_* below */
 
     union {
-        int socket; /* File descriptors -- examined with system select() call */
+        libssh2_socket_t socket; /* File descriptors -- examined with
+                                    system select() call */
         LIBSSH2_CHANNEL *channel; /* Examined by checking internal state */
         LIBSSH2_LISTENER *listener; /* Read polls only -- are inbound
                                        connections waiting to be accepted? */
@@ -501,6 +567,9 @@ LIBSSH2_API int libssh2_session_last_error(LIBSSH2_SESSION *session,
                                            char **errmsg,
                                            int *errmsg_len, int want_buf);
 LIBSSH2_API int libssh2_session_last_errno(LIBSSH2_SESSION *session);
+LIBSSH2_API int libssh2_session_set_last_error(LIBSSH2_SESSION* session,
+                                               int errcode,
+                                               const char* errmsg);
 LIBSSH2_API int libssh2_session_block_directions(LIBSSH2_SESSION *session);
 
 LIBSSH2_API int libssh2_session_flag(LIBSSH2_SESSION *session, int flag,
@@ -521,8 +590,9 @@ LIBSSH2_API int libssh2_userauth_password_ex(LIBSSH2_SESSION *session,
                                              LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)));
 
 #define libssh2_userauth_password(session, username, password) \
- libssh2_userauth_password_ex((session), (username), strlen(username), \
-                              (password), strlen(password), NULL)
+ libssh2_userauth_password_ex((session), (username),           \
+                              (unsigned int)strlen(username),  \
+                              (password), (unsigned int)strlen(password), NULL)
 
 LIBSSH2_API int
 libssh2_userauth_publickey_fromfile_ex(LIBSSH2_SESSION *session,
@@ -534,9 +604,10 @@ libssh2_userauth_publickey_fromfile_ex(LIBSSH2_SESSION *session,
 
 #define libssh2_userauth_publickey_fromfile(session, username, publickey, \
                                             privatekey, passphrase)     \
-  libssh2_userauth_publickey_fromfile_ex((session), (username), \
-                                         strlen(username), (publickey), \
-                                         (privatekey), (passphrase))
+    libssh2_userauth_publickey_fromfile_ex((session), (username),       \
+                                           (unsigned int)strlen(username), \
+                                           (publickey),                 \
+                                           (privatekey), (passphrase))
 
 LIBSSH2_API int
 libssh2_userauth_publickey(LIBSSH2_SESSION *session,
@@ -561,10 +632,23 @@ libssh2_userauth_hostbased_fromfile_ex(LIBSSH2_SESSION *session,
 #define libssh2_userauth_hostbased_fromfile(session, username, publickey, \
                                             privatekey, passphrase, hostname) \
  libssh2_userauth_hostbased_fromfile_ex((session), (username), \
-                                        strlen(username), (publickey), \
-                                        (privatekey), (passphrase), \
-                                        (hostname), strlen(hostname), \
-                                        (username), strlen(username))
+                                        (unsigned int)strlen(username), \
+                                        (publickey),                    \
+                                        (privatekey), (passphrase),     \
+                                        (hostname),                     \
+                                        (unsigned int)strlen(hostname), \
+                                        (username),                     \
+                                        (unsigned int)strlen(username))
+
+LIBSSH2_API int
+libssh2_userauth_publickey_frommemory(LIBSSH2_SESSION *session,
+                                      const char *username,
+                                      size_t username_len,
+                                      const char *publickeyfiledata,
+                                      size_t publickeyfiledata_len,
+                                      const char *privatekeyfiledata,
+                                      size_t privatekeyfiledata_len,
+                                      const char *passphrase);
 
 /*
  * response_callback is provided with filled by library prompts array,
@@ -578,16 +662,17 @@ libssh2_userauth_keyboard_interactive_ex(LIBSSH2_SESSION* session,
                                          unsigned int username_len,
                                          LIBSSH2_USERAUTH_KBDINT_RESPONSE_FUNC((*response_callback)));
 
-#define libssh2_userauth_keyboard_interactive(session, username, \
-                                              response_callback) \
- libssh2_userauth_keyboard_interactive_ex((session), (username), \
-                                          strlen(username), (response_callback))
+#define libssh2_userauth_keyboard_interactive(session, username,        \
+                                              response_callback)        \
+    libssh2_userauth_keyboard_interactive_ex((session), (username),     \
+                                             (unsigned int)strlen(username), \
+                                             (response_callback))
 
 LIBSSH2_API int libssh2_poll(LIBSSH2_POLLFD *fds, unsigned int nfds,
                              long timeout);
 
 /* Channel API */
-#define LIBSSH2_CHANNEL_WINDOW_DEFAULT  (256*1024)
+#define LIBSSH2_CHANNEL_WINDOW_DEFAULT  (2*1024*1024)
 #define LIBSSH2_CHANNEL_PACKET_DEFAULT  32768
 #define LIBSSH2_CHANNEL_MINADJUST       1024
 
@@ -635,9 +720,10 @@ LIBSSH2_API int libssh2_channel_setenv_ex(LIBSSH2_CHANNEL *channel,
                                           const char *value,
                                           unsigned int value_len);
 
-#define libssh2_channel_setenv(channel, varname, value) \
- libssh2_channel_setenv_ex((channel), (varname), strlen(varname), (value), \
-                           strlen(value))
+#define libssh2_channel_setenv(channel, varname, value)                 \
+    libssh2_channel_setenv_ex((channel), (varname),                     \
+                              (unsigned int)strlen(varname), (value),   \
+                              (unsigned int)strlen(value))
 
 LIBSSH2_API int libssh2_channel_request_pty_ex(LIBSSH2_CHANNEL *channel,
                                                const char *term,
@@ -646,10 +732,12 @@ LIBSSH2_API int libssh2_channel_request_pty_ex(LIBSSH2_CHANNEL *channel,
                                                unsigned int modes_len,
                                                int width, int height,
                                                int width_px, int height_px);
-#define libssh2_channel_request_pty(channel, term) \
- libssh2_channel_request_pty_ex((channel), (term), strlen(term), NULL, 0, \
-                                LIBSSH2_TERM_WIDTH, LIBSSH2_TERM_HEIGHT, \
-                                LIBSSH2_TERM_WIDTH_PX, LIBSSH2_TERM_HEIGHT_PX)
+#define libssh2_channel_request_pty(channel, term)                      \
+    libssh2_channel_request_pty_ex((channel), (term),                   \
+                                   (unsigned int)strlen(term),          \
+                                   NULL, 0,                             \
+                                   LIBSSH2_TERM_WIDTH, LIBSSH2_TERM_HEIGHT, \
+                                   LIBSSH2_TERM_WIDTH_PX, LIBSSH2_TERM_HEIGHT_PX)
 
 LIBSSH2_API int libssh2_channel_request_pty_size_ex(LIBSSH2_CHANNEL *channel,
                                                     int width, int height,
@@ -676,11 +764,11 @@ LIBSSH2_API int libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,
                                   NULL, 0)
 #define libssh2_channel_exec(channel, command) \
   libssh2_channel_process_startup((channel), "exec", sizeof("exec") - 1, \
-                                  (command), strlen(command))
+                                  (command), (unsigned int)strlen(command))
 #define libssh2_channel_subsystem(channel, subsystem) \
   libssh2_channel_process_startup((channel), "subsystem",              \
                                   sizeof("subsystem") - 1, (subsystem), \
-                                  strlen(subsystem))
+                                  (unsigned int)strlen(subsystem))
 
 LIBSSH2_API ssize_t libssh2_channel_read_ex(LIBSSH2_CHANNEL *channel,
                                             int stream_id, char *buf,
@@ -781,9 +869,14 @@ LIBSSH2_API int libssh2_channel_close(LIBSSH2_CHANNEL *channel);
 LIBSSH2_API int libssh2_channel_wait_closed(LIBSSH2_CHANNEL *channel);
 LIBSSH2_API int libssh2_channel_free(LIBSSH2_CHANNEL *channel);
 
+/* libssh2_scp_recv is DEPRECATED, do not use! */
 LIBSSH2_API LIBSSH2_CHANNEL *libssh2_scp_recv(LIBSSH2_SESSION *session,
                                               const char *path,
                                               struct stat *sb);
+/* Use libssh2_scp_recv2 for large (> 2GB) file support on windows */
+LIBSSH2_API LIBSSH2_CHANNEL *libssh2_scp_recv2(LIBSSH2_SESSION *session,
+                                               const char *path,
+                                               libssh2_struct_stat *sb);
 LIBSSH2_API LIBSSH2_CHANNEL *libssh2_scp_send_ex(LIBSSH2_SESSION *session,
                                                  const char *path, int mode,
                                                  size_t size, long mtime,
@@ -856,11 +949,12 @@ libssh2_knownhost_init(LIBSSH2_SESSION *session);
 #define LIBSSH2_KNOWNHOST_KEYENC_BASE64   (2<<16)
 
 /* type of key (2 bits) */
-#define LIBSSH2_KNOWNHOST_KEY_MASK     (3<<18)
+#define LIBSSH2_KNOWNHOST_KEY_MASK     (7<<18)
 #define LIBSSH2_KNOWNHOST_KEY_SHIFT    18
 #define LIBSSH2_KNOWNHOST_KEY_RSA1     (1<<18)
 #define LIBSSH2_KNOWNHOST_KEY_SSHRSA   (2<<18)
 #define LIBSSH2_KNOWNHOST_KEY_SSHDSS   (3<<18)
+#define LIBSSH2_KNOWNHOST_KEY_UNKNOWN  (7<<18)
 
 LIBSSH2_API int
 libssh2_knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
diff --git a/pgadmin/include/libssh2/libssh2_priv.h b/pgadmin/include/libssh2/libssh2_priv.h
index 4ec9f73..1023943 100644
--- a/pgadmin/include/libssh2/libssh2_priv.h
+++ b/pgadmin/include/libssh2/libssh2_priv.h
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2008, 2010, Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2009-2011 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * Copyright (c) 2010 Simon Josefsson
  * All rights reserved.
  *
@@ -108,6 +108,11 @@
 #define TRUE 1
 #endif
 
+#ifdef _MSC_VER
+/* "inline" keyword is valid only with C++ engine! */
+#define inline __inline
+#endif
+
 /* Provide iovec / writev on WIN32 platform. */
 #ifdef WIN32
 
@@ -116,8 +121,6 @@ struct iovec {
     void * iov_base;
 };
 
-#define inline __inline
-
 static inline int writev(int sock, struct iovec *iov, int nvecs)
 {
     DWORD ret;
@@ -134,14 +137,8 @@ static inline int writev(int sock, struct iovec *iov, int nvecs)
 #ifdef HAVE_WINSOCK2_H
 
 #include <winsock2.h>
-#include <mswsock.h>
 #include <ws2tcpip.h>
 
-#ifdef _MSC_VER
-/* "inline" keyword is valid only with C++ engine! */
-#define inline __inline
-#endif
-
 #endif
 
 /* RFC4253 section 6.1 Maximum Packet Length says:
@@ -152,9 +149,11 @@ static inline int writev(int sock, struct iovec *iov, int nvecs)
  * padding length, payload, padding, and MAC.)."
  */
 #define MAX_SSH_PACKET_LEN 35000
+#define MAX_SHA_DIGEST_LEN SHA256_DIGEST_LENGTH
 
 #define LIBSSH2_ALLOC(session, count) \
   session->alloc((count), &(session)->abstract)
+#define LIBSSH2_CALLOC(session, count) _libssh2_calloc(session, count)
 #define LIBSSH2_REALLOC(session, ptr, count) \
  ((ptr) ? session->realloc((ptr), (count), &(session)->abstract) : \
  session->alloc((count), &(session)->abstract))
@@ -217,7 +216,8 @@ typedef enum
     libssh2_NB_state_jump2,
     libssh2_NB_state_jump3,
     libssh2_NB_state_jump4,
-    libssh2_NB_state_jump5
+    libssh2_NB_state_jump5,
+    libssh2_NB_state_end
 } libssh2_nonblocking_states;
 
 typedef struct packet_require_state_t
@@ -231,13 +231,13 @@ typedef struct packet_requirev_state_t
     time_t start;
 } packet_requirev_state_t;
 
-typedef struct kmdhgGPsha1kex_state_t
+typedef struct kmdhgGPshakex_state_t
 {
     libssh2_nonblocking_states state;
     unsigned char *e_packet;
     unsigned char *s_packet;
     unsigned char *tmp;
-    unsigned char h_sig_comp[SHA_DIGEST_LENGTH];
+    unsigned char h_sig_comp[MAX_SHA_DIGEST_LEN];
     unsigned char c;
     size_t e_packet_len;
     size_t s_packet_len;
@@ -254,16 +254,16 @@ typedef struct kmdhgGPsha1kex_state_t
     size_t f_value_len;
     size_t k_value_len;
     size_t h_sig_len;
-    libssh2_sha1_ctx exchange_hash;
+    void *exchange_hash;
     packet_require_state_t req_state;
     libssh2_nonblocking_states burn_state;
-} kmdhgGPsha1kex_state_t;
+} kmdhgGPshakex_state_t;
 
 typedef struct key_exchange_state_low_t
 {
     libssh2_nonblocking_states state;
     packet_require_state_t req_state;
-    kmdhgGPsha1kex_state_t exchange_state;
+    kmdhgGPshakex_state_t exchange_state;
     _libssh2_bn *p;             /* SSH2 defined value (p_value) */
     _libssh2_bn *g;             /* SSH2 defined value (2) */
     unsigned char request[13];
@@ -357,6 +357,8 @@ struct _LIBSSH2_CHANNEL
     libssh2_channel_data local, remote;
     /* Amount of bytes to be refunded to receive window (but not yet sent) */
     uint32_t adjust_queue;
+    /* Data immediately available for reading */
+    uint32_t read_avail;
 
     LIBSSH2_SESSION *session;
 
@@ -575,7 +577,7 @@ struct _LIBSSH2_SESSION
 
     /* Agreed Key Exchange Method */
     const LIBSSH2_KEX_METHOD *kex;
-    int burn_optimistic_kexinit:1;
+    unsigned int burn_optimistic_kexinit:1;
 
     unsigned char *session_id;
     uint32_t session_id_len;
@@ -600,6 +602,7 @@ struct _LIBSSH2_SESSION
     int server_hostkey_md5_valid;
 #endif                          /* ! LIBSSH2_MD5 */
     unsigned char server_hostkey_sha1[SHA_DIGEST_LENGTH];
+    int server_hostkey_sha1_valid;
 
     /* (remote as source of data -- packet_read ) */
     libssh2_endpoint_data remote;
@@ -628,6 +631,7 @@ struct _LIBSSH2_SESSION
     /* Error tracking */
     const char *err_msg;
     int err_code;
+    int err_flags;
 
     /* struct members for packet-level reading */
     struct transportpacket packet;
@@ -778,7 +782,7 @@ struct _LIBSSH2_SESSION
     int sftpInit_sent; /* number of bytes from the buffer that have been
                           sent */
 
-    /* State variables used in libssh2_scp_recv() */
+    /* State variables used in libssh2_scp_recv() / libssh_scp_recv2() */
     libssh2_nonblocking_states scpRecv_state;
     unsigned char *scpRecv_command;
     size_t scpRecv_command_len;
@@ -789,6 +793,9 @@ struct _LIBSSH2_SESSION
     /* we have the type and we can parse such numbers */
     long long scpRecv_size;
 #define scpsize_strtol strtoll
+#elif defined(HAVE_STRTOI64)
+    __int64 scpRecv_size;
+#define scpsize_strtol _strtoi64
 #else
     long scpRecv_size;
 #define scpsize_strtol strtol
@@ -854,6 +861,9 @@ struct _LIBSSH2_HOSTKEY_METHOD
                  size_t hostkey_data_len, void **abstract);
     int (*initPEM) (LIBSSH2_SESSION * session, const char *privkeyfile,
                     unsigned const char *passphrase, void **abstract);
+    int (*initPEMFromMemory) (LIBSSH2_SESSION * session,
+                              const char *privkeyfiledata, size_t privkeyfiledata_len,
+                              unsigned const char *passphrase, void **abstract);
     int (*sig_verify) (LIBSSH2_SESSION * session, const unsigned char *sig,
                        size_t sig_len, const unsigned char *m,
                        size_t m_len, void **abstract);
@@ -923,6 +933,9 @@ void _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format,
 static inline void
 _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
 {
+    (void)session;
+    (void)context;
+    (void)format;
 }
 #endif
 #endif
@@ -938,6 +951,10 @@ _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
 /* Something very bad is going on */
 #define LIBSSH2_MAC_INVALID                     -1
 
+/* Flags for _libssh2_error_flags */
+/* Error message is allocated on the heap */
+#define LIBSSH2_ERR_FLAG_DUP                     1
+
 /* SSH Packet Types -- Defined by internet draft */
 /* Transport Layer */
 #define SSH_MSG_DISCONNECT                          1
@@ -954,7 +971,7 @@ _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
 #define SSH_MSG_KEXDH_INIT                          30
 #define SSH_MSG_KEXDH_REPLY                         31
 
-/* diffie-hellman-group-exchange-sha1 */
+/* diffie-hellman-group-exchange-sha1 and diffie-hellman-group-exchange-sha256 */
 #define SSH_MSG_KEX_DH_GEX_REQUEST_OLD              30
 #define SSH_MSG_KEX_DH_GEX_REQUEST                  34
 #define SSH_MSG_KEX_DH_GEX_GROUP                    31
@@ -1020,6 +1037,11 @@ int _libssh2_pem_parse(LIBSSH2_SESSION * session,
                        const char *headerbegin,
                        const char *headerend,
                        FILE * fp, unsigned char **data, unsigned int *datalen);
+int _libssh2_pem_parse_memory(LIBSSH2_SESSION * session,
+                              const char *headerbegin,
+                              const char *headerend,
+                              const char *filedata, size_t filedata_len,
+                              unsigned char **data, unsigned int *datalen);
 int _libssh2_pem_decode_sequence(unsigned char **data, unsigned int *datalen);
 int _libssh2_pem_decode_integer(unsigned char **data, unsigned int *datalen,
                                 unsigned char **i, unsigned int *ilen);
diff --git a/pgadmin/include/libssh2/libssh2_sftp.h b/pgadmin/include/libssh2/libssh2_sftp.h
index 74884fb..677faf2 100644
--- a/pgadmin/include/libssh2/libssh2_sftp.h
+++ b/pgadmin/include/libssh2/libssh2_sftp.h
@@ -247,6 +247,7 @@ LIBSSH2_API int libssh2_sftp_readdir_ex(LIBSSH2_SFTP_HANDLE *handle, \
 
 LIBSSH2_API ssize_t libssh2_sftp_write(LIBSSH2_SFTP_HANDLE *handle,
                                        const char *buffer, size_t count);
+LIBSSH2_API int libssh2_sftp_fsync(LIBSSH2_SFTP_HANDLE *handle);
 
 LIBSSH2_API int libssh2_sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle);
 #define libssh2_sftp_close(handle) libssh2_sftp_close_handle(handle)
diff --git a/pgadmin/include/libssh2/misc.h b/pgadmin/include/libssh2/misc.h
index e25248d..54ae546 100644
--- a/pgadmin/include/libssh2/misc.h
+++ b/pgadmin/include/libssh2/misc.h
@@ -1,6 +1,6 @@
 #ifndef __LIBSSH2_MISC_H
 #define __LIBSSH2_MISC_H
-/* Copyright (c) 2009-2011 by Daniel Stenberg
+/* Copyright (c) 2009-2014 by Daniel Stenberg
  *
  * All rights reserved.
  *
@@ -49,6 +49,7 @@ struct list_node {
     struct list_head *head;
 };
 
+int _libssh2_error_flags(LIBSSH2_SESSION* session, int errcode, const char* errmsg, int errflags);
 int _libssh2_error(LIBSSH2_SESSION* session, int errcode, const char* errmsg);
 
 void _libssh2_list_init(struct list_head *head);
@@ -77,6 +78,7 @@ libssh2_uint64_t _libssh2_ntohu64(const unsigned char *buf);
 void _libssh2_htonu32(unsigned char *buf, uint32_t val);
 void _libssh2_store_u32(unsigned char **buf, uint32_t value);
 void _libssh2_store_str(unsigned char **buf, const char *str, size_t len);
+void *_libssh2_calloc(LIBSSH2_SESSION* session, size_t size);
 
 #if defined(LIBSSH2_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
 /* provide a private one */
diff --git a/pgadmin/include/libssh2/openssl.h b/pgadmin/include/libssh2/openssl.h
index 6f21a1a..82d09f6 100644
--- a/pgadmin/include/libssh2/openssl.h
+++ b/pgadmin/include/libssh2/openssl.h
@@ -39,6 +39,11 @@
 
 #include <openssl/opensslconf.h>
 #include <openssl/sha.h>
+#include <openssl/rsa.h>
+#include <openssl/engine.h>
+#ifndef OPENSSL_NO_DSA
+#include <openssl/dsa.h>
+#endif
 #ifndef OPENSSL_NO_MD5
 #include <openssl/md5.h>
 #endif
@@ -72,6 +77,9 @@
 # define LIBSSH2_HMAC_RIPEMD 1
 #endif
 
+#define LIBSSH2_HMAC_SHA256 1
+#define LIBSSH2_HMAC_SHA512 1
+
 #if OPENSSL_VERSION_NUMBER >= 0x00907000L && !defined(OPENSSL_NO_AES)
 # define LIBSSH2_AES_CTR 1
 # define LIBSSH2_AES 1
@@ -80,7 +88,7 @@
 # define LIBSSH2_AES 0
 #endif
 
-#ifdef OPENSSL_NO_BLOWFISH
+#ifdef OPENSSL_NO_BF
 # define LIBSSH2_BLOWFISH 0
 #else
 # define LIBSSH2_BLOWFISH 1
@@ -107,33 +115,59 @@
 #define _libssh2_random(buf, len) RAND_bytes ((buf), (len))
 
 #define libssh2_sha1_ctx EVP_MD_CTX
-#define libssh2_sha1_init(ctx) EVP_DigestInit(ctx, EVP_get_digestbyname("sha1"))
+
+/* returns 0 in case of failure */
+int _libssh2_sha1_init(libssh2_sha1_ctx *ctx);
+#define libssh2_sha1_init(x) _libssh2_sha1_init(x)
 #define libssh2_sha1_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len)
 #define libssh2_sha1_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL)
-void libssh2_sha1(const unsigned char *message, unsigned long len, unsigned char *out);
+int _libssh2_sha1(const unsigned char *message, unsigned long len,
+                  unsigned char *out);
+#define libssh2_sha1(x,y,z) _libssh2_sha1(x,y,z)
 
-#define libssh2_md5_ctx EVP_MD_CTX
+#define libssh2_sha256_ctx EVP_MD_CTX
 
 /* returns 0 in case of failure */
-#define libssh2_md5_init(ctx) EVP_DigestInit(ctx, EVP_get_digestbyname("md5"))
+int _libssh2_sha256_init(libssh2_sha256_ctx *ctx);
+#define libssh2_sha256_init(x) _libssh2_sha256_init(x)
+#define libssh2_sha256_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len)
+#define libssh2_sha256_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL)
+int _libssh2_sha256(const unsigned char *message, unsigned long len,
+                  unsigned char *out);
+#define libssh2_sha256(x,y,z) _libssh2_sha256(x,y,z)
 
+#define libssh2_md5_ctx EVP_MD_CTX
+
+/* returns 0 in case of failure */
+int _libssh2_md5_init(libssh2_md5_ctx *);
+#define libssh2_md5_init(x) _libssh2_md5_init(x)
 #define libssh2_md5_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len)
 #define libssh2_md5_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL)
-void libssh2_md5(const unsigned char *message, unsigned long len, unsigned char *out);
 
 #define libssh2_hmac_ctx HMAC_CTX
+#define libssh2_hmac_ctx_init(ctx) \
+  HMAC_CTX_init(&ctx)
 #define libssh2_hmac_sha1_init(ctx, key, keylen) \
-  HMAC_Init(ctx, key, keylen, EVP_sha1())
+  HMAC_Init_ex(ctx, key, keylen, EVP_sha1(), NULL)
 #define libssh2_hmac_md5_init(ctx, key, keylen) \
-  HMAC_Init(ctx, key, keylen, EVP_md5())
+  HMAC_Init_ex(ctx, key, keylen, EVP_md5(), NULL)
 #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \
-  HMAC_Init(ctx, key, keylen, EVP_ripemd160())
+  HMAC_Init_ex(ctx, key, keylen, EVP_ripemd160(), NULL)
+#define libssh2_hmac_sha256_init(ctx, key, keylen) \
+  HMAC_Init_ex(ctx, key, keylen, EVP_sha256(), NULL)
+#define libssh2_hmac_sha512_init(ctx, key, keylen) \
+  HMAC_Init_ex(ctx, key, keylen, EVP_sha512(), NULL)
+
 #define libssh2_hmac_update(ctx, data, datalen) \
   HMAC_Update(&(ctx), data, datalen)
 #define libssh2_hmac_final(ctx, data) HMAC_Final(&(ctx), data, NULL)
 #define libssh2_hmac_cleanup(ctx) HMAC_cleanup(ctx)
 
-#define libssh2_crypto_init() OpenSSL_add_all_algorithms()
+#define libssh2_crypto_init() \
+  OpenSSL_add_all_algorithms(); \
+  ENGINE_load_builtin_engines(); \
+  ENGINE_register_all_complete()
+
 #define libssh2_crypto_exit()
 
 #define libssh2_rsa_ctx RSA
@@ -172,6 +206,7 @@ void libssh2_md5(const unsigned char *message, unsigned long len, unsigned char
 #define _libssh2_bn_ctx_new() BN_CTX_new()
 #define _libssh2_bn_ctx_free(bnctx) BN_CTX_free(bnctx)
 #define _libssh2_bn_init() BN_new()
+#define _libssh2_bn_init_from_bin() _libssh2_bn_init()
 #define _libssh2_bn_rand(bn, bits, top, bottom) BN_rand(bn, bits, top, bottom)
 #define _libssh2_bn_mod_exp(r, a, p, m, ctx) BN_mod_exp(r, a, p, m, ctx)
 #define _libssh2_bn_set_word(bn, val) BN_set_word(bn, val)
diff --git a/pgadmin/include/libssh2/sftp.h b/pgadmin/include/libssh2/sftp.h
index 55bdb46..b553b16 100644
--- a/pgadmin/include/libssh2/sftp.h
+++ b/pgadmin/include/libssh2/sftp.h
@@ -48,7 +48,7 @@
 /* MAX_SFTP_READ_SIZE is how much data is asked for at max in each FXP_READ
  * packets.
  */
-#define MAX_SFTP_READ_SIZE 2000
+#define MAX_SFTP_READ_SIZE 30000
 
 struct sftp_pipeline_chunk {
     struct list_node node;
@@ -175,6 +175,11 @@ struct _LIBSSH2_SFTP
     /* State variable used in sftp_write() */
     libssh2_nonblocking_states write_state;
 
+    /* State variables used in sftp_fsync() */
+    libssh2_nonblocking_states fsync_state;
+    unsigned char *fsync_packet;
+    uint32_t fsync_request_id;
+
     /* State variables used in libssh2_sftp_readdir() */
     libssh2_nonblocking_states readdir_state;
     unsigned char *readdir_packet;
diff --git a/pgadmin/include/utils/sshTunnel.h b/pgadmin/include/utils/sshTunnel.h
index c8557ee..d1e9aa4 100644
--- a/pgadmin/include/utils/sshTunnel.h
+++ b/pgadmin/include/utils/sshTunnel.h
@@ -45,7 +45,7 @@ enum enAuthenticationMethod
 	AUTH_PUBLICKEY = 4
 };
 
-void LogSSHTunnelErrors(const wxString &msg, const int &id);
+void LogSSHTunnelErrors(const wxString &msg, const int &id, struct _LIBSSH2_SESSION *session = NULL);
 static wxMutex g_SSHThreadMutex;
 
 WX_DECLARE_HASH_SET( int, wxIntegerHash, wxIntegerEqual, subThreadSDSet);
diff --git a/pgadmin/libssh2/agent.c b/pgadmin/libssh2/agent.c
index 1c65149..b797cbd 100644
--- a/pgadmin/libssh2/agent.c
+++ b/pgadmin/libssh2/agent.c
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2009 by Daiki Ueno
- * Copyright (C) 2010 by Daniel Stenberg
+ * Copyright (C) 2010-2014 by Daniel Stenberg
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -159,6 +159,8 @@ agent_connect_unix(LIBSSH2_AGENT *agent)
 
     s_un.sun_family = AF_UNIX;
     strncpy (s_un.sun_path, path, sizeof s_un.sun_path);
+    s_un.sun_path[sizeof(s_un.sun_path)-1]=0; /* make sure there's a trailing
+                                                 zero */
     if (connect(agent->fd, (struct sockaddr*)(&s_un), sizeof s_un) != 0) {
         close (agent->fd);
         return _libssh2_error(agent->session, LIBSSH2_ERROR_AGENT_PROTOCOL,
@@ -303,6 +305,12 @@ agent_transact_pageant(LIBSSH2_AGENT *agent, agent_transaction_ctx_t transctx)
                               "failed setting up pageant filemap");
 
     p2 = p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
+    if (p == NULL || p2 == NULL) {
+        CloseHandle(filemap);
+        return _libssh2_error(agent->session, LIBSSH2_ERROR_AGENT_PROTOCOL,
+                              "failed to open pageant filemap for writing");
+    }
+
     _libssh2_store_str(&p2, (const char *)transctx->request,
                        transctx->request_len);
 
@@ -537,18 +545,17 @@ agent_list_identities(LIBSSH2_AGENT *agent)
         struct agent_publickey *identity;
         ssize_t comment_len;
 
-        identity = LIBSSH2_ALLOC(agent->session, sizeof *identity);
-        if (!identity) {
-            rc = LIBSSH2_ERROR_ALLOC;
-            goto error;
-        }
-
         /* Read the length of the blob */
         len -= 4;
         if (len < 0) {
             rc = LIBSSH2_ERROR_AGENT_PROTOCOL;
             goto error;
         }
+        identity = LIBSSH2_ALLOC(agent->session, sizeof *identity);
+        if (!identity) {
+            rc = LIBSSH2_ERROR_ALLOC;
+            goto error;
+        }
         identity->external.blob_len = _libssh2_ntohu32(s);
         s += 4;
 
@@ -556,12 +563,15 @@ agent_list_identities(LIBSSH2_AGENT *agent)
         len -= identity->external.blob_len;
         if (len < 0) {
             rc = LIBSSH2_ERROR_AGENT_PROTOCOL;
+            LIBSSH2_FREE(agent->session, identity);
             goto error;
         }
+
         identity->external.blob = LIBSSH2_ALLOC(agent->session,
                                                 identity->external.blob_len);
         if (!identity->external.blob) {
             rc = LIBSSH2_ERROR_ALLOC;
+            LIBSSH2_FREE(agent->session, identity);
             goto error;
         }
         memcpy(identity->external.blob, s, identity->external.blob_len);
@@ -571,6 +581,8 @@ agent_list_identities(LIBSSH2_AGENT *agent)
         len -= 4;
         if (len < 0) {
             rc = LIBSSH2_ERROR_AGENT_PROTOCOL;
+            LIBSSH2_FREE(agent->session, identity->external.blob);
+            LIBSSH2_FREE(agent->session, identity);
             goto error;
         }
         comment_len = _libssh2_ntohu32(s);
@@ -580,12 +592,17 @@ agent_list_identities(LIBSSH2_AGENT *agent)
         len -= comment_len;
         if (len < 0) {
             rc = LIBSSH2_ERROR_AGENT_PROTOCOL;
+            LIBSSH2_FREE(agent->session, identity->external.blob);
+            LIBSSH2_FREE(agent->session, identity);
             goto error;
         }
+
         identity->external.comment = LIBSSH2_ALLOC(agent->session,
                                                    comment_len + 1);
         if (!identity->external.comment) {
             rc = LIBSSH2_ERROR_ALLOC;
+            LIBSSH2_FREE(agent->session, identity->external.blob);
+            LIBSSH2_FREE(agent->session, identity);
             goto error;
         }
         identity->external.comment[comment_len] = '\0';
@@ -645,13 +662,13 @@ libssh2_agent_init(LIBSSH2_SESSION *session)
 {
     LIBSSH2_AGENT *agent;
 
-    agent = LIBSSH2_ALLOC(session, sizeof *agent);
+    agent = LIBSSH2_CALLOC(session, sizeof *agent);
     if (!agent) {
         _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                        "Unable to allocate space for agent connection");
         return NULL;
     }
-    memset(agent, 0, sizeof *agent);
+    agent->fd = LIBSSH2_INVALID_SOCKET;
     agent->session = session;
     _libssh2_list_init(&agent->head);
 
@@ -698,7 +715,7 @@ libssh2_agent_list_identities(LIBSSH2_AGENT *agent)
  * libssh2_agent_get_identity()
  *
  * Traverse the internal list of public keys. Pass NULL to 'prev' to get
- * the first one. Or pass a poiner to the previously returned one to get the
+ * the first one. Or pass a pointer to the previously returned one to get the
  * next.
  *
  * Returns:
diff --git a/pgadmin/libssh2/channel.c b/pgadmin/libssh2/channel.c
index 4f41e1f..32d914d 100644
--- a/pgadmin/libssh2/channel.c
+++ b/pgadmin/libssh2/channel.c
@@ -1,6 +1,6 @@
 /* Copyright (c) 2004-2007 Sara Golemon <sarag@libssh2.org>
  * Copyright (c) 2005 Mikhail Gusarov <dottedmag@dottedmag.net>
- * Copyright (c) 2008-2011 by Daniel Stenberg
+ * Copyright (c) 2008-2014 by Daniel Stenberg
  *
  * All rights reserved.
  *
@@ -158,14 +158,12 @@ _libssh2_channel_open(LIBSSH2_SESSION * session, const char *channel_type,
                        "Opening Channel - win %d pack %d", window_size,
                        packet_size);
         session->open_channel =
-            LIBSSH2_ALLOC(session, sizeof(LIBSSH2_CHANNEL));
+            LIBSSH2_CALLOC(session, sizeof(LIBSSH2_CHANNEL));
         if (!session->open_channel) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                            "Unable to allocate space for channel data");
             return NULL;
         }
-        memset(session->open_channel, 0, sizeof(LIBSSH2_CHANNEL));
-
         session->open_channel->channel_type_len = channel_type_len;
         session->open_channel->channel_type =
             LIBSSH2_ALLOC(session, channel_type_len);
@@ -268,8 +266,28 @@ _libssh2_channel_open(LIBSSH2_SESSION * session, const char *channel_type,
         }
 
         if (session->open_data[0] == SSH_MSG_CHANNEL_OPEN_FAILURE) {
-            _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE,
-                           "Channel open failure");
+            unsigned int reason_code = _libssh2_ntohu32(session->open_data + 5);
+            switch (reason_code) {
+            case SSH_OPEN_ADMINISTRATIVELY_PROHIBITED:
+                _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE,
+                               "Channel open failure (admininstratively prohibited)");
+                break;
+            case SSH_OPEN_CONNECT_FAILED:
+                _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE,
+                               "Channel open failure (connect failed)");
+                break;
+            case SSH_OPEN_UNKNOWN_CHANNELTYPE:
+                _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE,
+                               "Channel open failure (unknown channel type)");
+                break;
+            case SSH_OPEN_RESOURCE_SHORTAGE:
+                _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE,
+                               "Channel open failure (resource shortage)");
+                break;
+            default:
+                _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE,
+                               "Channel open failure");
+            }
         }
     }
 
@@ -451,7 +469,7 @@ channel_forward_listen(LIBSSH2_SESSION * session, const char *host,
             LIBSSH2_ALLOC(session, session->fwdLstn_packet_len);
         if (!session->fwdLstn_packet) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
-                           "Unable to allocate memeory for setenv packet");
+                           "Unable to allocate memory for setenv packet");
             return NULL;
         }
 
@@ -509,12 +527,11 @@ channel_forward_listen(LIBSSH2_SESSION * session, const char *host,
         if (data[0] == SSH_MSG_REQUEST_SUCCESS) {
             LIBSSH2_LISTENER *listener;
 
-            listener = LIBSSH2_ALLOC(session, sizeof(LIBSSH2_LISTENER));
+            listener = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_LISTENER));
             if (!listener)
                 _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                "Unable to allocate memory for listener queue");
             else {
-                memset(listener, 0, sizeof(LIBSSH2_LISTENER));
                 listener->host =
                     LIBSSH2_ALLOC(session, session->fwdLstn_host_len + 1);
                 if (!listener->host) {
@@ -525,8 +542,7 @@ channel_forward_listen(LIBSSH2_SESSION * session, const char *host,
                 }
                 else {
                     listener->session = session;
-                    memcpy(listener->host, host ? host : "0.0.0.0",
-                           session->fwdLstn_host_len);
+                    memcpy(listener->host, host, session->fwdLstn_host_len);
                     listener->host[session->fwdLstn_host_len] = 0;
                     if (data_len >= 5 && !port) {
                         listener->port = _libssh2_ntohu32(data + 1);
@@ -606,6 +622,7 @@ int _libssh2_channel_forward_cancel(LIBSSH2_LISTENER *listener)
     size_t packet_len =
         host_len + 14 + sizeof("cancel-tcpip-forward") - 1;
     int rc;
+    int retcode = 0;
 
     if (listener->chanFwdCncl_state == libssh2_NB_state_idle) {
         _libssh2_debug(session, LIBSSH2_TRACE_CONN,
@@ -615,7 +632,7 @@ int _libssh2_channel_forward_cancel(LIBSSH2_LISTENER *listener)
         s = packet = LIBSSH2_ALLOC(session, packet_len);
         if (!packet) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
-                           "Unable to allocate memeory for setenv packet");
+                           "Unable to allocate memory for setenv packet");
             return LIBSSH2_ERROR_ALLOC;
         }
 
@@ -644,9 +661,11 @@ int _libssh2_channel_forward_cancel(LIBSSH2_LISTENER *listener)
             _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
                            "Unable to send global-request packet for forward "
                            "listen request");
-            LIBSSH2_FREE(session, packet);
-            listener->chanFwdCncl_state = libssh2_NB_state_idle;
-            return LIBSSH2_ERROR_SOCKET_SEND;
+            /* set the state to something we don't check for, for the
+               unfortunate situation where we get an EAGAIN further down
+               when trying to bail out due to errors! */
+            listener->chanFwdCncl_state = libssh2_NB_state_sent;
+            retcode = LIBSSH2_ERROR_SOCKET_SEND;
         }
         LIBSSH2_FREE(session, packet);
 
@@ -670,9 +689,7 @@ int _libssh2_channel_forward_cancel(LIBSSH2_LISTENER *listener)
 
     LIBSSH2_FREE(session, listener);
 
-    listener->chanFwdCncl_state = libssh2_NB_state_idle;
-
-    return 0;
+    return retcode;
 }
 
 /*
@@ -787,7 +804,7 @@ static int channel_setenv(LIBSSH2_CHANNEL *channel,
             LIBSSH2_ALLOC(session, channel->setenv_packet_len);
         if (!channel->setenv_packet) {
             return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
-                                  "Unable to allocate memeory "
+                                  "Unable to allocate memory "
                                   "for setenv packet");
         }
 
@@ -1235,6 +1252,11 @@ _libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,
         { SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };
     int rc;
 
+    if (channel->process_state == libssh2_NB_state_end) {
+        return _libssh2_error(session, LIBSSH2_ERROR_BAD_USE,
+                              "Channel can not be reused");
+    }
+
     if (channel->process_state == libssh2_NB_state_idle) {
         /* 10 = packet_type(1) + channel(4) + request_len(4) + want_reply(1) */
         channel->process_packet_len = request_len + 10;
@@ -1281,7 +1303,7 @@ _libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,
         else if (rc) {
             LIBSSH2_FREE(session, channel->process_packet);
             channel->process_packet = NULL;
-            channel->process_state = libssh2_NB_state_idle;
+            channel->process_state = libssh2_NB_state_end;
             return _libssh2_error(session, rc,
                                   "Unable to send channel request");
         }
@@ -1303,14 +1325,14 @@ _libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,
         if (rc == LIBSSH2_ERROR_EAGAIN) {
             return rc;
         } else if (rc) {
-            channel->process_state = libssh2_NB_state_idle;
+            channel->process_state = libssh2_NB_state_end;
             return _libssh2_error(session, rc,
                                   "Failed waiting for channel success");
         }
 
         code = data[0];
         LIBSSH2_FREE(session, data);
-        channel->process_state = libssh2_NB_state_idle;
+        channel->process_state = libssh2_NB_state_end;
 
         if (code == SSH_MSG_CHANNEL_SUCCESS)
             return 0;
@@ -1413,6 +1435,9 @@ _libssh2_channel_flush(LIBSSH2_CHANNEL *channel, int streamid)
         channel->flush_state = libssh2_NB_state_created;
     }
 
+    channel->read_avail -= channel->flush_flush_bytes;
+    channel->remote.window_size -= channel->flush_flush_bytes;
+
     if (channel->flush_refund_bytes) {
         int rc;
 
@@ -1543,6 +1568,9 @@ _libssh2_channel_receive_window_adjust(LIBSSH2_CHANNEL * channel,
 {
     int rc;
 
+    if(store)
+        *store = channel->remote.window_size;
+
     if (channel->adjust_state == libssh2_NB_state_idle) {
         if (!force
             && (adjustment + channel->adjust_queue <
@@ -1552,14 +1580,10 @@ _libssh2_channel_receive_window_adjust(LIBSSH2_CHANNEL * channel,
                            "for channel %lu/%lu",
                            adjustment, channel->local.id, channel->remote.id);
             channel->adjust_queue += adjustment;
-            if(store)
-                *store = channel->remote.window_size;
             return 0;
         }
 
         if (!adjustment && !channel->adjust_queue) {
-            if(store)
-                *store = channel->remote.window_size;
             return 0;
         }
 
@@ -1597,8 +1621,6 @@ _libssh2_channel_receive_window_adjust(LIBSSH2_CHANNEL * channel,
 
     channel->adjust_state = libssh2_NB_state_idle;
 
-    if(store)
-        *store = channel->remote.window_size;
     return 0;
 }
 
@@ -1624,7 +1646,7 @@ libssh2_channel_receive_window_adjust(LIBSSH2_CHANNEL *channel,
     int rc;
 
     if(!channel)
-        return LIBSSH2_ERROR_BAD_USE;
+        return (unsigned long)LIBSSH2_ERROR_BAD_USE;
 
     BLOCK_ADJUST(rc, channel->session,
                  _libssh2_channel_receive_window_adjust(channel, adj,
@@ -1671,7 +1693,7 @@ _libssh2_channel_extended_data(LIBSSH2_CHANNEL *channel, int ignore_mode)
                        "Setting channel %lu/%lu handle_extended_data"
                        " mode to %d",
                        channel->local.id, channel->remote.id, ignore_mode);
-        channel->remote.extended_data_ignore_mode = ignore_mode;
+        channel->remote.extended_data_ignore_mode = (char)ignore_mode;
 
         channel->extData2_state = libssh2_NB_state_created;
     }
@@ -1750,22 +1772,36 @@ ssize_t _libssh2_channel_read(LIBSSH2_CHANNEL *channel, int stream_id,
     LIBSSH2_PACKET *read_packet;
     LIBSSH2_PACKET *read_next;
 
-    if (channel->read_state == libssh2_NB_state_idle) {
-        _libssh2_debug(session, LIBSSH2_TRACE_CONN,
-                       "channel_read() wants %d bytes from channel %lu/%lu "
-                       "stream #%d",
-                       (int) buflen, channel->local.id, channel->remote.id,
-                       stream_id);
-        channel->read_state = libssh2_NB_state_created;
-    }
+    _libssh2_debug(session, LIBSSH2_TRACE_CONN,
+                   "channel_read() wants %d bytes from channel %lu/%lu "
+                   "stream #%d",
+                   (int) buflen, channel->local.id, channel->remote.id,
+                   stream_id);
+
+    /* expand the receiving window first if it has become too narrow */
+    if( (channel->read_state == libssh2_NB_state_jump1) ||
+        (channel->remote.window_size < channel->remote.window_size_initial / 4 * 3 + buflen) ) {
+
+        uint32_t adjustment = channel->remote.window_size_initial + buflen - channel->remote.window_size;
+        if (adjustment < LIBSSH2_CHANNEL_MINADJUST)
+            adjustment = LIBSSH2_CHANNEL_MINADJUST;
+
+        /* the actual window adjusting may not finish so we need to deal with
+           this special state here */
+        channel->read_state = libssh2_NB_state_jump1;
+        rc = _libssh2_channel_receive_window_adjust(channel, adjustment,
+                                                    0, NULL);
+        if (rc)
+            return rc;
 
-    rc = 1; /* set to >0 to let the while loop start */
+        channel->read_state = libssh2_NB_state_idle;
+    }
 
-    /* Process all pending incoming packets in all states in order to "even
-       out" the network readings. Tests prove that this way produces faster
-       transfers. */
-    while (rc > 0)
+    /* Process all pending incoming packets. Tests prove that this way
+       produces faster transfers. */
+    do {
         rc = _libssh2_transport_read(session);
+    } while (rc > 0);
 
     if ((rc < 0) && (rc != LIBSSH2_ERROR_EAGAIN))
         return _libssh2_error(session, rc, "transport read");
@@ -1847,8 +1883,6 @@ ssize_t _libssh2_channel_read(LIBSSH2_CHANNEL *channel, int stream_id,
     }
 
     if (!bytes_read) {
-        channel->read_state = libssh2_NB_state_idle;
-
         /* If the channel is already at EOF or even closed, we need to signal
            that back. We may have gotten that info while draining the incoming
            transport layer until EAGAIN so we must not be fooled by that
@@ -1861,11 +1895,9 @@ ssize_t _libssh2_channel_read(LIBSSH2_CHANNEL *channel, int stream_id,
         /* if the transport layer said EAGAIN then we say so as well */
         return _libssh2_error(session, rc, "would block");
     }
-    else
-        /* make sure we remain in the created state to focus on emptying the
-           data we already have in the packet brigade before we try to read
-           more off the network again */
-        channel->read_state = libssh2_NB_state_created;
+
+    channel->read_avail -= bytes_read;
+    channel->remote.window_size -= bytes_read;
 
     return bytes_read;
 }
@@ -2009,12 +2041,22 @@ _libssh2_channel_write(LIBSSH2_CHANNEL *channel, int stream_id,
             rc = _libssh2_transport_read(session);
         while (rc > 0);
 
-        if((rc < 0) && (rc != LIBSSH2_ERROR_EAGAIN))
-            return rc;
+        if((rc < 0) && (rc != LIBSSH2_ERROR_EAGAIN)) {
+            return _libssh2_error(channel->session, rc,
+                                  "Failure while draining incoming flow");
+        }
 
-        if(channel->local.window_size <= 0)
+        if(channel->local.window_size <= 0) {
             /* there's no room for data so we stop */
+
+            /* Waiting on the socket to be writable would be wrong because we
+             * would be back here immediately, but a readable socket might
+             * herald an incoming window adjustment.
+             */
+            session->socket_block_directions = LIBSSH2_SESSION_BLOCK_INBOUND;
+
             return (rc==LIBSSH2_ERROR_EAGAIN?rc:0);
+        }
 
         channel->write_bufwrite = buflen;
 
@@ -2251,7 +2293,6 @@ int _libssh2_channel_close(LIBSSH2_CHANNEL * channel)
 {
     LIBSSH2_SESSION *session = channel->session;
     int rc = 0;
-    int retcode;
 
     if (channel->local.close) {
         /* Already closed, act like we sent another close,
@@ -2260,9 +2301,15 @@ int _libssh2_channel_close(LIBSSH2_CHANNEL * channel)
         return 0;
     }
 
-    if (!channel->local.eof)
-        if ((retcode = channel_send_eof(channel)))
-            return retcode;
+    if (!channel->local.eof) {
+        if ((rc = channel_send_eof(channel))) {
+            if (rc == LIBSSH2_ERROR_EAGAIN) {
+                return rc;
+            }
+            _libssh2_error(session, rc,
+                "Unable to send EOF, but closing channel anyway");
+        }
+    }
 
     /* ignore if we have received a remote eof or not, as it is now too
        late for us to wait for it. Continue closing! */
@@ -2278,19 +2325,22 @@ int _libssh2_channel_close(LIBSSH2_CHANNEL * channel)
     }
 
     if (channel->close_state == libssh2_NB_state_created) {
-        retcode = _libssh2_transport_send(session, channel->close_packet, 5,
-                                          NULL, 0);
-        if (retcode == LIBSSH2_ERROR_EAGAIN) {
+        rc = _libssh2_transport_send(session, channel->close_packet, 5,
+                                     NULL, 0);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
             _libssh2_error(session, rc,
                            "Would block sending close-channel");
-            return retcode;
-        } else if (retcode) {
-            channel->close_state = libssh2_NB_state_idle;
-            return _libssh2_error(session, retcode,
-                                  "Unable to send close-channel request");
-        }
+            return rc;
+
+        } else if (rc) {
+            _libssh2_error(session, rc,
+                           "Unable to send close-channel request, "
+                           "but closing anyway");
+            /* skip waiting for the response and fall through to
+               LIBSSH2_CHANNEL_CLOSE below */
 
-        channel->close_state = libssh2_NB_state_sent;
+        } else
+            channel->close_state = libssh2_NB_state_sent;
     }
 
     if (channel->close_state == libssh2_NB_state_sent) {
@@ -2550,7 +2600,7 @@ libssh2_channel_window_read_ex(LIBSSH2_CHANNEL *channel,
  * libssh2_channel_window_write_ex
  *
  * Check the status of the write window Returns the number of bytes which may
- * be safely writen on the channel without blocking window_size_initial (if
+ * be safely written on the channel without blocking window_size_initial (if
  * passed) will be populated with the size of the initial window as defined by
  * the channel_open request
  */
diff --git a/pgadmin/libssh2/comp.c b/pgadmin/libssh2/comp.c
index 4593ce4..4560188 100644
--- a/pgadmin/libssh2/comp.c
+++ b/pgadmin/libssh2/comp.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2007, Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2010, Daniel Stenberg <daniel@haxx.se>
+ * Copyright (c) 2010-2014, Daniel Stenberg <daniel@haxx.se>
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -141,13 +141,12 @@ comp_method_zlib_init(LIBSSH2_SESSION * session, int compr,
     z_stream *strm;
     int status;
 
-    strm = LIBSSH2_ALLOC(session, sizeof(z_stream));
+    strm = LIBSSH2_CALLOC(session, sizeof(z_stream));
     if (!strm) {
         return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                               "Unable to allocate memory for "
                               "zlib compression/decompression");
     }
-    memset(strm, 0, sizeof(z_stream));
 
     strm->opaque = (voidpf) session;
     strm->zalloc = (alloc_func) comp_method_zlib_alloc;
@@ -198,15 +197,14 @@ comp_method_zlib_comp(LIBSSH2_SESSION *session,
 
     status = deflate(strm, Z_PARTIAL_FLUSH);
 
-    if (status != Z_OK) {
-        _libssh2_debug(session, LIBSSH2_TRACE_TRANS,
-                       "unhandled zlib compression error %d", status);
-        return _libssh2_error(session, LIBSSH2_ERROR_ZLIB,
-                              "compression failure");
+    if ((status == Z_OK) && (strm->avail_out > 0)) {
+        *dest_len = out_maxlen - strm->avail_out;
+        return 0;
     }
 
-    *dest_len = out_maxlen - strm->avail_out;
-    return 0;
+    _libssh2_debug(session, LIBSSH2_TRACE_TRANS,
+                   "unhandled zlib compression error %d, avail_out", status, strm->avail_out);
+    return _libssh2_error(session, LIBSSH2_ERROR_ZLIB, "compression failure");
 }
 
 /*
@@ -226,13 +224,12 @@ comp_method_zlib_decomp(LIBSSH2_SESSION * session,
     /* A short-term alloc of a full data chunk is better than a series of
        reallocs */
     char *out;
-    int out_maxlen = 8 * src_len;
-    int limiter = 0;
+    int out_maxlen = 4 * src_len;
 
     /* If strm is null, then we have not yet been initialized. */
     if (strm == NULL)
         return _libssh2_error(session, LIBSSH2_ERROR_COMPRESS,
-                              "decompression unitilized");;
+                              "decompression uninitialized");;
 
     /* In practice they never come smaller than this */
     if (out_maxlen < 25)
@@ -252,19 +249,19 @@ comp_method_zlib_decomp(LIBSSH2_SESSION * session,
 
     /* Loop until it's all inflated or hit error */
     for (;;) {
-        int status, grow_size;
+        int status;
         size_t out_ofs;
         char *newout;
 
         status = inflate(strm, Z_PARTIAL_FLUSH);
 
         if (status == Z_OK) {
-            if (! strm->avail_in) {
-                /* status is OK and input all used so we're done */
+            if (strm->avail_out > 0)
+                /* status is OK and the output buffer has not been exhausted so we're done */
                 break;
-            }
         } else if (status == Z_BUF_ERROR) {
-            /* This is OK, just drop through to grow the buffer */
+            /* the input data has been exhausted so we are done */
+            break;
         } else {
             /* error state */
             LIBSSH2_FREE(session, out);
@@ -274,22 +271,15 @@ comp_method_zlib_decomp(LIBSSH2_SESSION * session,
                                   "decompression failure");
         }
 
-        /* If we get here we need to grow the output buffer and try again */
-        out_ofs = out_maxlen - strm->avail_out;
-        if (strm->avail_in) {
-            grow_size = strm->avail_in * 8;
-        } else {
-            /* Not sure how much to grow by */
-            grow_size = 32;
-        }
-        out_maxlen += grow_size;
-
-        if ((out_maxlen > (int) payload_limit) && limiter++) {
+        if (out_maxlen >= (int) payload_limit) {
             LIBSSH2_FREE(session, out);
             return _libssh2_error(session, LIBSSH2_ERROR_ZLIB,
                                   "Excessive growth in decompression phase");
         }
 
+        /* If we get here we need to grow the output buffer and try again */
+        out_ofs = out_maxlen - strm->avail_out;
+        out_maxlen *= 2;
         newout = LIBSSH2_REALLOC(session, out, out_maxlen);
         if (!newout) {
             LIBSSH2_FREE(session, out);
@@ -298,7 +288,7 @@ comp_method_zlib_decomp(LIBSSH2_SESSION * session,
         }
         out = newout;
         strm->next_out = (unsigned char *) out + out_ofs;
-        strm->avail_out += grow_size;
+        strm->avail_out = out_maxlen - out_ofs;
     }
 
     *dest = (unsigned char *) out;
diff --git a/pgadmin/libssh2/hostkey.c b/pgadmin/libssh2/hostkey.c
index 753563d..add4495 100644
--- a/pgadmin/libssh2/hostkey.c
+++ b/pgadmin/libssh2/hostkey.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2006, Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2009 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -131,6 +131,38 @@ hostkey_method_ssh_rsa_initPEM(LIBSSH2_SESSION * session,
 }
 
 /*
+ * hostkey_method_ssh_rsa_initPEMFromMemory
+ *
+ * Load a Private Key from a memory
+ */
+static int
+hostkey_method_ssh_rsa_initPEMFromMemory(LIBSSH2_SESSION * session,
+                                         const char *privkeyfiledata,
+                                         size_t privkeyfiledata_len,
+                                         unsigned const char *passphrase,
+                                         void **abstract)
+{
+    libssh2_rsa_ctx *rsactx;
+    int ret;
+
+    if (*abstract) {
+        hostkey_method_ssh_rsa_dtor(session, abstract);
+        *abstract = NULL;
+    }
+
+    ret = _libssh2_rsa_new_private_frommemory(&rsactx, session,
+                                              privkeyfiledata,
+                                              privkeyfiledata_len, passphrase);
+    if (ret) {
+        return -1;
+    }
+
+    *abstract = rsactx;
+
+    return 0;
+}
+
+/*
  * hostkey_method_ssh_rsa_sign
  *
  * Verify signature created by remote
@@ -203,11 +235,16 @@ hostkey_method_ssh_rsa_dtor(LIBSSH2_SESSION * session, void **abstract)
     return 0;
 }
 
+#ifdef OPENSSL_NO_MD5
+#define MD5_DIGEST_LENGTH 16
+#endif
+
 static const LIBSSH2_HOSTKEY_METHOD hostkey_method_ssh_rsa = {
     "ssh-rsa",
     MD5_DIGEST_LENGTH,
     hostkey_method_ssh_rsa_init,
     hostkey_method_ssh_rsa_initPEM,
+    hostkey_method_ssh_rsa_initPEMFromMemory,
     hostkey_method_ssh_rsa_sig_verify,
     hostkey_method_ssh_rsa_signv,
     NULL,                       /* encrypt */
@@ -306,6 +343,38 @@ hostkey_method_ssh_dss_initPEM(LIBSSH2_SESSION * session,
 }
 
 /*
+ * hostkey_method_ssh_dss_initPEMFromMemory
+ *
+ * Load a Private Key from memory
+ */
+static int
+hostkey_method_ssh_dss_initPEMFromMemory(LIBSSH2_SESSION * session,
+                                         const char *privkeyfiledata,
+                                         size_t privkeyfiledata_len,
+                                         unsigned const char *passphrase,
+                                         void **abstract)
+{
+    libssh2_dsa_ctx *dsactx;
+    int ret;
+
+    if (*abstract) {
+        hostkey_method_ssh_dss_dtor(session, abstract);
+        *abstract = NULL;
+    }
+
+    ret = _libssh2_dsa_new_private_frommemory(&dsactx, session,
+                                              privkeyfiledata,
+                                              privkeyfiledata_len, passphrase);
+    if (ret) {
+        return -1;
+    }
+
+    *abstract = dsactx;
+
+    return 0;
+}
+
+/*
  * libssh2_hostkey_method_ssh_dss_sign
  *
  * Verify signature created by remote
@@ -347,13 +416,12 @@ hostkey_method_ssh_dss_signv(LIBSSH2_SESSION * session,
     libssh2_sha1_ctx ctx;
     int i;
 
-    *signature = LIBSSH2_ALLOC(session, 2 * SHA_DIGEST_LENGTH);
+    *signature = LIBSSH2_CALLOC(session, 2 * SHA_DIGEST_LENGTH);
     if (!*signature) {
         return -1;
     }
 
     *signature_len = 2 * SHA_DIGEST_LENGTH;
-    memset(*signature, 0, 2 * SHA_DIGEST_LENGTH);
 
     libssh2_sha1_init(&ctx);
     for(i = 0; i < veccount; i++) {
@@ -392,6 +460,7 @@ static const LIBSSH2_HOSTKEY_METHOD hostkey_method_ssh_dss = {
     MD5_DIGEST_LENGTH,
     hostkey_method_ssh_dss_init,
     hostkey_method_ssh_dss_initPEM,
+    hostkey_method_ssh_dss_initPEMFromMemory,
     hostkey_method_ssh_dss_sig_verify,
     hostkey_method_ssh_dss_signv,
     NULL,                       /* encrypt */
@@ -435,7 +504,9 @@ libssh2_hostkey_hash(LIBSSH2_SESSION * session, int hash_type)
         break;
 #endif /* LIBSSH2_MD5 */
     case LIBSSH2_HOSTKEY_HASH_SHA1:
-        return (char *) session->server_hostkey_sha1;
+        return (session->server_hostkey_sha1_valid)
+          ? (char *) session->server_hostkey_sha1
+          : NULL;
         break;
     default:
         return NULL;
diff --git a/pgadmin/libssh2/keepalive.c b/pgadmin/libssh2/keepalive.c
index 260206a..fd749dd 100644
--- a/pgadmin/libssh2/keepalive.c
+++ b/pgadmin/libssh2/keepalive.c
@@ -75,7 +75,8 @@ libssh2_keepalive_send (LIBSSH2_SESSION *session,
         size_t len = sizeof (keepalive_data) - 1;
         int rc;
 
-        keepalive_data[len - 1] = session->keepalive_want_reply;
+        keepalive_data[len - 1] =
+            (unsigned char)session->keepalive_want_reply;
 
         rc = _libssh2_transport_send(session, keepalive_data, len, NULL, 0);
         /* Silently ignore PACKET_EAGAIN here: if the write buffer is
@@ -90,8 +91,8 @@ libssh2_keepalive_send (LIBSSH2_SESSION *session,
         if (seconds_to_next)
             *seconds_to_next = session->keepalive_interval;
     } else if (seconds_to_next) {
-        *seconds_to_next = (int) session->keepalive_last_sent
-            + session->keepalive_interval - now;
+        *seconds_to_next = (int) (session->keepalive_last_sent - now)
+            + session->keepalive_interval;
     }
 
     return 0;
diff --git a/pgadmin/libssh2/kex.c b/pgadmin/libssh2/kex.c
index 07e717f..590b30a 100644
--- a/pgadmin/libssh2/kex.c
+++ b/pgadmin/libssh2/kex.c
@@ -70,23 +70,673 @@
             }                                                           \
     }
 
+
+/* Helper macro called from kex_method_diffie_hellman_group1_sha256_key_exchange */
+#define LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(value, reqlen, version) \
+{                                                                       \
+    libssh2_sha256_ctx hash;                                            \
+    unsigned long len = 0;                                              \
+    if (!(value)) {                                                     \
+        value = LIBSSH2_ALLOC(session, reqlen + SHA256_DIGEST_LENGTH);  \
+    }                                                                   \
+    if (value)                                                          \
+        while (len < (unsigned long)reqlen) {                           \
+            libssh2_sha256_init(&hash);                                 \
+            libssh2_sha256_update(hash, exchange_state->k_value,        \
+                                    exchange_state->k_value_len);       \
+            libssh2_sha256_update(hash, exchange_state->h_sig_comp,     \
+                                    SHA256_DIGEST_LENGTH);              \
+        if (len > 0) {                                                  \
+            libssh2_sha256_update(hash, value, len);                    \
+        }    else {                                                     \
+            libssh2_sha256_update(hash, (version), 1);                  \
+            libssh2_sha256_update(hash, session->session_id,            \
+                                    session->session_id_len);           \
+        }                                                               \
+        libssh2_sha256_final(hash, (value) + len);                      \
+        len += SHA256_DIGEST_LENGTH;                                    \
+        }                                                               \
+}
+
+
+/*
+ * diffie_hellman_sha1
+ *
+ * Diffie Hellman Key Exchange, Group Agnostic
+ */
+static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
+                               _libssh2_bn *g,
+                               _libssh2_bn *p,
+                               int group_order,
+                               unsigned char packet_type_init,
+                               unsigned char packet_type_reply,
+                               unsigned char *midhash,
+                               unsigned long midhash_len,
+                               kmdhgGPshakex_state_t *exchange_state)
+{
+    int ret = 0;
+    int rc;
+    libssh2_sha1_ctx exchange_hash_ctx;
+
+    if (exchange_state->state == libssh2_NB_state_idle) {
+        /* Setup initial values */
+        exchange_state->e_packet = NULL;
+        exchange_state->s_packet = NULL;
+        exchange_state->k_value = NULL;
+        exchange_state->ctx = _libssh2_bn_ctx_new();
+        exchange_state->x = _libssh2_bn_init(); /* Random from client */
+        exchange_state->e = _libssh2_bn_init(); /* g^x mod p */
+        exchange_state->f = _libssh2_bn_init_from_bin(); /* g^(Random from server) mod p */
+        exchange_state->k = _libssh2_bn_init(); /* The shared secret: f^x mod p */
+
+        /* Zero the whole thing out */
+        memset(&exchange_state->req_state, 0, sizeof(packet_require_state_t));
+
+        /* Generate x and e */
+        _libssh2_bn_rand(exchange_state->x, group_order, 0, -1);
+        _libssh2_bn_mod_exp(exchange_state->e, g, exchange_state->x, p,
+                            exchange_state->ctx);
+
+        /* Send KEX init */
+        /* packet_type(1) + String Length(4) + leading 0(1) */
+        exchange_state->e_packet_len =
+            _libssh2_bn_bytes(exchange_state->e) + 6;
+        if (_libssh2_bn_bits(exchange_state->e) % 8) {
+            /* Leading 00 not needed */
+            exchange_state->e_packet_len--;
+        }
+
+        exchange_state->e_packet =
+            LIBSSH2_ALLOC(session, exchange_state->e_packet_len);
+        if (!exchange_state->e_packet) {
+            ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                                 "Out of memory error");
+            goto clean_exit;
+        }
+        exchange_state->e_packet[0] = packet_type_init;
+        _libssh2_htonu32(exchange_state->e_packet + 1,
+                         exchange_state->e_packet_len - 5);
+        if (_libssh2_bn_bits(exchange_state->e) % 8) {
+            _libssh2_bn_to_bin(exchange_state->e,
+                               exchange_state->e_packet + 5);
+        } else {
+            exchange_state->e_packet[5] = 0;
+            _libssh2_bn_to_bin(exchange_state->e,
+                               exchange_state->e_packet + 6);
+        }
+
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending KEX packet %d",
+                       (int) packet_type_init);
+        exchange_state->state = libssh2_NB_state_created;
+    }
+
+    if (exchange_state->state == libssh2_NB_state_created) {
+        rc = _libssh2_transport_send(session, exchange_state->e_packet,
+                                     exchange_state->e_packet_len,
+                                     NULL, 0);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
+            return rc;
+        } else if (rc) {
+            ret = _libssh2_error(session, rc,
+                                 "Unable to send KEX init message");
+            goto clean_exit;
+        }
+        exchange_state->state = libssh2_NB_state_sent;
+    }
+
+    if (exchange_state->state == libssh2_NB_state_sent) {
+        if (session->burn_optimistic_kexinit) {
+            /* The first KEX packet to come along will be the guess initially
+             * sent by the server.  That guess turned out to be wrong so we
+             * need to silently ignore it */
+            int burn_type;
+
+            _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                           "Waiting for badly guessed KEX packet (to be ignored)");
+            burn_type =
+                _libssh2_packet_burn(session, &exchange_state->burn_state);
+            if (burn_type == LIBSSH2_ERROR_EAGAIN) {
+                return burn_type;
+            } else if (burn_type <= 0) {
+                /* Failed to receive a packet */
+                ret = burn_type;
+                goto clean_exit;
+            }
+            session->burn_optimistic_kexinit = 0;
+
+            _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                           "Burnt packet of type: %02x",
+                           (unsigned int) burn_type);
+        }
+
+        exchange_state->state = libssh2_NB_state_sent1;
+    }
+
+    if (exchange_state->state == libssh2_NB_state_sent1) {
+        /* Wait for KEX reply */
+        rc = _libssh2_packet_require(session, packet_type_reply,
+                                     &exchange_state->s_packet,
+                                     &exchange_state->s_packet_len, 0, NULL,
+                                     0, &exchange_state->req_state);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
+            return rc;
+        }
+        if (rc) {
+            ret = _libssh2_error(session, LIBSSH2_ERROR_TIMEOUT,
+                                 "Timed out waiting for KEX reply");
+            goto clean_exit;
+        }
+
+        /* Parse KEXDH_REPLY */
+        exchange_state->s = exchange_state->s_packet + 1;
+
+        session->server_hostkey_len = _libssh2_ntohu32(exchange_state->s);
+        exchange_state->s += 4;
+
+        if (session->server_hostkey)
+            LIBSSH2_FREE(session, session->server_hostkey);
+
+        session->server_hostkey =
+            LIBSSH2_ALLOC(session, session->server_hostkey_len);
+        if (!session->server_hostkey) {
+            ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                                 "Unable to allocate memory for a copy "
+                                 "of the host key");
+            goto clean_exit;
+        }
+        memcpy(session->server_hostkey, exchange_state->s,
+               session->server_hostkey_len);
+        exchange_state->s += session->server_hostkey_len;
+
+#if LIBSSH2_MD5
+        {
+            libssh2_md5_ctx fingerprint_ctx;
+
+            if (libssh2_md5_init(&fingerprint_ctx)) {
+                libssh2_md5_update(fingerprint_ctx, session->server_hostkey,
+                                   session->server_hostkey_len);
+                libssh2_md5_final(fingerprint_ctx,
+                                  session->server_hostkey_md5);
+                session->server_hostkey_md5_valid = TRUE;
+            }
+            else {
+                session->server_hostkey_md5_valid = FALSE;
+            }
+        }
+#ifdef LIBSSH2DEBUG
+        {
+            char fingerprint[50], *fprint = fingerprint;
+            int i;
+            for(i = 0; i < 16; i++, fprint += 3) {
+                snprintf(fprint, 4, "%02x:", session->server_hostkey_md5[i]);
+            }
+            *(--fprint) = '\0';
+            _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                           "Server's MD5 Fingerprint: %s", fingerprint);
+        }
+#endif /* LIBSSH2DEBUG */
+#endif /* ! LIBSSH2_MD5 */
+
+        {
+            libssh2_sha1_ctx fingerprint_ctx;
+
+            if (libssh2_sha1_init(&fingerprint_ctx)) {
+                libssh2_sha1_update(fingerprint_ctx, session->server_hostkey,
+                                    session->server_hostkey_len);
+                libssh2_sha1_final(fingerprint_ctx,
+                                   session->server_hostkey_sha1);
+                session->server_hostkey_sha1_valid = TRUE;
+            }
+            else {
+                session->server_hostkey_sha1_valid = FALSE;
+            }
+        }
+#ifdef LIBSSH2DEBUG
+        {
+            char fingerprint[64], *fprint = fingerprint;
+            int i;
+
+            for(i = 0; i < 20; i++, fprint += 3) {
+                snprintf(fprint, 4, "%02x:", session->server_hostkey_sha1[i]);
+            }
+            *(--fprint) = '\0';
+            _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                           "Server's SHA1 Fingerprint: %s", fingerprint);
+        }
+#endif /* LIBSSH2DEBUG */
+
+        if (session->hostkey->init(session, session->server_hostkey,
+                                   session->server_hostkey_len,
+                                   &session->server_hostkey_abstract)) {
+            ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT,
+                                 "Unable to initialize hostkey importer");
+            goto clean_exit;
+        }
+
+        exchange_state->f_value_len = _libssh2_ntohu32(exchange_state->s);
+        exchange_state->s += 4;
+        exchange_state->f_value = exchange_state->s;
+        exchange_state->s += exchange_state->f_value_len;
+        _libssh2_bn_from_bin(exchange_state->f, exchange_state->f_value_len,
+                             exchange_state->f_value);
+
+        exchange_state->h_sig_len = _libssh2_ntohu32(exchange_state->s);
+        exchange_state->s += 4;
+        exchange_state->h_sig = exchange_state->s;
+
+        /* Compute the shared secret */
+        _libssh2_bn_mod_exp(exchange_state->k, exchange_state->f,
+                            exchange_state->x, p, exchange_state->ctx);
+        exchange_state->k_value_len = _libssh2_bn_bytes(exchange_state->k) + 5;
+        if (_libssh2_bn_bits(exchange_state->k) % 8) {
+            /* don't need leading 00 */
+            exchange_state->k_value_len--;
+        }
+        exchange_state->k_value =
+            LIBSSH2_ALLOC(session, exchange_state->k_value_len);
+        if (!exchange_state->k_value) {
+            ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                                 "Unable to allocate buffer for K");
+            goto clean_exit;
+        }
+        _libssh2_htonu32(exchange_state->k_value,
+                         exchange_state->k_value_len - 4);
+        if (_libssh2_bn_bits(exchange_state->k) % 8) {
+            _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 4);
+        } else {
+            exchange_state->k_value[4] = 0;
+            _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5);
+        }
+
+        exchange_state->exchange_hash = (void*)&exchange_hash_ctx;
+        libssh2_sha1_init(&exchange_hash_ctx);
+
+        if (session->local.banner) {
+            _libssh2_htonu32(exchange_state->h_sig_comp,
+                             strlen((char *) session->local.banner) - 2);
+            libssh2_sha1_update(exchange_hash_ctx,
+                                exchange_state->h_sig_comp, 4);
+            libssh2_sha1_update(exchange_hash_ctx,
+                                (char *) session->local.banner,
+                                strlen((char *) session->local.banner) - 2);
+        } else {
+            _libssh2_htonu32(exchange_state->h_sig_comp,
+                             sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
+            libssh2_sha1_update(exchange_hash_ctx,
+                                exchange_state->h_sig_comp, 4);
+            libssh2_sha1_update(exchange_hash_ctx,
+                                LIBSSH2_SSH_DEFAULT_BANNER,
+                                sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
+        }
+
+        _libssh2_htonu32(exchange_state->h_sig_comp,
+                         strlen((char *) session->remote.banner));
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->h_sig_comp, 4);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            session->remote.banner,
+                            strlen((char *) session->remote.banner));
+
+        _libssh2_htonu32(exchange_state->h_sig_comp,
+                         session->local.kexinit_len);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->h_sig_comp, 4);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            session->local.kexinit,
+                            session->local.kexinit_len);
+
+        _libssh2_htonu32(exchange_state->h_sig_comp,
+                         session->remote.kexinit_len);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->h_sig_comp, 4);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            session->remote.kexinit,
+                            session->remote.kexinit_len);
+
+        _libssh2_htonu32(exchange_state->h_sig_comp,
+                         session->server_hostkey_len);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->h_sig_comp, 4);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            session->server_hostkey,
+                            session->server_hostkey_len);
+
+        if (packet_type_init == SSH_MSG_KEX_DH_GEX_INIT) {
+            /* diffie-hellman-group-exchange hashes additional fields */
+#ifdef LIBSSH2_DH_GEX_NEW
+            _libssh2_htonu32(exchange_state->h_sig_comp,
+                             LIBSSH2_DH_GEX_MINGROUP);
+            _libssh2_htonu32(exchange_state->h_sig_comp + 4,
+                             LIBSSH2_DH_GEX_OPTGROUP);
+            _libssh2_htonu32(exchange_state->h_sig_comp + 8,
+                             LIBSSH2_DH_GEX_MAXGROUP);
+            libssh2_sha1_update(exchange_hash_ctx,
+                                exchange_state->h_sig_comp, 12);
+#else
+            _libssh2_htonu32(exchange_state->h_sig_comp,
+                             LIBSSH2_DH_GEX_OPTGROUP);
+            libssh2_sha1_update(exchange_hash_ctx,
+                                exchange_state->h_sig_comp, 4);
+#endif
+        }
+
+        if (midhash) {
+            libssh2_sha1_update(exchange_hash_ctx, midhash,
+                                midhash_len);
+        }
+
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->e_packet + 1,
+                            exchange_state->e_packet_len - 1);
+
+        _libssh2_htonu32(exchange_state->h_sig_comp,
+                         exchange_state->f_value_len);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->h_sig_comp, 4);
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->f_value,
+                            exchange_state->f_value_len);
+
+        libssh2_sha1_update(exchange_hash_ctx,
+                            exchange_state->k_value,
+                            exchange_state->k_value_len);
+
+        libssh2_sha1_final(exchange_hash_ctx,
+                           exchange_state->h_sig_comp);
+
+        if (session->hostkey->
+            sig_verify(session, exchange_state->h_sig,
+                       exchange_state->h_sig_len, exchange_state->h_sig_comp,
+                       20, &session->server_hostkey_abstract)) {
+            ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN,
+                                 "Unable to verify hostkey signature");
+            goto clean_exit;
+        }
+
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending NEWKEYS message");
+        exchange_state->c = SSH_MSG_NEWKEYS;
+
+        exchange_state->state = libssh2_NB_state_sent2;
+    }
+
+    if (exchange_state->state == libssh2_NB_state_sent2) {
+        rc = _libssh2_transport_send(session, &exchange_state->c, 1, NULL, 0);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
+            return rc;
+        } else if (rc) {
+            ret = _libssh2_error(session, rc, "Unable to send NEWKEYS message");
+            goto clean_exit;
+        }
+
+        exchange_state->state = libssh2_NB_state_sent3;
+    }
+
+    if (exchange_state->state == libssh2_NB_state_sent3) {
+        rc = _libssh2_packet_require(session, SSH_MSG_NEWKEYS,
+                                     &exchange_state->tmp,
+                                     &exchange_state->tmp_len, 0, NULL, 0,
+                                     &exchange_state->req_state);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
+            return rc;
+        } else if (rc) {
+            ret = _libssh2_error(session, rc, "Timed out waiting for NEWKEYS");
+            goto clean_exit;
+        }
+        /* The first key exchange has been performed,
+           switch to active crypt/comp/mac mode */
+        session->state |= LIBSSH2_STATE_NEWKEYS;
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Received NEWKEYS message");
+
+        /* This will actually end up being just packet_type(1)
+           for this packet type anyway */
+        LIBSSH2_FREE(session, exchange_state->tmp);
+
+        if (!session->session_id) {
+            session->session_id = LIBSSH2_ALLOC(session, SHA_DIGEST_LENGTH);
+            if (!session->session_id) {
+                ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                                     "Unable to allocate buffer for SHA digest");
+                goto clean_exit;
+            }
+            memcpy(session->session_id, exchange_state->h_sig_comp,
+                   SHA_DIGEST_LENGTH);
+            session->session_id_len = SHA_DIGEST_LENGTH;
+            _libssh2_debug(session, LIBSSH2_TRACE_KEX, "session_id calculated");
+        }
+
+        /* Cleanup any existing cipher */
+        if (session->local.crypt->dtor) {
+            session->local.crypt->dtor(session,
+                                       &session->local.crypt_abstract);
+        }
+
+        /* Calculate IV/Secret/Key for each direction */
+        if (session->local.crypt->init) {
+            unsigned char *iv = NULL, *secret = NULL;
+            int free_iv = 0, free_secret = 0;
+
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv,
+                                                        session->local.crypt->
+                                                        iv_len, "A");
+            if (!iv) {
+                ret = -1;
+                goto clean_exit;
+            }
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret,
+                                                        session->local.crypt->
+                                                        secret_len, "C");
+            if (!secret) {
+                LIBSSH2_FREE(session, iv);
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+            if (session->local.crypt->
+                init(session, session->local.crypt, iv, &free_iv, secret,
+                     &free_secret, 1, &session->local.crypt_abstract)) {
+                LIBSSH2_FREE(session, iv);
+                LIBSSH2_FREE(session, secret);
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+
+            if (free_iv) {
+                memset(iv, 0, session->local.crypt->iv_len);
+                LIBSSH2_FREE(session, iv);
+            }
+
+            if (free_secret) {
+                memset(secret, 0, session->local.crypt->secret_len);
+                LIBSSH2_FREE(session, secret);
+            }
+        }
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Client to Server IV and Key calculated");
+
+        if (session->remote.crypt->dtor) {
+            /* Cleanup any existing cipher */
+            session->remote.crypt->dtor(session,
+                                        &session->remote.crypt_abstract);
+        }
+
+        if (session->remote.crypt->init) {
+            unsigned char *iv = NULL, *secret = NULL;
+            int free_iv = 0, free_secret = 0;
+
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv,
+                                                        session->remote.crypt->
+                                                        iv_len, "B");
+            if (!iv) {
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret,
+                                                        session->remote.crypt->
+                                                        secret_len, "D");
+            if (!secret) {
+                LIBSSH2_FREE(session, iv);
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+            if (session->remote.crypt->
+                init(session, session->remote.crypt, iv, &free_iv, secret,
+                     &free_secret, 0, &session->remote.crypt_abstract)) {
+                LIBSSH2_FREE(session, iv);
+                LIBSSH2_FREE(session, secret);
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+
+            if (free_iv) {
+                memset(iv, 0, session->remote.crypt->iv_len);
+                LIBSSH2_FREE(session, iv);
+            }
+
+            if (free_secret) {
+                memset(secret, 0, session->remote.crypt->secret_len);
+                LIBSSH2_FREE(session, secret);
+            }
+        }
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Server to Client IV and Key calculated");
+
+        if (session->local.mac->dtor) {
+            session->local.mac->dtor(session, &session->local.mac_abstract);
+        }
+
+        if (session->local.mac->init) {
+            unsigned char *key = NULL;
+            int free_key = 0;
+
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key,
+                                                        session->local.mac->
+                                                        key_len, "E");
+            if (!key) {
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+            session->local.mac->init(session, key, &free_key,
+                                     &session->local.mac_abstract);
+
+            if (free_key) {
+                memset(key, 0, session->local.mac->key_len);
+                LIBSSH2_FREE(session, key);
+            }
+        }
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Client to Server HMAC Key calculated");
+
+        if (session->remote.mac->dtor) {
+            session->remote.mac->dtor(session, &session->remote.mac_abstract);
+        }
+
+        if (session->remote.mac->init) {
+            unsigned char *key = NULL;
+            int free_key = 0;
+
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key,
+                                                        session->remote.mac->
+                                                        key_len, "F");
+            if (!key) {
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+            session->remote.mac->init(session, key, &free_key,
+                                      &session->remote.mac_abstract);
+
+            if (free_key) {
+                memset(key, 0, session->remote.mac->key_len);
+                LIBSSH2_FREE(session, key);
+            }
+        }
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Server to Client HMAC Key calculated");
+
+        /* Initialize compression for each direction */
+
+        /* Cleanup any existing compression */
+        if (session->local.comp && session->local.comp->dtor) {
+            session->local.comp->dtor(session, 1,
+                                      &session->local.comp_abstract);
+        }
+
+        if (session->local.comp && session->local.comp->init) {
+            if (session->local.comp->init(session, 1,
+                                          &session->local.comp_abstract)) {
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+        }
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Client to Server compression initialized");
+
+        if (session->remote.comp && session->remote.comp->dtor) {
+            session->remote.comp->dtor(session, 0,
+                                       &session->remote.comp_abstract);
+        }
+
+        if (session->remote.comp && session->remote.comp->init) {
+            if (session->remote.comp->init(session, 0,
+                                           &session->remote.comp_abstract)) {
+                ret = LIBSSH2_ERROR_KEX_FAILURE;
+                goto clean_exit;
+            }
+        }
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Server to Client compression initialized");
+
+    }
+
+  clean_exit:
+    _libssh2_bn_free(exchange_state->x);
+    exchange_state->x = NULL;
+    _libssh2_bn_free(exchange_state->e);
+    exchange_state->e = NULL;
+    _libssh2_bn_free(exchange_state->f);
+    exchange_state->f = NULL;
+    _libssh2_bn_free(exchange_state->k);
+    exchange_state->k = NULL;
+    _libssh2_bn_ctx_free(exchange_state->ctx);
+    exchange_state->ctx = NULL;
+
+    if (exchange_state->e_packet) {
+        LIBSSH2_FREE(session, exchange_state->e_packet);
+        exchange_state->e_packet = NULL;
+    }
+
+    if (exchange_state->s_packet) {
+        LIBSSH2_FREE(session, exchange_state->s_packet);
+        exchange_state->s_packet = NULL;
+    }
+
+    if (exchange_state->k_value) {
+        LIBSSH2_FREE(session, exchange_state->k_value);
+        exchange_state->k_value = NULL;
+    }
+
+    exchange_state->state = libssh2_NB_state_idle;
+
+    return ret;
+}
+
+
 /*
- * diffie_hellman_sha1
+ * diffie_hellman_sha256
  *
  * Diffie Hellman Key Exchange, Group Agnostic
  */
-static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
-                               _libssh2_bn *g,
-                               _libssh2_bn *p,
-                               int group_order,
-                               unsigned char packet_type_init,
-                               unsigned char packet_type_reply,
-                               unsigned char *midhash,
-                               unsigned long midhash_len,
-                               kmdhgGPsha1kex_state_t *exchange_state)
+static int diffie_hellman_sha256(LIBSSH2_SESSION *session,
+                                 _libssh2_bn *g,
+                                 _libssh2_bn *p,
+                                 int group_order,
+                                 unsigned char packet_type_init,
+                                 unsigned char packet_type_reply,
+                                 unsigned char *midhash,
+                                 unsigned long midhash_len,
+                                 kmdhgGPshakex_state_t *exchange_state)
 {
     int ret = 0;
     int rc;
+    libssh2_sha256_ctx exchange_hash_ctx;
 
     if (exchange_state->state == libssh2_NB_state_idle) {
         /* Setup initial values */
@@ -96,7 +746,7 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
         exchange_state->ctx = _libssh2_bn_ctx_new();
         exchange_state->x = _libssh2_bn_init(); /* Random from client */
         exchange_state->e = _libssh2_bn_init(); /* g^x mod p */
-        exchange_state->f = _libssh2_bn_init(); /* g^(Random from server) mod p */
+        exchange_state->f = _libssh2_bn_init_from_bin(); /* g^(Random from server) mod p */
         exchange_state->k = _libssh2_bn_init(); /* The shared secret: f^x mod p */
 
         /* Zero the whole thing out */
@@ -202,6 +852,10 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
 
         session->server_hostkey_len = _libssh2_ntohu32(exchange_state->s);
         exchange_state->s += 4;
+
+        if (session->server_hostkey)
+            LIBSSH2_FREE(session, session->server_hostkey);
+
         session->server_hostkey =
             LIBSSH2_ALLOC(session, session->server_hostkey_len);
         if (!session->server_hostkey) {
@@ -221,7 +875,8 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
             if (libssh2_md5_init(&fingerprint_ctx)) {
                 libssh2_md5_update(fingerprint_ctx, session->server_hostkey,
                                    session->server_hostkey_len);
-                libssh2_md5_final(fingerprint_ctx, session->server_hostkey_md5);
+                libssh2_md5_final(fingerprint_ctx,
+                                  session->server_hostkey_md5);
                 session->server_hostkey_md5_valid = TRUE;
             }
             else {
@@ -245,10 +900,16 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
         {
             libssh2_sha1_ctx fingerprint_ctx;
 
-            libssh2_sha1_init(&fingerprint_ctx);
-            libssh2_sha1_update(fingerprint_ctx, session->server_hostkey,
-                                session->server_hostkey_len);
-            libssh2_sha1_final(fingerprint_ctx, session->server_hostkey_sha1);
+            if (libssh2_sha1_init(&fingerprint_ctx)) {
+                libssh2_sha1_update(fingerprint_ctx, session->server_hostkey,
+                                    session->server_hostkey_len);
+                libssh2_sha1_final(fingerprint_ctx,
+                                   session->server_hostkey_sha1);
+                session->server_hostkey_sha1_valid = TRUE;
+            }
+            else {
+                session->server_hostkey_sha1_valid = FALSE;
+            }
         }
 #ifdef LIBSSH2DEBUG
         {
@@ -307,56 +968,58 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
             _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5);
         }
 
-        libssh2_sha1_init(&exchange_state->exchange_hash);
+        exchange_state->exchange_hash = (void*)&exchange_hash_ctx;
+        libssh2_sha256_init(&exchange_hash_ctx);
+
         if (session->local.banner) {
             _libssh2_htonu32(exchange_state->h_sig_comp,
                              strlen((char *) session->local.banner) - 2);
-            libssh2_sha1_update(exchange_state->exchange_hash,
-                                exchange_state->h_sig_comp, 4);
-            libssh2_sha1_update(exchange_state->exchange_hash,
-                                (char *) session->local.banner,
-                                strlen((char *) session->local.banner) - 2);
+            libssh2_sha256_update(exchange_hash_ctx,
+                                  exchange_state->h_sig_comp, 4);
+            libssh2_sha256_update(exchange_hash_ctx,
+                                  (char *) session->local.banner,
+                                  strlen((char *) session->local.banner) - 2);
         } else {
             _libssh2_htonu32(exchange_state->h_sig_comp,
                              sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
-            libssh2_sha1_update(exchange_state->exchange_hash,
-                                exchange_state->h_sig_comp, 4);
-            libssh2_sha1_update(exchange_state->exchange_hash,
-                                LIBSSH2_SSH_DEFAULT_BANNER,
-                                sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
+            libssh2_sha256_update(exchange_hash_ctx,
+                                  exchange_state->h_sig_comp, 4);
+            libssh2_sha256_update(exchange_hash_ctx,
+                                  LIBSSH2_SSH_DEFAULT_BANNER,
+                                  sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
         }
 
         _libssh2_htonu32(exchange_state->h_sig_comp,
                          strlen((char *) session->remote.banner));
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->h_sig_comp, 4);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            session->remote.banner,
-                            strlen((char *) session->remote.banner));
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->h_sig_comp, 4);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              session->remote.banner,
+                              strlen((char *) session->remote.banner));
 
         _libssh2_htonu32(exchange_state->h_sig_comp,
                          session->local.kexinit_len);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->h_sig_comp, 4);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            session->local.kexinit,
-                            session->local.kexinit_len);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->h_sig_comp, 4);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              session->local.kexinit,
+                              session->local.kexinit_len);
 
         _libssh2_htonu32(exchange_state->h_sig_comp,
                          session->remote.kexinit_len);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->h_sig_comp, 4);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            session->remote.kexinit,
-                            session->remote.kexinit_len);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->h_sig_comp, 4);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              session->remote.kexinit,
+                              session->remote.kexinit_len);
 
         _libssh2_htonu32(exchange_state->h_sig_comp,
                          session->server_hostkey_len);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->h_sig_comp, 4);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            session->server_hostkey,
-                            session->server_hostkey_len);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->h_sig_comp, 4);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              session->server_hostkey,
+                              session->server_hostkey_len);
 
         if (packet_type_init == SSH_MSG_KEX_DH_GEX_INIT) {
             /* diffie-hellman-group-exchange hashes additional fields */
@@ -367,49 +1030,51 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
                              LIBSSH2_DH_GEX_OPTGROUP);
             _libssh2_htonu32(exchange_state->h_sig_comp + 8,
                              LIBSSH2_DH_GEX_MAXGROUP);
-            libssh2_sha1_update(exchange_state->exchange_hash,
-                                exchange_state->h_sig_comp, 12);
+            libssh2_sha256_update(exchange_hash_ctx,
+                                  exchange_state->h_sig_comp, 12);
 #else
             _libssh2_htonu32(exchange_state->h_sig_comp,
                              LIBSSH2_DH_GEX_OPTGROUP);
-            libssh2_sha1_update(exchange_state->exchange_hash,
-                                exchange_state->h_sig_comp, 4);
+            libssh2_sha256_update(exchange_hash_ctx,
+                                  exchange_state->h_sig_comp, 4);
 #endif
         }
 
         if (midhash) {
-            libssh2_sha1_update(exchange_state->exchange_hash, midhash,
-                                midhash_len);
+            libssh2_sha256_update(exchange_hash_ctx, midhash,
+                                  midhash_len);
         }
 
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->e_packet + 1,
-                            exchange_state->e_packet_len - 1);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->e_packet + 1,
+                              exchange_state->e_packet_len - 1);
 
         _libssh2_htonu32(exchange_state->h_sig_comp,
                          exchange_state->f_value_len);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->h_sig_comp, 4);
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->f_value,
-                            exchange_state->f_value_len);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->h_sig_comp, 4);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->f_value,
+                              exchange_state->f_value_len);
 
-        libssh2_sha1_update(exchange_state->exchange_hash,
-                            exchange_state->k_value,
-                            exchange_state->k_value_len);
+        libssh2_sha256_update(exchange_hash_ctx,
+                              exchange_state->k_value,
+                              exchange_state->k_value_len);
 
-        libssh2_sha1_final(exchange_state->exchange_hash,
-                           exchange_state->h_sig_comp);
+        libssh2_sha256_final(exchange_hash_ctx,
+                             exchange_state->h_sig_comp);
 
         if (session->hostkey->
             sig_verify(session, exchange_state->h_sig,
                        exchange_state->h_sig_len, exchange_state->h_sig_comp,
-                       20, &session->server_hostkey_abstract)) {
+                       SHA256_DIGEST_LENGTH, &session->server_hostkey_abstract)) {
             ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN,
                                  "Unable to verify hostkey signature");
             goto clean_exit;
         }
 
+
+
         _libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending NEWKEYS message");
         exchange_state->c = SSH_MSG_NEWKEYS;
 
@@ -449,15 +1114,15 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
         LIBSSH2_FREE(session, exchange_state->tmp);
 
         if (!session->session_id) {
-            session->session_id = LIBSSH2_ALLOC(session, SHA_DIGEST_LENGTH);
+            session->session_id = LIBSSH2_ALLOC(session, SHA256_DIGEST_LENGTH);
             if (!session->session_id) {
                 ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                      "Unable to allocate buffer for SHA digest");
                 goto clean_exit;
             }
             memcpy(session->session_id, exchange_state->h_sig_comp,
-                   SHA_DIGEST_LENGTH);
-            session->session_id_len = SHA_DIGEST_LENGTH;
+                   SHA256_DIGEST_LENGTH);
+            session->session_id_len = SHA256_DIGEST_LENGTH;
             _libssh2_debug(session, LIBSSH2_TRACE_KEX, "session_id calculated");
         }
 
@@ -472,16 +1137,16 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
             unsigned char *iv = NULL, *secret = NULL;
             int free_iv = 0, free_secret = 0;
 
-            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv,
-                                                        session->local.crypt->
-                                                        iv_len, "A");
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(iv,
+                                                          session->local.crypt->
+                                                          iv_len, "A");
             if (!iv) {
                 ret = -1;
                 goto clean_exit;
             }
-            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret,
-                                                        session->local.crypt->
-                                                        secret_len, "C");
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(secret,
+                                                          session->local.crypt->
+                                                          secret_len, "C");
             if (!secret) {
                 LIBSSH2_FREE(session, iv);
                 ret = LIBSSH2_ERROR_KEX_FAILURE;
@@ -519,16 +1184,16 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
             unsigned char *iv = NULL, *secret = NULL;
             int free_iv = 0, free_secret = 0;
 
-            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv,
-                                                        session->remote.crypt->
-                                                        iv_len, "B");
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(iv,
+                                                          session->remote.crypt->
+                                                          iv_len, "B");
             if (!iv) {
                 ret = LIBSSH2_ERROR_KEX_FAILURE;
                 goto clean_exit;
             }
-            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret,
-                                                        session->remote.crypt->
-                                                        secret_len, "D");
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(secret,
+                                                          session->remote.crypt->
+                                                          secret_len, "D");
             if (!secret) {
                 LIBSSH2_FREE(session, iv);
                 ret = LIBSSH2_ERROR_KEX_FAILURE;
@@ -564,9 +1229,9 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
             unsigned char *key = NULL;
             int free_key = 0;
 
-            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key,
-                                                        session->local.mac->
-                                                        key_len, "E");
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(key,
+                                                          session->local.mac->
+                                                          key_len, "E");
             if (!key) {
                 ret = LIBSSH2_ERROR_KEX_FAILURE;
                 goto clean_exit;
@@ -590,9 +1255,9 @@ static int diffie_hellman_sha1(LIBSSH2_SESSION *session,
             unsigned char *key = NULL;
             int free_key = 0;
 
-            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key,
-                                                        session->remote.mac->
-                                                        key_len, "F");
+            LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA256_HASH(key,
+                                                          session->remote.mac->
+                                                          key_len, "F");
             if (!key) {
                 ret = LIBSSH2_ERROR_KEX_FAILURE;
                 goto clean_exit;
@@ -708,7 +1373,7 @@ kex_method_diffie_hellman_group1_sha1_key_exchange(LIBSSH2_SESSION *session,
 
     if (key_state->state == libssh2_NB_state_idle) {
         /* g == 2 */
-        key_state->p = _libssh2_bn_init();      /* SSH2 defined value (p_value) */
+        key_state->p = _libssh2_bn_init_from_bin();      /* SSH2 defined value (p_value) */
         key_state->g = _libssh2_bn_init();      /* SSH2 defined value (2) */
 
         /* Initialize P and G */
@@ -783,7 +1448,7 @@ kex_method_diffie_hellman_group14_sha1_key_exchange(LIBSSH2_SESSION *session,
     int ret;
 
     if (key_state->state == libssh2_NB_state_idle) {
-        key_state->p = _libssh2_bn_init();      /* SSH2 defined value (p_value) */
+        key_state->p = _libssh2_bn_init_from_bin();      /* SSH2 defined value (p_value) */
         key_state->g = _libssh2_bn_init();      /* SSH2 defined value (2) */
 
         /* g == 2 */
@@ -827,8 +1492,8 @@ kex_method_diffie_hellman_group_exchange_sha1_key_exchange
     int rc;
 
     if (key_state->state == libssh2_NB_state_idle) {
-        key_state->p = _libssh2_bn_init();
-        key_state->g = _libssh2_bn_init();
+        key_state->p = _libssh2_bn_init_from_bin();
+        key_state->g = _libssh2_bn_init_from_bin();
         /* Ask for a P and G pair */
 #ifdef LIBSSH2_DH_GEX_NEW
         key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST;
@@ -914,6 +1579,105 @@ kex_method_diffie_hellman_group_exchange_sha1_key_exchange
 
 
 
+/* kex_method_diffie_hellman_group_exchange_sha256_key_exchange
+ * Diffie-Hellman Group Exchange Key Exchange using SHA256
+ * Negotiates random(ish) group for secret derivation
+ */
+static int
+kex_method_diffie_hellman_group_exchange_sha256_key_exchange
+(LIBSSH2_SESSION * session, key_exchange_state_low_t * key_state)
+{
+    unsigned long p_len, g_len;
+    int ret = 0;
+    int rc;
+
+    if (key_state->state == libssh2_NB_state_idle) {
+        key_state->p = _libssh2_bn_init();
+        key_state->g = _libssh2_bn_init();
+        /* Ask for a P and G pair */
+#ifdef LIBSSH2_DH_GEX_NEW
+        key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST;
+        _libssh2_htonu32(key_state->request + 1, LIBSSH2_DH_GEX_MINGROUP);
+        _libssh2_htonu32(key_state->request + 5, LIBSSH2_DH_GEX_OPTGROUP);
+        _libssh2_htonu32(key_state->request + 9, LIBSSH2_DH_GEX_MAXGROUP);
+        key_state->request_len = 13;
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Initiating Diffie-Hellman Group-Exchange (New Method SHA256)");
+#else
+        key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST_OLD;
+        _libssh2_htonu32(key_state->request + 1, LIBSSH2_DH_GEX_OPTGROUP);
+        key_state->request_len = 5;
+        _libssh2_debug(session, LIBSSH2_TRACE_KEX,
+                       "Initiating Diffie-Hellman Group-Exchange (Old Method SHA256)");
+#endif
+
+        key_state->state = libssh2_NB_state_created;
+    }
+
+    if (key_state->state == libssh2_NB_state_created) {
+        rc = _libssh2_transport_send(session, key_state->request,
+                                     key_state->request_len, NULL, 0);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
+            return rc;
+        } else if (rc) {
+            ret = _libssh2_error(session, rc,
+                                 "Unable to send Group Exchange Request SHA256");
+            goto dh_gex_clean_exit;
+        }
+
+        key_state->state = libssh2_NB_state_sent;
+    }
+
+    if (key_state->state == libssh2_NB_state_sent) {
+        rc = _libssh2_packet_require(session, SSH_MSG_KEX_DH_GEX_GROUP,
+                                     &key_state->data, &key_state->data_len,
+                                     0, NULL, 0, &key_state->req_state);
+        if (rc == LIBSSH2_ERROR_EAGAIN) {
+            return rc;
+        } else if (rc) {
+            ret = _libssh2_error(session, rc,
+                                 "Timeout waiting for GEX_GROUP reply SHA256");
+            goto dh_gex_clean_exit;
+        }
+
+        key_state->state = libssh2_NB_state_sent1;
+    }
+
+    if (key_state->state == libssh2_NB_state_sent1) {
+        unsigned char *s = key_state->data + 1;
+        p_len = _libssh2_ntohu32(s);
+        s += 4;
+        _libssh2_bn_from_bin(key_state->p, p_len, s);
+        s += p_len;
+
+        g_len = _libssh2_ntohu32(s);
+        s += 4;
+        _libssh2_bn_from_bin(key_state->g, g_len, s);
+
+        ret = diffie_hellman_sha256(session, key_state->g, key_state->p, p_len,
+                                    SSH_MSG_KEX_DH_GEX_INIT,
+                                    SSH_MSG_KEX_DH_GEX_REPLY,
+                                    key_state->data + 1,
+                                    key_state->data_len - 1,
+                                    &key_state->exchange_state);
+        if (ret == LIBSSH2_ERROR_EAGAIN) {
+            return ret;
+        }
+
+        LIBSSH2_FREE(session, key_state->data);
+    }
+
+  dh_gex_clean_exit:
+    key_state->state = libssh2_NB_state_idle;
+    _libssh2_bn_free(key_state->g);
+    key_state->g = NULL;
+    _libssh2_bn_free(key_state->p);
+    key_state->p = NULL;
+
+    return ret;
+}
+
+
 #define LIBSSH2_KEX_METHOD_FLAG_REQ_ENC_HOSTKEY     0x0001
 #define LIBSSH2_KEX_METHOD_FLAG_REQ_SIGN_HOSTKEY    0x0002
 
@@ -936,9 +1700,17 @@ kex_method_diffie_helman_group_exchange_sha1 = {
     LIBSSH2_KEX_METHOD_FLAG_REQ_SIGN_HOSTKEY,
 };
 
+static const LIBSSH2_KEX_METHOD
+kex_method_diffie_helman_group_exchange_sha256 = {
+    "diffie-hellman-group-exchange-sha256",
+    kex_method_diffie_hellman_group_exchange_sha256_key_exchange,
+    LIBSSH2_KEX_METHOD_FLAG_REQ_SIGN_HOSTKEY,
+};
+
 static const LIBSSH2_KEX_METHOD *libssh2_kex_methods[] = {
-    &kex_method_diffie_helman_group14_sha1,
+    &kex_method_diffie_helman_group_exchange_sha256,
     &kex_method_diffie_helman_group_exchange_sha1,
+    &kex_method_diffie_helman_group14_sha1,
     &kex_method_diffie_helman_group1_sha1,
     NULL
 };
@@ -1549,6 +2321,30 @@ static int kex_agree_comp(LIBSSH2_SESSION *session,
  * The Client gets to make the final call on "agreed methods"
  */
 
+/*
+ * kex_string_pair() extracts a string from the packet and makes sure it fits
+ * within the given packet.
+ */
+static int kex_string_pair(unsigned char **sp,   /* parsing position */
+                           unsigned char *data,  /* start pointer to packet */
+                           size_t data_len,      /* size of total packet */
+                           size_t *lenp,         /* length of the string */
+                           unsigned char **strp) /* pointer to string start */
+{
+    unsigned char *s = *sp;
+    *lenp = _libssh2_ntohu32(s);
+
+    /* the length of the string must fit within the current pointer and the
+       end of the packet */
+    if (*lenp > (data_len - (s - data) -4))
+        return 1;
+    *strp = s + 4;
+    s += 4 + *lenp;
+
+    *sp = s;
+    return 0;
+}
+
 /* kex_agree_methods
  * Decide which specific method to use of the methods offered by each party
  */
@@ -1568,38 +2364,23 @@ static int kex_agree_methods(LIBSSH2_SESSION * session, unsigned char *data,
     s += 16;
 
     /* Locate each string */
-    kex_len = _libssh2_ntohu32(s);
-    kex = s + 4;
-    s += 4 + kex_len;
-    hostkey_len = _libssh2_ntohu32(s);
-    hostkey = s + 4;
-    s += 4 + hostkey_len;
-    crypt_cs_len = _libssh2_ntohu32(s);
-    crypt_cs = s + 4;
-    s += 4 + crypt_cs_len;
-    crypt_sc_len = _libssh2_ntohu32(s);
-    crypt_sc = s + 4;
-    s += 4 + crypt_sc_len;
-    mac_cs_len = _libssh2_ntohu32(s);
-    mac_cs = s + 4;
-    s += 4 + mac_cs_len;
-    mac_sc_len = _libssh2_ntohu32(s);
-    mac_sc = s + 4;
-    s += 4 + mac_sc_len;
-    comp_cs_len = _libssh2_ntohu32(s);
-    comp_cs = s + 4;
-    s += 4 + comp_cs_len;
-    comp_sc_len = _libssh2_ntohu32(s);
-    comp_sc = s + 4;
-#if 0
-    s += 4 + comp_sc_len;
-    lang_cs_len = _libssh2_ntohu32(s);
-    lang_cs = s + 4;
-    s += 4 + lang_cs_len;
-    lang_sc_len = _libssh2_ntohu32(s);
-    lang_sc = s + 4;
-    s += 4 + lang_sc_len;
-#endif
+    if(kex_string_pair(&s, data, data_len, &kex_len, &kex))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &hostkey_len, &hostkey))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &crypt_cs_len, &crypt_cs))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &crypt_sc_len, &crypt_sc))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &mac_cs_len, &mac_cs))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &mac_sc_len, &mac_sc))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &comp_cs_len, &comp_cs))
+        return -1;
+    if(kex_string_pair(&s, data, data_len, &comp_sc_len, &comp_sc))
+        return -1;
+
     /* If the server sent an optimistic packet, assume that it guessed wrong.
      * If the guess is determined to be right (by kex_agree_kex_hostkey)
      * This flag will be reset to zero so that it's not ignored */
@@ -1666,7 +2447,7 @@ static int kex_agree_methods(LIBSSH2_SESSION * session, unsigned char *data,
  */
 int
 _libssh2_kex_exchange(LIBSSH2_SESSION * session, int reexchange,
-                     key_exchange_state_t * key_state)
+                      key_exchange_state_t * key_state)
 {
     int rc = 0;
     int retcode;
@@ -1756,7 +2537,7 @@ _libssh2_kex_exchange(LIBSSH2_SESSION * session, int reexchange,
         key_state->state = libssh2_NB_state_sent2;
     }
 
-    if (rc == 0) {
+    if (rc == 0 && session->kex) {
         if (key_state->state == libssh2_NB_state_sent2) {
             retcode = session->kex->exchange_keys(session,
                                                   &key_state->key_state_low);
@@ -1866,7 +2647,7 @@ libssh2_session_method_pref(LIBSSH2_SESSION * session, int method_type,
     }
     memcpy(s, prefs, prefs_len + 1);
 
-    while (s && *s) {
+    while (s && *s && mlist) {
         char *p = strchr(s, ',');
         int method_len = p ? (p - s) : (int) strlen(s);
 
diff --git a/pgadmin/libssh2/knownhost.c b/pgadmin/libssh2/knownhost.c
index 1087bc2..a32dcf8 100644
--- a/pgadmin/libssh2/knownhost.c
+++ b/pgadmin/libssh2/knownhost.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2011 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -50,7 +50,11 @@ struct known_host {
     size_t salt_len; /* size of salt */
     char *key;       /* the (allocated) associated key. This is kept base64
                         encoded in memory. */
-    char *comment;   /* the (allocated) optional comment text, may be NULL */
+    char *key_type_name; /* the (allocated) key type name */
+    size_t key_type_len; /* size of key_type_name */
+    char *comment;       /* the (allocated) optional comment text, may be
+                            NULL */
+    size_t comment_len;  /* the size of comment */
 
     /* this is the struct we expose externally */
     struct libssh2_knownhost external;
@@ -67,6 +71,8 @@ static void free_host(LIBSSH2_SESSION *session, struct known_host *entry)
     if(entry) {
         if(entry->comment)
             LIBSSH2_FREE(session, entry->comment);
+        if (entry->key_type_name)
+            LIBSSH2_FREE(session, entry->key_type_name);
         if(entry->key)
             LIBSSH2_FREE(session, entry->key);
         if(entry->salt)
@@ -127,6 +133,7 @@ static struct libssh2_knownhost *knownhost_to_external(struct known_host *node)
 static int
 knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
               const char *host, const char *salt,
+              const char *key_type_name, size_t key_type_len,
               const char *key, size_t keylen,
               const char *comment, size_t commentlen,
               int typemask, struct libssh2_knownhost **store)
@@ -142,13 +149,11 @@ knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
         return _libssh2_error(hosts->session, LIBSSH2_ERROR_INVAL,
                               "No key type set");
 
-    if(!(entry = LIBSSH2_ALLOC(hosts->session, sizeof(struct known_host))))
+    if(!(entry = LIBSSH2_CALLOC(hosts->session, sizeof(struct known_host))))
         return _libssh2_error(hosts->session, LIBSSH2_ERROR_ALLOC,
                               "Unable to allocate memory for known host "
                               "entry");
 
-    memset(entry, 0, sizeof(struct known_host));
-
     entry->typemask = typemask;
 
     switch(entry->typemask  & LIBSSH2_KNOWNHOST_TYPE_MASK) {
@@ -161,6 +166,7 @@ knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
             goto error;
         }
         memcpy(entry->name, host, hostlen+1);
+        entry->name_len = hostlen;
         break;
     case LIBSSH2_KNOWNHOST_TYPE_SHA1:
         rc = libssh2_base64_decode(hosts->session, &ptr, &ptrlen,
@@ -210,6 +216,19 @@ knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
         entry->key = ptr;
     }
 
+    if (key_type_name && ((typemask & LIBSSH2_KNOWNHOST_KEY_MASK) ==
+                          LIBSSH2_KNOWNHOST_KEY_UNKNOWN)) {
+        entry->key_type_name = LIBSSH2_ALLOC(hosts->session, key_type_len+1);
+        if (!entry->key_type_name) {
+            rc = _libssh2_error(hosts->session, LIBSSH2_ERROR_ALLOC,
+                                "Unable to allocate memory for key type");
+            goto error;
+        }
+        memcpy(entry->key_type_name, key_type_name, key_type_len);
+        entry->key_type_name[key_type_len]=0;
+        entry->key_type_len = key_type_len;
+    }
+
     if (comment) {
         entry->comment = LIBSSH2_ALLOC(hosts->session, commentlen+1);
         if(!entry->comment) {
@@ -219,6 +238,7 @@ knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
         }
         memcpy(entry->comment, comment, commentlen+1);
         entry->comment[commentlen]=0; /* force a terminating zero trailer */
+        entry->comment_len = commentlen;
     }
     else {
         entry->comment = NULL;
@@ -264,8 +284,8 @@ libssh2_knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
                       const char *key, size_t keylen,
                       int typemask, struct libssh2_knownhost **store)
 {
-    return knownhost_add(hosts, host, salt, key, keylen, NULL, 0, typemask,
-                         store);
+    return knownhost_add(hosts, host, salt, NULL, 0, key, keylen, NULL,
+                         0, typemask, store);
 }
 
 
@@ -303,8 +323,8 @@ libssh2_knownhost_addc(LIBSSH2_KNOWNHOSTS *hosts,
                        const char *comment, size_t commentlen,
                        int typemask, struct libssh2_knownhost **store)
 {
-    return knownhost_add(hosts, host, salt, key, keylen, comment, commentlen,
-                         typemask, store);
+    return knownhost_add(hosts, host, salt, NULL, 0, key, keylen,
+                         comment, commentlen, typemask, store);
 }
 
 /*
@@ -346,6 +366,24 @@ knownhost_check(LIBSSH2_KNOWNHOSTS *hosts,
         /* we can't work with a sha1 as given input */
         return LIBSSH2_KNOWNHOST_CHECK_MISMATCH;
 
+    /* if a port number is given, check for a '[host]:port' first before the
+       plain 'host' */
+    if(port >= 0) {
+        int len = snprintf(hostbuff, sizeof(hostbuff), "[%s]:%d", hostp, port);
+        if (len < 0 || len >= (int)sizeof(hostbuff)) {
+            _libssh2_error(hosts->session,
+                           LIBSSH2_ERROR_BUFFER_TOO_SMALL,
+                           "Known-host write buffer too small");
+            return LIBSSH2_KNOWNHOST_CHECK_FAILURE;
+        }
+        host = hostbuff;
+        numcheck = 2; /* check both combos, start with this */
+    }
+    else {
+        host = hostp;
+        numcheck = 1; /* only check this host version */
+    }
+
     if(!(typemask & LIBSSH2_KNOWNHOST_KEYENC_BASE64)) {
         /* we got a raw key input, convert it to base64 for the checks below */
         size_t nlen = _libssh2_base64_encode(hosts->session, key, keylen,
@@ -361,18 +399,6 @@ knownhost_check(LIBSSH2_KNOWNHOSTS *hosts,
         key = keyalloc;
     }
 
-    /* if a port number is given, check for a '[host]:port' first before the
-       plain 'host' */
-    if(port >= 0) {
-        snprintf(hostbuff, sizeof(hostbuff), "[%s]:%d", hostp, port);
-        host = hostbuff;
-        numcheck = 2; /* check both combos, start with this */
-    }
-    else {
-        host = hostp;
-        numcheck = 1; /* only check this host version */
-    }
-
     do {
         node = _libssh2_list_first(&hosts->head);
         while (node) {
@@ -391,15 +417,17 @@ knownhost_check(LIBSSH2_KNOWNHOSTS *hosts,
                        plain input to produce a hash to compare with the
                        stored hash.
                     */
-                    libssh2_hmac_ctx ctx;
                     unsigned char hash[SHA_DIGEST_LENGTH];
+                    libssh2_hmac_ctx ctx;
+                    libssh2_hmac_ctx_init(ctx);
 
                     if(SHA_DIGEST_LENGTH != node->name_len) {
                         /* the name hash length must be the sha1 size or
                            we can't match it */
                         break;
                     }
-                    libssh2_hmac_sha1_init(&ctx, node->salt, node->salt_len);
+                    libssh2_hmac_sha1_init(&ctx, (unsigned char *)node->salt,
+                                           node->salt_len);
                     libssh2_hmac_update(ctx, (unsigned char *)host,
                                         strlen(host));
                     libssh2_hmac_final(ctx, hash);
@@ -414,23 +442,35 @@ knownhost_check(LIBSSH2_KNOWNHOSTS *hosts,
                 break;
             }
             if(match) {
-                /* host name match, now compare the keys */
-                if(!strcmp(key, node->key)) {
-                    /* they match! */
-                    if (ext)
-                        *ext = knownhost_to_external(node);
-                    badkey = NULL;
-                    rc = LIBSSH2_KNOWNHOST_CHECK_MATCH;
-                    break;
-                }
-                else {
-                    /* remember the first node that had a host match but a
-                       failed key match since we continue our search from
-                       here */
-                    if(!badkey)
-                        badkey = node;
-                    match = 0; /* don't count this as a match anymore */
+                int host_key_type = typemask & LIBSSH2_KNOWNHOST_KEY_MASK;
+                int known_key_type =
+                    node->typemask & LIBSSH2_KNOWNHOST_KEY_MASK;
+                /* match on key type as follows:
+                   - never match on an unknown key type
+                   - if key_type is set to zero, ignore it an match always
+                   - otherwise match when both key types are equal
+                */
+                if ( (host_key_type != LIBSSH2_KNOWNHOST_KEY_UNKNOWN ) &&
+                     ( (host_key_type == 0) ||
+                       (host_key_type == known_key_type) ) ) {
+                    /* host name and key type match, now compare the keys */
+                    if(!strcmp(key, node->key)) {
+                        /* they match! */
+                        if (ext)
+                            *ext = knownhost_to_external(node);
+                        badkey = NULL;
+                        rc = LIBSSH2_KNOWNHOST_CHECK_MATCH;
+                        break;
+                    }
+                    else {
+                        /* remember the first node that had a host match but a
+                           failed key match since we continue our search from
+                           here */
+                        if(!badkey)
+                            badkey = node;
+                    }
                 }
+                match = 0; /* don't count this as a match anymore */
             }
             node= _libssh2_list_next(&node->node);
         }
@@ -573,6 +613,7 @@ libssh2_knownhost_free(LIBSSH2_KNOWNHOSTS *hosts)
 */
 static int oldstyle_hostline(LIBSSH2_KNOWNHOSTS *hosts,
                              const char *host, size_t hostlen,
+                             const char *key_type_name, size_t key_type_len,
                              const char *key, size_t keylen, int key_type,
                              const char *comment, size_t commentlen)
 {
@@ -607,7 +648,9 @@ static int oldstyle_hostline(LIBSSH2_KNOWNHOSTS *hosts,
             memcpy(hostbuf, name, namelen);
             hostbuf[namelen]=0;
 
-            rc = knownhost_add(hosts, hostbuf, NULL, key, keylen,
+            rc = knownhost_add(hosts, hostbuf, NULL,
+                               key_type_name, key_type_len,
+                               key, keylen,
                                comment, commentlen,
                                key_type | LIBSSH2_KNOWNHOST_TYPE_PLAIN |
                                LIBSSH2_KNOWNHOST_KEYENC_BASE64, NULL);
@@ -627,6 +670,7 @@ static int oldstyle_hostline(LIBSSH2_KNOWNHOSTS *hosts,
 /* |1|[salt]|[hash] */
 static int hashed_hostline(LIBSSH2_KNOWNHOSTS *hosts,
                            const char *host, size_t hostlen,
+                           const char *key_type_name, size_t key_type_len,
                            const char *key, size_t keylen, int key_type,
                            const char *comment, size_t commentlen)
 {
@@ -670,9 +714,11 @@ static int hashed_hostline(LIBSSH2_KNOWNHOSTS *hosts,
         memcpy(hostbuf, host, hostlen);
         hostbuf[hostlen]=0;
 
-        return knownhost_add(hosts, hostbuf, salt, key, keylen, comment,
-                             commentlen,
-                             key_type | LIBSSH2_KNOWNHOST_TYPE_SHA1 | 
+        return knownhost_add(hosts, hostbuf, salt,
+                             key_type_name, key_type_len,
+                             key, keylen,
+                             comment, commentlen,
+                             key_type | LIBSSH2_KNOWNHOST_TYPE_SHA1 |
                              LIBSSH2_KNOWNHOST_KEYENC_BASE64, NULL);
     }
     else
@@ -694,7 +740,9 @@ static int hostline(LIBSSH2_KNOWNHOSTS *hosts,
                     const char *key, size_t keylen)
 {
     const char *comment = NULL;
+    const char *key_type_name = NULL;
     size_t commentlen = 0;
+    size_t key_type_len = 0;
     int key_type;
 
     /* make some checks that the lengths seem sensible */
@@ -703,7 +751,7 @@ static int hostline(LIBSSH2_KNOWNHOSTS *hosts,
                               LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
                               "Failed to parse known_hosts line "
                               "(key too short)");
-    
+
     switch(key[0]) {
     case '0': case '1': case '2': case '3': case '4':
     case '5': case '6': case '7': case '8': case '9':
@@ -716,19 +764,21 @@ static int hostline(LIBSSH2_KNOWNHOSTS *hosts,
          */
         break;
 
-    case 's': /* ssh-dss or ssh-rsa */
-        if(!strncmp(key, "ssh-dss", 7))
+    default:
+        key_type_name = key;
+        while (keylen && *key &&
+               (*key != ' ') && (*key != '\t')) {
+            key++;
+            keylen--;
+        }
+        key_type_len = key - key_type_name;
+
+        if (!strncmp(key_type_name, "ssh-dss", key_type_len))
             key_type = LIBSSH2_KNOWNHOST_KEY_SSHDSS;
-        else if(!strncmp(key, "ssh-rsa", 7))
+        else if (!strncmp(key_type_name, "ssh-rsa", key_type_len))
             key_type = LIBSSH2_KNOWNHOST_KEY_SSHRSA;
         else
-            /* unknown key type */
-            return _libssh2_error(hosts->session,
-                                  LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
-                                  "Unknown key type");
-
-        key += 7;
-        keylen -= 7;
+            key_type = LIBSSH2_KNOWNHOST_KEY_UNKNOWN;
 
         /* skip whitespaces */
         while((*key ==' ') || (*key == '\t')) {
@@ -760,11 +810,6 @@ static int hostline(LIBSSH2_KNOWNHOSTS *hosts,
             commentlen--;
         }
         break;
-
-    default: /* unknown key format */
-        return _libssh2_error(hosts->session,
-                              LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
-                              "Unknown key format");
     }
 
     /* Figure out host format */
@@ -774,12 +819,14 @@ static int hostline(LIBSSH2_KNOWNHOSTS *hosts,
            for the sake of simplicity, we add them as separate hosts with the
            same key
         */
-        return oldstyle_hostline(hosts, host, hostlen, key, keylen, key_type,
+        return oldstyle_hostline(hosts, host, hostlen, key_type_name,
+                                 key_type_len, key, keylen, key_type,
                                  comment, commentlen);
     }
     else {
         /* |1|[salt]|[hash] */
-        return hashed_hostline(hosts, host, hostlen, key, keylen, key_type,
+        return hashed_hostline(hosts, host, hostlen, key_type_name,
+                               key_type_len, key, keylen, key_type,
                                comment, commentlen);
     }
 }
@@ -943,17 +990,10 @@ knownhost_writeline(LIBSSH2_KNOWNHOSTS *hosts,
                     char *buf, size_t buflen,
                     size_t *outlen, int type)
 {
-    int rc = LIBSSH2_ERROR_NONE;
-    int tindex;
-    const char *keytypes[4]={
-        "", /* not used */
-        "", /* this type has no name in the file */
-        " ssh-rsa",
-        " ssh-dss"
-    };
-    const char *keytype;
-    size_t nlen;
-    size_t commentlen = 0;
+    size_t required_size;
+
+    const char *key_type_name;
+    size_t key_type_len;
 
     /* we only support this single file type for now, bail out on all other
        attempts */
@@ -963,75 +1003,131 @@ knownhost_writeline(LIBSSH2_KNOWNHOSTS *hosts,
                               "Unsupported type of known-host information "
                               "store");
 
-    tindex = (node->typemask & LIBSSH2_KNOWNHOST_KEY_MASK) >>
-        LIBSSH2_KNOWNHOST_KEY_SHIFT;
-
-    /* set the string used in the file */
-    keytype = keytypes[tindex];
+    switch(node->typemask & LIBSSH2_KNOWNHOST_KEY_MASK) {
+    case LIBSSH2_KNOWNHOST_KEY_RSA1:
+        key_type_name = NULL;
+        key_type_len = 0;
+        break;
+    case LIBSSH2_KNOWNHOST_KEY_SSHRSA:
+        key_type_name = "ssh-rsa";
+        key_type_len = 7;
+        break;
+    case LIBSSH2_KNOWNHOST_KEY_SSHDSS:
+        key_type_name = "ssh-dss";
+        key_type_len = 7;
+        break;
+    case LIBSSH2_KNOWNHOST_KEY_UNKNOWN:
+        key_type_name = node->key_type_name;
+        if (key_type_name) {
+            key_type_len = node->key_type_len;
+            break;
+        }
+        /* otherwise fallback to default and error */
+    default:
+        return _libssh2_error(hosts->session,
+                              LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
+                              "Unsupported type of known-host entry");
+    }
 
-    /* calculate extra space needed for comment */
+    /* When putting together the host line there are three aspects to consider:
+       - Hashed (SHA1) or unhashed hostname
+       - key name or no key name (RSA1)
+       - comment or no comment
+      
+       This means there are 2^3 different formats:
+       ("|1|%s|%s %s %s %s\n", salt, hashed_host, key_name, key, comment)
+       ("|1|%s|%s %s %s\n", salt, hashed_host, key_name, key)
+       ("|1|%s|%s %s %s\n", salt, hashed_host, key, comment)
+       ("|1|%s|%s %s\n", salt, hashed_host, key)
+       ("%s %s %s %s\n", host, key_name, key, comment)
+       ("%s %s %s\n", host, key_name, key)
+       ("%s %s %s\n", host, key, comment)
+       ("%s %s\n", host, key)
+      
+       Even if the buffer is too small, we have to set outlen to the number of
+       characters the complete line would have taken.  We also don't write
+       anything to the buffer unless we are sure we can write everything to the
+       buffer. */
+
+    required_size = strlen(node->key);
+
+    if(key_type_len)
+        required_size += key_type_len + 1; /* ' ' = 1 */
     if(node->comment)
-        commentlen = strlen(node->comment) + 1;
+        required_size += node->comment_len + 1; /* ' ' = 1 */
 
     if((node->typemask & LIBSSH2_KNOWNHOST_TYPE_MASK) ==
        LIBSSH2_KNOWNHOST_TYPE_SHA1) {
         char *namealloc;
+        size_t name_base64_len;
         char *saltalloc;
-        nlen = _libssh2_base64_encode(hosts->session, node->name,
-                                      node->name_len, &namealloc);
-        if(!nlen)
+        size_t salt_base64_len;
+
+        name_base64_len = _libssh2_base64_encode(hosts->session, node->name,
+                                                 node->name_len, &namealloc);
+        if(!name_base64_len)
             return _libssh2_error(hosts->session, LIBSSH2_ERROR_ALLOC,
                                   "Unable to allocate memory for "
                                   "base64-encoded host name");
 
-        nlen = _libssh2_base64_encode(hosts->session,
-                                      node->salt, node->salt_len,
-                                      &saltalloc);
-        if(!nlen) {
-            free(namealloc);
+        salt_base64_len = _libssh2_base64_encode(hosts->session,
+                                                 node->salt, node->salt_len,
+                                                 &saltalloc);
+        if(!salt_base64_len) {
+            LIBSSH2_FREE(hosts->session, namealloc);
             return _libssh2_error(hosts->session, LIBSSH2_ERROR_ALLOC,
                                   "Unable to allocate memory for "
                                   "base64-encoded salt");
         }
 
-        nlen = strlen(saltalloc) + strlen(namealloc) + strlen(keytype) +
-            strlen(node->key) + commentlen + 7;
+        required_size += salt_base64_len + name_base64_len + 7;
         /* |1| + | + ' ' + \n + \0 = 7 */
 
-        if(nlen <= buflen)
-            if(node->comment)
-                snprintf(buf, buflen, "|1|%s|%s%s %s %s\n", saltalloc, namealloc,
-                        keytype, node->key, node->comment);
+        if(required_size <= buflen) {
+            if(node->comment && key_type_len)
+                snprintf(buf, buflen, "|1|%s|%s %s %s %s\n", saltalloc,
+                         namealloc, key_type_name, node->key, node->comment);
+            else if (node->comment)
+                snprintf(buf, buflen, "|1|%s|%s %s %s\n", saltalloc, namealloc,
+                         node->key, node->comment);
+            else if (key_type_len)
+                snprintf(buf, buflen, "|1|%s|%s %s %s\n", saltalloc, namealloc,
+                         key_type_name, node->key);
             else
-                snprintf(buf, buflen, "|1|%s|%s%s %s\n", saltalloc, namealloc,
-                        keytype, node->key);
-        else
-            rc = _libssh2_error(hosts->session, LIBSSH2_ERROR_BUFFER_TOO_SMALL,
-                                "Known-host write buffer too small");
+                snprintf(buf, buflen, "|1|%s|%s %s\n", saltalloc, namealloc,
+                         node->key);
+        }
 
-        free(namealloc);
-        free(saltalloc);
+        LIBSSH2_FREE(hosts->session, namealloc);
+        LIBSSH2_FREE(hosts->session, saltalloc);
     }
     else {
-        nlen = strlen(node->name) + strlen(keytype) + strlen(node->key) +
-            commentlen + 3;
+        required_size += node->name_len + 3;
         /* ' ' + '\n' + \0 = 3 */
-        if(nlen <= buflen)
-            /* these types have the plain name */
-            if(node->comment)
-                snprintf(buf, buflen, "%s%s %s %s\n", node->name, keytype, node->key,
-                        node->comment);
+
+        if(required_size <= buflen) {
+            if(node->comment && key_type_len)
+                snprintf(buf, buflen, "%s %s %s %s\n", node->name,
+                         key_type_name, node->key, node->comment);
+            else if (node->comment)
+                snprintf(buf, buflen, "%s %s %s\n", node->name, node->key,
+                         node->comment);
+            else if (key_type_len)
+                snprintf(buf, buflen, "%s %s %s\n", node->name, key_type_name,
+                         node->key);
             else
-                snprintf(buf, buflen, "%s%s %s\n", node->name, keytype, node->key);
-        else
-            rc = _libssh2_error(hosts->session, LIBSSH2_ERROR_BUFFER_TOO_SMALL,
-                                "Known-host write buffer too small");
+                snprintf(buf, buflen, "%s %s\n", node->name, node->key);
+        }
     }
 
     /* we report the full length of the data with the trailing zero excluded */
-    *outlen = nlen-1;
+    *outlen = required_size-1;
 
-    return rc;
+    if(required_size <= buflen)
+        return LIBSSH2_ERROR_NONE;
+    else
+        return _libssh2_error(hosts->session, LIBSSH2_ERROR_BUFFER_TOO_SMALL,
+                              "Known-host write buffer too small");
 }
 
 /*
@@ -1089,8 +1185,8 @@ libssh2_knownhost_writefile(LIBSSH2_KNOWNHOSTS *hosts,
 
     for(node = _libssh2_list_first(&hosts->head);
         node;
-        node= _libssh2_list_next(&node->node) ) {
-        size_t wrote;
+        node = _libssh2_list_next(&node->node)) {
+        size_t wrote = 0;
         size_t nwrote;
         rc = knownhost_writeline(hosts, node, buffer, sizeof(buffer), &wrote,
                                  type);
diff --git a/pgadmin/libssh2/libgcrypt.c b/pgadmin/libssh2/libgcrypt.c
index 29770c7..e85aecd 100644
--- a/pgadmin/libssh2/libgcrypt.c
+++ b/pgadmin/libssh2/libgcrypt.c
@@ -150,6 +150,17 @@ _libssh2_dsa_new(libssh2_dsa_ctx ** dsactx,
 }
 
 int
+_libssh2_rsa_new_private_frommemory(libssh2_rsa_ctx ** rsa,
+                                    LIBSSH2_SESSION * session,
+                                    const char *filedata, size_t filedata_len,
+                                    unsigned const char *passphrase)
+{
+    return _libssh2_error(session, LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
+                         "Unable to extract private key from memory: "
+                         "Method unimplemented in libgcrypt backend");
+}
+
+int
 _libssh2_rsa_new_private(libssh2_rsa_ctx ** rsa,
                          LIBSSH2_SESSION * session,
                          const char *filename, unsigned const char *passphrase)
@@ -252,6 +263,17 @@ _libssh2_rsa_new_private(libssh2_rsa_ctx ** rsa,
 }
 
 int
+_libssh2_dsa_new_private_frommemory(libssh2_dsa_ctx ** dsa,
+                                    LIBSSH2_SESSION * session,
+                                    const char *filedata, size_t filedata_len,
+                                    unsigned const char *passphrase)
+{
+    return _libssh2_error(session, LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
+                         "Unable to extract private key from memory: "
+                         "Method unimplemented in libgcrypt backend");
+}
+
+int
 _libssh2_dsa_new_private(libssh2_dsa_ctx ** dsa,
                          LIBSSH2_SESSION * session,
                          const char *filename, unsigned const char *passphrase)
@@ -342,7 +364,7 @@ _libssh2_dsa_new_private(libssh2_dsa_ctx ** dsa,
 
 int
 _libssh2_rsa_sha1_sign(LIBSSH2_SESSION * session,
-                       libssh2_dsa_ctx * rsactx,
+                       libssh2_rsa_ctx * rsactx,
                        const unsigned char *hash,
                        size_t hash_len,
                        unsigned char **signature, size_t *signature_len)
@@ -567,6 +589,21 @@ _libssh2_cipher_crypt(_libssh2_cipher_ctx * ctx,
 }
 
 int
+_libssh2_pub_priv_keyfilememory(LIBSSH2_SESSION *session,
+                                unsigned char **method,
+                                size_t *method_len,
+                                unsigned char **pubkeydata,
+                                size_t *pubkeydata_len,
+                                const char *privatekeydata,
+                                size_t privatekeydata_len,
+                                const char *passphrase)
+{
+    return _libssh2_error(session, LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
+                         "Unable to extract public key from private key in memory: "
+                         "Method unimplemented in libgcrypt backend");
+}
+
+int
 _libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session,
                           unsigned char **method,
                           size_t *method_len,
diff --git a/pgadmin/libssh2/mac.c b/pgadmin/libssh2/mac.c
index 76894fc..5ec26eb 100644
--- a/pgadmin/libssh2/mac.c
+++ b/pgadmin/libssh2/mac.c
@@ -96,6 +96,97 @@ mac_method_common_dtor(LIBSSH2_SESSION * session, void **abstract)
 
 
 
+#if LIBSSH2_HMAC_SHA512
+/* mac_method_hmac_sha512_hash
+ * Calculate hash using full sha512 value
+ */
+static int
+mac_method_hmac_sha2_512_hash(LIBSSH2_SESSION * session,
+                          unsigned char *buf, uint32_t seqno,
+                          const unsigned char *packet,
+                          uint32_t packet_len,
+                          const unsigned char *addtl,
+                          uint32_t addtl_len, void **abstract)
+{
+    libssh2_hmac_ctx ctx;
+    unsigned char seqno_buf[4];
+    (void) session;
+
+    _libssh2_htonu32(seqno_buf, seqno);
+
+    libssh2_hmac_ctx_init(ctx);
+    libssh2_hmac_sha512_init(&ctx, *abstract, 64);
+    libssh2_hmac_update(ctx, seqno_buf, 4);
+    libssh2_hmac_update(ctx, packet, packet_len);
+    if (addtl && addtl_len) {
+        libssh2_hmac_update(ctx, addtl, addtl_len);
+    }
+    libssh2_hmac_final(ctx, buf);
+    libssh2_hmac_cleanup(&ctx);
+
+    return 0;
+}
+
+
+
+static const LIBSSH2_MAC_METHOD mac_method_hmac_sha2_512 = {
+    "hmac-sha2-512",
+    64,
+    64,
+    mac_method_common_init,
+    mac_method_hmac_sha2_512_hash,
+    mac_method_common_dtor,
+};
+#endif
+
+
+
+#if LIBSSH2_HMAC_SHA256
+/* mac_method_hmac_sha256_hash
+ * Calculate hash using full sha256 value
+ */
+static int
+mac_method_hmac_sha2_256_hash(LIBSSH2_SESSION * session,
+                          unsigned char *buf, uint32_t seqno,
+                          const unsigned char *packet,
+                          uint32_t packet_len,
+                          const unsigned char *addtl,
+                          uint32_t addtl_len, void **abstract)
+{
+    libssh2_hmac_ctx ctx;
+    unsigned char seqno_buf[4];
+    (void) session;
+
+    _libssh2_htonu32(seqno_buf, seqno);
+
+    libssh2_hmac_ctx_init(ctx);
+    libssh2_hmac_sha256_init(&ctx, *abstract, 32);
+    libssh2_hmac_update(ctx, seqno_buf, 4);
+    libssh2_hmac_update(ctx, packet, packet_len);
+    if (addtl && addtl_len) {
+        libssh2_hmac_update(ctx, addtl, addtl_len);
+    }
+    libssh2_hmac_final(ctx, buf);
+    libssh2_hmac_cleanup(&ctx);
+
+    return 0;
+}
+
+
+
+static const LIBSSH2_MAC_METHOD mac_method_hmac_sha2_256 = {
+    "hmac-sha2-256",
+    32,
+    32,
+    mac_method_common_init,
+    mac_method_hmac_sha2_256_hash,
+    mac_method_common_dtor,
+};
+#endif
+
+
+
+
 /* mac_method_hmac_sha1_hash
  * Calculate hash using full sha1 value
  */
@@ -113,6 +204,7 @@ mac_method_hmac_sha1_hash(LIBSSH2_SESSION * session,
 
     _libssh2_htonu32(seqno_buf, seqno);
 
+    libssh2_hmac_ctx_init(ctx);
     libssh2_hmac_sha1_init(&ctx, *abstract, 20);
     libssh2_hmac_update(ctx, seqno_buf, 4);
     libssh2_hmac_update(ctx, packet, packet_len);
@@ -185,6 +277,7 @@ mac_method_hmac_md5_hash(LIBSSH2_SESSION * session, unsigned char *buf,
 
     _libssh2_htonu32(seqno_buf, seqno);
 
+    libssh2_hmac_ctx_init(ctx);
     libssh2_hmac_md5_init(&ctx, *abstract, 16);
     libssh2_hmac_update(ctx, seqno_buf, 4);
     libssh2_hmac_update(ctx, packet, packet_len);
@@ -257,6 +350,7 @@ mac_method_hmac_ripemd160_hash(LIBSSH2_SESSION * session,
 
     _libssh2_htonu32(seqno_buf, seqno);
 
+    libssh2_hmac_ctx_init(ctx);
     libssh2_hmac_ripemd160_init(&ctx, *abstract, 20);
     libssh2_hmac_update(ctx, seqno_buf, 4);
     libssh2_hmac_update(ctx, packet, packet_len);
@@ -291,6 +385,12 @@ static const LIBSSH2_MAC_METHOD mac_method_hmac_ripemd160_openssh_com = {
 #endif /* LIBSSH2_HMAC_RIPEMD */
 
 static const LIBSSH2_MAC_METHOD *mac_methods[] = {
+#if LIBSSH2_HMAC_SHA256
+    &mac_method_hmac_sha2_256,
+#endif
+#if LIBSSH2_HMAC_SHA512
+    &mac_method_hmac_sha2_512,
+#endif
     &mac_method_hmac_sha1,
     &mac_method_hmac_sha1_96,
 #if LIBSSH2_MD5
diff --git a/pgadmin/libssh2/misc.c b/pgadmin/libssh2/misc.c
index a9f423a..320df44 100644
--- a/pgadmin/libssh2/misc.c
+++ b/pgadmin/libssh2/misc.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2007 Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2009-2010 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * Copyright (c) 2010  Simon Josefsson
  * All rights reserved.
  *
@@ -51,10 +51,29 @@
 #include <stdio.h>
 #include <errno.h>
 
-int _libssh2_error(LIBSSH2_SESSION* session, int errcode, const char* errmsg)
+int _libssh2_error_flags(LIBSSH2_SESSION* session, int errcode, const char* errmsg, int errflags)
 {
-    session->err_msg = errmsg;
+    if (session->err_flags & LIBSSH2_ERR_FLAG_DUP)
+        LIBSSH2_FREE(session, (char *)session->err_msg);
+
     session->err_code = errcode;
+    session->err_flags = 0;
+
+    if ((errmsg != NULL) && ((errflags & LIBSSH2_ERR_FLAG_DUP) != 0)) {
+        size_t len = strlen(errmsg);
+        char *copy = LIBSSH2_ALLOC(session, len + 1);
+        if (copy) {
+            memcpy(copy, errmsg, len + 1);
+            session->err_flags = LIBSSH2_ERR_FLAG_DUP;
+            session->err_msg = copy;
+        }
+        else
+            /* Out of memory: this code path is very unlikely */
+            session->err_msg = "former error forgotten (OOM)";
+    }
+    else
+        session->err_msg = errmsg;
+
 #ifdef LIBSSH2DEBUG
     if((errcode == LIBSSH2_ERROR_EAGAIN) && !session->api_block_mode)
         /* if this is EAGAIN and we're in non-blocking mode, don't generate
@@ -67,6 +86,11 @@ int _libssh2_error(LIBSSH2_SESSION* session, int errcode, const char* errmsg)
     return errcode;
 }
 
+int _libssh2_error(LIBSSH2_SESSION* session, int errcode, const char* errmsg)
+{
+    return _libssh2_error_flags(session, errcode, errmsg, 0);
+}
+
 #ifdef WIN32
 static int wsa2errno(void)
 {
@@ -94,9 +118,14 @@ static int wsa2errno(void)
  * Replacement for the standard recv, return -errno on failure.
  */
 ssize_t
-_libssh2_recv(libssh2_socket_t sock, void *buffer, size_t length, int flags, void **abstract)
+_libssh2_recv(libssh2_socket_t sock, void *buffer, size_t length,
+              int flags, void **abstract)
 {
-    ssize_t rc = recv(sock, buffer, length, flags);
+    ssize_t rc;
+
+    (void) abstract;
+
+    rc = recv(sock, buffer, length, flags);
 #ifdef WIN32
     if (rc < 0 )
         return -wsa2errno();
@@ -128,7 +157,11 @@ ssize_t
 _libssh2_send(libssh2_socket_t sock, const void *buffer, size_t length,
               int flags, void **abstract)
 {
-    ssize_t rc = send(sock, buffer, length, flags);
+    ssize_t rc;
+
+    (void) abstract;
+
+    rc = send(sock, buffer, length, flags);
 #ifdef WIN32
     if (rc < 0 )
         return -wsa2errno();
@@ -257,15 +290,15 @@ libssh2_base64_decode(LIBSSH2_SESSION *session, char **data,
             continue;
         switch (i % 4) {
         case 0:
-            d[len] = v << 2;
+            d[len] = (unsigned char)(v << 2);
             break;
         case 1:
             d[len++] |= v >> 4;
-            d[len] = v << 4;
+            d[len] = (unsigned char)(v << 4);
             break;
         case 2:
             d[len++] |= v >> 2;
-            d[len] = v << 6;
+            d[len] = (unsigned char)(v << 6);
             break;
         case 3:
             d[len++] |= v;
@@ -596,7 +629,7 @@ int __cdecl _libssh2_gettimeofday(struct timeval *tp, void *tzp)
     unsigned __int64 ns100; /*time since 1 Jan 1601 in 100ns units */
     FILETIME ft;
   }  _now;
-
+  (void)tzp;
   if(tp)
     {
       GetSystemTimeAsFileTime (&_now.ft);
@@ -610,3 +643,12 @@ int __cdecl _libssh2_gettimeofday(struct timeval *tp, void *tzp)
 
 
 #endif
+
+void *_libssh2_calloc(LIBSSH2_SESSION* session, size_t size)
+{
+    void *p = LIBSSH2_ALLOC(session, size);
+    if(p) {
+        memset(p, 0, size);
+    }
+    return p;
+}
diff --git a/pgadmin/libssh2/openssl.c b/pgadmin/libssh2/openssl.c
index 29c8f47..c3de2d1 100644
--- a/pgadmin/libssh2/openssl.c
+++ b/pgadmin/libssh2/openssl.c
@@ -40,7 +40,7 @@
 
 #include "libssh2_priv.h"
 
-#ifndef LIBSSH2_LIBGCRYPT /* compile only if we build with OpenSSL */
+#ifdef LIBSSH2_OPENSSL /* compile only if we build with openssl */
 
 #include <string.h>
 
@@ -105,7 +105,8 @@ _libssh2_rsa_sha1_verify(libssh2_rsa_ctx * rsactx,
     unsigned char hash[SHA_DIGEST_LENGTH];
     int ret;
 
-    libssh2_sha1(m, m_len, hash);
+    if (_libssh2_sha1(m, m_len, hash))
+        return -1; /* failure */
     ret = RSA_verify(NID_sha1, hash, SHA_DIGEST_LENGTH,
                      (unsigned char *) sig, sig_len, rsactx);
     return (ret == 1) ? 0 : -1;
@@ -153,15 +154,17 @@ _libssh2_dsa_sha1_verify(libssh2_dsa_ctx * dsactx,
 {
     unsigned char hash[SHA_DIGEST_LENGTH];
     DSA_SIG dsasig;
-    int ret;
+    int ret = -1;
 
     dsasig.r = BN_new();
     BN_bin2bn(sig, 20, dsasig.r);
     dsasig.s = BN_new();
     BN_bin2bn(sig + 20, 20, dsasig.s);
 
-    libssh2_sha1(m, m_len, hash);
-    ret = DSA_do_verify(hash, SHA_DIGEST_LENGTH, &dsasig, dsactx);
+    if (!_libssh2_sha1(m, m_len, hash))
+        /* _libssh2_sha1() succeeded */
+        ret = DSA_do_verify(hash, SHA_DIGEST_LENGTH, &dsasig, dsactx);
+
     BN_clear_free(dsasig.s);
     BN_clear_free(dsasig.r);
 
@@ -388,6 +391,28 @@ typedef void * (*pem_read_bio_func)(BIO *, void **, pem_password_cb *,
                                     void * u);
 
 static int
+read_private_key_from_memory(void ** key_ctx,
+                             pem_read_bio_func read_private_key,
+                             const char * filedata,
+                             size_t filedata_len,
+                             unsigned const char *passphrase)
+{
+    BIO * bp;
+
+    *key_ctx = NULL;
+
+    bp = BIO_new_mem_buf((char *)filedata, filedata_len);
+    if (!bp) {
+        return -1;
+    }
+    *key_ctx = read_private_key(bp, NULL, (pem_password_cb *) passphrase_cb,
+                                (void *) passphrase);
+
+    BIO_free(bp);
+    return (*key_ctx) ? 0 : -1;
+}
+
+static int
 read_private_key_from_file(void ** key_ctx,
                            pem_read_bio_func read_private_key,
                            const char * filename,
@@ -410,6 +435,22 @@ read_private_key_from_file(void ** key_ctx,
 }
 
 int
+_libssh2_rsa_new_private_frommemory(libssh2_rsa_ctx ** rsa,
+                                    LIBSSH2_SESSION * session,
+                                    const char *filedata, size_t filedata_len,
+                                    unsigned const char *passphrase)
+{
+    pem_read_bio_func read_rsa =
+        (pem_read_bio_func) &PEM_read_bio_RSAPrivateKey;
+    (void) session;
+
+    _libssh2_init_if_needed();
+
+    return read_private_key_from_memory((void **) rsa, read_rsa,
+                                        filedata, filedata_len, passphrase);
+}
+
+int
 _libssh2_rsa_new_private(libssh2_rsa_ctx ** rsa,
                          LIBSSH2_SESSION * session,
                          const char *filename, unsigned const char *passphrase)
@@ -426,6 +467,22 @@ _libssh2_rsa_new_private(libssh2_rsa_ctx ** rsa,
 
 #if LIBSSH2_DSA
 int
+_libssh2_dsa_new_private_frommemory(libssh2_dsa_ctx ** dsa,
+                                    LIBSSH2_SESSION * session,
+                                    const char *filedata, size_t filedata_len,
+                                    unsigned const char *passphrase)
+{
+    pem_read_bio_func read_dsa =
+        (pem_read_bio_func) &PEM_read_bio_DSAPrivateKey;
+    (void) session;
+
+    _libssh2_init_if_needed();
+
+    return read_private_key_from_memory((void **) dsa, read_dsa,
+                                        filedata, filedata_len, passphrase);
+}
+
+int
 _libssh2_dsa_new_private(libssh2_dsa_ctx ** dsa,
                          LIBSSH2_SESSION * session,
                          const char *filename, unsigned const char *passphrase)
@@ -509,26 +566,55 @@ _libssh2_dsa_sha1_sign(libssh2_dsa_ctx * dsactx,
 }
 #endif /* LIBSSH_DSA */
 
-void
-libssh2_sha1(const unsigned char *message, unsigned long len,
-             unsigned char *out)
+int
+_libssh2_sha1_init(libssh2_sha1_ctx *ctx)
+{
+    EVP_MD_CTX_init(ctx);
+    return EVP_DigestInit(ctx, EVP_get_digestbyname("sha1"));
+}
+
+int
+_libssh2_sha1(const unsigned char *message, unsigned long len,
+              unsigned char *out)
 {
     EVP_MD_CTX ctx;
 
-    EVP_DigestInit(&ctx, EVP_get_digestbyname("sha1"));
-    EVP_DigestUpdate(&ctx, message, len);
-    EVP_DigestFinal(&ctx, out, NULL);
+    EVP_MD_CTX_init(&ctx);
+    if (EVP_DigestInit(&ctx, EVP_get_digestbyname("sha1"))) {
+        EVP_DigestUpdate(&ctx, message, len);
+        EVP_DigestFinal(&ctx, out, NULL);
+        return 0; /* success */
+    }
+    return 1; /* error */
+}
+
+int
+_libssh2_sha256_init(libssh2_sha256_ctx *ctx)
+{
+    EVP_MD_CTX_init(ctx);
+    return EVP_DigestInit(ctx, EVP_get_digestbyname("sha256"));
 }
 
-void
-libssh2_md5(const unsigned char *message, unsigned long len,
-            unsigned char *out)
+int
+_libssh2_sha256(const unsigned char *message, unsigned long len,
+                unsigned char *out)
 {
     EVP_MD_CTX ctx;
 
-    EVP_DigestInit(&ctx, EVP_get_digestbyname("md5"));
-    EVP_DigestUpdate(&ctx, message, len);
-    EVP_DigestFinal(&ctx, out, NULL);
+    EVP_MD_CTX_init(&ctx);
+    if(EVP_DigestInit(&ctx, EVP_get_digestbyname("sha256"))) {
+        EVP_DigestUpdate(&ctx, message, len);
+        EVP_DigestFinal(&ctx, out, NULL);
+        return 0; /* success */
+    }
+    return 1; /* error */
+}
+
+int
+_libssh2_md5_init(libssh2_md5_ctx *ctx)
+{
+    EVP_MD_CTX_init(ctx);
+    return EVP_DigestInit(ctx, EVP_get_digestbyname("md5"));
 }
 
 static unsigned char *
@@ -584,6 +670,7 @@ gen_publickey_from_rsa(LIBSSH2_SESSION *session, RSA *rsa,
     return key;
 }
 
+#if LIBSSH2_DSA
 static unsigned char *
 gen_publickey_from_dsa(LIBSSH2_SESSION* session, DSA *dsa,
                        size_t *key_len)
@@ -622,6 +709,7 @@ gen_publickey_from_dsa(LIBSSH2_SESSION* session, DSA *dsa,
     *key_len = (size_t)(p - key);
     return key;
 }
+#endif /* LIBSSH_DSA */
 
 static int
 gen_publickey_from_rsa_evp(LIBSSH2_SESSION *session,
@@ -677,6 +765,7 @@ gen_publickey_from_rsa_evp(LIBSSH2_SESSION *session,
                           "Unable to allocate memory for private key data");
 }
 
+#if LIBSSH2_DSA
 static int
 gen_publickey_from_dsa_evp(LIBSSH2_SESSION *session,
                            unsigned char **method,
@@ -730,6 +819,7 @@ gen_publickey_from_dsa_evp(LIBSSH2_SESSION *session,
                           LIBSSH2_ERROR_ALLOC,
                           "Unable to allocate memory for private key data");
 }
+#endif /* LIBSSH_DSA */
 
 int
 _libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session,
@@ -783,11 +873,80 @@ _libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session,
             session, method, method_len, pubkeydata, pubkeydata_len, pk);
         break;
 
+#if LIBSSH2_DSA
     case EVP_PKEY_DSA :
         st = gen_publickey_from_dsa_evp(
             session, method, method_len, pubkeydata, pubkeydata_len, pk);
         break;
+#endif /* LIBSSH_DSA */
+
+    default :
+        st = _libssh2_error(session,
+                            LIBSSH2_ERROR_FILE,
+                            "Unable to extract public key "
+                            "from private key file: "
+                            "Unsupported private key file format");
+        break;
+    }
+
+    EVP_PKEY_free(pk);
+    return st;
+}
+
+int
+_libssh2_pub_priv_keyfilememory(LIBSSH2_SESSION *session,
+                                unsigned char **method,
+                                size_t *method_len,
+                                unsigned char **pubkeydata,
+                                size_t *pubkeydata_len,
+                                const char *privatekeydata,
+                                size_t privatekeydata_len,
+                                const char *passphrase)
+{
+    int       st;
+    BIO*      bp;
+    EVP_PKEY* pk;
 
+    _libssh2_debug(session,
+                   LIBSSH2_TRACE_AUTH,
+                   "Computing public key from private key.");
+
+    bp = BIO_new_mem_buf((char *)privatekeydata, privatekeydata_len);
+    if (!bp) {
+        return -1;
+    }
+    if (!EVP_get_cipherbyname("des")) {
+        /* If this cipher isn't loaded it's a pretty good indication that none
+         * are.  I have *NO DOUBT* that there's a better way to deal with this
+         * ($#&%#$(%$#( Someone buy me an OpenSSL manual and I'll read up on
+         * it.
+         */
+        OpenSSL_add_all_ciphers();
+    }
+    BIO_reset(bp);
+    pk = PEM_read_bio_PrivateKey(bp, NULL, NULL, (void*)passphrase);
+    BIO_free(bp);
+
+    if (pk == NULL) {
+        return _libssh2_error(session,
+                              LIBSSH2_ERROR_FILE,
+                              "Unable to extract public key "
+                              "from private key file: "
+                              "Wrong passphrase or invalid/unrecognized "
+                              "private key file format");
+    }
+
+    switch (pk->type) {
+    case EVP_PKEY_RSA :
+        st = gen_publickey_from_rsa_evp(session, method, method_len,
+                                        pubkeydata, pubkeydata_len, pk);
+        break;
+#if LIBSSH2_DSA
+    case EVP_PKEY_DSA :
+        st = gen_publickey_from_dsa_evp(session, method, method_len,
+                                        pubkeydata, pubkeydata_len, pk);
+        break;
+#endif /* LIBSSH_DSA */
     default :
         st = _libssh2_error(session,
                             LIBSSH2_ERROR_FILE,
@@ -801,4 +960,4 @@ _libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session,
     return st;
 }
 
-#endif /* !LIBSSH2_LIBGCRYPT */
+#endif /* LIBSSH2_OPENSSL */
diff --git a/pgadmin/libssh2/packet.c b/pgadmin/libssh2/packet.c
index bfbd56a..5f1feb8 100644
--- a/pgadmin/libssh2/packet.c
+++ b/pgadmin/libssh2/packet.c
@@ -1,6 +1,6 @@
 /* Copyright (c) 2004-2007, Sara Golemon <sarag@libssh2.org>
  * Copyright (c) 2005,2006 Mikhail Gusarov
- * Copyright (c) 2009-2010 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * Copyright (c) 2010 Simon Josefsson
  * All rights reserved.
  *
@@ -139,7 +139,7 @@ packet_queue_listener(LIBSSH2_SESSION * session, unsigned char *data,
                         break;
                     }
 
-                    channel = LIBSSH2_ALLOC(session, sizeof(LIBSSH2_CHANNEL));
+                    channel = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_CHANNEL));
                     if (!channel) {
                         _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                        "Unable to allocate a channel for "
@@ -150,8 +150,6 @@ packet_queue_listener(LIBSSH2_SESSION * session, unsigned char *data,
                     }
                     listen_state->channel = channel;
 
-                    memset(channel, 0, sizeof(LIBSSH2_CHANNEL));
-
                     channel->session = session;
                     channel->channel_type_len = sizeof("forwarded-tcpip") - 1;
                     channel->channel_type = LIBSSH2_ALLOC(session,
@@ -218,9 +216,11 @@ packet_queue_listener(LIBSSH2_SESSION * session, unsigned char *data,
                     }
 
                     /* Link the channel into the end of the queue list */
-                    _libssh2_list_add(&listn->queue,
-                                      &listen_state->channel->node);
-                    listn->queue_size++;
+                    if (listen_state->channel) {
+                        _libssh2_list_add(&listn->queue,
+                                          &listen_state->channel->node);
+                        listn->queue_size++;
+                    }
 
                     listen_state->state = libssh2_NB_state_idle;
                     return 0;
@@ -297,14 +297,13 @@ packet_x11_open(LIBSSH2_SESSION * session, unsigned char *data,
 
     if (session->x11) {
         if (x11open_state->state == libssh2_NB_state_allocated) {
-            channel = LIBSSH2_ALLOC(session, sizeof(LIBSSH2_CHANNEL));
+            channel = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_CHANNEL));
             if (!channel) {
                 _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                "allocate a channel for new connection");
                 failure_code = SSH_OPEN_RESOURCE_SHORTAGE;
                 goto x11_exit;
             }
-            memset(channel, 0, sizeof(LIBSSH2_CHANNEL));
 
             channel->session = session;
             channel->channel_type_len = sizeof("x11") - 1;
@@ -408,6 +407,7 @@ packet_x11_open(LIBSSH2_SESSION * session, unsigned char *data,
  *
  * The input pointer 'data' is pointing to allocated data that this function
  * is asked to deal with so on failure OR success, it must be freed fine.
+ * The only exception is when the return code is LIBSSH2_ERROR_EAGAIN.
  *
  * This function will always be called with 'datalen' greater than zero.
  */
@@ -583,7 +583,8 @@ _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,
 
 
                 if (want_reply) {
-                    unsigned char packet = SSH_MSG_REQUEST_FAILURE;
+                    static const unsigned char packet =
+                        SSH_MSG_REQUEST_FAILURE;
                   libssh2_packet_add_jump_point5:
                     session->packAdd_state = libssh2_NB_state_jump5;
                     rc = _libssh2_transport_send(session, &packet, 1, NULL, 0);
@@ -653,6 +654,18 @@ _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,
                 _libssh2_debug(session, LIBSSH2_TRACE_CONN,
                                "Ignoring extended data and refunding %d bytes",
                                (int) (datalen - 13));
+                if (channelp->read_avail + datalen - data_head >=
+                    channelp->remote.window_size)
+                    datalen = channelp->remote.window_size -
+                        channelp->read_avail + data_head;
+
+                channelp->remote.window_size -= datalen - data_head;
+                _libssh2_debug(session, LIBSSH2_TRACE_CONN,
+                               "shrinking window size by %lu bytes to %lu, read_avail %lu",
+                               datalen - data_head,
+                               channelp->remote.window_size,
+                               channelp->read_avail);
+
                 session->packAdd_channelp = channelp;
 
                 /* Adjust the window based on the block we just freed */
@@ -684,7 +697,7 @@ _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,
                                " to receive, truncating");
                 datalen = channelp->remote.packet_size + data_head;
             }
-            if (channelp->remote.window_size <= 0) {
+            if (channelp->remote.window_size <= channelp->read_avail) {
                 /*
                  * Spec says we MAY ignore bytes sent beyond
                  * window_size
@@ -700,17 +713,26 @@ _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,
             /* Reset EOF status */
             channelp->remote.eof = 0;
 
-            if ((datalen - data_head) > channelp->remote.window_size) {
+            if (channelp->read_avail + datalen - data_head >
+                channelp->remote.window_size) {
                 _libssh2_error(session,
                                LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,
                                "Remote sent more data than current "
                                "window allows, truncating");
-                datalen = channelp->remote.window_size + data_head;
-                channelp->remote.window_size = 0;
+                datalen = channelp->remote.window_size -
+                    channelp->read_avail + data_head;
             }
-            else
-                /* Now that we've received it, shrink our window */
-                channelp->remote.window_size -= datalen - data_head;
+
+            /* Update the read_avail counter. The window size will be
+             * updated once the data is actually read from the queue
+             * from an upper layer */
+            channelp->read_avail += datalen - data_head;
+
+            _libssh2_debug(session, LIBSSH2_TRACE_CONN,
+                           "increasing read_avail by %lu bytes to %lu/%lu",
+                           (long)(datalen - data_head),
+                           (long)channelp->read_avail,
+                           (long)channelp->remote.window_size);
 
             break;
 
@@ -945,6 +967,7 @@ _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,
         if (!packetp) {
             _libssh2_debug(session, LIBSSH2_ERROR_ALLOC,
                            "memory for packet");
+            LIBSSH2_FREE(session, data);
             session->packAdd_state = libssh2_NB_state_idle;
             return LIBSSH2_ERROR_ALLOC;
         }
@@ -1134,14 +1157,14 @@ _libssh2_packet_burn(LIBSSH2_SESSION * session,
 {
     unsigned char *data;
     size_t data_len;
-    unsigned char all_packets[255];
-    int i;
+    unsigned char i, all_packets[255];
     int ret;
 
     if (*state == libssh2_NB_state_idle) {
-        for(i = 1; i < 256; i++) {
+        for(i = 1; i < 255; i++) {
             all_packets[i - 1] = i;
         }
+        all_packets[254] = 0;
 
         if (_libssh2_packet_askv(session, all_packets, &data, &data_len, 0,
                                  NULL, 0) == 0) {
@@ -1170,7 +1193,8 @@ _libssh2_packet_burn(LIBSSH2_SESSION * session,
 
         /* Be lazy, let packet_ask pull it out of the brigade */
         if (0 ==
-            _libssh2_packet_ask(session, ret, &data, &data_len, 0, NULL, 0)) {
+            _libssh2_packet_ask(session, (unsigned char)ret,
+                                         &data, &data_len, 0, NULL, 0)) {
             /* Smoke 'em if you got 'em */
             LIBSSH2_FREE(session, data);
             *state = libssh2_NB_state_idle;
diff --git a/pgadmin/libssh2/pem.c b/pgadmin/libssh2/pem.c
index 5749bc8..9f51bba 100644
--- a/pgadmin/libssh2/pem.c
+++ b/pgadmin/libssh2/pem.c
@@ -38,20 +38,59 @@
 
 #include "libssh2_priv.h"
 
-#ifdef LIBSSH2_LIBGCRYPT /* compile only if we build with libgcrypt */
-
 static int
 readline(char *line, int line_size, FILE * fp)
 {
+    size_t len;
+
+    if (!line) {
+        return -1;
+    }
     if (!fgets(line, line_size, fp)) {
         return -1;
     }
-    if (*line && line[strlen(line) - 1] == '\n') {
-        line[strlen(line) - 1] = '\0';
+
+    if (*line) {
+        len = strlen(line);
+        if (len > 0 && line[len - 1] == '\n') {
+            line[len - 1] = '\0';
+        }
     }
-    if (*line && line[strlen(line) - 1] == '\r') {
-        line[strlen(line) - 1] = '\0';
+
+    if (*line) {
+        len = strlen(line);
+        if (len > 0 && line[len - 1] == '\r') {
+            line[len - 1] = '\0';
+        }
     }
+
+    return 0;
+}
+
+static int
+readline_memory(char *line, size_t line_size,
+                const char *filedata, size_t filedata_len,
+                size_t *filedata_offset)
+{
+    size_t off, len;
+
+    off = *filedata_offset;
+
+    for (len = 0; off + len < filedata_len && len < line_size; len++) {
+        if (filedata[off + len] == '\n' ||
+            filedata[off + len] == '\r') {
+                break;
+        }
+    }
+
+    if (len) {
+        memcpy(line, filedata + off, len);
+        *filedata_offset += len;
+    }
+
+    line[len] = '\0';
+    *filedata_offset += 1;
+
     return 0;
 }
 
@@ -69,6 +108,8 @@ _libssh2_pem_parse(LIBSSH2_SESSION * session,
     int ret;
 
     do {
+        *line = '\0';
+
         if (readline(line, LINE_SIZE, fp)) {
             return -1;
         }
@@ -93,12 +134,84 @@ _libssh2_pem_parse(LIBSSH2_SESSION * session,
             b64datalen += linelen;
         }
 
+        *line = '\0';
+
         if (readline(line, LINE_SIZE, fp)) {
             ret = -1;
             goto out;
         }
     } while (strcmp(line, headerend) != 0);
 
+    if (!b64data) {
+        return -1;
+    }
+
+    if (libssh2_base64_decode(session, (char**) data, datalen,
+                              b64data, b64datalen)) {
+        ret = -1;
+        goto out;
+    }
+
+    ret = 0;
+  out:
+    if (b64data) {
+        LIBSSH2_FREE(session, b64data);
+    }
+    return ret;
+}
+
+int
+_libssh2_pem_parse_memory(LIBSSH2_SESSION * session,
+                          const char *headerbegin,
+                          const char *headerend,
+                          const char *filedata, size_t filedata_len,
+                          unsigned char **data, unsigned int *datalen)
+{
+    char line[LINE_SIZE];
+    char *b64data = NULL;
+    unsigned int b64datalen = 0;
+    size_t off = 0;
+    int ret;
+
+    do {
+        *line = '\0';
+
+        if (readline_memory(line, LINE_SIZE, filedata, filedata_len, &off)) {
+            return -1;
+        }
+    }
+    while (strcmp(line, headerbegin) != 0);
+
+    *line = '\0';
+
+    do {
+        if (*line) {
+            char *tmp;
+            size_t linelen;
+
+            linelen = strlen(line);
+            tmp = LIBSSH2_REALLOC(session, b64data, b64datalen + linelen);
+            if (!tmp) {
+                ret = -1;
+                goto out;
+            }
+            memcpy(tmp + b64datalen, line, linelen);
+            b64data = tmp;
+            b64datalen += linelen;
+        }
+
+        *line = '\0';
+
+        if (readline_memory(line, LINE_SIZE, filedata, filedata_len, &off)) {
+            ret = -1;
+            goto out;
+        }
+    } while (strcmp(line, headerend) != 0);
+
+    if (!b64data) {
+        return -1;
+    }
+
     if (libssh2_base64_decode(session, (char**) data, datalen,
                               b64data, b64datalen)) {
         ret = -1;
@@ -209,5 +322,3 @@ _libssh2_pem_decode_integer(unsigned char **data, unsigned int *datalen,
 
     return 0;
 }
-
-#endif /* LIBSSH2_LIBGCRYPT */
diff --git a/pgadmin/libssh2/publickey.c b/pgadmin/libssh2/publickey.c
index 282fffe..bfee0a8 100644
--- a/pgadmin/libssh2/publickey.c
+++ b/pgadmin/libssh2/publickey.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2007, Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2010-2012 by Daniel Stenberg
+ * Copyright (c) 2010-2014 by Daniel Stenberg
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -136,6 +136,8 @@ publickey_packet_receive(LIBSSH2_PUBLICKEY * pkey,
     LIBSSH2_SESSION *session = channel->session;
     unsigned char buffer[4];
     int rc;
+    *data = NULL; /* default to nothing returned */
+    *data_len = 0;
 
     if (pkey->receive_state == libssh2_NB_state_idle) {
         rc = _libssh2_channel_read(channel, 0, (char *) buffer, 4);
@@ -348,13 +350,12 @@ static LIBSSH2_PUBLICKEY *publickey_init(LIBSSH2_SESSION *session)
         }
 
         session->pkeyInit_pkey =
-            LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PUBLICKEY));
+            LIBSSH2_CALLOC(session, sizeof(LIBSSH2_PUBLICKEY));
         if (!session->pkeyInit_pkey) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                            "Unable to allocate a new publickey structure");
             goto err_exit;
         }
-        memset(session->pkeyInit_pkey, 0, sizeof(LIBSSH2_PUBLICKEY));
         session->pkeyInit_pkey->channel = session->pkeyInit_channel;
         session->pkeyInit_pkey->version = 0;
 
diff --git a/pgadmin/libssh2/scp.c b/pgadmin/libssh2/scp.c
index 63d181e..22778dd 100644
--- a/pgadmin/libssh2/scp.c
+++ b/pgadmin/libssh2/scp.c
@@ -133,7 +133,7 @@ shell_quotearg(const char *path, unsigned char *buf,
      * Processing States:
      *  UQSTRING:       unquoted string: ... -- used for quoting exclamation
      *                  marks. This is the initial state
-     *  SQSTRING:       single-qouted-string: '... -- any character may follow
+     *  SQSTRING:       single-quoted-string: '... -- any character may follow
      *  QSTRING:        quoted string: "... -- only apostrophes may follow
      */
     enum { UQSTRING, SQSTRING, QSTRING } state = UQSTRING;
@@ -268,7 +268,7 @@ shell_quotearg(const char *path, unsigned char *buf,
  *
  */
 static LIBSSH2_CHANNEL *
-scp_recv(LIBSSH2_SESSION * session, const char *path, struct stat * sb)
+scp_recv(LIBSSH2_SESSION * session, const char *path, libssh2_struct_stat * sb)
 {
     int cmd_len;
     int rc;
@@ -295,14 +295,16 @@ scp_recv(LIBSSH2_SESSION * session, const char *path, struct stat * sb)
         }
 
         snprintf((char *)session->scpRecv_command,
-                 session->scpRecv_command_len, "scp -%sf ", sb?"p":"");
+                 session->scpRecv_command_len,
+                 "scp -%sf ", sb?"p":"");
 
         cmd_len = strlen((char *)session->scpRecv_command);
+        cmd_len += shell_quotearg(path,
+                                  &session->scpRecv_command[cmd_len],
+                                  session->scpRecv_command_len - cmd_len);
 
-        (void) shell_quotearg(path,
-                              &session->scpRecv_command[cmd_len],
-                              session->scpRecv_command_len - cmd_len);
-
+        session->scpRecv_command[cmd_len] = '\0';
+        session->scpRecv_command_len = cmd_len + 1;
 
         _libssh2_debug(session, LIBSSH2_TRACE_SCP,
                        "Opening channel for SCP receive");
@@ -722,12 +724,12 @@ scp_recv(LIBSSH2_SESSION * session, const char *path, struct stat * sb)
     }
 
     if (sb) {
-        memset(sb, 0, sizeof(struct stat));
+        memset(sb, 0, sizeof(libssh2_struct_stat));
 
         sb->st_mtime = session->scpRecv_mtime;
         sb->st_atime = session->scpRecv_atime;
         sb->st_size = session->scpRecv_size;
-        sb->st_mode = session->scpRecv_mode;
+        sb->st_mode = (unsigned short)session->scpRecv_mode;
     }
 
     session->scpRecv_state = libssh2_NB_state_idle;
@@ -757,13 +759,49 @@ scp_recv(LIBSSH2_SESSION * session, const char *path, struct stat * sb)
 /*
  * libssh2_scp_recv
  *
- * Open a channel and request a remote file via SCP
+ * DEPRECATED
+ *
+ * Open a channel and request a remote file via SCP.  This receives files larger
+ * than 2 GB, but is unable to report the proper size on platforms where the
+ * st_size member of struct stat is limited to 2 GB (e.g. windows).
  *
  */
 LIBSSH2_API LIBSSH2_CHANNEL *
 libssh2_scp_recv(LIBSSH2_SESSION *session, const char *path, struct stat * sb)
 {
     LIBSSH2_CHANNEL *ptr;
+
+    /* scp_recv uses libssh2_struct_stat, so pass one if the caller gave us a struct to populate... */
+    libssh2_struct_stat sb_intl;
+    libssh2_struct_stat *sb_ptr;
+    sb_ptr = sb ? &sb_intl : NULL;
+
+    BLOCK_ADJUST_ERRNO(ptr, session, scp_recv(session, path, sb_ptr));
+
+    /* ...and populate the caller's with as much info as fits. */
+    if (sb) {
+        memset(sb, 0, sizeof(struct stat));
+
+        sb->st_mtime = sb_intl.st_mtime;
+        sb->st_atime = sb_intl.st_atime;
+        sb->st_size = (off_t)sb_intl.st_size;
+        sb->st_mode = sb_intl.st_mode;
+    }
+
+    return ptr;
+}
+
+/*
+ * libssh2_scp_recv2
+ *
+ * Open a channel and request a remote file via SCP.  This supports files > 2GB
+ * on platforms that support it.
+ *
+ */
+LIBSSH2_API LIBSSH2_CHANNEL *
+libssh2_scp_recv2(LIBSSH2_SESSION *session, const char *path, libssh2_struct_stat * sb)
+{
+    LIBSSH2_CHANNEL *ptr;
     BLOCK_ADJUST_ERRNO(ptr, session, scp_recv(session, path, sb));
     return ptr;
 }
@@ -790,22 +828,25 @@ scp_send(LIBSSH2_SESSION * session, const char *path, int mode,
 
         session->scpSend_command =
             LIBSSH2_ALLOC(session, session->scpSend_command_len);
+
         if (!session->scpSend_command) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
-                           "Unable to allocate a command buffer for scp session");
+                           "Unable to allocate a command buffer for "
+                           "SCP session");
             return NULL;
         }
 
-        snprintf((char *)session->scpSend_command, session->scpSend_command_len,
+        snprintf((char *)session->scpSend_command,
+                 session->scpSend_command_len,
                  "scp -%st ", (mtime || atime)?"p":"");
 
         cmd_len = strlen((char *)session->scpSend_command);
+        cmd_len += shell_quotearg(path,
+                                  &session->scpSend_command[cmd_len],
+                                  session->scpSend_command_len - cmd_len);
 
-        (void)shell_quotearg(path,
-                             &session->scpSend_command[cmd_len],
-                             session->scpSend_command_len - cmd_len);
-
-        session->scpSend_command[session->scpSend_command_len - 1] = '\0';
+        session->scpSend_command[cmd_len] = '\0';
+        session->scpSend_command_len = cmd_len + 1;
 
         _libssh2_debug(session, LIBSSH2_TRACE_SCP,
                        "Opening channel for SCP send");
diff --git a/pgadmin/libssh2/session.c b/pgadmin/libssh2/session.c
index 9838d2b..06e61dd 100644
--- a/pgadmin/libssh2/session.c
+++ b/pgadmin/libssh2/session.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2004-2007 Sara Golemon <sarag@libssh2.org>
- * Copyright (c) 2009-2011 by Daniel Stenberg
+ * Copyright (c) 2009-2015 by Daniel Stenberg
  * Copyright (c) 2010 Simon Josefsson <simon@josefsson.org>
  * All rights reserved.
  *
@@ -601,7 +601,7 @@ int _libssh2_wait_socket(LIBSSH2_SESSION *session, time_t start_time)
         (seconds_to_next == 0 ||
          seconds_to_next > session->api_timeout)) {
         time_t now = time (NULL);
-        elapsed_ms = (long)(1000*difftime(start_time, now));
+        elapsed_ms = (long)(1000*difftime(now, start_time));
         if (elapsed_ms > session->api_timeout) {
             session->err_code = LIBSSH2_ERROR_TIMEOUT;
             return LIBSSH2_ERROR_TIMEOUT;
@@ -686,8 +686,13 @@ session_startup(LIBSSH2_SESSION *session, libssh2_socket_t sock)
             !get_socket_nonblocking(session->socket_fd);
 
         if (session->socket_prev_blockstate) {
-            /* If in blocking state chang to non-blocking */
-            session_nonblock(session->socket_fd, 1);
+            /* If in blocking state change to non-blocking */
+            rc = session_nonblock(session->socket_fd, 1);
+            if (rc) {
+                return _libssh2_error(session, rc,
+                                      "Failed changing socket's "
+                                      "blocking state to non-blocking");
+            }
         }
 
         session->startup_state = libssh2_NB_state_created;
@@ -1016,6 +1021,14 @@ session_free(LIBSSH2_SESSION *session)
     if (session->scpSend_command) {
         LIBSSH2_FREE(session, session->scpSend_command);
     }
+    if (session->sftpInit_sftp) {
+        LIBSSH2_FREE(session, session->sftpInit_sftp);
+    }
+
+    /* Free payload buffer */
+    if (session->packet.total_num) {
+        LIBSSH2_FREE(session, session->packet.payload);
+    }
 
     /* Cleanup all remaining packets */
     while ((pkg = _libssh2_list_first(&session->packets))) {
@@ -1032,14 +1045,24 @@ session_free(LIBSSH2_SESSION *session)
     _libssh2_debug(session, LIBSSH2_TRACE_TRANS,
          "Extra packets left %d", packets_left);
 
-    if(session->socket_prev_blockstate)
+    if(session->socket_prev_blockstate) {
         /* if the socket was previously blocking, put it back so */
-        session_nonblock(session->socket_fd, 0);
+        rc = session_nonblock(session->socket_fd, 0);
+        if (rc) {
+            _libssh2_debug(session, LIBSSH2_TRACE_TRANS,
+             "unable to reset socket's blocking state");
+        }
+    }
 
     if (session->server_hostkey) {
         LIBSSH2_FREE(session, session->server_hostkey);
     }
 
+    /* error string */
+    if (session->err_msg && ((session->err_flags & LIBSSH2_ERR_FLAG_DUP) != 0)) {
+        LIBSSH2_FREE(session, (char *)session->err_msg);
+    }
+
     LIBSSH2_FREE(session, session);
 
     return 0;
@@ -1267,7 +1290,24 @@ libssh2_session_last_errno(LIBSSH2_SESSION * session)
     return session->err_code;
 }
 
-/* libssh2_session_flag
+/* libssh2_session_set_last_error
+ *
+ * Sets the internal error code for the session.
+ *
+ * This function is available specifically to be used by high level
+ * language wrappers (i.e. Python or Perl) that may extend the library
+ * features while still relying on its error reporting mechanism.
+ */
+LIBSSH2_API int
+libssh2_session_set_last_error(LIBSSH2_SESSION* session,
+                               int errcode,
+                               const char* errmsg)
+{
+    return _libssh2_error_flags(session, errcode, errmsg,
+                                LIBSSH2_ERR_FLAG_DUP);
+}
+
+/* Libssh2_session_flag
  *
  * Set/Get session flags
  *
@@ -1514,7 +1554,7 @@ libssh2_poll(LIBSSH2_POLLFD * fds, unsigned int nfds, long timeout)
     }
 #else
     /* No select() or poll()
-     * no sockets sturcture to setup
+     * no sockets structure to setup
      */
 
     timeout = 0;
diff --git a/pgadmin/libssh2/sftp.c b/pgadmin/libssh2/sftp.c
index d0536dd..b0a3f1d 100644
--- a/pgadmin/libssh2/sftp.c
+++ b/pgadmin/libssh2/sftp.c
@@ -1,6 +1,6 @@
 /* Copyright (c) 2004-2008, Sara Golemon <sarag@libssh2.org>
  * Copyright (c) 2007 Eli Fant <elifantu@mail.ru>
- * Copyright (c) 2009-2012 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -93,7 +93,6 @@
    some kind of server problem. */
 #define LIBSSH2_SFTP_PACKET_MAXLEN  80000
 
-static int sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle);
 static int sftp_packet_ask(LIBSSH2_SFTP *sftp, unsigned char packet_type,
                            uint32_t request_id, unsigned char **data,
                            size_t *data_len);
@@ -205,7 +204,8 @@ sftp_packet_add(LIBSSH2_SFTP *sftp, unsigned char *data,
     LIBSSH2_SFTP_PACKET *packet;
     uint32_t request_id;
 
-    _libssh2_debug(session, LIBSSH2_TRACE_SFTP, "Received packet %d (len %d)",
+    _libssh2_debug(session, LIBSSH2_TRACE_SFTP,
+                   "Received packet type %d (len %d)",
                    (int) data[0], data_len);
 
     /*
@@ -251,6 +251,9 @@ sftp_packet_add(LIBSSH2_SFTP *sftp, unsigned char *data,
 
     request_id = _libssh2_ntohu32(&data[1]);
 
+    _libssh2_debug(session, LIBSSH2_TRACE_SFTP, "Received packet id %d",
+                   request_id);
+
     /* Don't add the packet if it answers a request we've given up on. */
     if((data[0] == SSH_FXP_STATUS || data[0] == SSH_FXP_DATA)
         && find_zombie_request(sftp, request_id)) {
@@ -535,7 +538,7 @@ sftp_packet_require(LIBSSH2_SFTP *sftp, unsigned char packet_type,
 }
 
 /* sftp_packet_requirev
- * Require one of N possible reponses
+ * Require one of N possible responses
  */
 static int
 sftp_packet_requirev(LIBSSH2_SFTP *sftp, int num_valid_responses,
@@ -721,7 +724,7 @@ static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
          *
          * Note that you MUST NOT try to call libssh2_sftp_init() again to get
          * another handle until the previous call has finished and either
-         * succesffully made a handle or failed and returned error (not
+         * successfully made a handle or failed and returned error (not
          * including *EAGAIN).
          */
 
@@ -782,13 +785,12 @@ static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
 
         sftp_handle =
             session->sftpInit_sftp =
-            LIBSSH2_ALLOC(session, sizeof(LIBSSH2_SFTP));
+            LIBSSH2_CALLOC(session, sizeof(LIBSSH2_SFTP));
         if (!sftp_handle) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                            "Unable to allocate a new SFTP structure");
             goto sftp_init_error;
         }
-        memset(sftp_handle, 0, sizeof(LIBSSH2_SFTP));
         sftp_handle->channel = session->sftpInit_channel;
         sftp_handle->request_id = 0;
 
@@ -844,6 +846,7 @@ static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
     if (data_len < 5) {
         _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
                        "Invalid SSH_FXP_VERSION response");
+        LIBSSH2_FREE(session, data);
         goto sftp_init_error;
     }
 
@@ -857,7 +860,7 @@ static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
         sftp_handle->version = LIBSSH2_SFTP_VERSION;
     }
     _libssh2_debug(session, LIBSSH2_TRACE_SFTP,
-                   "Enabling SFTP version %lu compatability",
+                   "Enabling SFTP version %lu compatibility",
                    sftp_handle->version);
     while (s < (data + data_len)) {
         size_t extname_len, extdata_len;
@@ -928,7 +931,7 @@ LIBSSH2_API LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
 /*
  * sftp_shutdown
  *
- * Shutsdown the SFTP subsystem
+ * Shuts down the SFTP subsystem
  */
 static int
 sftp_shutdown(LIBSSH2_SFTP *sftp)
@@ -986,6 +989,10 @@ sftp_shutdown(LIBSSH2_SFTP *sftp)
         LIBSSH2_FREE(session, sftp->symlink_packet);
         sftp->symlink_packet = NULL;
     }
+    if (sftp->fsync_packet) {
+        LIBSSH2_FREE(session, sftp->fsync_packet);
+        sftp->fsync_packet = NULL;
+    }
 
     sftp_packet_flush(sftp);
 
@@ -1169,14 +1176,13 @@ sftp_open(LIBSSH2_SFTP *sftp, const char *filename,
             return NULL;
         }
 
-        fp = LIBSSH2_ALLOC(session, sizeof(LIBSSH2_SFTP_HANDLE));
+        fp = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_SFTP_HANDLE));
         if (!fp) {
             _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                            "Unable to allocate new SFTP handle structure");
             LIBSSH2_FREE(session, data);
             return NULL;
         }
-        memset(fp, 0, sizeof(LIBSSH2_SFTP_HANDLE));
         fp->handle_type = open_file ? LIBSSH2_SFTP_HANDLE_FILE :
             LIBSSH2_SFTP_HANDLE_DIR;
 
@@ -1243,6 +1249,8 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
     ssize_t rc;
     struct _libssh2_sftp_handle_file_data *filep =
         &handle->u.file;
+    size_t bytes_in_buffer = 0;
+    char *sliding_bufferp = buffer;
 
     /* This function can be interrupted in three different places where it
        might need to wait for data from the network.  It returns EAGAIN to
@@ -1303,7 +1311,7 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
            without having been acked - until we reach EOF. */
         if(!filep->eof) {
             /* Number of bytes asked for that haven't been acked yet */
-            size_t already = (filep->offset_sent - filep->offset);
+            size_t already = (size_t)(filep->offset_sent - filep->offset);
 
             size_t max_read_ahead = buffer_size*4;
             unsigned long recv_window;
@@ -1389,6 +1397,7 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
             _libssh2_list_add(&handle->packet_list, &chunk->node);
             count -= size; /* deduct the size we used, as we might have
                               to create more packets */
+            _libssh2_debug(session, LIBSSH2_TRACE_SFTP, "read request id %d sent", request_id);
         }
 
     case libssh2_NB_state_sent:
@@ -1473,7 +1482,7 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
 
                 if (rc32 == LIBSSH2_FX_EOF) {
                     filep->eof = TRUE;
-                    return 0;
+                    return bytes_in_buffer;
                 }
                 else {
                     sftp->last_errno = rc32;
@@ -1503,13 +1512,13 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
                     filep->offset_sent -= (chunk->len - rc32);
                 }
 
-                if(rc32 > buffer_size) {
+                if((bytes_in_buffer + rc32) > buffer_size) {
                     /* figure out the overlap amount */
-                    filep->data_left = rc32 - buffer_size;
+                    filep->data_left = (bytes_in_buffer + rc32) - buffer_size;
 
                     /* getting the full packet would overflow the buffer, so
                        only get the correct amount and keep the remainder */
-                    rc32 = (uint32_t)buffer_size;
+                    rc32 = (uint32_t)buffer_size - bytes_in_buffer;
 
                     /* store data to keep for next call */
                     filep->data = data;
@@ -1520,7 +1529,7 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
 
                 /* copy the received data from the received FXP_DATA packet to
                    the buffer at the correct index */
-                memcpy(buffer, data + 9, rc32);
+                memcpy(sliding_bufferp, data + 9, rc32);
                 filep->offset += rc32;
 
                 if(filep->data_len == 0)
@@ -1536,8 +1545,10 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
                 chunk = NULL;
 
                 if(rc32 > 0) {
-                    /* we must return as we wrote some data to the buffer */
-                    return rc32;
+                    /* continue to the next chunk */
+                    bytes_in_buffer += rc32;
+                    sliding_bufferp += rc32;
+                    chunk = next;
                 } else {
                     /* A zero-byte read is not necessarily EOF so we must not
                      * return 0 (that would signal EOF to the caller) so
@@ -1553,6 +1564,9 @@ static ssize_t sftp_read(LIBSSH2_SFTP_HANDLE * handle, char *buffer,
             }
         }
 
+        if (bytes_in_buffer > 0)
+            return bytes_in_buffer;
+
         break;
 
     default:
@@ -1616,7 +1630,7 @@ static ssize_t sftp_readdir(LIBSSH2_SFTP_HANDLE *handle, char *buffer,
 
             filename_len = real_filename_len;
             if (filename_len >= buffer_maxlen) {
-                filename_len = LIBSSH2_ERROR_BUFFER_TOO_SMALL;
+                filename_len = (size_t)LIBSSH2_ERROR_BUFFER_TOO_SMALL;
                 goto end;
             }
 
@@ -1631,7 +1645,7 @@ static ssize_t sftp_readdir(LIBSSH2_SFTP_HANDLE *handle, char *buffer,
                 longentry_len = real_longentry_len;
 
                 if (longentry_len >= longentry_maxlen) {
-                    filename_len = LIBSSH2_ERROR_BUFFER_TOO_SMALL;
+                    filename_len = (size_t)LIBSSH2_ERROR_BUFFER_TOO_SMALL;
                     goto end;
                 }
 
@@ -1825,7 +1839,7 @@ static ssize_t sftp_write(LIBSSH2_SFTP_HANDLE *handle, const char *buffer,
            acked but we haven't been able to return as such yet, so we will
            get that data as well passed in here again.
         */
-        already = (handle->u.file.offset_sent - handle->u.file.offset)+
+        already = (size_t) (handle->u.file.offset_sent - handle->u.file.offset)+
             handle->u.file.acked;
 
         if(count >= already) {
@@ -1955,7 +1969,7 @@ static ssize_t sftp_write(LIBSSH2_SFTP_HANDLE *handle, const char *buffer,
                 /* flush all pending packets from the outgoing list */
                 sftp_packetlist_flush(handle);
 
-                /* since we return error now, the applicaton will not get any
+                /* since we return error now, the application will not get any
                    outstanding data acked, so we need to rewind the offset to
                    where the application knows it has reached with acked data */
                 handle->u.file.offset -= handle->u.file.acked;
@@ -2014,6 +2028,99 @@ libssh2_sftp_write(LIBSSH2_SFTP_HANDLE *hnd, const char *buffer,
 
 }
 
+static int sftp_fsync(LIBSSH2_SFTP_HANDLE *handle)
+{
+    LIBSSH2_SFTP *sftp = handle->sftp;
+    LIBSSH2_CHANNEL *channel = sftp->channel;
+    LIBSSH2_SESSION *session = channel->session;
+    /* 34 = packet_len(4) + packet_type(1) + request_id(4) +
+       string_len(4) + strlen("fsync@openssh.com")(17) + handle_len(4) */
+    uint32_t packet_len = handle->handle_len + 34;
+    size_t data_len;
+    unsigned char *packet, *s, *data;
+    ssize_t rc;
+    uint32_t retcode;
+
+    if (sftp->fsync_state == libssh2_NB_state_idle) {
+        _libssh2_debug(session, LIBSSH2_TRACE_SFTP,
+                       "Issuing fsync command");
+        s = packet = LIBSSH2_ALLOC(session, packet_len);
+        if (!packet) {
+            return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                                  "Unable to allocate memory for FXP_EXTENDED "
+                                  "packet");
+        }
+
+        _libssh2_store_u32(&s, packet_len - 4);
+        *(s++) = SSH_FXP_EXTENDED;
+        sftp->fsync_request_id = sftp->request_id++;
+        _libssh2_store_u32(&s, sftp->fsync_request_id);
+        _libssh2_store_str(&s, "fsync@openssh.com", 17);
+        _libssh2_store_str(&s, handle->handle, handle->handle_len);
+
+        sftp->fsync_state = libssh2_NB_state_created;
+    } else {
+        packet = sftp->fsync_packet;
+    }
+
+    if (sftp->fsync_state == libssh2_NB_state_created) {
+        rc = _libssh2_channel_write(channel, 0, packet, packet_len);
+        if (rc == LIBSSH2_ERROR_EAGAIN ||
+            (0 <= rc && rc < (ssize_t)packet_len)) {
+            sftp->fsync_packet = packet;
+            return LIBSSH2_ERROR_EAGAIN;
+        }
+
+        LIBSSH2_FREE(session, packet);
+        sftp->fsync_packet = NULL;
+
+        if (rc < 0) {
+            sftp->fsync_state = libssh2_NB_state_idle;
+            return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
+                                  "_libssh2_channel_write() failed");
+        }
+        sftp->fsync_state = libssh2_NB_state_sent;
+    }
+
+    rc = sftp_packet_require(sftp, SSH_FXP_STATUS,
+                             sftp->fsync_request_id, &data, &data_len);
+    if (rc == LIBSSH2_ERROR_EAGAIN) {
+        return rc;
+    } else if (rc) {
+        sftp->fsync_state = libssh2_NB_state_idle;
+        return _libssh2_error(session, rc,
+                              "Error waiting for FXP EXTENDED REPLY");
+    }
+
+    sftp->fsync_state = libssh2_NB_state_idle;
+
+    retcode = _libssh2_ntohu32(data + 5);
+    LIBSSH2_FREE(session, data);
+
+    if (retcode != LIBSSH2_FX_OK) {
+        sftp->last_errno = retcode;
+        return _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
+                              "fsync failed");
+    }
+
+    return 0;
+}
+
+/* libssh2_sftp_fsync
+ * Commit data on the handle to disk.
+ */
+LIBSSH2_API int
+libssh2_sftp_fsync(LIBSSH2_SFTP_HANDLE *hnd)
+{
+    int rc;
+    if(!hnd)
+        return LIBSSH2_ERROR_BAD_USE;
+    BLOCK_ADJUST(rc, hnd->sftp->channel->session,
+                 sftp_fsync(hnd));
+    return rc;
+}
+
+
 /*
  * sftp_fstat
  *
@@ -2132,21 +2239,24 @@ libssh2_sftp_fstat_ex(LIBSSH2_SFTP_HANDLE *hnd,
 LIBSSH2_API void
 libssh2_sftp_seek64(LIBSSH2_SFTP_HANDLE *handle, libssh2_uint64_t offset)
 {
-    if(handle) {
-        handle->u.file.offset = handle->u.file.offset_sent = offset;
-        /* discard all pending requests and currently read data */
-        sftp_packetlist_flush(handle);
+    if(!handle)
+        return;
+    if(handle->u.file.offset == offset && handle->u.file.offset_sent == offset)
+        return;
 
-        /* free the left received buffered data */
-        if (handle->u.file.data_left) {
-            LIBSSH2_FREE(handle->sftp->channel->session, handle->u.file.data);
-            handle->u.file.data_left = handle->u.file.data_len = 0;
-            handle->u.file.data = NULL;
-        }
+    handle->u.file.offset = handle->u.file.offset_sent = offset;
+    /* discard all pending requests and currently read data */
+    sftp_packetlist_flush(handle);
 
-        /* reset EOF to False */
-        handle->u.file.eof = FALSE;
+    /* free the left received buffered data */
+    if (handle->u.file.data_left) {
+        LIBSSH2_FREE(handle->sftp->channel->session, handle->u.file.data);
+        handle->u.file.data_left = handle->u.file.data_len = 0;
+        handle->u.file.data = NULL;
     }
+
+    /* reset EOF to False */
+    handle->u.file.eof = FALSE;
 }
 
 /* libssh2_sftp_seek
@@ -2222,8 +2332,11 @@ static void sftp_packet_flush(LIBSSH2_SFTP *sftp)
 
 /* sftp_close_handle
  *
- * Close a file or directory handle
- * Also frees handle resource and unlinks it from the SFTP structure
+ * Close a file or directory handle.
+ * Also frees handle resource and unlinks it from the SFTP structure.
+ * The handle is no longer usable after return of this function, unless
+ * the return value is LIBSSH2_ERROR_EAGAIN in which case this function
+ * should be called again.
  */
 static int
 sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle)
@@ -2232,27 +2345,28 @@ sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle)
     LIBSSH2_CHANNEL *channel = sftp->channel;
     LIBSSH2_SESSION *session = channel->session;
     size_t data_len;
-    int retcode;
     /* 13 = packet_len(4) + packet_type(1) + request_id(4) + handle_len(4) */
     uint32_t packet_len = handle->handle_len + 13;
     unsigned char *s, *data = NULL;
-    int rc;
+    int rc = 0;
 
     if (handle->close_state == libssh2_NB_state_idle) {
         _libssh2_debug(session, LIBSSH2_TRACE_SFTP, "Closing handle");
         s = handle->close_packet = LIBSSH2_ALLOC(session, packet_len);
         if (!handle->close_packet) {
-            return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
-                                  "Unable to allocate memory for FXP_CLOSE "
-                                  "packet");
-        }
+            handle->close_state = libssh2_NB_state_idle;
+            rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                                "Unable to allocate memory for FXP_CLOSE "
+                                "packet");
+	} else {
 
-        _libssh2_store_u32(&s, packet_len - 4);
-        *(s++) = SSH_FXP_CLOSE;
-        handle->close_request_id = sftp->request_id++;
-        _libssh2_store_u32(&s, handle->close_request_id);
-        _libssh2_store_str(&s, handle->handle, handle->handle_len);
-        handle->close_state = libssh2_NB_state_created;
+	    _libssh2_store_u32(&s, packet_len - 4);
+	    *(s++) = SSH_FXP_CLOSE;
+	    handle->close_request_id = sftp->request_id++;
+	    _libssh2_store_u32(&s, handle->close_request_id);
+	    _libssh2_store_str(&s, handle->handle, handle->handle_len);
+	    handle->close_state = libssh2_NB_state_created;
+	}
     }
 
     if (handle->close_state == libssh2_NB_state_created) {
@@ -2261,16 +2375,14 @@ sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle)
         if (rc == LIBSSH2_ERROR_EAGAIN) {
             return rc;
         } else if ((ssize_t)packet_len != rc) {
-            LIBSSH2_FREE(session, handle->close_packet);
-            handle->close_packet = NULL;
             handle->close_state = libssh2_NB_state_idle;
-            return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
-                                  "Unable to send FXP_CLOSE command");
-        }
+            rc = _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
+                                "Unable to send FXP_CLOSE command");
+        } else
+	    handle->close_state = libssh2_NB_state_sent;
+
         LIBSSH2_FREE(session, handle->close_packet);
         handle->close_packet = NULL;
-
-        handle->close_state = libssh2_NB_state_sent;
     }
 
     if (handle->close_state == libssh2_NB_state_sent) {
@@ -2279,29 +2391,30 @@ sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle)
                                  &data_len);
         if (rc == LIBSSH2_ERROR_EAGAIN) {
             return rc;
+
         } else if (rc) {
-            handle->close_state = libssh2_NB_state_idle;
-            return _libssh2_error(session, rc,
-                                  "Error waiting for status message");
+            _libssh2_error(session, rc,
+                           "Error waiting for status message");
         }
 
         handle->close_state = libssh2_NB_state_sent1;
     }
 
-    if(!data)
+    if(!data) {
         /* if it reaches this point with data unset, something unwanted
-           happened (like this function is called again when in
-           libssh2_NB_state_sent1 state) and we just bail out */
-        return LIBSSH2_ERROR_INVAL;
+           happened for which we should have set an error code */
+        assert(rc);
 
-    retcode = _libssh2_ntohu32(data + 5);
-    LIBSSH2_FREE(session, data);
+    } else {
+	int retcode = _libssh2_ntohu32(data + 5);
+	LIBSSH2_FREE(session, data);
 
-    if (retcode != LIBSSH2_FX_OK) {
-        sftp->last_errno = retcode;
-        handle->close_state = libssh2_NB_state_idle;
-        return _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
-                              "SFTP Protocol Error");
+	if (retcode != LIBSSH2_FX_OK) {
+	    sftp->last_errno = retcode;
+	    handle->close_state = libssh2_NB_state_idle;
+	    rc = _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
+			       "SFTP Protocol Error");
+	}
     }
 
     /* remove this handle from the parent's list */
@@ -2323,7 +2436,7 @@ sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle)
 
     LIBSSH2_FREE(session, handle);
 
-    return 0;
+    return rc;
 }
 
 /* libssh2_sftp_close_handle
@@ -2583,6 +2696,8 @@ static int sftp_fstatvfs(LIBSSH2_SFTP_HANDLE *handle, LIBSSH2_SFTP_STATVFS *st)
     unsigned char *packet, *s, *data;
     ssize_t rc;
     unsigned int flag;
+    static const unsigned char responses[2] =
+        { SSH_FXP_EXTENDED_REPLY, SSH_FXP_STATUS };
 
     if (sftp->fstatvfs_state == libssh2_NB_state_idle) {
         _libssh2_debug(session, LIBSSH2_TRACE_SFTP,
@@ -2626,15 +2741,27 @@ static int sftp_fstatvfs(LIBSSH2_SFTP_HANDLE *handle, LIBSSH2_SFTP_STATVFS *st)
         sftp->fstatvfs_state = libssh2_NB_state_sent;
     }
 
-    rc = sftp_packet_require(sftp, SSH_FXP_EXTENDED_REPLY,
-                             sftp->fstatvfs_request_id, &data, &data_len);
+    rc = sftp_packet_requirev(sftp, 2, responses, sftp->fstatvfs_request_id,
+                              &data, &data_len);
+
     if (rc == LIBSSH2_ERROR_EAGAIN) {
         return rc;
     } else if (rc) {
         sftp->fstatvfs_state = libssh2_NB_state_idle;
         return _libssh2_error(session, rc,
                               "Error waiting for FXP EXTENDED REPLY");
-    } else if (data_len < 93) {
+    }
+
+    if (data[0] == SSH_FXP_STATUS) {
+        int retcode = _libssh2_ntohu32(data + 5);
+        sftp->fstatvfs_state = libssh2_NB_state_idle;
+        LIBSSH2_FREE(session, data);
+        sftp->last_errno = retcode;
+        return _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
+                              "SFTP Protocol Error");
+    }
+
+    if (data_len < 93) {
         LIBSSH2_FREE(session, data);
         sftp->fstatvfs_state = libssh2_NB_state_idle;
         return _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
@@ -2652,13 +2779,13 @@ static int sftp_fstatvfs(LIBSSH2_SFTP_HANDLE *handle, LIBSSH2_SFTP_STATVFS *st)
     st->f_ffree = _libssh2_ntohu64(data + 53);
     st->f_favail = _libssh2_ntohu64(data + 61);
     st->f_fsid = _libssh2_ntohu64(data + 69);
-    flag = _libssh2_ntohu64(data + 77);
+    flag = (unsigned int)_libssh2_ntohu64(data + 77);
     st->f_namemax = _libssh2_ntohu64(data + 85);
 
     st->f_flag = (flag & SSH_FXE_STATVFS_ST_RDONLY)
-                  ? LIBSSH2_SFTP_ST_RDONLY : 0;
+        ? LIBSSH2_SFTP_ST_RDONLY : 0;
     st->f_flag |= (flag & SSH_FXE_STATVFS_ST_NOSUID)
-                  ? LIBSSH2_SFTP_ST_NOSUID : 0;
+        ? LIBSSH2_SFTP_ST_NOSUID : 0;
 
     LIBSSH2_FREE(session, data);
     return 0;
@@ -2696,6 +2823,8 @@ static int sftp_statvfs(LIBSSH2_SFTP *sftp, const char *path,
     unsigned char *packet, *s, *data;
     ssize_t rc;
     unsigned int flag;
+    static const unsigned char responses[2] =
+        { SSH_FXP_EXTENDED_REPLY, SSH_FXP_STATUS };
 
     if (sftp->statvfs_state == libssh2_NB_state_idle) {
         _libssh2_debug(session, LIBSSH2_TRACE_SFTP,
@@ -2739,17 +2868,28 @@ static int sftp_statvfs(LIBSSH2_SFTP *sftp, const char *path,
         sftp->statvfs_state = libssh2_NB_state_sent;
     }
 
-    rc = sftp_packet_require(sftp, SSH_FXP_EXTENDED_REPLY,
-                             sftp->statvfs_request_id, &data, &data_len);
+    rc = sftp_packet_requirev(sftp, 2, responses, sftp->statvfs_request_id,
+                              &data, &data_len);
     if (rc == LIBSSH2_ERROR_EAGAIN) {
         return rc;
     } else if (rc) {
         sftp->statvfs_state = libssh2_NB_state_idle;
         return _libssh2_error(session, rc,
                               "Error waiting for FXP EXTENDED REPLY");
-    } else if (data_len < 93) {
+    }
+
+    if (data[0] == SSH_FXP_STATUS) {
+        int retcode = _libssh2_ntohu32(data + 5);
+        sftp->statvfs_state = libssh2_NB_state_idle;
         LIBSSH2_FREE(session, data);
-        sftp->fstatvfs_state = libssh2_NB_state_idle;
+        sftp->last_errno = retcode;
+        return _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
+                              "SFTP Protocol Error");
+    }
+
+    if (data_len < 93) {
+        LIBSSH2_FREE(session, data);
+        sftp->statvfs_state = libssh2_NB_state_idle;
         return _libssh2_error(session, LIBSSH2_ERROR_SFTP_PROTOCOL,
                               "SFTP Protocol Error: short response");
     }
@@ -2765,7 +2905,7 @@ static int sftp_statvfs(LIBSSH2_SFTP *sftp, const char *path,
     st->f_ffree = _libssh2_ntohu64(data + 53);
     st->f_favail = _libssh2_ntohu64(data + 61);
     st->f_fsid = _libssh2_ntohu64(data + 69);
-    flag = _libssh2_ntohu64(data + 77);
+    flag = (unsigned int)_libssh2_ntohu64(data + 77);
     st->f_namemax = _libssh2_ntohu64(data + 85);
 
     st->f_flag = (flag & SSH_FXE_STATVFS_ST_RDONLY)
diff --git a/pgadmin/libssh2/transport.c b/pgadmin/libssh2/transport.c
index b4ec037..8725da0 100644
--- a/pgadmin/libssh2/transport.c
+++ b/pgadmin/libssh2/transport.c
@@ -52,7 +52,7 @@
 #include "mac.h"
 
 #define MAX_BLOCKSIZE 32    /* MUST fit biggest crypto block size we use/get */
-#define MAX_MACSIZE 20      /* MUST fit biggest MAC length we support */
+#define MAX_MACSIZE 64      /* MUST fit biggest MAC length we support */
 
 #ifdef LIBSSH2DEBUG
 #define UNPRINTABLE_CHAR '.'
@@ -241,8 +241,12 @@ fullpacket(LIBSSH2_SESSION * session, int encrypted /* 1 or 0 */ )
         rc = _libssh2_packet_add(session, p->payload,
                                  session->fullpacket_payload_len,
                                  session->fullpacket_macstate);
-        if (rc)
+        if (rc == LIBSSH2_ERROR_EAGAIN)
+            return rc;
+        if (rc) {
+            session->fullpacket_state = libssh2_NB_state_idle;
             return rc;
+        }
     }
 
     session->fullpacket_state = libssh2_NB_state_idle;
@@ -524,6 +528,7 @@ int _libssh2_transport_read(LIBSSH2_SESSION * session)
             /* now decrypt the lot */
             rc = decrypt(session, &p->buf[p->readidx], p->wptr, numdecrypt);
             if (rc != LIBSSH2_ERROR_NONE) {
+                p->total_num = 0;   /* no packet buffer available */
                 return rc;
             }
 
@@ -531,7 +536,7 @@ int _libssh2_transport_read(LIBSSH2_SESSION * session)
             p->readidx += numdecrypt;
             /* advance write pointer */
             p->wptr += numdecrypt;
-            /* increse data_num */
+            /* increase data_num */
             p->data_num += numdecrypt;
 
             /* bytes left to take care of without decryption */
@@ -547,7 +552,7 @@ int _libssh2_transport_read(LIBSSH2_SESSION * session)
             p->readidx += numbytes;
             /* advance write pointer */
             p->wptr += numbytes;
-            /* increse data_num */
+            /* increase data_num */
             p->data_num += numbytes;
         }
 
@@ -824,7 +829,7 @@ int _libssh2_transport_send(LIBSSH2_SESSION *session,
        the MAC and the packet_length field itself */
     _libssh2_htonu32(p->outbuf, packet_length - 4);
     /* store padding_length */
-    p->outbuf[4] = padding_length;
+    p->outbuf[4] = (unsigned char)padding_length;
 
     /* fill the padding area with random junk */
     _libssh2_random(p->outbuf + 5 + data_len, padding_length);
diff --git a/pgadmin/libssh2/userauth.c b/pgadmin/libssh2/userauth.c
index a0733d5..67bb9d2 100644
--- a/pgadmin/libssh2/userauth.c
+++ b/pgadmin/libssh2/userauth.c
@@ -1,6 +1,6 @@
 /* Copyright (c) 2004-2007, Sara Golemon <sarag@libssh2.org>
  * Copyright (c) 2005 Mikhail Gusarov <dottedmag@dottedmag.net>
- * Copyright (c) 2009-2011 by Daniel Stenberg
+ * Copyright (c) 2009-2014 by Daniel Stenberg
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms,
@@ -211,12 +211,13 @@ userauth_password(LIBSSH2_SESSION *session,
                sizeof(session->userauth_pswd_packet_requirev_state));
 
         /*
-         * 40 = acket_type(1) + username_len(4) + service_len(4) +
+         * 40 = packet_type(1) + username_len(4) + service_len(4) +
          * service(14)"ssh-connection" + method_len(4) + method(8)"password" +
          * chgpwdbool(1) + password_len(4) */
         session->userauth_pswd_data_len = username_len + 40;
 
-        session->userauth_pswd_data0 = ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;
+        session->userauth_pswd_data0 =
+            (unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;
 
         /* TODO: remove this alloc with a fixed buffer in the session
            struct */
@@ -276,13 +277,13 @@ userauth_password(LIBSSH2_SESSION *session,
                                           0, NULL, 0,
                                           &session->
                                           userauth_pswd_packet_requirev_state);
-            if (rc == LIBSSH2_ERROR_EAGAIN) {
-                return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,
-                                      "Would block waiting");
-            } else if (rc) {
-                session->userauth_pswd_state = libssh2_NB_state_idle;
-                return _libssh2_error(session, LIBSSH2_ERROR_TIMEOUT,
-                                      "Would block waiting");
+
+            if (rc) {
+                if (rc != LIBSSH2_ERROR_EAGAIN)
+                    session->userauth_pswd_state = libssh2_NB_state_idle;
+
+                return _libssh2_error(session, rc,
+                                      "Waiting for password response");
             }
 
             if (session->userauth_pswd_data[0] == SSH_MSG_USERAUTH_SUCCESS) {
@@ -441,6 +442,76 @@ libssh2_userauth_password_ex(LIBSSH2_SESSION *session, const char *username,
     return rc;
 }
 
+static int
+memory_read_publickey(LIBSSH2_SESSION * session, unsigned char **method,
+                      size_t *method_len,
+                      unsigned char **pubkeydata,
+                      size_t *pubkeydata_len,
+                      const char *pubkeyfiledata,
+                      size_t pubkeyfiledata_len)
+{
+    unsigned char *pubkey = NULL, *sp1, *sp2, *tmp;
+    size_t pubkey_len = pubkeyfiledata_len;
+    unsigned int tmp_len;
+
+    if (pubkeyfiledata_len <= 1) {
+        return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                              "Invalid data in public key file");
+    }
+
+    pubkey = LIBSSH2_ALLOC(session, pubkeyfiledata_len);
+    if (!pubkey) {
+        return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
+                              "Unable to allocate memory for public key data");
+    }
+
+    memcpy(pubkey, pubkeyfiledata, pubkeyfiledata_len);
+
+    /*
+     *   Remove trailing whitespace
+     */
+    while (pubkey_len && isspace(pubkey[pubkey_len - 1]))
+        pubkey_len--;
+
+    if (!pubkey_len) {
+        LIBSSH2_FREE(session, pubkey);
+        return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                              "Missing public key data");
+    }
+
+    if ((sp1 = memchr(pubkey, ' ', pubkey_len)) == NULL) {
+        LIBSSH2_FREE(session, pubkey);
+        return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                              "Invalid public key data");
+    }
+
+    sp1++;
+
+    if ((sp2 = memchr(sp1, ' ', pubkey_len - (sp1 - pubkey - 1))) == NULL) {
+        /* Assume that the id string is missing, but that it's okay */
+        sp2 = pubkey + pubkey_len;
+    }
+
+    if (libssh2_base64_decode(session, (char **) &tmp, &tmp_len,
+                              (char *) sp1, sp2 - sp1)) {
+        LIBSSH2_FREE(session, pubkey);
+        return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                                  "Invalid key data, not base64 encoded");
+    }
+
+    /* Wasting some bytes here (okay, more than some), but since it's likely
+     * to be freed soon anyway, we'll just avoid the extra free/alloc and call
+     * it a wash
+     */
+    *method = pubkey;
+    *method_len = sp1 - pubkey - 1;
+
+    *pubkeydata = tmp;
+    *pubkeydata_len = tmp_len;
+
+    return 0;
+}
+
 /*
  * file_read_publickey
  *
@@ -461,7 +532,7 @@ file_read_publickey(LIBSSH2_SESSION * session, unsigned char **method,
     FILE *fd;
     char c;
     unsigned char *pubkey = NULL, *sp1, *sp2, *tmp;
-    size_t pubkey_len = 0;
+    size_t pubkey_len = 0, sp_len;
     unsigned int tmp_len;
 
     _libssh2_debug(session, LIBSSH2_TRACE_AUTH, "Loading public key file: %s",
@@ -472,11 +543,8 @@ file_read_publickey(LIBSSH2_SESSION * session, unsigned char **method,
         return _libssh2_error(session, LIBSSH2_ERROR_FILE,
                               "Unable to open public key file");
     }
-    while (!feof(fd) && 1 == fread(&c, 1, 1, fd) && c != '\r' && c != '\n')
+    while (!feof(fd) && 1 == fread(&c, 1, 1, fd) && c != '\r' && c != '\n') {
         pubkey_len++;
-    if (feof(fd)) {
-        /* the last character was EOF */
-        pubkey_len--;
     }
     rewind(fd);
 
@@ -502,8 +570,9 @@ file_read_publickey(LIBSSH2_SESSION * session, unsigned char **method,
     /*
      * Remove trailing whitespace
      */
-    while (pubkey_len && isspace(pubkey[pubkey_len - 1]))
+    while (pubkey_len && isspace(pubkey[pubkey_len - 1])) {
         pubkey_len--;
+    }
 
     if (!pubkey_len) {
         LIBSSH2_FREE(session, pubkey);
@@ -519,7 +588,8 @@ file_read_publickey(LIBSSH2_SESSION * session, unsigned char **method,
 
     sp1++;
 
-    if ((sp2 = memchr(sp1, ' ', pubkey_len - (sp1 - pubkey - 1))) == NULL) {
+    sp_len = sp1 > pubkey ? (sp1 - pubkey) - 1 : 0;
+    if ((sp2 = memchr(sp1, ' ', pubkey_len - sp_len)) == NULL) {
         /* Assume that the id string is missing, but that it's okay */
         sp2 = pubkey + pubkey_len;
     }
@@ -543,7 +613,43 @@ file_read_publickey(LIBSSH2_SESSION * session, unsigned char **method,
     return 0;
 }
 
+static int
+memory_read_privatekey(LIBSSH2_SESSION * session,
+                       const LIBSSH2_HOSTKEY_METHOD ** hostkey_method,
+                       void **hostkey_abstract,
+                       const unsigned char *method, int method_len,
+                       const char *privkeyfiledata, size_t privkeyfiledata_len,
+                       const char *passphrase)
+{
+    const LIBSSH2_HOSTKEY_METHOD **hostkey_methods_avail =
+        libssh2_hostkey_methods();
 
+    *hostkey_method = NULL;
+    *hostkey_abstract = NULL;
+    while (*hostkey_methods_avail && (*hostkey_methods_avail)->name) {
+        if ((*hostkey_methods_avail)->initPEMFromMemory
+             && strncmp((*hostkey_methods_avail)->name, (const char *) method,
+                        method_len) == 0) {
+            *hostkey_method = *hostkey_methods_avail;
+            break;
+        }
+        hostkey_methods_avail++;
+    }
+    if (!*hostkey_method) {
+        return _libssh2_error(session, LIBSSH2_ERROR_METHOD_NONE,
+                              "No handler for specified private key");
+    }
+
+    if ((*hostkey_method)->
+        initPEMFromMemory(session, privkeyfiledata, privkeyfiledata_len,
+                          (unsigned char *) passphrase,
+                          hostkey_abstract)) {
+        return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                              "Unable to initialize private key from file");
+    }
+
+    return 0;
+}
 
 /* libssh2_file_read_privatekey
  * Read a PEM encoded private key from an id_??? style file
@@ -592,6 +698,42 @@ struct privkey_file {
 };
 
 static int
+sign_frommemory(LIBSSH2_SESSION *session, unsigned char **sig, size_t *sig_len,
+                const unsigned char *data, size_t data_len, void **abstract)
+{
+    struct privkey_file *pk_file = (struct privkey_file *) (*abstract);
+    const LIBSSH2_HOSTKEY_METHOD *privkeyobj;
+    void *hostkey_abstract;
+    struct iovec datavec;
+    int rc;
+
+    rc = memory_read_privatekey(session, &privkeyobj, &hostkey_abstract,
+                                session->userauth_pblc_method,
+                                session->userauth_pblc_method_len,
+                                pk_file->filename,
+                                strlen(pk_file->filename),
+                                pk_file->passphrase);
+    if(rc)
+        return rc;
+
+    datavec.iov_base = (void *)data;
+    datavec.iov_len  = data_len;
+
+    if (privkeyobj->signv(session, sig, sig_len, 1, &datavec,
+                          &hostkey_abstract)) {
+        if (privkeyobj->dtor) {
+            privkeyobj->dtor(session, abstract);
+        }
+        return -1;
+    }
+
+    if (privkeyobj->dtor) {
+        privkeyobj->dtor(session, &hostkey_abstract);
+    }
+    return 0;
+}
+
+static int
 sign_fromfile(LIBSSH2_SESSION *session, unsigned char **sig, size_t *sig_len,
               const unsigned char *data, size_t data_len, void **abstract)
 {
@@ -615,7 +757,7 @@ sign_fromfile(LIBSSH2_SESSION *session, unsigned char **sig, size_t *sig_len,
     if (privkeyobj->signv(session, sig, sig_len, 1, &datavec,
                           &hostkey_abstract)) {
         if (privkeyobj->dtor) {
-            privkeyobj->dtor(session, abstract);
+            privkeyobj->dtor(session, &hostkey_abstract);
         }
         return -1;
     }
@@ -644,9 +786,9 @@ userauth_hostbased_fromfile(LIBSSH2_SESSION *session,
 
     if (session->userauth_host_state == libssh2_NB_state_idle) {
         const LIBSSH2_HOSTKEY_METHOD *privkeyobj;
-        unsigned char *pubkeydata, *sig;
-        size_t pubkeydata_len;
-        size_t sig_len;
+        unsigned char *pubkeydata, *sig = NULL;
+        size_t pubkeydata_len = 0;
+        size_t sig_len = 0;
         void *abstract;
         unsigned char buf[5];
         struct iovec datavec[4];
@@ -738,7 +880,9 @@ userauth_hostbased_fromfile(LIBSSH2_SESSION *session,
         datavec[2].iov_base = (void *)session->userauth_host_packet;
         datavec[2].iov_len = session->userauth_host_packet_len;
 
-        if (privkeyobj->signv(session, &sig, &sig_len, 3, datavec, &abstract)) {
+        if (privkeyobj && privkeyobj->signv &&
+                          privkeyobj->signv(session, &sig, &sig_len, 3,
+                                            datavec, &abstract)) {
             LIBSSH2_FREE(session, session->userauth_host_method);
             session->userauth_host_method = NULL;
             LIBSSH2_FREE(session, session->userauth_host_packet);
@@ -749,7 +893,7 @@ userauth_hostbased_fromfile(LIBSSH2_SESSION *session,
             return -1;
         }
 
-        if (privkeyobj->dtor) {
+        if (privkeyobj && privkeyobj->dtor) {
             privkeyobj->dtor(session, &abstract);
         }
 
@@ -1211,6 +1355,65 @@ _libssh2_userauth_publickey(LIBSSH2_SESSION *session,
                           "username/public key combination");
 }
 
+ /*
+  * userauth_publickey_frommemory
+  * Authenticate using a keypair from memory
+  */
+static int
+userauth_publickey_frommemory(LIBSSH2_SESSION *session,
+                              const char *username,
+                              size_t username_len,
+                              const char *publickeydata,
+                              size_t publickeydata_len,
+                              const char *privatekeydata,
+                              size_t privatekeydata_len,
+                              const char *passphrase)
+{
+    unsigned char *pubkeydata = NULL;
+    size_t pubkeydata_len = 0;
+    struct privkey_file privkey_file;
+    void *abstract = &privkey_file;
+    int rc;
+
+    privkey_file.filename = privatekeydata;
+    privkey_file.passphrase = passphrase;
+
+    if (session->userauth_pblc_state == libssh2_NB_state_idle) {
+        if (publickeydata_len && publickeydata) {
+            rc = memory_read_publickey(session, &session->userauth_pblc_method,
+                                       &session->userauth_pblc_method_len,
+                                       &pubkeydata, &pubkeydata_len,
+                                       publickeydata, publickeydata_len);
+            if(rc)
+                return rc;
+        }
+        else if (privatekeydata_len && privatekeydata) {
+            /* Compute public key from private key. */
+            if (_libssh2_pub_priv_keyfilememory(session,
+                                                &session->userauth_pblc_method,
+                                                &session->userauth_pblc_method_len,
+                                                &pubkeydata, &pubkeydata_len,
+                                                privatekeydata, privatekeydata_len,
+                                                passphrase))
+                return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                                      "Unable to extract public key "
+                                      "from private key.");
+        }
+        else {
+            return _libssh2_error(session, LIBSSH2_ERROR_FILE,
+                                  "Invalid data in public and private key.");
+        }
+    }
+
+    rc = _libssh2_userauth_publickey(session, username, username_len,
+                                     pubkeydata, pubkeydata_len,
+                                     sign_frommemory, &abstract);
+    if(pubkeydata)
+        LIBSSH2_FREE(session, pubkeydata);
+
+    return rc;
+}
+
 /*
  * userauth_publickey_fromfile
  * Authenticate using a keypair found in the named files
@@ -1263,6 +1466,36 @@ userauth_publickey_fromfile(LIBSSH2_SESSION *session,
     return rc;
 }
 
+/* libssh2_userauth_publickey_frommemory
+ * Authenticate using a keypair from memory
+ */
+LIBSSH2_API int
+libssh2_userauth_publickey_frommemory(LIBSSH2_SESSION *session,
+                                      const char *user,
+                                      size_t user_len,
+                                      const char *publickeyfiledata,
+                                      size_t publickeyfiledata_len,
+                                      const char *privatekeyfiledata,
+                                      size_t privatekeyfiledata_len,
+                                      const char *passphrase)
+{
+    int rc;
+
+    if(NULL == passphrase)
+        /* if given a NULL pointer, make it point to a zero-length
+           string to save us from having to check this all over */
+        passphrase="";
+
+    BLOCK_ADJUST(rc, session,
+                 userauth_publickey_frommemory(session, user, user_len,
+                                               publickeyfiledata,
+                                               publickeyfiledata_len,
+                                               privatekeyfiledata,
+                                               privatekeyfiledata_len,
+                                               passphrase));
+    return rc;
+}
+
 /* libssh2_userauth_publickey_fromfile_ex
  * Authenticate using a keypair found in the named files
  */
@@ -1501,41 +1734,35 @@ userauth_keyboard_interactive(LIBSSH2_SESSION * session,
 
             if(session->userauth_kybd_num_prompts) {
                 session->userauth_kybd_prompts =
-                    LIBSSH2_ALLOC(session,
-                                  sizeof(LIBSSH2_USERAUTH_KBDINT_PROMPT) *
-                                  session->userauth_kybd_num_prompts);
+                    LIBSSH2_CALLOC(session,
+                                   sizeof(LIBSSH2_USERAUTH_KBDINT_PROMPT) *
+                                   session->userauth_kybd_num_prompts);
                 if (!session->userauth_kybd_prompts) {
                     _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                    "Unable to allocate memory for "
                                    "keyboard-interactive prompts array");
                     goto cleanup;
                 }
-                memset(session->userauth_kybd_prompts, 0,
-                       sizeof(LIBSSH2_USERAUTH_KBDINT_PROMPT) *
-                       session->userauth_kybd_num_prompts);
 
                 session->userauth_kybd_responses =
-                    LIBSSH2_ALLOC(session,
-                                  sizeof(LIBSSH2_USERAUTH_KBDINT_RESPONSE) *
-                                  session->userauth_kybd_num_prompts);
+                    LIBSSH2_CALLOC(session,
+                                   sizeof(LIBSSH2_USERAUTH_KBDINT_RESPONSE) *
+                                   session->userauth_kybd_num_prompts);
                 if (!session->userauth_kybd_responses) {
                     _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                    "Unable to allocate memory for "
                                    "keyboard-interactive responses array");
                     goto cleanup;
                 }
-                memset(session->userauth_kybd_responses, 0,
-                       sizeof(LIBSSH2_USERAUTH_KBDINT_RESPONSE) *
-                       session->userauth_kybd_num_prompts);
 
-                for(i = 0; i != session->userauth_kybd_num_prompts; ++i) {
+                for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
                     /* string    prompt[1] (ISO-10646 UTF-8) */
                     session->userauth_kybd_prompts[i].length =
                         _libssh2_ntohu32(s);
                     s += 4;
                     session->userauth_kybd_prompts[i].text =
-                        LIBSSH2_ALLOC(session,
-                                      session->userauth_kybd_prompts[i].length);
+                        LIBSSH2_CALLOC(session,
+                                       session->userauth_kybd_prompts[i].length);
                     if (!session->userauth_kybd_prompts[i].text) {
                         _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
                                        "Unable to allocate memory for "
@@ -1569,7 +1796,7 @@ userauth_keyboard_interactive(LIBSSH2_SESSION * session,
                 + 4             /* int       num-responses */
                 ;
 
-            for(i = 0; i != session->userauth_kybd_num_prompts; ++i) {
+            for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
                 /* string    response[1] (ISO-10646 UTF-8) */
                 session->userauth_kybd_packet_len +=
                     4 + session->userauth_kybd_responses[i].length;
@@ -1592,7 +1819,7 @@ userauth_keyboard_interactive(LIBSSH2_SESSION * session,
             s++;
             _libssh2_store_u32(&s, session->userauth_kybd_num_prompts);
 
-            for(i = 0; i != session->userauth_kybd_num_prompts; ++i) {
+            for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
                 _libssh2_store_str(&s,
                                    session->userauth_kybd_responses[i].text,
                                    session->userauth_kybd_responses[i].length);
@@ -1628,14 +1855,14 @@ userauth_keyboard_interactive(LIBSSH2_SESSION * session,
         session->userauth_kybd_data = NULL;
 
         if (session->userauth_kybd_prompts) {
-            for(i = 0; i != session->userauth_kybd_num_prompts; ++i) {
+            for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
                 LIBSSH2_FREE(session, session->userauth_kybd_prompts[i].text);
                 session->userauth_kybd_prompts[i].text = NULL;
             }
         }
 
         if (session->userauth_kybd_responses) {
-            for(i = 0; i != session->userauth_kybd_num_prompts; ++i) {
+            for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
                 LIBSSH2_FREE(session,
                              session->userauth_kybd_responses[i].text);
                 session->userauth_kybd_responses[i].text = NULL;
diff --git a/pgadmin/pgAdmin3.vcxproj b/pgadmin/pgAdmin3.vcxproj
index b3a1bcf..c0f8b29 100644
--- a/pgadmin/pgAdmin3.vcxproj
+++ b/pgadmin/pgAdmin3.vcxproj
@@ -169,7 +169,7 @@
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
       <AdditionalIncludeDirectories>$(OPENSSL)/include;$(WXWIN)/lib/vc_dll/mswu/;$(WXWIN)/include;$(WXWIN)/contrib/include;$(PGDIR)/include;$(PGBUILD)/include/;$(PGBUILD)/libxml2/include/;$(PGBUILD)/libxslt/include/;$(PGBUILD)/iconv/include/;$(PROJECTDIR)/include;$(PGDIR)/include/server;$(PROJECTDIR)/include/libssh2;$(PROJECTDIR)/include/libssh2/Win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;NDEBUG;WIN32;_WINDOWS;__WINDOWS__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;__WXMSW__;WXUSINGDLL;wxUSE_UNICODE=1;UNICODE;EMBED_XRC;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;LIBSSH2_OPENSSL;NDEBUG;WIN32;_WINDOWS;__WINDOWS__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;__WXMSW__;WXUSINGDLL;wxUSE_UNICODE=1;UNICODE;EMBED_XRC;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
@@ -282,7 +282,7 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
       <AdditionalIncludeDirectories>$(OPENSSL)/include;$(WXWIN)/lib/vc_dll/mswud/;$(WXWIN)/include;$(WXWIN)/contrib/include;$(PGDIR)/include;$(PGBUILD)/include/;$(PGBUILD)/libxml2/include/;$(PGBUILD)/libxslt/include/;$(PGBUILD)/iconv/include/;$(PROJECTDIR)/include;$(PGDIR)/include/server;$(PROJECTDIR)/include/libssh2;$(PROJECTDIR)/include/libssh2/Win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;WIN32;_DEBUG;_WINDOWS;__WINDOWS__;__WXMSW__;WXUSINGDLL;DEBUG=1;__WXDEBUG__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;wxUSE_UNICODE=1;UNICODE;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;LIBSSH2_OPENSSL;WIN32;_DEBUG;_WINDOWS;__WINDOWS__;__WXMSW__;WXUSINGDLL;DEBUG=1;__WXDEBUG__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;wxUSE_UNICODE=1;UNICODE;PG_SSL;HAVE_CONNINFO_PARSE;LIBSSH2_OPENSSL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
       <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
       <PrecompiledHeader>Use</PrecompiledHeader>
@@ -402,7 +402,7 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
       <AdditionalIncludeDirectories>$(WXWIN)/lib/vc_dll/mswud/;$(WXWIN)/include;$(OPENSSL)/include;$(WXWIN)/contrib/include;$(PGDIR)/include;$(PGBUILD)/include/;$(PGBUILD)/libxml2/include/;$(PGBUILD)/libxslt/include/;$(PGBUILD)/iconv/include/;$(PROJECTDIR)/include;$(PGDIR)/include/server;$(PROJECTDIR)/include/libssh2;$(PROJECTDIR)/include/libssh2/Win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;WIN32;_DEBUG;_WINDOWS;__WINDOWS__;__WXMSW__;WXUSINGDLL;DEBUG=1;__WXDEBUG__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;wxUSE_UNICODE=1;UNICODE;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;LIBSSH2_OPENSSL;WIN32;_DEBUG;_WINDOWS;__WINDOWS__;__WXMSW__;WXUSINGDLL;DEBUG=1;__WXDEBUG__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;wxUSE_UNICODE=1;UNICODE;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
       <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
       <PrecompiledHeader>Use</PrecompiledHeader>
@@ -523,7 +523,7 @@
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
       <AdditionalIncludeDirectories>$(WXWIN)/lib/vc_dll/mswu/;$(WXWIN)/include;$(OPENSSL)/include;$(WXWIN)/contrib/include;$(PGDIR)/include;$(PGBUILD)/include/;$(PGBUILD)/libxml2/include/;$(PGBUILD)/libxslt/include/;$(PGBUILD)/iconv/include/;$(PROJECTDIR)/include;$(PGDIR)/include/server;$(PROJECTDIR)/include/libssh2;$(PROJECTDIR)/include/libssh2/Win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;NDEBUG;WIN32;_WINDOWS;__WINDOWS__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;__WXMSW__;WXUSINGDLL;wxUSE_UNICODE=1;UNICODE;EMBED_XRC;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PreprocessorDefinitions>_CRT_SECURE_NO_DEPRECATE=1;HAVE_OPENSSL_CRYPTO;LIBSSH2_OPENSSL;NDEBUG;WIN32;_WINDOWS;__WINDOWS__;__WIN95__;__WIN32__;WINVER=0x0400;STRICT;__WXMSW__;WXUSINGDLL;wxUSE_UNICODE=1;UNICODE;EMBED_XRC;PG_SSL;HAVE_CONNINFO_PARSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
diff --git a/pgadmin/utils/sshTunnel.cpp b/pgadmin/utils/sshTunnel.cpp
index 9a24668..85e06d4 100644
--- a/pgadmin/utils/sshTunnel.cpp
+++ b/pgadmin/utils/sshTunnel.cpp
@@ -131,7 +131,7 @@ bool CSSHTunnelThread::Initialize()
 		rc = libssh2_session_handshake(m_session, m_sock);
 		if (rc)
 		{
-			LogSSHTunnelErrors(wxString::Format(_("SSH error: Error when starting up SSH session with error code %d"), rc), GetId());
+			LogSSHTunnelErrors(wxString::Format(_("SSH error: Error when starting up SSH session with error code %d"), rc), GetId(), m_session);
 			return false;
 		}
 
@@ -177,7 +177,7 @@ bool CSSHTunnelThread::Initialize()
 			rc = libssh2_userauth_password(m_session, m_username.mb_str(), m_password.mb_str());
 			if (rc)
 			{
-				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId());
+				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId(), m_session);
 				Cleanup();
 				return false;
 			}
@@ -187,7 +187,7 @@ bool CSSHTunnelThread::Initialize()
 			rc = libssh2_userauth_keyboard_interactive(m_session, m_username.mb_str(), &CSSHTunnelThread::keyboard_interactive);
 			if (rc)
 			{
-				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId());
+				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId(), m_session);
 				Cleanup();
 				return false;
 			}
@@ -201,7 +201,7 @@ bool CSSHTunnelThread::Initialize()
 #endif
 			if (rc)
 			{
-				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by identity file failed with error code %d"), rc), GetId());
+				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by identity file failed with error code %d"), rc), GetId(), m_session);
 				Cleanup();
 				return false;
 			}
@@ -599,13 +599,27 @@ shutdown:
 	return NULL;
 }
 
-void LogSSHTunnelErrors(const wxString &msg, const int &id)
+void LogSSHTunnelErrors(const wxString &msg, const int &id, struct _LIBSSH2_SESSION *session)
 {
 	g_SSHThreadMutex.TryLock();
 
+	wxString errorMsg = msg;
+	// If session is not NULL then fetch the last error on that session
+	if (session)
+	{
+		char* errmsg;
+		int errmsg_len;
+		libssh2_session_last_error(session, &errmsg, &errmsg_len, 0);
+		if (errmsg_len > 0)
+		{
+			wxString errmsg_s(errmsg, wxConvLibc);
+			errorMsg += wxString::Format(_(" [%s]"), errmsg_s.c_str());
+		}
+	}
+
 	wxCommandEvent event(SSH_TUNNEL_ERROR_EVENT, id);
 	// Give it some contents
-	event.SetString(msg);
+	event.SetString(errorMsg);
 
 	// Do send it
 	wxPostEvent(winMain, event);
