Imported Upstream version 7.44.0
[platform/upstream/curl.git] / lib / ssh.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 /* #define CURL_LIBSSH2_DEBUG */
24
25 #include "curl_setup.h"
26
27 #ifdef USE_LIBSSH2
28
29 #ifdef HAVE_LIMITS_H
30 #  include <limits.h>
31 #endif
32
33 #include <libssh2.h>
34 #include <libssh2_sftp.h>
35
36 #ifdef HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39
40 #ifdef HAVE_NETINET_IN_H
41 #include <netinet/in.h>
42 #endif
43 #ifdef HAVE_ARPA_INET_H
44 #include <arpa/inet.h>
45 #endif
46 #ifdef HAVE_UTSNAME_H
47 #include <sys/utsname.h>
48 #endif
49 #ifdef HAVE_NETDB_H
50 #include <netdb.h>
51 #endif
52 #ifdef __VMS
53 #include <in.h>
54 #include <inet.h>
55 #endif
56
57 #if (defined(NETWARE) && defined(__NOVELL_LIBC__))
58 #undef in_addr_t
59 #define in_addr_t unsigned long
60 #endif
61
62 #include <curl/curl.h>
63 #include "urldata.h"
64 #include "sendf.h"
65 #include "hostip.h"
66 #include "progress.h"
67 #include "transfer.h"
68 #include "escape.h"
69 #include "http.h" /* for HTTP proxy tunnel stuff */
70 #include "ssh.h"
71 #include "url.h"
72 #include "speedcheck.h"
73 #include "getinfo.h"
74
75 #include "strequal.h"
76 #include "vtls/vtls.h"
77 #include "connect.h"
78 #include "strerror.h"
79 #include "inet_ntop.h"
80 #include "parsedate.h" /* for the week day and month names */
81 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
82 #include "strtoofft.h"
83 #include "multiif.h"
84 #include "select.h"
85 #include "warnless.h"
86 #include "curl_printf.h"
87 #include "curl_memory.h"
88 /* The last #include file should be: */
89 #include "memdebug.h"
90
91 #ifdef WIN32
92 #  undef  PATH_MAX
93 #  define PATH_MAX MAX_PATH
94 #  ifndef R_OK
95 #    define R_OK 4
96 #  endif
97 #endif
98
99 #ifndef PATH_MAX
100 #define PATH_MAX 1024 /* just an extra precaution since there are systems that
101                          have their definition hidden well */
102 #endif
103
104 #define sftp_libssh2_last_error(s) curlx_ultosi(libssh2_sftp_last_error(s))
105
106 #define sftp_libssh2_realpath(s,p,t,m) \
107         libssh2_sftp_symlink_ex((s), (p), curlx_uztoui(strlen(p)), \
108                                 (t), (m), LIBSSH2_SFTP_REALPATH)
109
110 /* Local functions: */
111 static const char *sftp_libssh2_strerror(int err);
112 static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc);
113 static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc);
114 static LIBSSH2_FREE_FUNC(my_libssh2_free);
115
116 static CURLcode get_pathname(const char **cpp, char **path);
117
118 static CURLcode ssh_connect(struct connectdata *conn, bool *done);
119 static CURLcode ssh_multi_statemach(struct connectdata *conn, bool *done);
120 static CURLcode ssh_do(struct connectdata *conn, bool *done);
121
122 static CURLcode ssh_getworkingpath(struct connectdata *conn,
123                                    char *homedir, /* when SFTP is used */
124                                    char **path);
125
126 static CURLcode scp_done(struct connectdata *conn,
127                          CURLcode, bool premature);
128 static CURLcode scp_doing(struct connectdata *conn,
129                           bool *dophase_done);
130 static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection);
131
132 static CURLcode sftp_done(struct connectdata *conn,
133                           CURLcode, bool premature);
134 static CURLcode sftp_doing(struct connectdata *conn,
135                            bool *dophase_done);
136 static CURLcode sftp_disconnect(struct connectdata *conn, bool dead);
137 static
138 CURLcode sftp_perform(struct connectdata *conn,
139                       bool *connected,
140                       bool *dophase_done);
141
142 static int ssh_getsock(struct connectdata *conn,
143                        curl_socket_t *sock, /* points to numsocks number
144                                                of sockets */
145                        int numsocks);
146
147 static int ssh_perform_getsock(const struct connectdata *conn,
148                                curl_socket_t *sock, /* points to numsocks
149                                                        number of sockets */
150                                int numsocks);
151
152 static CURLcode ssh_setup_connection(struct connectdata *conn);
153
154 /*
155  * SCP protocol handler.
156  */
157
158 const struct Curl_handler Curl_handler_scp = {
159   "SCP",                                /* scheme */
160   ssh_setup_connection,                 /* setup_connection */
161   ssh_do,                               /* do_it */
162   scp_done,                             /* done */
163   ZERO_NULL,                            /* do_more */
164   ssh_connect,                          /* connect_it */
165   ssh_multi_statemach,                  /* connecting */
166   scp_doing,                            /* doing */
167   ssh_getsock,                          /* proto_getsock */
168   ssh_getsock,                          /* doing_getsock */
169   ZERO_NULL,                            /* domore_getsock */
170   ssh_perform_getsock,                  /* perform_getsock */
171   scp_disconnect,                       /* disconnect */
172   ZERO_NULL,                            /* readwrite */
173   PORT_SSH,                             /* defport */
174   CURLPROTO_SCP,                        /* protocol */
175   PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION
176   | PROTOPT_NOURLQUERY                  /* flags */
177 };
178
179
180 /*
181  * SFTP protocol handler.
182  */
183
184 const struct Curl_handler Curl_handler_sftp = {
185   "SFTP",                               /* scheme */
186   ssh_setup_connection,                 /* setup_connection */
187   ssh_do,                               /* do_it */
188   sftp_done,                            /* done */
189   ZERO_NULL,                            /* do_more */
190   ssh_connect,                          /* connect_it */
191   ssh_multi_statemach,                  /* connecting */
192   sftp_doing,                           /* doing */
193   ssh_getsock,                          /* proto_getsock */
194   ssh_getsock,                          /* doing_getsock */
195   ZERO_NULL,                            /* domore_getsock */
196   ssh_perform_getsock,                  /* perform_getsock */
197   sftp_disconnect,                      /* disconnect */
198   ZERO_NULL,                            /* readwrite */
199   PORT_SSH,                             /* defport */
200   CURLPROTO_SFTP,                       /* protocol */
201   PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION
202   | PROTOPT_NOURLQUERY                  /* flags */
203 };
204
205 static void
206 kbd_callback(const char *name, int name_len, const char *instruction,
207              int instruction_len, int num_prompts,
208              const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
209              LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
210              void **abstract)
211 {
212   struct connectdata *conn = (struct connectdata *)*abstract;
213
214 #ifdef CURL_LIBSSH2_DEBUG
215   fprintf(stderr, "name=%s\n", name);
216   fprintf(stderr, "name_len=%d\n", name_len);
217   fprintf(stderr, "instruction=%s\n", instruction);
218   fprintf(stderr, "instruction_len=%d\n", instruction_len);
219   fprintf(stderr, "num_prompts=%d\n", num_prompts);
220 #else
221   (void)name;
222   (void)name_len;
223   (void)instruction;
224   (void)instruction_len;
225 #endif  /* CURL_LIBSSH2_DEBUG */
226   if(num_prompts == 1) {
227     responses[0].text = strdup(conn->passwd);
228     responses[0].length = curlx_uztoui(strlen(conn->passwd));
229   }
230   (void)prompts;
231   (void)abstract;
232 } /* kbd_callback */
233
234 static CURLcode sftp_libssh2_error_to_CURLE(int err)
235 {
236   switch (err) {
237     case LIBSSH2_FX_OK:
238       return CURLE_OK;
239
240     case LIBSSH2_FX_NO_SUCH_FILE:
241     case LIBSSH2_FX_NO_SUCH_PATH:
242       return CURLE_REMOTE_FILE_NOT_FOUND;
243
244     case LIBSSH2_FX_PERMISSION_DENIED:
245     case LIBSSH2_FX_WRITE_PROTECT:
246     case LIBSSH2_FX_LOCK_CONFlICT:
247       return CURLE_REMOTE_ACCESS_DENIED;
248
249     case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM:
250     case LIBSSH2_FX_QUOTA_EXCEEDED:
251       return CURLE_REMOTE_DISK_FULL;
252
253     case LIBSSH2_FX_FILE_ALREADY_EXISTS:
254       return CURLE_REMOTE_FILE_EXISTS;
255
256     case LIBSSH2_FX_DIR_NOT_EMPTY:
257       return CURLE_QUOTE_ERROR;
258
259     default:
260       break;
261   }
262
263   return CURLE_SSH;
264 }
265
266 static CURLcode libssh2_session_error_to_CURLE(int err)
267 {
268   switch (err) {
269     /* Ordered by order of appearance in libssh2.h */
270     case LIBSSH2_ERROR_NONE:
271       return CURLE_OK;
272
273     case LIBSSH2_ERROR_SOCKET_NONE:
274       return CURLE_COULDNT_CONNECT;
275
276     case LIBSSH2_ERROR_ALLOC:
277       return CURLE_OUT_OF_MEMORY;
278
279     case LIBSSH2_ERROR_SOCKET_SEND:
280       return CURLE_SEND_ERROR;
281
282     case LIBSSH2_ERROR_HOSTKEY_INIT:
283     case LIBSSH2_ERROR_HOSTKEY_SIGN:
284     case LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED:
285     case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED:
286       return CURLE_PEER_FAILED_VERIFICATION;
287
288     case LIBSSH2_ERROR_PASSWORD_EXPIRED:
289       return CURLE_LOGIN_DENIED;
290
291     case LIBSSH2_ERROR_SOCKET_TIMEOUT:
292     case LIBSSH2_ERROR_TIMEOUT:
293       return CURLE_OPERATION_TIMEDOUT;
294
295     case LIBSSH2_ERROR_EAGAIN:
296       return CURLE_AGAIN;
297   }
298
299   /* TODO: map some more of the libssh2 errors to the more appropriate CURLcode
300      error code, and possibly add a few new SSH-related one. We must however
301      not return or even depend on libssh2 errors in the public libcurl API */
302
303   return CURLE_SSH;
304 }
305
306 static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc)
307 {
308   (void)abstract; /* arg not used */
309   return malloc(count);
310 }
311
312 static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc)
313 {
314   (void)abstract; /* arg not used */
315   return realloc(ptr, count);
316 }
317
318 static LIBSSH2_FREE_FUNC(my_libssh2_free)
319 {
320   (void)abstract; /* arg not used */
321   if(ptr) /* ssh2 agent sometimes call free with null ptr */
322     free(ptr);
323 }
324
325 /*
326  * SSH State machine related code
327  */
328 /* This is the ONLY way to change SSH state! */
329 static void state(struct connectdata *conn, sshstate nowstate)
330 {
331   struct ssh_conn *sshc = &conn->proto.sshc;
332 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
333   /* for debug purposes */
334   static const char * const names[] = {
335     "SSH_STOP",
336     "SSH_INIT",
337     "SSH_S_STARTUP",
338     "SSH_HOSTKEY",
339     "SSH_AUTHLIST",
340     "SSH_AUTH_PKEY_INIT",
341     "SSH_AUTH_PKEY",
342     "SSH_AUTH_PASS_INIT",
343     "SSH_AUTH_PASS",
344     "SSH_AUTH_AGENT_INIT",
345     "SSH_AUTH_AGENT_LIST",
346     "SSH_AUTH_AGENT",
347     "SSH_AUTH_HOST_INIT",
348     "SSH_AUTH_HOST",
349     "SSH_AUTH_KEY_INIT",
350     "SSH_AUTH_KEY",
351     "SSH_AUTH_DONE",
352     "SSH_SFTP_INIT",
353     "SSH_SFTP_REALPATH",
354     "SSH_SFTP_QUOTE_INIT",
355     "SSH_SFTP_POSTQUOTE_INIT",
356     "SSH_SFTP_QUOTE",
357     "SSH_SFTP_NEXT_QUOTE",
358     "SSH_SFTP_QUOTE_STAT",
359     "SSH_SFTP_QUOTE_SETSTAT",
360     "SSH_SFTP_QUOTE_SYMLINK",
361     "SSH_SFTP_QUOTE_MKDIR",
362     "SSH_SFTP_QUOTE_RENAME",
363     "SSH_SFTP_QUOTE_RMDIR",
364     "SSH_SFTP_QUOTE_UNLINK",
365     "SSH_SFTP_TRANS_INIT",
366     "SSH_SFTP_UPLOAD_INIT",
367     "SSH_SFTP_CREATE_DIRS_INIT",
368     "SSH_SFTP_CREATE_DIRS",
369     "SSH_SFTP_CREATE_DIRS_MKDIR",
370     "SSH_SFTP_READDIR_INIT",
371     "SSH_SFTP_READDIR",
372     "SSH_SFTP_READDIR_LINK",
373     "SSH_SFTP_READDIR_BOTTOM",
374     "SSH_SFTP_READDIR_DONE",
375     "SSH_SFTP_DOWNLOAD_INIT",
376     "SSH_SFTP_DOWNLOAD_STAT",
377     "SSH_SFTP_CLOSE",
378     "SSH_SFTP_SHUTDOWN",
379     "SSH_SCP_TRANS_INIT",
380     "SSH_SCP_UPLOAD_INIT",
381     "SSH_SCP_DOWNLOAD_INIT",
382     "SSH_SCP_DONE",
383     "SSH_SCP_SEND_EOF",
384     "SSH_SCP_WAIT_EOF",
385     "SSH_SCP_WAIT_CLOSE",
386     "SSH_SCP_CHANNEL_FREE",
387     "SSH_SESSION_DISCONNECT",
388     "SSH_SESSION_FREE",
389     "QUIT"
390   };
391
392   if(sshc->state != nowstate) {
393     infof(conn->data, "SFTP %p state change from %s to %s\n",
394           (void *)sshc, names[sshc->state], names[nowstate]);
395   }
396 #endif
397
398   sshc->state = nowstate;
399 }
400
401 /* figure out the path to work with in this particular request */
402 static CURLcode ssh_getworkingpath(struct connectdata *conn,
403                                    char *homedir,  /* when SFTP is used */
404                                    char **path) /* returns the  allocated
405                                                    real path to work with */
406 {
407   struct SessionHandle *data = conn->data;
408   char *real_path = NULL;
409   char *working_path;
410   int working_path_len;
411
412   working_path = curl_easy_unescape(data, data->state.path, 0,
413                                     &working_path_len);
414   if(!working_path)
415     return CURLE_OUT_OF_MEMORY;
416
417   /* Check for /~/ , indicating relative to the user's home directory */
418   if(conn->handler->protocol & CURLPROTO_SCP) {
419     real_path = malloc(working_path_len+1);
420     if(real_path == NULL) {
421       free(working_path);
422       return CURLE_OUT_OF_MEMORY;
423     }
424     if((working_path_len > 3) && (!memcmp(working_path, "/~/", 3)))
425       /* It is referenced to the home directory, so strip the leading '/~/' */
426       memcpy(real_path, working_path+3, 4 + working_path_len-3);
427     else
428       memcpy(real_path, working_path, 1 + working_path_len);
429   }
430   else if(conn->handler->protocol & CURLPROTO_SFTP) {
431     if((working_path_len > 1) && (working_path[1] == '~')) {
432       size_t homelen = strlen(homedir);
433       real_path = malloc(homelen + working_path_len + 1);
434       if(real_path == NULL) {
435         free(working_path);
436         return CURLE_OUT_OF_MEMORY;
437       }
438       /* It is referenced to the home directory, so strip the
439          leading '/' */
440       memcpy(real_path, homedir, homelen);
441       real_path[homelen] = '/';
442       real_path[homelen+1] = '\0';
443       if(working_path_len > 3) {
444         memcpy(real_path+homelen+1, working_path + 3,
445                1 + working_path_len -3);
446       }
447     }
448     else {
449       real_path = malloc(working_path_len+1);
450       if(real_path == NULL) {
451         free(working_path);
452         return CURLE_OUT_OF_MEMORY;
453       }
454       memcpy(real_path, working_path, 1+working_path_len);
455     }
456   }
457
458   free(working_path);
459
460   /* store the pointer for the caller to receive */
461   *path = real_path;
462
463   return CURLE_OK;
464 }
465
466 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
467 static int sshkeycallback(CURL *easy,
468                           const struct curl_khkey *knownkey, /* known */
469                           const struct curl_khkey *foundkey, /* found */
470                           enum curl_khmatch match,
471                           void *clientp)
472 {
473   (void)easy;
474   (void)knownkey;
475   (void)foundkey;
476   (void)clientp;
477
478   /* we only allow perfect matches, and we reject everything else */
479   return (match != CURLKHMATCH_OK)?CURLKHSTAT_REJECT:CURLKHSTAT_FINE;
480 }
481 #endif
482
483 /*
484  * Earlier libssh2 versions didn't have the ability to seek to 64bit positions
485  * with 32bit size_t.
486  */
487 #ifdef HAVE_LIBSSH2_SFTP_SEEK64
488 #define SFTP_SEEK(x,y) libssh2_sftp_seek64(x, (libssh2_uint64_t)y)
489 #else
490 #define SFTP_SEEK(x,y) libssh2_sftp_seek(x, (size_t)y)
491 #endif
492
493 /*
494  * Earlier libssh2 versions didn't do SCP properly beyond 32bit sizes on 32bit
495  * architectures so we check of the necessary function is present.
496  */
497 #ifndef HAVE_LIBSSH2_SCP_SEND64
498 #define SCP_SEND(a,b,c,d) libssh2_scp_send_ex(a, b, (int)(c), (size_t)d, 0, 0)
499 #else
500 #define SCP_SEND(a,b,c,d) libssh2_scp_send64(a, b, (int)(c),            \
501                                              (libssh2_uint64_t)d, 0, 0)
502 #endif
503
504 /*
505  * libssh2 1.2.8 fixed the problem with 32bit ints used for sockets on win64.
506  */
507 #ifdef HAVE_LIBSSH2_SESSION_HANDSHAKE
508 #define libssh2_session_startup(x,y) libssh2_session_handshake(x,y)
509 #endif
510
511 static CURLcode ssh_knownhost(struct connectdata *conn)
512 {
513   CURLcode result = CURLE_OK;
514
515 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
516   struct SessionHandle *data = conn->data;
517
518   if(data->set.str[STRING_SSH_KNOWNHOSTS]) {
519     /* we're asked to verify the host against a file */
520     struct ssh_conn *sshc = &conn->proto.sshc;
521     int rc;
522     int keytype;
523     size_t keylen;
524     const char *remotekey = libssh2_session_hostkey(sshc->ssh_session,
525                                                     &keylen, &keytype);
526     int keycheck = LIBSSH2_KNOWNHOST_CHECK_FAILURE;
527     int keybit = 0;
528
529     if(remotekey) {
530       /*
531        * A subject to figure out is what host name we need to pass in here.
532        * What host name does OpenSSH store in its file if an IDN name is
533        * used?
534        */
535       struct libssh2_knownhost *host;
536       enum curl_khmatch keymatch;
537       curl_sshkeycallback func =
538         data->set.ssh_keyfunc?data->set.ssh_keyfunc:sshkeycallback;
539       struct curl_khkey knownkey;
540       struct curl_khkey *knownkeyp = NULL;
541       struct curl_khkey foundkey;
542
543       keybit = (keytype == LIBSSH2_HOSTKEY_TYPE_RSA)?
544         LIBSSH2_KNOWNHOST_KEY_SSHRSA:LIBSSH2_KNOWNHOST_KEY_SSHDSS;
545
546 #ifdef HAVE_LIBSSH2_KNOWNHOST_CHECKP
547       keycheck = libssh2_knownhost_checkp(sshc->kh,
548                                           conn->host.name,
549                                           (conn->remote_port != PORT_SSH)?
550                                           conn->remote_port:-1,
551                                           remotekey, keylen,
552                                           LIBSSH2_KNOWNHOST_TYPE_PLAIN|
553                                           LIBSSH2_KNOWNHOST_KEYENC_RAW|
554                                           keybit,
555                                           &host);
556 #else
557       keycheck = libssh2_knownhost_check(sshc->kh,
558                                          conn->host.name,
559                                          remotekey, keylen,
560                                          LIBSSH2_KNOWNHOST_TYPE_PLAIN|
561                                          LIBSSH2_KNOWNHOST_KEYENC_RAW|
562                                          keybit,
563                                          &host);
564 #endif
565
566       infof(data, "SSH host check: %d, key: %s\n", keycheck,
567             (keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)?
568             host->key:"<none>");
569
570       /* setup 'knownkey' */
571       if(keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) {
572         knownkey.key = host->key;
573         knownkey.len = 0;
574         knownkey.keytype = (keytype == LIBSSH2_HOSTKEY_TYPE_RSA)?
575           CURLKHTYPE_RSA : CURLKHTYPE_DSS;
576         knownkeyp = &knownkey;
577       }
578
579       /* setup 'foundkey' */
580       foundkey.key = remotekey;
581       foundkey.len = keylen;
582       foundkey.keytype = (keytype == LIBSSH2_HOSTKEY_TYPE_RSA)?
583         CURLKHTYPE_RSA : CURLKHTYPE_DSS;
584
585       /*
586        * if any of the LIBSSH2_KNOWNHOST_CHECK_* defines and the
587        * curl_khmatch enum are ever modified, we need to introduce a
588        * translation table here!
589        */
590       keymatch = (enum curl_khmatch)keycheck;
591
592       /* Ask the callback how to behave */
593       rc = func(data, knownkeyp, /* from the knownhosts file */
594                 &foundkey, /* from the remote host */
595                 keymatch, data->set.ssh_keyfunc_userp);
596     }
597     else
598       /* no remotekey means failure! */
599       rc = CURLKHSTAT_REJECT;
600
601     switch(rc) {
602     default: /* unknown return codes will equal reject */
603       /* FALLTHROUGH */
604     case CURLKHSTAT_REJECT:
605       state(conn, SSH_SESSION_FREE);
606       /* FALLTHROUGH */
607     case CURLKHSTAT_DEFER:
608       /* DEFER means bail out but keep the SSH_HOSTKEY state */
609       result = sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION;
610       break;
611     case CURLKHSTAT_FINE:
612     case CURLKHSTAT_FINE_ADD_TO_FILE:
613       /* proceed */
614       if(keycheck != LIBSSH2_KNOWNHOST_CHECK_MATCH) {
615         /* the found host+key didn't match but has been told to be fine
616            anyway so we add it in memory */
617         int addrc = libssh2_knownhost_add(sshc->kh,
618                                           conn->host.name, NULL,
619                                           remotekey, keylen,
620                                           LIBSSH2_KNOWNHOST_TYPE_PLAIN|
621                                           LIBSSH2_KNOWNHOST_KEYENC_RAW|
622                                           keybit, NULL);
623         if(addrc)
624           infof(data, "Warning adding the known host %s failed!\n",
625                 conn->host.name);
626         else if(rc == CURLKHSTAT_FINE_ADD_TO_FILE) {
627           /* now we write the entire in-memory list of known hosts to the
628              known_hosts file */
629           int wrc =
630             libssh2_knownhost_writefile(sshc->kh,
631                                         data->set.str[STRING_SSH_KNOWNHOSTS],
632                                         LIBSSH2_KNOWNHOST_FILE_OPENSSH);
633           if(wrc) {
634             infof(data, "Warning, writing %s failed!\n",
635                   data->set.str[STRING_SSH_KNOWNHOSTS]);
636           }
637         }
638       }
639       break;
640     }
641   }
642 #else /* HAVE_LIBSSH2_KNOWNHOST_API */
643   (void)conn;
644 #endif
645   return result;
646 }
647
648 static CURLcode ssh_check_fingerprint(struct connectdata *conn)
649 {
650   struct ssh_conn *sshc = &conn->proto.sshc;
651   struct SessionHandle *data = conn->data;
652   const char *pubkey_md5 = data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5];
653   char md5buffer[33];
654   int i;
655
656   const char *fingerprint = libssh2_hostkey_hash(sshc->ssh_session,
657       LIBSSH2_HOSTKEY_HASH_MD5);
658
659   if(fingerprint) {
660     /* The fingerprint points to static storage (!), don't free() it. */
661     for(i = 0; i < 16; i++)
662       snprintf(&md5buffer[i*2], 3, "%02x", (unsigned char) fingerprint[i]);
663     infof(data, "SSH MD5 fingerprint: %s\n", md5buffer);
664   }
665
666   /* Before we authenticate we check the hostkey's MD5 fingerprint
667    * against a known fingerprint, if available.
668    */
669   if(pubkey_md5 && strlen(pubkey_md5) == 32) {
670     if(!fingerprint || !strequal(md5buffer, pubkey_md5)) {
671       if(fingerprint)
672         failf(data,
673             "Denied establishing ssh session: mismatch md5 fingerprint. "
674             "Remote %s is not equal to %s", md5buffer, pubkey_md5);
675       else
676         failf(data,
677             "Denied establishing ssh session: md5 fingerprint not available");
678       state(conn, SSH_SESSION_FREE);
679       sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION;
680       return sshc->actualcode;
681     }
682     else {
683       infof(data, "MD5 checksum match!\n");
684       /* as we already matched, we skip the check for known hosts */
685       return CURLE_OK;
686     }
687   }
688   else
689     return ssh_knownhost(conn);
690 }
691
692 /*
693  * ssh_statemach_act() runs the SSH state machine as far as it can without
694  * blocking and without reaching the end.  The data the pointer 'block' points
695  * to will be set to TRUE if the libssh2 function returns LIBSSH2_ERROR_EAGAIN
696  * meaning it wants to be called again when the socket is ready
697  */
698
699 static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
700 {
701   CURLcode result = CURLE_OK;
702   struct SessionHandle *data = conn->data;
703   struct SSHPROTO *sftp_scp = data->req.protop;
704   struct ssh_conn *sshc = &conn->proto.sshc;
705   curl_socket_t sock = conn->sock[FIRSTSOCKET];
706   char *new_readdir_line;
707   int rc = LIBSSH2_ERROR_NONE;
708   int err;
709   int seekerr = CURL_SEEKFUNC_OK;
710   *block = 0; /* we're not blocking by default */
711
712   do {
713
714     switch(sshc->state) {
715     case SSH_INIT:
716       sshc->secondCreateDirs = 0;
717       sshc->nextstate = SSH_NO_STATE;
718       sshc->actualcode = CURLE_OK;
719
720       /* Set libssh2 to non-blocking, since everything internally is
721          non-blocking */
722       libssh2_session_set_blocking(sshc->ssh_session, 0);
723
724       state(conn, SSH_S_STARTUP);
725       /* fall-through */
726
727     case SSH_S_STARTUP:
728       rc = libssh2_session_startup(sshc->ssh_session, (int)sock);
729       if(rc == LIBSSH2_ERROR_EAGAIN) {
730         break;
731       }
732       else if(rc) {
733         failf(data, "Failure establishing ssh session");
734         state(conn, SSH_SESSION_FREE);
735         sshc->actualcode = CURLE_FAILED_INIT;
736         break;
737       }
738
739       state(conn, SSH_HOSTKEY);
740
741       /* fall-through */
742     case SSH_HOSTKEY:
743       /*
744        * Before we authenticate we should check the hostkey's fingerprint
745        * against our known hosts. How that is handled (reading from file,
746        * whatever) is up to us.
747        */
748       result = ssh_check_fingerprint(conn);
749       if(!result)
750         state(conn, SSH_AUTHLIST);
751       /* ssh_check_fingerprint sets state appropriately on error */
752       break;
753
754     case SSH_AUTHLIST:
755       /*
756        * Figure out authentication methods
757        * NB: As soon as we have provided a username to an openssh server we
758        * must never change it later. Thus, always specify the correct username
759        * here, even though the libssh2 docs kind of indicate that it should be
760        * possible to get a 'generic' list (not user-specific) of authentication
761        * methods, presumably with a blank username. That won't work in my
762        * experience.
763        * So always specify it here.
764        */
765       sshc->authlist = libssh2_userauth_list(sshc->ssh_session,
766                                              conn->user,
767                                              curlx_uztoui(strlen(conn->user)));
768
769       if(!sshc->authlist) {
770         if(libssh2_userauth_authenticated(sshc->ssh_session)) {
771           sshc->authed = TRUE;
772           infof(data, "SSH user accepted with no authentication\n");
773           state(conn, SSH_AUTH_DONE);
774           break;
775         }
776         else if((err = libssh2_session_last_errno(sshc->ssh_session)) ==
777            LIBSSH2_ERROR_EAGAIN) {
778           rc = LIBSSH2_ERROR_EAGAIN;
779           break;
780         }
781         else {
782           state(conn, SSH_SESSION_FREE);
783           sshc->actualcode = libssh2_session_error_to_CURLE(err);
784           break;
785         }
786       }
787       infof(data, "SSH authentication methods available: %s\n",
788             sshc->authlist);
789
790       state(conn, SSH_AUTH_PKEY_INIT);
791       break;
792
793     case SSH_AUTH_PKEY_INIT:
794       /*
795        * Check the supported auth types in the order I feel is most secure
796        * with the requested type of authentication
797        */
798       sshc->authed = FALSE;
799
800       if((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) &&
801          (strstr(sshc->authlist, "publickey") != NULL)) {
802         char *home = NULL;
803         bool out_of_memory = FALSE;
804
805         sshc->rsa_pub = sshc->rsa = NULL;
806
807         /* To ponder about: should really the lib be messing about with the
808            HOME environment variable etc? */
809         home = curl_getenv("HOME");
810
811         if(data->set.str[STRING_SSH_PRIVATE_KEY])
812           sshc->rsa = strdup(data->set.str[STRING_SSH_PRIVATE_KEY]);
813         else {
814           /* If no private key file is specified, try some common paths. */
815           if(home) {
816             /* Try ~/.ssh first. */
817             sshc->rsa = aprintf("%s/.ssh/id_rsa", home);
818             if(!sshc->rsa)
819               out_of_memory = TRUE;
820             else if(access(sshc->rsa, R_OK) != 0) {
821               Curl_safefree(sshc->rsa);
822               sshc->rsa = aprintf("%s/.ssh/id_dsa", home);
823               if(!sshc->rsa)
824                 out_of_memory = TRUE;
825               else if(access(sshc->rsa, R_OK) != 0) {
826                 Curl_safefree(sshc->rsa);
827               }
828             }
829           }
830           if(!out_of_memory && !sshc->rsa) {
831             /* Nothing found; try the current dir. */
832             sshc->rsa = strdup("id_rsa");
833             if(sshc->rsa && access(sshc->rsa, R_OK) != 0) {
834               Curl_safefree(sshc->rsa);
835               sshc->rsa = strdup("id_dsa");
836               if(sshc->rsa && access(sshc->rsa, R_OK) != 0) {
837                 Curl_safefree(sshc->rsa);
838                 /* Out of guesses. Set to the empty string to avoid
839                  * surprising info messages. */
840                 sshc->rsa = strdup("");
841               }
842             }
843           }
844         }
845
846         /*
847          * Unless the user explicitly specifies a public key file, let
848          * libssh2 extract the public key from the private key file.
849          * This is done by simply passing sshc->rsa_pub = NULL.
850          */
851         if(data->set.str[STRING_SSH_PUBLIC_KEY]) {
852           sshc->rsa_pub = strdup(data->set.str[STRING_SSH_PUBLIC_KEY]);
853           if(!sshc->rsa_pub)
854             out_of_memory = TRUE;
855         }
856
857         if(out_of_memory || sshc->rsa == NULL) {
858           free(home);
859           Curl_safefree(sshc->rsa);
860           Curl_safefree(sshc->rsa_pub);
861           state(conn, SSH_SESSION_FREE);
862           sshc->actualcode = CURLE_OUT_OF_MEMORY;
863           break;
864         }
865
866         sshc->passphrase = data->set.str[STRING_KEY_PASSWD];
867         if(!sshc->passphrase)
868           sshc->passphrase = "";
869
870         free(home);
871
872         infof(data, "Using SSH public key file '%s'\n", sshc->rsa_pub);
873         infof(data, "Using SSH private key file '%s'\n", sshc->rsa);
874
875         state(conn, SSH_AUTH_PKEY);
876       }
877       else {
878         state(conn, SSH_AUTH_PASS_INIT);
879       }
880       break;
881
882     case SSH_AUTH_PKEY:
883       /* The function below checks if the files exists, no need to stat() here.
884        */
885       rc = libssh2_userauth_publickey_fromfile_ex(sshc->ssh_session,
886                                                   conn->user,
887                                                   curlx_uztoui(
888                                                     strlen(conn->user)),
889                                                   sshc->rsa_pub,
890                                                   sshc->rsa, sshc->passphrase);
891       if(rc == LIBSSH2_ERROR_EAGAIN) {
892         break;
893       }
894
895       Curl_safefree(sshc->rsa_pub);
896       Curl_safefree(sshc->rsa);
897
898       if(rc == 0) {
899         sshc->authed = TRUE;
900         infof(data, "Initialized SSH public key authentication\n");
901         state(conn, SSH_AUTH_DONE);
902       }
903       else {
904         char *err_msg;
905         (void)libssh2_session_last_error(sshc->ssh_session,
906                                          &err_msg, NULL, 0);
907         infof(data, "SSH public key authentication failed: %s\n", err_msg);
908         state(conn, SSH_AUTH_PASS_INIT);
909       }
910       break;
911
912     case SSH_AUTH_PASS_INIT:
913       if((data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) &&
914          (strstr(sshc->authlist, "password") != NULL)) {
915         state(conn, SSH_AUTH_PASS);
916       }
917       else {
918         state(conn, SSH_AUTH_HOST_INIT);
919       }
920       break;
921
922     case SSH_AUTH_PASS:
923       rc = libssh2_userauth_password_ex(sshc->ssh_session, conn->user,
924                                         curlx_uztoui(strlen(conn->user)),
925                                         conn->passwd,
926                                         curlx_uztoui(strlen(conn->passwd)),
927                                         NULL);
928       if(rc == LIBSSH2_ERROR_EAGAIN) {
929         break;
930       }
931       else if(rc == 0) {
932         sshc->authed = TRUE;
933         infof(data, "Initialized password authentication\n");
934         state(conn, SSH_AUTH_DONE);
935       }
936       else {
937         state(conn, SSH_AUTH_HOST_INIT);
938         rc = 0; /* clear rc and continue */
939       }
940       break;
941
942     case SSH_AUTH_HOST_INIT:
943       if((data->set.ssh_auth_types & CURLSSH_AUTH_HOST) &&
944          (strstr(sshc->authlist, "hostbased") != NULL)) {
945         state(conn, SSH_AUTH_HOST);
946       }
947       else {
948         state(conn, SSH_AUTH_AGENT_INIT);
949       }
950       break;
951
952     case SSH_AUTH_HOST:
953       state(conn, SSH_AUTH_AGENT_INIT);
954       break;
955
956     case SSH_AUTH_AGENT_INIT:
957 #ifdef HAVE_LIBSSH2_AGENT_API
958       if((data->set.ssh_auth_types & CURLSSH_AUTH_AGENT)
959          && (strstr(sshc->authlist, "publickey") != NULL)) {
960
961         /* Connect to the ssh-agent */
962         /* The agent could be shared by a curl thread i believe
963            but nothing obvious as keys can be added/removed at any time */
964         if(!sshc->ssh_agent) {
965           sshc->ssh_agent = libssh2_agent_init(sshc->ssh_session);
966           if(!sshc->ssh_agent) {
967             infof(data, "Could not create agent object\n");
968
969             state(conn, SSH_AUTH_KEY_INIT);
970             break;
971           }
972         }
973
974         rc = libssh2_agent_connect(sshc->ssh_agent);
975         if(rc == LIBSSH2_ERROR_EAGAIN)
976           break;
977         if(rc < 0) {
978           infof(data, "Failure connecting to agent\n");
979           state(conn, SSH_AUTH_KEY_INIT);
980         }
981         else {
982           state(conn, SSH_AUTH_AGENT_LIST);
983         }
984       }
985       else
986 #endif /* HAVE_LIBSSH2_AGENT_API */
987         state(conn, SSH_AUTH_KEY_INIT);
988       break;
989
990     case SSH_AUTH_AGENT_LIST:
991 #ifdef HAVE_LIBSSH2_AGENT_API
992       rc = libssh2_agent_list_identities(sshc->ssh_agent);
993
994       if(rc == LIBSSH2_ERROR_EAGAIN)
995         break;
996       if(rc < 0) {
997         infof(data, "Failure requesting identities to agent\n");
998         state(conn, SSH_AUTH_KEY_INIT);
999       }
1000       else {
1001         state(conn, SSH_AUTH_AGENT);
1002         sshc->sshagent_prev_identity = NULL;
1003       }
1004 #endif
1005       break;
1006
1007     case SSH_AUTH_AGENT:
1008 #ifdef HAVE_LIBSSH2_AGENT_API
1009       /* as prev_identity evolves only after an identity user auth finished we
1010          can safely request it again as long as EAGAIN is returned here or by
1011          libssh2_agent_userauth */
1012       rc = libssh2_agent_get_identity(sshc->ssh_agent,
1013                                       &sshc->sshagent_identity,
1014                                       sshc->sshagent_prev_identity);
1015       if(rc == LIBSSH2_ERROR_EAGAIN)
1016         break;
1017
1018       if(rc == 0) {
1019         rc = libssh2_agent_userauth(sshc->ssh_agent, conn->user,
1020                                     sshc->sshagent_identity);
1021
1022         if(rc < 0) {
1023           if(rc != LIBSSH2_ERROR_EAGAIN)
1024             /* tried and failed? go to next identity */
1025             sshc->sshagent_prev_identity = sshc->sshagent_identity;
1026           else
1027             break;
1028         }
1029       }
1030
1031       if(rc < 0)
1032         infof(data, "Failure requesting identities to agent\n");
1033       else if(rc == 1)
1034         infof(data, "No identity would match\n");
1035
1036       if(rc == LIBSSH2_ERROR_NONE) {
1037         sshc->authed = TRUE;
1038         infof(data, "Agent based authentication successful\n");
1039         state(conn, SSH_AUTH_DONE);
1040       }
1041       else {
1042         state(conn, SSH_AUTH_KEY_INIT);
1043         rc = 0; /* clear rc and continue */
1044       }
1045 #endif
1046       break;
1047
1048     case SSH_AUTH_KEY_INIT:
1049       if((data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD)
1050          && (strstr(sshc->authlist, "keyboard-interactive") != NULL)) {
1051         state(conn, SSH_AUTH_KEY);
1052       }
1053       else {
1054         state(conn, SSH_AUTH_DONE);
1055       }
1056       break;
1057
1058     case SSH_AUTH_KEY:
1059       /* Authentication failed. Continue with keyboard-interactive now. */
1060       rc = libssh2_userauth_keyboard_interactive_ex(sshc->ssh_session,
1061                                                     conn->user,
1062                                                     curlx_uztoui(
1063                                                       strlen(conn->user)),
1064                                                     &kbd_callback);
1065       if(rc == LIBSSH2_ERROR_EAGAIN) {
1066         break;
1067       }
1068       else if(rc == 0) {
1069         sshc->authed = TRUE;
1070         infof(data, "Initialized keyboard interactive authentication\n");
1071       }
1072       state(conn, SSH_AUTH_DONE);
1073       break;
1074
1075     case SSH_AUTH_DONE:
1076       if(!sshc->authed) {
1077         failf(data, "Authentication failure");
1078         state(conn, SSH_SESSION_FREE);
1079         sshc->actualcode = CURLE_LOGIN_DENIED;
1080         break;
1081       }
1082
1083       /*
1084        * At this point we have an authenticated ssh session.
1085        */
1086       infof(data, "Authentication complete\n");
1087
1088       Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSH is connected */
1089
1090       conn->sockfd = sock;
1091       conn->writesockfd = CURL_SOCKET_BAD;
1092
1093       if(conn->handler->protocol == CURLPROTO_SFTP) {
1094         state(conn, SSH_SFTP_INIT);
1095         break;
1096       }
1097       infof(data, "SSH CONNECT phase done\n");
1098       state(conn, SSH_STOP);
1099       break;
1100
1101     case SSH_SFTP_INIT:
1102       /*
1103        * Start the libssh2 sftp session
1104        */
1105       sshc->sftp_session = libssh2_sftp_init(sshc->ssh_session);
1106       if(!sshc->sftp_session) {
1107         if(libssh2_session_last_errno(sshc->ssh_session) ==
1108            LIBSSH2_ERROR_EAGAIN) {
1109           rc = LIBSSH2_ERROR_EAGAIN;
1110           break;
1111         }
1112         else {
1113           char *err_msg;
1114
1115           (void)libssh2_session_last_error(sshc->ssh_session,
1116                                            &err_msg, NULL, 0);
1117           failf(data, "Failure initializing sftp session: %s", err_msg);
1118           state(conn, SSH_SESSION_FREE);
1119           sshc->actualcode = CURLE_FAILED_INIT;
1120           break;
1121         }
1122       }
1123       state(conn, SSH_SFTP_REALPATH);
1124       break;
1125
1126     case SSH_SFTP_REALPATH:
1127     {
1128       char tempHome[PATH_MAX];
1129
1130       /*
1131        * Get the "home" directory
1132        */
1133       rc = sftp_libssh2_realpath(sshc->sftp_session, ".",
1134                                  tempHome, PATH_MAX-1);
1135       if(rc == LIBSSH2_ERROR_EAGAIN) {
1136         break;
1137       }
1138       else if(rc > 0) {
1139         /* It seems that this string is not always NULL terminated */
1140         tempHome[rc] = '\0';
1141         sshc->homedir = strdup(tempHome);
1142         if(!sshc->homedir) {
1143           state(conn, SSH_SFTP_CLOSE);
1144           sshc->actualcode = CURLE_OUT_OF_MEMORY;
1145           break;
1146         }
1147         conn->data->state.most_recent_ftp_entrypath = sshc->homedir;
1148       }
1149       else {
1150         /* Return the error type */
1151         err = sftp_libssh2_last_error(sshc->sftp_session);
1152         result = sftp_libssh2_error_to_CURLE(err);
1153         sshc->actualcode = result?result:CURLE_SSH;
1154         DEBUGF(infof(data, "error = %d makes libcurl = %d\n",
1155                      err, (int)result));
1156         state(conn, SSH_STOP);
1157         break;
1158       }
1159     }
1160     /* This is the last step in the SFTP connect phase. Do note that while
1161        we get the homedir here, we get the "workingpath" in the DO action
1162        since the homedir will remain the same between request but the
1163        working path will not. */
1164     DEBUGF(infof(data, "SSH CONNECT phase done\n"));
1165     state(conn, SSH_STOP);
1166     break;
1167
1168     case SSH_SFTP_QUOTE_INIT:
1169
1170       result = ssh_getworkingpath(conn, sshc->homedir, &sftp_scp->path);
1171       if(result) {
1172         sshc->actualcode = result;
1173         state(conn, SSH_STOP);
1174         break;
1175       }
1176
1177       if(data->set.quote) {
1178         infof(data, "Sending quote commands\n");
1179         sshc->quote_item = data->set.quote;
1180         state(conn, SSH_SFTP_QUOTE);
1181       }
1182       else {
1183         state(conn, SSH_SFTP_TRANS_INIT);
1184       }
1185       break;
1186
1187     case SSH_SFTP_POSTQUOTE_INIT:
1188       if(data->set.postquote) {
1189         infof(data, "Sending quote commands\n");
1190         sshc->quote_item = data->set.postquote;
1191         state(conn, SSH_SFTP_QUOTE);
1192       }
1193       else {
1194         state(conn, SSH_STOP);
1195       }
1196       break;
1197
1198     case SSH_SFTP_QUOTE:
1199       /* Send any quote commands */
1200     {
1201       const char *cp;
1202
1203       /*
1204        * Support some of the "FTP" commands
1205        */
1206       char *cmd = sshc->quote_item->data;
1207       sshc->acceptfail = FALSE;
1208
1209       /* if a command starts with an asterisk, which a legal SFTP command never
1210          can, the command will be allowed to fail without it causing any
1211          aborts or cancels etc. It will cause libcurl to act as if the command
1212          is successful, whatever the server reponds. */
1213
1214       if(cmd[0] == '*') {
1215         cmd++;
1216         sshc->acceptfail = TRUE;
1217       }
1218
1219       if(curl_strequal("pwd", cmd)) {
1220         /* output debug output if that is requested */
1221         char *tmp = aprintf("257 \"%s\" is current directory.\n",
1222                             sftp_scp->path);
1223         if(!tmp) {
1224           result = CURLE_OUT_OF_MEMORY;
1225           state(conn, SSH_SFTP_CLOSE);
1226           sshc->nextstate = SSH_NO_STATE;
1227           break;
1228         }
1229         if(data->set.verbose) {
1230           Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"PWD\n", 4, conn);
1231           Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp), conn);
1232         }
1233         /* this sends an FTP-like "header" to the header callback so that the
1234            current directory can be read very similar to how it is read when
1235            using ordinary FTP. */
1236         result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp));
1237         free(tmp);
1238         if(result) {
1239           state(conn, SSH_SFTP_CLOSE);
1240           sshc->nextstate = SSH_NO_STATE;
1241           sshc->actualcode = result;
1242         }
1243         else
1244           state(conn, SSH_SFTP_NEXT_QUOTE);
1245         break;
1246       }
1247       else if(cmd) {
1248         /*
1249          * the arguments following the command must be separated from the
1250          * command with a space so we can check for it unconditionally
1251          */
1252         cp = strchr(cmd, ' ');
1253         if(cp == NULL) {
1254           failf(data, "Syntax error in SFTP command. Supply parameter(s)!");
1255           state(conn, SSH_SFTP_CLOSE);
1256           sshc->nextstate = SSH_NO_STATE;
1257           sshc->actualcode = CURLE_QUOTE_ERROR;
1258           break;
1259         }
1260
1261         /*
1262          * also, every command takes at least one argument so we get that
1263          * first argument right now
1264          */
1265         result = get_pathname(&cp, &sshc->quote_path1);
1266         if(result) {
1267           if(result == CURLE_OUT_OF_MEMORY)
1268             failf(data, "Out of memory");
1269           else
1270             failf(data, "Syntax error: Bad first parameter");
1271           state(conn, SSH_SFTP_CLOSE);
1272           sshc->nextstate = SSH_NO_STATE;
1273           sshc->actualcode = result;
1274           break;
1275         }
1276
1277         /*
1278          * SFTP is a binary protocol, so we don't send text commands
1279          * to the server. Instead, we scan for commands used by
1280          * OpenSSH's sftp program and call the appropriate libssh2
1281          * functions.
1282          */
1283         if(curl_strnequal(cmd, "chgrp ", 6) ||
1284            curl_strnequal(cmd, "chmod ", 6) ||
1285            curl_strnequal(cmd, "chown ", 6) ) {
1286           /* attribute change */
1287
1288           /* sshc->quote_path1 contains the mode to set */
1289           /* get the destination */
1290           result = get_pathname(&cp, &sshc->quote_path2);
1291           if(result) {
1292             if(result == CURLE_OUT_OF_MEMORY)
1293               failf(data, "Out of memory");
1294             else
1295               failf(data, "Syntax error in chgrp/chmod/chown: "
1296                     "Bad second parameter");
1297             Curl_safefree(sshc->quote_path1);
1298             state(conn, SSH_SFTP_CLOSE);
1299             sshc->nextstate = SSH_NO_STATE;
1300             sshc->actualcode = result;
1301             break;
1302           }
1303           memset(&sshc->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES));
1304           state(conn, SSH_SFTP_QUOTE_STAT);
1305           break;
1306         }
1307         else if(curl_strnequal(cmd, "ln ", 3) ||
1308                 curl_strnequal(cmd, "symlink ", 8)) {
1309           /* symbolic linking */
1310           /* sshc->quote_path1 is the source */
1311           /* get the destination */
1312           result = get_pathname(&cp, &sshc->quote_path2);
1313           if(result) {
1314             if(result == CURLE_OUT_OF_MEMORY)
1315               failf(data, "Out of memory");
1316             else
1317               failf(data,
1318                     "Syntax error in ln/symlink: Bad second parameter");
1319             Curl_safefree(sshc->quote_path1);
1320             state(conn, SSH_SFTP_CLOSE);
1321             sshc->nextstate = SSH_NO_STATE;
1322             sshc->actualcode = result;
1323             break;
1324           }
1325           state(conn, SSH_SFTP_QUOTE_SYMLINK);
1326           break;
1327         }
1328         else if(curl_strnequal(cmd, "mkdir ", 6)) {
1329           /* create dir */
1330           state(conn, SSH_SFTP_QUOTE_MKDIR);
1331           break;
1332         }
1333         else if(curl_strnequal(cmd, "rename ", 7)) {
1334           /* rename file */
1335           /* first param is the source path */
1336           /* second param is the dest. path */
1337           result = get_pathname(&cp, &sshc->quote_path2);
1338           if(result) {
1339             if(result == CURLE_OUT_OF_MEMORY)
1340               failf(data, "Out of memory");
1341             else
1342               failf(data, "Syntax error in rename: Bad second parameter");
1343             Curl_safefree(sshc->quote_path1);
1344             state(conn, SSH_SFTP_CLOSE);
1345             sshc->nextstate = SSH_NO_STATE;
1346             sshc->actualcode = result;
1347             break;
1348           }
1349           state(conn, SSH_SFTP_QUOTE_RENAME);
1350           break;
1351         }
1352         else if(curl_strnequal(cmd, "rmdir ", 6)) {
1353           /* delete dir */
1354           state(conn, SSH_SFTP_QUOTE_RMDIR);
1355           break;
1356         }
1357         else if(curl_strnequal(cmd, "rm ", 3)) {
1358           state(conn, SSH_SFTP_QUOTE_UNLINK);
1359           break;
1360         }
1361
1362         failf(data, "Unknown SFTP command");
1363         Curl_safefree(sshc->quote_path1);
1364         Curl_safefree(sshc->quote_path2);
1365         state(conn, SSH_SFTP_CLOSE);
1366         sshc->nextstate = SSH_NO_STATE;
1367         sshc->actualcode = CURLE_QUOTE_ERROR;
1368         break;
1369       }
1370     }
1371     if(!sshc->quote_item) {
1372       state(conn, SSH_SFTP_TRANS_INIT);
1373     }
1374     break;
1375
1376     case SSH_SFTP_NEXT_QUOTE:
1377       Curl_safefree(sshc->quote_path1);
1378       Curl_safefree(sshc->quote_path2);
1379
1380       sshc->quote_item = sshc->quote_item->next;
1381
1382       if(sshc->quote_item) {
1383         state(conn, SSH_SFTP_QUOTE);
1384       }
1385       else {
1386         if(sshc->nextstate != SSH_NO_STATE) {
1387           state(conn, sshc->nextstate);
1388           sshc->nextstate = SSH_NO_STATE;
1389         }
1390         else {
1391           state(conn, SSH_SFTP_TRANS_INIT);
1392         }
1393       }
1394       break;
1395
1396     case SSH_SFTP_QUOTE_STAT:
1397     {
1398       char *cmd = sshc->quote_item->data;
1399       sshc->acceptfail = FALSE;
1400
1401       /* if a command starts with an asterisk, which a legal SFTP command never
1402          can, the command will be allowed to fail without it causing any
1403          aborts or cancels etc. It will cause libcurl to act as if the command
1404          is successful, whatever the server reponds. */
1405
1406       if(cmd[0] == '*') {
1407         cmd++;
1408         sshc->acceptfail = TRUE;
1409       }
1410
1411       if(!curl_strnequal(cmd, "chmod", 5)) {
1412         /* Since chown and chgrp only set owner OR group but libssh2 wants to
1413          * set them both at once, we need to obtain the current ownership
1414          * first.  This takes an extra protocol round trip.
1415          */
1416         rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2,
1417                                   curlx_uztoui(strlen(sshc->quote_path2)),
1418                                   LIBSSH2_SFTP_STAT,
1419                                   &sshc->quote_attrs);
1420         if(rc == LIBSSH2_ERROR_EAGAIN) {
1421           break;
1422         }
1423         else if(rc != 0 && !sshc->acceptfail) { /* get those attributes */
1424           err = sftp_libssh2_last_error(sshc->sftp_session);
1425           Curl_safefree(sshc->quote_path1);
1426           Curl_safefree(sshc->quote_path2);
1427           failf(data, "Attempt to get SFTP stats failed: %s",
1428                 sftp_libssh2_strerror(err));
1429           state(conn, SSH_SFTP_CLOSE);
1430           sshc->nextstate = SSH_NO_STATE;
1431           sshc->actualcode = CURLE_QUOTE_ERROR;
1432           break;
1433         }
1434       }
1435
1436       /* Now set the new attributes... */
1437       if(curl_strnequal(cmd, "chgrp", 5)) {
1438         sshc->quote_attrs.gid = strtoul(sshc->quote_path1, NULL, 10);
1439         sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID;
1440         if(sshc->quote_attrs.gid == 0 && !ISDIGIT(sshc->quote_path1[0]) &&
1441            !sshc->acceptfail) {
1442           Curl_safefree(sshc->quote_path1);
1443           Curl_safefree(sshc->quote_path2);
1444           failf(data, "Syntax error: chgrp gid not a number");
1445           state(conn, SSH_SFTP_CLOSE);
1446           sshc->nextstate = SSH_NO_STATE;
1447           sshc->actualcode = CURLE_QUOTE_ERROR;
1448           break;
1449         }
1450       }
1451       else if(curl_strnequal(cmd, "chmod", 5)) {
1452         sshc->quote_attrs.permissions = strtoul(sshc->quote_path1, NULL, 8);
1453         sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS;
1454         /* permissions are octal */
1455         if(sshc->quote_attrs.permissions == 0 &&
1456            !ISDIGIT(sshc->quote_path1[0])) {
1457           Curl_safefree(sshc->quote_path1);
1458           Curl_safefree(sshc->quote_path2);
1459           failf(data, "Syntax error: chmod permissions not a number");
1460           state(conn, SSH_SFTP_CLOSE);
1461           sshc->nextstate = SSH_NO_STATE;
1462           sshc->actualcode = CURLE_QUOTE_ERROR;
1463           break;
1464         }
1465       }
1466       else if(curl_strnequal(cmd, "chown", 5)) {
1467         sshc->quote_attrs.uid = strtoul(sshc->quote_path1, NULL, 10);
1468         sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID;
1469         if(sshc->quote_attrs.uid == 0 && !ISDIGIT(sshc->quote_path1[0]) &&
1470            !sshc->acceptfail) {
1471           Curl_safefree(sshc->quote_path1);
1472           Curl_safefree(sshc->quote_path2);
1473           failf(data, "Syntax error: chown uid not a number");
1474           state(conn, SSH_SFTP_CLOSE);
1475           sshc->nextstate = SSH_NO_STATE;
1476           sshc->actualcode = CURLE_QUOTE_ERROR;
1477           break;
1478         }
1479       }
1480
1481       /* Now send the completed structure... */
1482       state(conn, SSH_SFTP_QUOTE_SETSTAT);
1483       break;
1484     }
1485
1486     case SSH_SFTP_QUOTE_SETSTAT:
1487       rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2,
1488                                 curlx_uztoui(strlen(sshc->quote_path2)),
1489                                 LIBSSH2_SFTP_SETSTAT,
1490                                 &sshc->quote_attrs);
1491       if(rc == LIBSSH2_ERROR_EAGAIN) {
1492         break;
1493       }
1494       else if(rc != 0 && !sshc->acceptfail) {
1495         err = sftp_libssh2_last_error(sshc->sftp_session);
1496         Curl_safefree(sshc->quote_path1);
1497         Curl_safefree(sshc->quote_path2);
1498         failf(data, "Attempt to set SFTP stats failed: %s",
1499               sftp_libssh2_strerror(err));
1500         state(conn, SSH_SFTP_CLOSE);
1501         sshc->nextstate = SSH_NO_STATE;
1502         sshc->actualcode = CURLE_QUOTE_ERROR;
1503         break;
1504       }
1505       state(conn, SSH_SFTP_NEXT_QUOTE);
1506       break;
1507
1508     case SSH_SFTP_QUOTE_SYMLINK:
1509       rc = libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->quote_path1,
1510                                    curlx_uztoui(strlen(sshc->quote_path1)),
1511                                    sshc->quote_path2,
1512                                    curlx_uztoui(strlen(sshc->quote_path2)),
1513                                    LIBSSH2_SFTP_SYMLINK);
1514       if(rc == LIBSSH2_ERROR_EAGAIN) {
1515         break;
1516       }
1517       else if(rc != 0 && !sshc->acceptfail) {
1518         err = sftp_libssh2_last_error(sshc->sftp_session);
1519         Curl_safefree(sshc->quote_path1);
1520         Curl_safefree(sshc->quote_path2);
1521         failf(data, "symlink command failed: %s",
1522               sftp_libssh2_strerror(err));
1523         state(conn, SSH_SFTP_CLOSE);
1524         sshc->nextstate = SSH_NO_STATE;
1525         sshc->actualcode = CURLE_QUOTE_ERROR;
1526         break;
1527       }
1528       state(conn, SSH_SFTP_NEXT_QUOTE);
1529       break;
1530
1531     case SSH_SFTP_QUOTE_MKDIR:
1532       rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshc->quote_path1,
1533                                  curlx_uztoui(strlen(sshc->quote_path1)),
1534                                  data->set.new_directory_perms);
1535       if(rc == LIBSSH2_ERROR_EAGAIN) {
1536         break;
1537       }
1538       else if(rc != 0 && !sshc->acceptfail) {
1539         err = sftp_libssh2_last_error(sshc->sftp_session);
1540         Curl_safefree(sshc->quote_path1);
1541         failf(data, "mkdir command failed: %s", sftp_libssh2_strerror(err));
1542         state(conn, SSH_SFTP_CLOSE);
1543         sshc->nextstate = SSH_NO_STATE;
1544         sshc->actualcode = CURLE_QUOTE_ERROR;
1545         break;
1546       }
1547       state(conn, SSH_SFTP_NEXT_QUOTE);
1548       break;
1549
1550     case SSH_SFTP_QUOTE_RENAME:
1551       rc = libssh2_sftp_rename_ex(sshc->sftp_session, sshc->quote_path1,
1552                                   curlx_uztoui(strlen(sshc->quote_path1)),
1553                                   sshc->quote_path2,
1554                                   curlx_uztoui(strlen(sshc->quote_path2)),
1555                                   LIBSSH2_SFTP_RENAME_OVERWRITE |
1556                                   LIBSSH2_SFTP_RENAME_ATOMIC |
1557                                   LIBSSH2_SFTP_RENAME_NATIVE);
1558
1559       if(rc == LIBSSH2_ERROR_EAGAIN) {
1560         break;
1561       }
1562       else if(rc != 0 && !sshc->acceptfail) {
1563         err = sftp_libssh2_last_error(sshc->sftp_session);
1564         Curl_safefree(sshc->quote_path1);
1565         Curl_safefree(sshc->quote_path2);
1566         failf(data, "rename command failed: %s", sftp_libssh2_strerror(err));
1567         state(conn, SSH_SFTP_CLOSE);
1568         sshc->nextstate = SSH_NO_STATE;
1569         sshc->actualcode = CURLE_QUOTE_ERROR;
1570         break;
1571       }
1572       state(conn, SSH_SFTP_NEXT_QUOTE);
1573       break;
1574
1575     case SSH_SFTP_QUOTE_RMDIR:
1576       rc = libssh2_sftp_rmdir_ex(sshc->sftp_session, sshc->quote_path1,
1577                                  curlx_uztoui(strlen(sshc->quote_path1)));
1578       if(rc == LIBSSH2_ERROR_EAGAIN) {
1579         break;
1580       }
1581       else if(rc != 0 && !sshc->acceptfail) {
1582         err = sftp_libssh2_last_error(sshc->sftp_session);
1583         Curl_safefree(sshc->quote_path1);
1584         failf(data, "rmdir command failed: %s", sftp_libssh2_strerror(err));
1585         state(conn, SSH_SFTP_CLOSE);
1586         sshc->nextstate = SSH_NO_STATE;
1587         sshc->actualcode = CURLE_QUOTE_ERROR;
1588         break;
1589       }
1590       state(conn, SSH_SFTP_NEXT_QUOTE);
1591       break;
1592
1593     case SSH_SFTP_QUOTE_UNLINK:
1594       rc = libssh2_sftp_unlink_ex(sshc->sftp_session, sshc->quote_path1,
1595                                   curlx_uztoui(strlen(sshc->quote_path1)));
1596       if(rc == LIBSSH2_ERROR_EAGAIN) {
1597         break;
1598       }
1599       else if(rc != 0 && !sshc->acceptfail) {
1600         err = sftp_libssh2_last_error(sshc->sftp_session);
1601         Curl_safefree(sshc->quote_path1);
1602         failf(data, "rm command failed: %s", sftp_libssh2_strerror(err));
1603         state(conn, SSH_SFTP_CLOSE);
1604         sshc->nextstate = SSH_NO_STATE;
1605         sshc->actualcode = CURLE_QUOTE_ERROR;
1606         break;
1607       }
1608       state(conn, SSH_SFTP_NEXT_QUOTE);
1609       break;
1610
1611     case SSH_SFTP_TRANS_INIT:
1612       if(data->set.upload)
1613         state(conn, SSH_SFTP_UPLOAD_INIT);
1614       else {
1615         if(sftp_scp->path[strlen(sftp_scp->path)-1] == '/')
1616           state(conn, SSH_SFTP_READDIR_INIT);
1617         else
1618           state(conn, SSH_SFTP_DOWNLOAD_INIT);
1619       }
1620       break;
1621
1622     case SSH_SFTP_UPLOAD_INIT:
1623     {
1624       unsigned long flags;
1625       /*
1626        * NOTE!!!  libssh2 requires that the destination path is a full path
1627        *          that includes the destination file and name OR ends in a "/"
1628        *          If this is not done the destination file will be named the
1629        *          same name as the last directory in the path.
1630        */
1631
1632       if(data->state.resume_from != 0) {
1633         LIBSSH2_SFTP_ATTRIBUTES attrs;
1634         if(data->state.resume_from < 0) {
1635           rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path,
1636                                     curlx_uztoui(strlen(sftp_scp->path)),
1637                                     LIBSSH2_SFTP_STAT, &attrs);
1638           if(rc == LIBSSH2_ERROR_EAGAIN) {
1639             break;
1640           }
1641           else if(rc) {
1642             data->state.resume_from = 0;
1643           }
1644           else {
1645             curl_off_t size = attrs.filesize;
1646             if(size < 0) {
1647               failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size);
1648               return CURLE_BAD_DOWNLOAD_RESUME;
1649             }
1650             data->state.resume_from = attrs.filesize;
1651           }
1652         }
1653       }
1654
1655       if(data->set.ftp_append)
1656         /* Try to open for append, but create if nonexisting */
1657         flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_APPEND;
1658       else if(data->state.resume_from > 0)
1659         /* If we have restart position then open for append */
1660         flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_APPEND;
1661       else
1662         /* Clear file before writing (normal behaviour) */
1663         flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC;
1664
1665       sshc->sftp_handle =
1666         libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path,
1667                              curlx_uztoui(strlen(sftp_scp->path)),
1668                              flags, data->set.new_file_perms,
1669                              LIBSSH2_SFTP_OPENFILE);
1670
1671       if(!sshc->sftp_handle) {
1672         rc = libssh2_session_last_errno(sshc->ssh_session);
1673
1674         if(LIBSSH2_ERROR_EAGAIN == rc)
1675           break;
1676         else {
1677           if(LIBSSH2_ERROR_SFTP_PROTOCOL == rc)
1678             /* only when there was an SFTP protocol error can we extract
1679                the sftp error! */
1680             err = sftp_libssh2_last_error(sshc->sftp_session);
1681           else
1682             err = -1; /* not an sftp error at all */
1683
1684           if(sshc->secondCreateDirs) {
1685             state(conn, SSH_SFTP_CLOSE);
1686             sshc->actualcode = err>= LIBSSH2_FX_OK?
1687               sftp_libssh2_error_to_CURLE(err):CURLE_SSH;
1688             failf(data, "Creating the dir/file failed: %s",
1689                   sftp_libssh2_strerror(err));
1690             break;
1691           }
1692           else if(((err == LIBSSH2_FX_NO_SUCH_FILE) ||
1693                    (err == LIBSSH2_FX_FAILURE) ||
1694                    (err == LIBSSH2_FX_NO_SUCH_PATH)) &&
1695                   (data->set.ftp_create_missing_dirs &&
1696                    (strlen(sftp_scp->path) > 1))) {
1697             /* try to create the path remotely */
1698             sshc->secondCreateDirs = 1;
1699             state(conn, SSH_SFTP_CREATE_DIRS_INIT);
1700             break;
1701           }
1702           state(conn, SSH_SFTP_CLOSE);
1703           sshc->actualcode = err>= LIBSSH2_FX_OK?
1704             sftp_libssh2_error_to_CURLE(err):CURLE_SSH;
1705           if(!sshc->actualcode) {
1706             /* Sometimes, for some reason libssh2_sftp_last_error() returns
1707                zero even though libssh2_sftp_open() failed previously! We need
1708                to work around that! */
1709             sshc->actualcode = CURLE_SSH;
1710             err=-1;
1711           }
1712           failf(data, "Upload failed: %s (%d/%d)",
1713                 err>= LIBSSH2_FX_OK?sftp_libssh2_strerror(err):"ssh error",
1714                 err, rc);
1715           break;
1716         }
1717       }
1718
1719       /* If we have a restart point then we need to seek to the correct
1720          position. */
1721       if(data->state.resume_from > 0) {
1722         /* Let's read off the proper amount of bytes from the input. */
1723         if(conn->seek_func) {
1724           seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
1725                                     SEEK_SET);
1726         }
1727
1728         if(seekerr != CURL_SEEKFUNC_OK) {
1729
1730           if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
1731             failf(data, "Could not seek stream");
1732             return CURLE_FTP_COULDNT_USE_REST;
1733           }
1734           /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
1735           else {
1736             curl_off_t passed=0;
1737             do {
1738               size_t readthisamountnow =
1739                 (data->state.resume_from - passed > CURL_OFF_T_C(BUFSIZE)) ?
1740                 BUFSIZE : curlx_sotouz(data->state.resume_from - passed);
1741
1742               size_t actuallyread =
1743                 data->set.fread_func(data->state.buffer, 1, readthisamountnow,
1744                                      data->set.in);
1745
1746               passed += actuallyread;
1747               if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
1748                 /* this checks for greater-than only to make sure that the
1749                    CURL_READFUNC_ABORT return code still aborts */
1750                 failf(data, "Failed to read data");
1751                 return CURLE_FTP_COULDNT_USE_REST;
1752               }
1753             } while(passed < data->state.resume_from);
1754           }
1755         }
1756
1757         /* now, decrease the size of the read */
1758         if(data->state.infilesize > 0) {
1759           data->state.infilesize -= data->state.resume_from;
1760           data->req.size = data->state.infilesize;
1761           Curl_pgrsSetUploadSize(data, data->state.infilesize);
1762         }
1763
1764         SFTP_SEEK(sshc->sftp_handle, data->state.resume_from);
1765       }
1766       if(data->state.infilesize > 0) {
1767         data->req.size = data->state.infilesize;
1768         Curl_pgrsSetUploadSize(data, data->state.infilesize);
1769       }
1770       /* upload data */
1771       Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL);
1772
1773       /* not set by Curl_setup_transfer to preserve keepon bits */
1774       conn->sockfd = conn->writesockfd;
1775
1776       if(result) {
1777         state(conn, SSH_SFTP_CLOSE);
1778         sshc->actualcode = result;
1779       }
1780       else {
1781         /* store this original bitmask setup to use later on if we can't
1782            figure out a "real" bitmask */
1783         sshc->orig_waitfor = data->req.keepon;
1784
1785         /* we want to use the _sending_ function even when the socket turns
1786            out readable as the underlying libssh2 sftp send function will deal
1787            with both accordingly */
1788         conn->cselect_bits = CURL_CSELECT_OUT;
1789
1790         /* since we don't really wait for anything at this point, we want the
1791            state machine to move on as soon as possible so we set a very short
1792            timeout here */
1793         Curl_expire(data, 1);
1794
1795         state(conn, SSH_STOP);
1796       }
1797       break;
1798     }
1799
1800     case SSH_SFTP_CREATE_DIRS_INIT:
1801       if(strlen(sftp_scp->path) > 1) {
1802         sshc->slash_pos = sftp_scp->path + 1; /* ignore the leading '/' */
1803         state(conn, SSH_SFTP_CREATE_DIRS);
1804       }
1805       else {
1806         state(conn, SSH_SFTP_UPLOAD_INIT);
1807       }
1808       break;
1809
1810     case SSH_SFTP_CREATE_DIRS:
1811       sshc->slash_pos = strchr(sshc->slash_pos, '/');
1812       if(sshc->slash_pos) {
1813         *sshc->slash_pos = 0;
1814
1815         infof(data, "Creating directory '%s'\n", sftp_scp->path);
1816         state(conn, SSH_SFTP_CREATE_DIRS_MKDIR);
1817         break;
1818       }
1819       else {
1820         state(conn, SSH_SFTP_UPLOAD_INIT);
1821       }
1822       break;
1823
1824     case SSH_SFTP_CREATE_DIRS_MKDIR:
1825       /* 'mode' - parameter is preliminary - default to 0644 */
1826       rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sftp_scp->path,
1827                                  curlx_uztoui(strlen(sftp_scp->path)),
1828                                  data->set.new_directory_perms);
1829       if(rc == LIBSSH2_ERROR_EAGAIN) {
1830         break;
1831       }
1832       *sshc->slash_pos = '/';
1833       ++sshc->slash_pos;
1834       if(rc == -1) {
1835         /*
1836          * Abort if failure wasn't that the dir already exists or the
1837          * permission was denied (creation might succeed further down the
1838          * path) - retry on unspecific FAILURE also
1839          */
1840         err = sftp_libssh2_last_error(sshc->sftp_session);
1841         if((err != LIBSSH2_FX_FILE_ALREADY_EXISTS) &&
1842            (err != LIBSSH2_FX_FAILURE) &&
1843            (err != LIBSSH2_FX_PERMISSION_DENIED)) {
1844           result = sftp_libssh2_error_to_CURLE(err);
1845           state(conn, SSH_SFTP_CLOSE);
1846           sshc->actualcode = result?result:CURLE_SSH;
1847           break;
1848         }
1849       }
1850       state(conn, SSH_SFTP_CREATE_DIRS);
1851       break;
1852
1853     case SSH_SFTP_READDIR_INIT:
1854       Curl_pgrsSetDownloadSize(data, -1);
1855       if(data->set.opt_no_body) {
1856         state(conn, SSH_STOP);
1857         break;
1858       }
1859
1860       /*
1861        * This is a directory that we are trying to get, so produce a directory
1862        * listing
1863        */
1864       sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session,
1865                                                sftp_scp->path,
1866                                                curlx_uztoui(
1867                                                  strlen(sftp_scp->path)),
1868                                                0, 0, LIBSSH2_SFTP_OPENDIR);
1869       if(!sshc->sftp_handle) {
1870         if(libssh2_session_last_errno(sshc->ssh_session) ==
1871            LIBSSH2_ERROR_EAGAIN) {
1872           rc = LIBSSH2_ERROR_EAGAIN;
1873           break;
1874         }
1875         else {
1876           err = sftp_libssh2_last_error(sshc->sftp_session);
1877           failf(data, "Could not open directory for reading: %s",
1878                 sftp_libssh2_strerror(err));
1879           state(conn, SSH_SFTP_CLOSE);
1880           result = sftp_libssh2_error_to_CURLE(err);
1881           sshc->actualcode = result?result:CURLE_SSH;
1882           break;
1883         }
1884       }
1885       if((sshc->readdir_filename = malloc(PATH_MAX+1)) == NULL) {
1886         state(conn, SSH_SFTP_CLOSE);
1887         sshc->actualcode = CURLE_OUT_OF_MEMORY;
1888         break;
1889       }
1890       if((sshc->readdir_longentry = malloc(PATH_MAX+1)) == NULL) {
1891         Curl_safefree(sshc->readdir_filename);
1892         state(conn, SSH_SFTP_CLOSE);
1893         sshc->actualcode = CURLE_OUT_OF_MEMORY;
1894         break;
1895       }
1896       state(conn, SSH_SFTP_READDIR);
1897       break;
1898
1899     case SSH_SFTP_READDIR:
1900       sshc->readdir_len = libssh2_sftp_readdir_ex(sshc->sftp_handle,
1901                                                   sshc->readdir_filename,
1902                                                   PATH_MAX,
1903                                                   sshc->readdir_longentry,
1904                                                   PATH_MAX,
1905                                                   &sshc->readdir_attrs);
1906       if(sshc->readdir_len == LIBSSH2_ERROR_EAGAIN) {
1907         rc = LIBSSH2_ERROR_EAGAIN;
1908         break;
1909       }
1910       if(sshc->readdir_len > 0) {
1911         sshc->readdir_filename[sshc->readdir_len] = '\0';
1912
1913         if(data->set.ftp_list_only) {
1914           char *tmpLine;
1915
1916           tmpLine = aprintf("%s\n", sshc->readdir_filename);
1917           if(tmpLine == NULL) {
1918             state(conn, SSH_SFTP_CLOSE);
1919             sshc->actualcode = CURLE_OUT_OF_MEMORY;
1920             break;
1921           }
1922           result = Curl_client_write(conn, CLIENTWRITE_BODY,
1923                                      tmpLine, sshc->readdir_len+1);
1924           free(tmpLine);
1925
1926           if(result) {
1927             state(conn, SSH_STOP);
1928             break;
1929           }
1930           /* since this counts what we send to the client, we include the
1931              newline in this counter */
1932           data->req.bytecount += sshc->readdir_len+1;
1933
1934           /* output debug output if that is requested */
1935           if(data->set.verbose) {
1936             Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_filename,
1937                        sshc->readdir_len, conn);
1938           }
1939         }
1940         else {
1941           sshc->readdir_currLen = (int)strlen(sshc->readdir_longentry);
1942           sshc->readdir_totalLen = 80 + sshc->readdir_currLen;
1943           sshc->readdir_line = calloc(sshc->readdir_totalLen, 1);
1944           if(!sshc->readdir_line) {
1945             Curl_safefree(sshc->readdir_filename);
1946             Curl_safefree(sshc->readdir_longentry);
1947             state(conn, SSH_SFTP_CLOSE);
1948             sshc->actualcode = CURLE_OUT_OF_MEMORY;
1949             break;
1950           }
1951
1952           memcpy(sshc->readdir_line, sshc->readdir_longentry,
1953                  sshc->readdir_currLen);
1954           if((sshc->readdir_attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) &&
1955              ((sshc->readdir_attrs.permissions & LIBSSH2_SFTP_S_IFMT) ==
1956               LIBSSH2_SFTP_S_IFLNK)) {
1957             sshc->readdir_linkPath = malloc(PATH_MAX + 1);
1958             if(sshc->readdir_linkPath == NULL) {
1959               Curl_safefree(sshc->readdir_filename);
1960               Curl_safefree(sshc->readdir_longentry);
1961               state(conn, SSH_SFTP_CLOSE);
1962               sshc->actualcode = CURLE_OUT_OF_MEMORY;
1963               break;
1964             }
1965
1966             snprintf(sshc->readdir_linkPath, PATH_MAX, "%s%s", sftp_scp->path,
1967                      sshc->readdir_filename);
1968             state(conn, SSH_SFTP_READDIR_LINK);
1969             break;
1970           }
1971           state(conn, SSH_SFTP_READDIR_BOTTOM);
1972           break;
1973         }
1974       }
1975       else if(sshc->readdir_len == 0) {
1976         Curl_safefree(sshc->readdir_filename);
1977         Curl_safefree(sshc->readdir_longentry);
1978         state(conn, SSH_SFTP_READDIR_DONE);
1979         break;
1980       }
1981       else if(sshc->readdir_len <= 0) {
1982         err = sftp_libssh2_last_error(sshc->sftp_session);
1983         result = sftp_libssh2_error_to_CURLE(err);
1984         sshc->actualcode = result?result:CURLE_SSH;
1985         failf(data, "Could not open remote file for reading: %s :: %d",
1986               sftp_libssh2_strerror(err),
1987               libssh2_session_last_errno(sshc->ssh_session));
1988         Curl_safefree(sshc->readdir_filename);
1989         Curl_safefree(sshc->readdir_longentry);
1990         state(conn, SSH_SFTP_CLOSE);
1991         break;
1992       }
1993       break;
1994
1995     case SSH_SFTP_READDIR_LINK:
1996       sshc->readdir_len =
1997         libssh2_sftp_symlink_ex(sshc->sftp_session,
1998                                 sshc->readdir_linkPath,
1999                                 curlx_uztoui(strlen(sshc->readdir_linkPath)),
2000                                 sshc->readdir_filename,
2001                                 PATH_MAX, LIBSSH2_SFTP_READLINK);
2002       if(sshc->readdir_len == LIBSSH2_ERROR_EAGAIN) {
2003         rc = LIBSSH2_ERROR_EAGAIN;
2004         break;
2005       }
2006       Curl_safefree(sshc->readdir_linkPath);
2007
2008       /* get room for the filename and extra output */
2009       sshc->readdir_totalLen += 4 + sshc->readdir_len;
2010       new_readdir_line = realloc(sshc->readdir_line, sshc->readdir_totalLen);
2011       if(!new_readdir_line) {
2012         Curl_safefree(sshc->readdir_line);
2013         Curl_safefree(sshc->readdir_filename);
2014         Curl_safefree(sshc->readdir_longentry);
2015         state(conn, SSH_SFTP_CLOSE);
2016         sshc->actualcode = CURLE_OUT_OF_MEMORY;
2017         break;
2018       }
2019       sshc->readdir_line = new_readdir_line;
2020
2021       sshc->readdir_currLen += snprintf(sshc->readdir_line +
2022                                         sshc->readdir_currLen,
2023                                         sshc->readdir_totalLen -
2024                                         sshc->readdir_currLen,
2025                                         " -> %s",
2026                                         sshc->readdir_filename);
2027
2028       state(conn, SSH_SFTP_READDIR_BOTTOM);
2029       break;
2030
2031     case SSH_SFTP_READDIR_BOTTOM:
2032       sshc->readdir_currLen += snprintf(sshc->readdir_line +
2033                                         sshc->readdir_currLen,
2034                                         sshc->readdir_totalLen -
2035                                         sshc->readdir_currLen, "\n");
2036       result = Curl_client_write(conn, CLIENTWRITE_BODY,
2037                                  sshc->readdir_line,
2038                                  sshc->readdir_currLen);
2039
2040       if(!result) {
2041
2042         /* output debug output if that is requested */
2043         if(data->set.verbose) {
2044           Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_line,
2045                      sshc->readdir_currLen, conn);
2046         }
2047         data->req.bytecount += sshc->readdir_currLen;
2048       }
2049       Curl_safefree(sshc->readdir_line);
2050       if(result) {
2051         state(conn, SSH_STOP);
2052       }
2053       else
2054         state(conn, SSH_SFTP_READDIR);
2055       break;
2056
2057     case SSH_SFTP_READDIR_DONE:
2058       if(libssh2_sftp_closedir(sshc->sftp_handle) ==
2059          LIBSSH2_ERROR_EAGAIN) {
2060         rc = LIBSSH2_ERROR_EAGAIN;
2061         break;
2062       }
2063       sshc->sftp_handle = NULL;
2064       Curl_safefree(sshc->readdir_filename);
2065       Curl_safefree(sshc->readdir_longentry);
2066
2067       /* no data to transfer */
2068       Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
2069       state(conn, SSH_STOP);
2070       break;
2071
2072     case SSH_SFTP_DOWNLOAD_INIT:
2073       /*
2074        * Work on getting the specified file
2075        */
2076       sshc->sftp_handle =
2077         libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path,
2078                              curlx_uztoui(strlen(sftp_scp->path)),
2079                              LIBSSH2_FXF_READ, data->set.new_file_perms,
2080                              LIBSSH2_SFTP_OPENFILE);
2081       if(!sshc->sftp_handle) {
2082         if(libssh2_session_last_errno(sshc->ssh_session) ==
2083            LIBSSH2_ERROR_EAGAIN) {
2084           rc = LIBSSH2_ERROR_EAGAIN;
2085           break;
2086         }
2087         else {
2088           err = sftp_libssh2_last_error(sshc->sftp_session);
2089           failf(data, "Could not open remote file for reading: %s",
2090                 sftp_libssh2_strerror(err));
2091           state(conn, SSH_SFTP_CLOSE);
2092           result = sftp_libssh2_error_to_CURLE(err);
2093           sshc->actualcode = result?result:CURLE_SSH;
2094           break;
2095         }
2096       }
2097       state(conn, SSH_SFTP_DOWNLOAD_STAT);
2098       break;
2099
2100     case SSH_SFTP_DOWNLOAD_STAT:
2101     {
2102       LIBSSH2_SFTP_ATTRIBUTES attrs;
2103
2104       rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path,
2105                                 curlx_uztoui(strlen(sftp_scp->path)),
2106                                 LIBSSH2_SFTP_STAT, &attrs);
2107       if(rc == LIBSSH2_ERROR_EAGAIN) {
2108         break;
2109       }
2110       else if(rc ||
2111               !(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) ||
2112               (attrs.filesize == 0)) {
2113         /*
2114          * libssh2_sftp_open() didn't return an error, so maybe the server
2115          * just doesn't support stat()
2116          * OR the server doesn't return a file size with a stat()
2117          * OR file size is 0
2118          */
2119         data->req.size = -1;
2120         data->req.maxdownload = -1;
2121         Curl_pgrsSetDownloadSize(data, -1);
2122       }
2123       else {
2124         curl_off_t size = attrs.filesize;
2125
2126         if(size < 0) {
2127           failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size);
2128           return CURLE_BAD_DOWNLOAD_RESUME;
2129         }
2130         if(conn->data->state.use_range) {
2131           curl_off_t from, to;
2132           char *ptr;
2133           char *ptr2;
2134
2135           from=curlx_strtoofft(conn->data->state.range, &ptr, 0);
2136           while(*ptr && (ISSPACE(*ptr) || (*ptr=='-')))
2137             ptr++;
2138           to=curlx_strtoofft(ptr, &ptr2, 0);
2139           if((ptr == ptr2) /* no "to" value given */
2140              || (to >= size)) {
2141             to = size - 1;
2142           }
2143           if(from < 0) {
2144             /* from is relative to end of file */
2145             from += size;
2146           }
2147           if(from > size) {
2148             failf(data, "Offset (%"
2149                   CURL_FORMAT_CURL_OFF_T ") was beyond file size (%"
2150                   CURL_FORMAT_CURL_OFF_T ")", from, attrs.filesize);
2151             return CURLE_BAD_DOWNLOAD_RESUME;
2152           }
2153           if(from > to) {
2154             from = to;
2155             size = 0;
2156           }
2157           else {
2158             size = to - from + 1;
2159           }
2160
2161           SFTP_SEEK(conn->proto.sshc.sftp_handle, from);
2162         }
2163         data->req.size = size;
2164         data->req.maxdownload = size;
2165         Curl_pgrsSetDownloadSize(data, size);
2166       }
2167
2168       /* We can resume if we can seek to the resume position */
2169       if(data->state.resume_from) {
2170         if(data->state.resume_from < 0) {
2171           /* We're supposed to download the last abs(from) bytes */
2172           if((curl_off_t)attrs.filesize < -data->state.resume_from) {
2173             failf(data, "Offset (%"
2174                   CURL_FORMAT_CURL_OFF_T ") was beyond file size (%"
2175                   CURL_FORMAT_CURL_OFF_T ")",
2176                   data->state.resume_from, attrs.filesize);
2177             return CURLE_BAD_DOWNLOAD_RESUME;
2178           }
2179           /* download from where? */
2180           data->state.resume_from += attrs.filesize;
2181         }
2182         else {
2183           if((curl_off_t)attrs.filesize < data->state.resume_from) {
2184             failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T
2185                   ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")",
2186                   data->state.resume_from, attrs.filesize);
2187             return CURLE_BAD_DOWNLOAD_RESUME;
2188           }
2189         }
2190         /* Does a completed file need to be seeked and started or closed ? */
2191         /* Now store the number of bytes we are expected to download */
2192         data->req.size = attrs.filesize - data->state.resume_from;
2193         data->req.maxdownload = attrs.filesize - data->state.resume_from;
2194         Curl_pgrsSetDownloadSize(data,
2195                                  attrs.filesize - data->state.resume_from);
2196         SFTP_SEEK(sshc->sftp_handle, data->state.resume_from);
2197       }
2198     }
2199
2200     /* Setup the actual download */
2201     if(data->req.size == 0) {
2202       /* no data to transfer */
2203       Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
2204       infof(data, "File already completely downloaded\n");
2205       state(conn, SSH_STOP);
2206       break;
2207     }
2208     else {
2209       Curl_setup_transfer(conn, FIRSTSOCKET, data->req.size,
2210                           FALSE, NULL, -1, NULL);
2211
2212       /* not set by Curl_setup_transfer to preserve keepon bits */
2213       conn->writesockfd = conn->sockfd;
2214
2215       /* we want to use the _receiving_ function even when the socket turns
2216          out writableable as the underlying libssh2 recv function will deal
2217          with both accordingly */
2218       conn->cselect_bits = CURL_CSELECT_IN;
2219     }
2220     if(result) {
2221       /* this should never occur; the close state should be entered
2222          at the time the error occurs */
2223       state(conn, SSH_SFTP_CLOSE);
2224       sshc->actualcode = result;
2225     }
2226     else {
2227       state(conn, SSH_STOP);
2228     }
2229     break;
2230
2231     case SSH_SFTP_CLOSE:
2232       if(sshc->sftp_handle) {
2233         rc = libssh2_sftp_close(sshc->sftp_handle);
2234         if(rc == LIBSSH2_ERROR_EAGAIN) {
2235           break;
2236         }
2237         else if(rc < 0) {
2238           infof(data, "Failed to close libssh2 file\n");
2239         }
2240         sshc->sftp_handle = NULL;
2241       }
2242       if(sftp_scp)
2243         Curl_safefree(sftp_scp->path);
2244
2245       DEBUGF(infof(data, "SFTP DONE done\n"));
2246
2247       /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT
2248          After nextstate is executed, the control should come back to
2249          SSH_SFTP_CLOSE to pass the correct result back  */
2250       if(sshc->nextstate != SSH_NO_STATE &&
2251          sshc->nextstate != SSH_SFTP_CLOSE) {
2252         state(conn, sshc->nextstate);
2253         sshc->nextstate = SSH_SFTP_CLOSE;
2254       }
2255       else {
2256         state(conn, SSH_STOP);
2257         result = sshc->actualcode;
2258       }
2259       break;
2260
2261     case SSH_SFTP_SHUTDOWN:
2262       /* during times we get here due to a broken transfer and then the
2263          sftp_handle might not have been taken down so make sure that is done
2264          before we proceed */
2265
2266       if(sshc->sftp_handle) {
2267         rc = libssh2_sftp_close(sshc->sftp_handle);
2268         if(rc == LIBSSH2_ERROR_EAGAIN) {
2269           break;
2270         }
2271         else if(rc < 0) {
2272           infof(data, "Failed to close libssh2 file\n");
2273         }
2274         sshc->sftp_handle = NULL;
2275       }
2276       if(sshc->sftp_session) {
2277         rc = libssh2_sftp_shutdown(sshc->sftp_session);
2278         if(rc == LIBSSH2_ERROR_EAGAIN) {
2279           break;
2280         }
2281         else if(rc < 0) {
2282           infof(data, "Failed to stop libssh2 sftp subsystem\n");
2283         }
2284         sshc->sftp_session = NULL;
2285       }
2286
2287       Curl_safefree(sshc->homedir);
2288       conn->data->state.most_recent_ftp_entrypath = NULL;
2289
2290       state(conn, SSH_SESSION_DISCONNECT);
2291       break;
2292
2293     case SSH_SCP_TRANS_INIT:
2294       result = ssh_getworkingpath(conn, sshc->homedir, &sftp_scp->path);
2295       if(result) {
2296         sshc->actualcode = result;
2297         state(conn, SSH_STOP);
2298         break;
2299       }
2300
2301       if(data->set.upload) {
2302         if(data->state.infilesize < 0) {
2303           failf(data, "SCP requires a known file size for upload");
2304           sshc->actualcode = CURLE_UPLOAD_FAILED;
2305           state(conn, SSH_SCP_CHANNEL_FREE);
2306           break;
2307         }
2308         state(conn, SSH_SCP_UPLOAD_INIT);
2309       }
2310       else {
2311         state(conn, SSH_SCP_DOWNLOAD_INIT);
2312       }
2313       break;
2314
2315     case SSH_SCP_UPLOAD_INIT:
2316       /*
2317        * libssh2 requires that the destination path is a full path that
2318        * includes the destination file and name OR ends in a "/" .  If this is
2319        * not done the destination file will be named the same name as the last
2320        * directory in the path.
2321        */
2322       sshc->ssh_channel =
2323         SCP_SEND(sshc->ssh_session, sftp_scp->path, data->set.new_file_perms,
2324                  data->state.infilesize);
2325       if(!sshc->ssh_channel) {
2326         if(libssh2_session_last_errno(sshc->ssh_session) ==
2327            LIBSSH2_ERROR_EAGAIN) {
2328           rc = LIBSSH2_ERROR_EAGAIN;
2329           break;
2330         }
2331         else {
2332           int ssh_err;
2333           char *err_msg;
2334
2335           ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session,
2336                                                      &err_msg, NULL, 0));
2337           failf(conn->data, "%s", err_msg);
2338           state(conn, SSH_SCP_CHANNEL_FREE);
2339           sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err);
2340           break;
2341         }
2342       }
2343
2344       /* upload data */
2345       Curl_setup_transfer(conn, -1, data->req.size, FALSE, NULL,
2346                           FIRSTSOCKET, NULL);
2347
2348       /* not set by Curl_setup_transfer to preserve keepon bits */
2349       conn->sockfd = conn->writesockfd;
2350
2351       if(result) {
2352         state(conn, SSH_SCP_CHANNEL_FREE);
2353         sshc->actualcode = result;
2354       }
2355       else {
2356         /* store this original bitmask setup to use later on if we can't
2357            figure out a "real" bitmask */
2358         sshc->orig_waitfor = data->req.keepon;
2359
2360         /* we want to use the _sending_ function even when the socket turns
2361            out readable as the underlying libssh2 scp send function will deal
2362            with both accordingly */
2363         conn->cselect_bits = CURL_CSELECT_OUT;
2364
2365         state(conn, SSH_STOP);
2366       }
2367       break;
2368
2369     case SSH_SCP_DOWNLOAD_INIT:
2370     {
2371       /*
2372        * We must check the remote file; if it is a directory no values will
2373        * be set in sb
2374        */
2375       struct stat sb;
2376       curl_off_t bytecount;
2377
2378       /* clear the struct scp recv will fill in */
2379       memset(&sb, 0, sizeof(struct stat));
2380
2381       /* get a fresh new channel from the ssh layer */
2382       sshc->ssh_channel = libssh2_scp_recv(sshc->ssh_session,
2383                                            sftp_scp->path, &sb);
2384       if(!sshc->ssh_channel) {
2385         if(libssh2_session_last_errno(sshc->ssh_session) ==
2386            LIBSSH2_ERROR_EAGAIN) {
2387           rc = LIBSSH2_ERROR_EAGAIN;
2388           break;
2389         }
2390         else {
2391           int ssh_err;
2392           char *err_msg;
2393
2394           ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session,
2395                                                      &err_msg, NULL, 0));
2396           failf(conn->data, "%s", err_msg);
2397           state(conn, SSH_SCP_CHANNEL_FREE);
2398           sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err);
2399           break;
2400         }
2401       }
2402
2403       /* download data */
2404       bytecount = (curl_off_t)sb.st_size;
2405       data->req.maxdownload =  (curl_off_t)sb.st_size;
2406       Curl_setup_transfer(conn, FIRSTSOCKET, bytecount, FALSE, NULL, -1, NULL);
2407
2408       /* not set by Curl_setup_transfer to preserve keepon bits */
2409       conn->writesockfd = conn->sockfd;
2410
2411       /* we want to use the _receiving_ function even when the socket turns
2412          out writableable as the underlying libssh2 recv function will deal
2413          with both accordingly */
2414       conn->cselect_bits = CURL_CSELECT_IN;
2415
2416       if(result) {
2417         state(conn, SSH_SCP_CHANNEL_FREE);
2418         sshc->actualcode = result;
2419       }
2420       else
2421         state(conn, SSH_STOP);
2422     }
2423     break;
2424
2425     case SSH_SCP_DONE:
2426       if(data->set.upload)
2427         state(conn, SSH_SCP_SEND_EOF);
2428       else
2429         state(conn, SSH_SCP_CHANNEL_FREE);
2430       break;
2431
2432     case SSH_SCP_SEND_EOF:
2433       if(sshc->ssh_channel) {
2434         rc = libssh2_channel_send_eof(sshc->ssh_channel);
2435         if(rc == LIBSSH2_ERROR_EAGAIN) {
2436           break;
2437         }
2438         else if(rc) {
2439           infof(data, "Failed to send libssh2 channel EOF\n");
2440         }
2441       }
2442       state(conn, SSH_SCP_WAIT_EOF);
2443       break;
2444
2445     case SSH_SCP_WAIT_EOF:
2446       if(sshc->ssh_channel) {
2447         rc = libssh2_channel_wait_eof(sshc->ssh_channel);
2448         if(rc == LIBSSH2_ERROR_EAGAIN) {
2449           break;
2450         }
2451         else if(rc) {
2452           infof(data, "Failed to get channel EOF: %d\n", rc);
2453         }
2454       }
2455       state(conn, SSH_SCP_WAIT_CLOSE);
2456       break;
2457
2458     case SSH_SCP_WAIT_CLOSE:
2459       if(sshc->ssh_channel) {
2460         rc = libssh2_channel_wait_closed(sshc->ssh_channel);
2461         if(rc == LIBSSH2_ERROR_EAGAIN) {
2462           break;
2463         }
2464         else if(rc) {
2465           infof(data, "Channel failed to close: %d\n", rc);
2466         }
2467       }
2468       state(conn, SSH_SCP_CHANNEL_FREE);
2469       break;
2470
2471     case SSH_SCP_CHANNEL_FREE:
2472       if(sshc->ssh_channel) {
2473         rc = libssh2_channel_free(sshc->ssh_channel);
2474         if(rc == LIBSSH2_ERROR_EAGAIN) {
2475           break;
2476         }
2477         else if(rc < 0) {
2478           infof(data, "Failed to free libssh2 scp subsystem\n");
2479         }
2480         sshc->ssh_channel = NULL;
2481       }
2482       DEBUGF(infof(data, "SCP DONE phase complete\n"));
2483 #if 0 /* PREV */
2484       state(conn, SSH_SESSION_DISCONNECT);
2485 #endif
2486       state(conn, SSH_STOP);
2487       result = sshc->actualcode;
2488       break;
2489
2490     case SSH_SESSION_DISCONNECT:
2491       /* during weird times when we've been prematurely aborted, the channel
2492          is still alive when we reach this state and we MUST kill the channel
2493          properly first */
2494       if(sshc->ssh_channel) {
2495         rc = libssh2_channel_free(sshc->ssh_channel);
2496         if(rc == LIBSSH2_ERROR_EAGAIN) {
2497           break;
2498         }
2499         else if(rc < 0) {
2500           infof(data, "Failed to free libssh2 scp subsystem\n");
2501         }
2502         sshc->ssh_channel = NULL;
2503       }
2504
2505       if(sshc->ssh_session) {
2506         rc = libssh2_session_disconnect(sshc->ssh_session, "Shutdown");
2507         if(rc == LIBSSH2_ERROR_EAGAIN) {
2508           break;
2509         }
2510         else if(rc < 0) {
2511           infof(data, "Failed to disconnect libssh2 session\n");
2512         }
2513       }
2514
2515       Curl_safefree(sshc->homedir);
2516       conn->data->state.most_recent_ftp_entrypath = NULL;
2517
2518       state(conn, SSH_SESSION_FREE);
2519       break;
2520
2521     case SSH_SESSION_FREE:
2522 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2523       if(sshc->kh) {
2524         libssh2_knownhost_free(sshc->kh);
2525         sshc->kh = NULL;
2526       }
2527 #endif
2528
2529 #ifdef HAVE_LIBSSH2_AGENT_API
2530       if(sshc->ssh_agent) {
2531         rc = libssh2_agent_disconnect(sshc->ssh_agent);
2532         if(rc == LIBSSH2_ERROR_EAGAIN) {
2533           break;
2534         }
2535         else if(rc < 0) {
2536           infof(data, "Failed to disconnect from libssh2 agent\n");
2537         }
2538         libssh2_agent_free (sshc->ssh_agent);
2539         sshc->ssh_agent = NULL;
2540
2541         /* NB: there is no need to free identities, they are part of internal
2542            agent stuff */
2543         sshc->sshagent_identity = NULL;
2544         sshc->sshagent_prev_identity = NULL;
2545       }
2546 #endif
2547
2548       if(sshc->ssh_session) {
2549         rc = libssh2_session_free(sshc->ssh_session);
2550         if(rc == LIBSSH2_ERROR_EAGAIN) {
2551           break;
2552         }
2553         else if(rc < 0) {
2554           infof(data, "Failed to free libssh2 session\n");
2555         }
2556         sshc->ssh_session = NULL;
2557       }
2558
2559       /* worst-case scenario cleanup */
2560
2561       DEBUGASSERT(sshc->ssh_session == NULL);
2562       DEBUGASSERT(sshc->ssh_channel == NULL);
2563       DEBUGASSERT(sshc->sftp_session == NULL);
2564       DEBUGASSERT(sshc->sftp_handle == NULL);
2565 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2566       DEBUGASSERT(sshc->kh == NULL);
2567 #endif
2568 #ifdef HAVE_LIBSSH2_AGENT_API
2569       DEBUGASSERT(sshc->ssh_agent == NULL);
2570 #endif
2571
2572       Curl_safefree(sshc->rsa_pub);
2573       Curl_safefree(sshc->rsa);
2574
2575       Curl_safefree(sshc->quote_path1);
2576       Curl_safefree(sshc->quote_path2);
2577
2578       Curl_safefree(sshc->homedir);
2579
2580       Curl_safefree(sshc->readdir_filename);
2581       Curl_safefree(sshc->readdir_longentry);
2582       Curl_safefree(sshc->readdir_line);
2583       Curl_safefree(sshc->readdir_linkPath);
2584
2585       /* the code we are about to return */
2586       result = sshc->actualcode;
2587
2588       memset(sshc, 0, sizeof(struct ssh_conn));
2589
2590       connclose(conn, "SSH session free");
2591       sshc->state = SSH_SESSION_FREE; /* current */
2592       sshc->nextstate = SSH_NO_STATE;
2593       state(conn, SSH_STOP);
2594       break;
2595
2596     case SSH_QUIT:
2597       /* fallthrough, just stop! */
2598     default:
2599       /* internal error */
2600       sshc->nextstate = SSH_NO_STATE;
2601       state(conn, SSH_STOP);
2602       break;
2603     }
2604
2605   } while(!rc && (sshc->state != SSH_STOP));
2606
2607   if(rc == LIBSSH2_ERROR_EAGAIN) {
2608     /* we would block, we need to wait for the socket to be ready (in the
2609        right direction too)! */
2610     *block = TRUE;
2611   }
2612
2613   return result;
2614 }
2615
2616 /* called by the multi interface to figure out what socket(s) to wait for and
2617    for what actions in the DO_DONE, PERFORM and WAITPERFORM states */
2618 static int ssh_perform_getsock(const struct connectdata *conn,
2619                                curl_socket_t *sock, /* points to numsocks
2620                                                        number of sockets */
2621                                int numsocks)
2622 {
2623 #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION
2624   int bitmap = GETSOCK_BLANK;
2625   (void)numsocks;
2626
2627   sock[0] = conn->sock[FIRSTSOCKET];
2628
2629   if(conn->waitfor & KEEP_RECV)
2630     bitmap |= GETSOCK_READSOCK(FIRSTSOCKET);
2631
2632   if(conn->waitfor & KEEP_SEND)
2633     bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET);
2634
2635   return bitmap;
2636 #else
2637   /* if we don't know the direction we can use the generic *_getsock()
2638      function even for the protocol_connect and doing states */
2639   return Curl_single_getsock(conn, sock, numsocks);
2640 #endif
2641 }
2642
2643 /* Generic function called by the multi interface to figure out what socket(s)
2644    to wait for and for what actions during the DOING and PROTOCONNECT states*/
2645 static int ssh_getsock(struct connectdata *conn,
2646                        curl_socket_t *sock, /* points to numsocks number
2647                                                of sockets */
2648                        int numsocks)
2649 {
2650 #ifndef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION
2651   (void)conn;
2652   (void)sock;
2653   (void)numsocks;
2654   /* if we don't know any direction we can just play along as we used to and
2655      not provide any sensible info */
2656   return GETSOCK_BLANK;
2657 #else
2658   /* if we know the direction we can use the generic *_getsock() function even
2659      for the protocol_connect and doing states */
2660   return ssh_perform_getsock(conn, sock, numsocks);
2661 #endif
2662 }
2663
2664 #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION
2665 /*
2666  * When one of the libssh2 functions has returned LIBSSH2_ERROR_EAGAIN this
2667  * function is used to figure out in what direction and stores this info so
2668  * that the multi interface can take advantage of it. Make sure to call this
2669  * function in all cases so that when it _doesn't_ return EAGAIN we can
2670  * restore the default wait bits.
2671  */
2672 static void ssh_block2waitfor(struct connectdata *conn, bool block)
2673 {
2674   struct ssh_conn *sshc = &conn->proto.sshc;
2675   int dir;
2676   if(block && (dir = libssh2_session_block_directions(sshc->ssh_session))) {
2677     /* translate the libssh2 define bits into our own bit defines */
2678     conn->waitfor = ((dir&LIBSSH2_SESSION_BLOCK_INBOUND)?KEEP_RECV:0) |
2679       ((dir&LIBSSH2_SESSION_BLOCK_OUTBOUND)?KEEP_SEND:0);
2680   }
2681   else
2682     /* It didn't block or libssh2 didn't reveal in which direction, put back
2683        the original set */
2684     conn->waitfor = sshc->orig_waitfor;
2685 }
2686 #else
2687   /* no libssh2 directional support so we simply don't know */
2688 #define ssh_block2waitfor(x,y) Curl_nop_stmt
2689 #endif
2690
2691 /* called repeatedly until done from multi.c */
2692 static CURLcode ssh_multi_statemach(struct connectdata *conn, bool *done)
2693 {
2694   struct ssh_conn *sshc = &conn->proto.sshc;
2695   CURLcode result = CURLE_OK;
2696   bool block; /* we store the status and use that to provide a ssh_getsock()
2697                  implementation */
2698
2699   result = ssh_statemach_act(conn, &block);
2700   *done = (sshc->state == SSH_STOP) ? TRUE : FALSE;
2701   ssh_block2waitfor(conn, block);
2702
2703   return result;
2704 }
2705
2706 static CURLcode ssh_block_statemach(struct connectdata *conn,
2707                                    bool duringconnect)
2708 {
2709   struct ssh_conn *sshc = &conn->proto.sshc;
2710   CURLcode result = CURLE_OK;
2711   struct SessionHandle *data = conn->data;
2712
2713   while((sshc->state != SSH_STOP) && !result) {
2714     bool block;
2715     long left;
2716
2717     result = ssh_statemach_act(conn, &block);
2718     if(result)
2719       break;
2720
2721     if(Curl_pgrsUpdate(conn))
2722       return CURLE_ABORTED_BY_CALLBACK;
2723     else {
2724       struct timeval now = Curl_tvnow();
2725       result = Curl_speedcheck(data, now);
2726       if(result)
2727         break;
2728     }
2729
2730     left = Curl_timeleft(data, NULL, duringconnect);
2731     if(left < 0) {
2732       failf(data, "Operation timed out");
2733       return CURLE_OPERATION_TIMEDOUT;
2734     }
2735
2736 #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION
2737     if(!result && block) {
2738       int dir = libssh2_session_block_directions(sshc->ssh_session);
2739       curl_socket_t sock = conn->sock[FIRSTSOCKET];
2740       curl_socket_t fd_read = CURL_SOCKET_BAD;
2741       curl_socket_t fd_write = CURL_SOCKET_BAD;
2742       if(LIBSSH2_SESSION_BLOCK_INBOUND & dir)
2743         fd_read = sock;
2744       if(LIBSSH2_SESSION_BLOCK_OUTBOUND & dir)
2745         fd_write = sock;
2746       /* wait for the socket to become ready */
2747       Curl_socket_ready(fd_read, fd_write,
2748                         left>1000?1000:left); /* ignore result */
2749     }
2750 #endif
2751
2752   }
2753
2754   return result;
2755 }
2756
2757 /*
2758  * SSH setup and connection
2759  */
2760 static CURLcode ssh_setup_connection(struct connectdata *conn)
2761 {
2762   struct SSHPROTO *ssh;
2763
2764   conn->data->req.protop = ssh = calloc(1, sizeof(struct SSHPROTO));
2765   if(!ssh)
2766     return CURLE_OUT_OF_MEMORY;
2767
2768   return CURLE_OK;
2769 }
2770
2771 static Curl_recv scp_recv, sftp_recv;
2772 static Curl_send scp_send, sftp_send;
2773
2774 /*
2775  * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to
2776  * do protocol-specific actions at connect-time.
2777  */
2778 static CURLcode ssh_connect(struct connectdata *conn, bool *done)
2779 {
2780 #ifdef CURL_LIBSSH2_DEBUG
2781   curl_socket_t sock;
2782 #endif
2783   struct ssh_conn *ssh;
2784   CURLcode result;
2785   struct SessionHandle *data = conn->data;
2786
2787   /* initialize per-handle data if not already */
2788   if(!data->req.protop)
2789     ssh_setup_connection(conn);
2790
2791   /* We default to persistent connections. We set this already in this connect
2792      function to make the re-use checks properly be able to check this bit. */
2793   connkeep(conn, "SSH default");
2794
2795   if(conn->handler->protocol & CURLPROTO_SCP) {
2796     conn->recv[FIRSTSOCKET] = scp_recv;
2797     conn->send[FIRSTSOCKET] = scp_send;
2798   }
2799   else {
2800     conn->recv[FIRSTSOCKET] = sftp_recv;
2801     conn->send[FIRSTSOCKET] = sftp_send;
2802   }
2803   ssh = &conn->proto.sshc;
2804
2805 #ifdef CURL_LIBSSH2_DEBUG
2806   if(conn->user) {
2807     infof(data, "User: %s\n", conn->user);
2808   }
2809   if(conn->passwd) {
2810     infof(data, "Password: %s\n", conn->passwd);
2811   }
2812   sock = conn->sock[FIRSTSOCKET];
2813 #endif /* CURL_LIBSSH2_DEBUG */
2814
2815   ssh->ssh_session = libssh2_session_init_ex(my_libssh2_malloc,
2816                                              my_libssh2_free,
2817                                              my_libssh2_realloc, conn);
2818   if(ssh->ssh_session == NULL) {
2819     failf(data, "Failure initialising ssh session");
2820     return CURLE_FAILED_INIT;
2821   }
2822
2823 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2824   if(data->set.str[STRING_SSH_KNOWNHOSTS]) {
2825     int rc;
2826     ssh->kh = libssh2_knownhost_init(ssh->ssh_session);
2827     if(!ssh->kh) {
2828       /* eeek. TODO: free the ssh_session! */
2829       return CURLE_FAILED_INIT;
2830     }
2831
2832     /* read all known hosts from there */
2833     rc = libssh2_knownhost_readfile(ssh->kh,
2834                                     data->set.str[STRING_SSH_KNOWNHOSTS],
2835                                     LIBSSH2_KNOWNHOST_FILE_OPENSSH);
2836     if(rc < 0)
2837       infof(data, "Failed to read known hosts from %s\n",
2838             data->set.str[STRING_SSH_KNOWNHOSTS]);
2839   }
2840 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2841
2842 #ifdef CURL_LIBSSH2_DEBUG
2843   libssh2_trace(ssh->ssh_session, ~0);
2844   infof(data, "SSH socket: %d\n", (int)sock);
2845 #endif /* CURL_LIBSSH2_DEBUG */
2846
2847   state(conn, SSH_INIT);
2848
2849   result = ssh_multi_statemach(conn, done);
2850
2851   return result;
2852 }
2853
2854 /*
2855  ***********************************************************************
2856  *
2857  * scp_perform()
2858  *
2859  * This is the actual DO function for SCP. Get a file according to
2860  * the options previously setup.
2861  */
2862
2863 static
2864 CURLcode scp_perform(struct connectdata *conn,
2865                       bool *connected,
2866                       bool *dophase_done)
2867 {
2868   CURLcode result = CURLE_OK;
2869
2870   DEBUGF(infof(conn->data, "DO phase starts\n"));
2871
2872   *dophase_done = FALSE; /* not done yet */
2873
2874   /* start the first command in the DO phase */
2875   state(conn, SSH_SCP_TRANS_INIT);
2876
2877   /* run the state-machine */
2878   result = ssh_multi_statemach(conn, dophase_done);
2879
2880   *connected = conn->bits.tcpconnect[FIRSTSOCKET];
2881
2882   if(*dophase_done) {
2883     DEBUGF(infof(conn->data, "DO phase is complete\n"));
2884   }
2885
2886   return result;
2887 }
2888
2889 /* called from multi.c while DOing */
2890 static CURLcode scp_doing(struct connectdata *conn,
2891                                bool *dophase_done)
2892 {
2893   CURLcode result;
2894   result = ssh_multi_statemach(conn, dophase_done);
2895
2896   if(*dophase_done) {
2897     DEBUGF(infof(conn->data, "DO phase is complete\n"));
2898   }
2899   return result;
2900 }
2901
2902 /*
2903  * The DO function is generic for both protocols. There was previously two
2904  * separate ones but this way means less duplicated code.
2905  */
2906
2907 static CURLcode ssh_do(struct connectdata *conn, bool *done)
2908 {
2909   CURLcode result;
2910   bool connected = 0;
2911   struct SessionHandle *data = conn->data;
2912   struct ssh_conn *sshc = &conn->proto.sshc;
2913
2914   *done = FALSE; /* default to false */
2915
2916   data->req.size = -1; /* make sure this is unknown at this point */
2917
2918   sshc->actualcode = CURLE_OK; /* reset error code */
2919   sshc->secondCreateDirs =0;   /* reset the create dir attempt state
2920                                   variable */
2921
2922   Curl_pgrsSetUploadCounter(data, 0);
2923   Curl_pgrsSetDownloadCounter(data, 0);
2924   Curl_pgrsSetUploadSize(data, -1);
2925   Curl_pgrsSetDownloadSize(data, -1);
2926
2927   if(conn->handler->protocol & CURLPROTO_SCP)
2928     result = scp_perform(conn, &connected,  done);
2929   else
2930     result = sftp_perform(conn, &connected,  done);
2931
2932   return result;
2933 }
2934
2935 /* BLOCKING, but the function is using the state machine so the only reason
2936    this is still blocking is that the multi interface code has no support for
2937    disconnecting operations that takes a while */
2938 static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection)
2939 {
2940   CURLcode result = CURLE_OK;
2941   struct ssh_conn *ssh = &conn->proto.sshc;
2942   (void) dead_connection;
2943
2944   Curl_safefree(conn->data->req.protop);
2945
2946   if(ssh->ssh_session) {
2947     /* only if there's a session still around to use! */
2948
2949     state(conn, SSH_SESSION_DISCONNECT);
2950
2951     result = ssh_block_statemach(conn, FALSE);
2952   }
2953
2954   return result;
2955 }
2956
2957 /* generic done function for both SCP and SFTP called from their specific
2958    done functions */
2959 static CURLcode ssh_done(struct connectdata *conn, CURLcode status)
2960 {
2961   CURLcode result = CURLE_OK;
2962   struct SSHPROTO *sftp_scp = conn->data->req.protop;
2963
2964   if(!status) {
2965     /* run the state-machine
2966
2967        TODO: when the multi interface is used, this _really_ should be using
2968        the ssh_multi_statemach function but we have no general support for
2969        non-blocking DONE operations, not in the multi state machine and with
2970        Curl_done() invokes on several places in the code!
2971     */
2972     result = ssh_block_statemach(conn, FALSE);
2973   }
2974   else
2975     result = status;
2976
2977   if(sftp_scp)
2978     Curl_safefree(sftp_scp->path);
2979   if(Curl_pgrsDone(conn))
2980     return CURLE_ABORTED_BY_CALLBACK;
2981
2982   conn->data->req.keepon = 0; /* clear all bits */
2983   return result;
2984 }
2985
2986
2987 static CURLcode scp_done(struct connectdata *conn, CURLcode status,
2988                          bool premature)
2989 {
2990   (void)premature; /* not used */
2991
2992   if(!status)
2993     state(conn, SSH_SCP_DONE);
2994
2995   return ssh_done(conn, status);
2996
2997 }
2998
2999 /* return number of received (decrypted) bytes */
3000 static ssize_t scp_send(struct connectdata *conn, int sockindex,
3001                         const void *mem, size_t len, CURLcode *err)
3002 {
3003   ssize_t nwrite;
3004   (void)sockindex; /* we only support SCP on the fixed known primary socket */
3005
3006   /* libssh2_channel_write() returns int! */
3007   nwrite = (ssize_t)
3008     libssh2_channel_write(conn->proto.sshc.ssh_channel, mem, len);
3009
3010   ssh_block2waitfor(conn, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE);
3011
3012   if(nwrite == LIBSSH2_ERROR_EAGAIN) {
3013     *err = CURLE_AGAIN;
3014     nwrite = 0;
3015   }
3016   else if(nwrite < LIBSSH2_ERROR_NONE) {
3017     *err = libssh2_session_error_to_CURLE((int)nwrite);
3018     nwrite = -1;
3019   }
3020
3021   return nwrite;
3022 }
3023
3024 /*
3025  * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return
3026  * a regular CURLcode value.
3027  */
3028 static ssize_t scp_recv(struct connectdata *conn, int sockindex,
3029                         char *mem, size_t len, CURLcode *err)
3030 {
3031   ssize_t nread;
3032   (void)sockindex; /* we only support SCP on the fixed known primary socket */
3033
3034   /* libssh2_channel_read() returns int */
3035   nread = (ssize_t)
3036     libssh2_channel_read(conn->proto.sshc.ssh_channel, mem, len);
3037
3038   ssh_block2waitfor(conn, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE);
3039   if(nread == LIBSSH2_ERROR_EAGAIN) {
3040     *err = CURLE_AGAIN;
3041     nread = -1;
3042   }
3043
3044   return nread;
3045 }
3046
3047 /*
3048  * =============== SFTP ===============
3049  */
3050
3051 /*
3052  ***********************************************************************
3053  *
3054  * sftp_perform()
3055  *
3056  * This is the actual DO function for SFTP. Get a file/directory according to
3057  * the options previously setup.
3058  */
3059
3060 static
3061 CURLcode sftp_perform(struct connectdata *conn,
3062                       bool *connected,
3063                       bool *dophase_done)
3064 {
3065   CURLcode result = CURLE_OK;
3066
3067   DEBUGF(infof(conn->data, "DO phase starts\n"));
3068
3069   *dophase_done = FALSE; /* not done yet */
3070
3071   /* start the first command in the DO phase */
3072   state(conn, SSH_SFTP_QUOTE_INIT);
3073
3074   /* run the state-machine */
3075   result = ssh_multi_statemach(conn, dophase_done);
3076
3077   *connected = conn->bits.tcpconnect[FIRSTSOCKET];
3078
3079   if(*dophase_done) {
3080     DEBUGF(infof(conn->data, "DO phase is complete\n"));
3081   }
3082
3083   return result;
3084 }
3085
3086 /* called from multi.c while DOing */
3087 static CURLcode sftp_doing(struct connectdata *conn,
3088                            bool *dophase_done)
3089 {
3090   CURLcode result = ssh_multi_statemach(conn, dophase_done);
3091
3092   if(*dophase_done) {
3093     DEBUGF(infof(conn->data, "DO phase is complete\n"));
3094   }
3095   return result;
3096 }
3097
3098 /* BLOCKING, but the function is using the state machine so the only reason
3099    this is still blocking is that the multi interface code has no support for
3100    disconnecting operations that takes a while */
3101 static CURLcode sftp_disconnect(struct connectdata *conn, bool dead_connection)
3102 {
3103   CURLcode result = CURLE_OK;
3104   (void) dead_connection;
3105
3106   DEBUGF(infof(conn->data, "SSH DISCONNECT starts now\n"));
3107
3108   Curl_safefree(conn->data->req.protop);
3109
3110   if(conn->proto.sshc.ssh_session) {
3111     /* only if there's a session still around to use! */
3112     state(conn, SSH_SFTP_SHUTDOWN);
3113     result = ssh_block_statemach(conn, FALSE);
3114   }
3115
3116   DEBUGF(infof(conn->data, "SSH DISCONNECT is done\n"));
3117
3118   return result;
3119
3120 }
3121
3122 static CURLcode sftp_done(struct connectdata *conn, CURLcode status,
3123                                bool premature)
3124 {
3125   struct ssh_conn *sshc = &conn->proto.sshc;
3126
3127   if(!status) {
3128     /* Post quote commands are executed after the SFTP_CLOSE state to avoid
3129        errors that could happen due to open file handles during POSTQUOTE
3130        operation */
3131     if(!status && !premature && conn->data->set.postquote) {
3132       sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT;
3133       state(conn, SSH_SFTP_CLOSE);
3134     }
3135     else
3136       state(conn, SSH_SFTP_CLOSE);
3137   }
3138   return ssh_done(conn, status);
3139 }
3140
3141 /* return number of sent bytes */
3142 static ssize_t sftp_send(struct connectdata *conn, int sockindex,
3143                          const void *mem, size_t len, CURLcode *err)
3144 {
3145   ssize_t nwrite;   /* libssh2_sftp_write() used to return size_t in 0.14
3146                        but is changed to ssize_t in 0.15. These days we don't
3147                        support libssh2 0.15*/
3148   (void)sockindex;
3149
3150   nwrite = libssh2_sftp_write(conn->proto.sshc.sftp_handle, mem, len);
3151
3152   ssh_block2waitfor(conn, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE);
3153
3154   if(nwrite == LIBSSH2_ERROR_EAGAIN) {
3155     *err = CURLE_AGAIN;
3156     nwrite = 0;
3157   }
3158   else if(nwrite < LIBSSH2_ERROR_NONE) {
3159     *err = libssh2_session_error_to_CURLE((int)nwrite);
3160     nwrite = -1;
3161   }
3162
3163   return nwrite;
3164 }
3165
3166 /*
3167  * Return number of received (decrypted) bytes
3168  * or <0 on error
3169  */
3170 static ssize_t sftp_recv(struct connectdata *conn, int sockindex,
3171                          char *mem, size_t len, CURLcode *err)
3172 {
3173   ssize_t nread;
3174   (void)sockindex;
3175
3176   nread = libssh2_sftp_read(conn->proto.sshc.sftp_handle, mem, len);
3177
3178   ssh_block2waitfor(conn, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE);
3179
3180   if(nread == LIBSSH2_ERROR_EAGAIN) {
3181     *err = CURLE_AGAIN;
3182     nread = -1;
3183
3184   }
3185   else if(nread < 0) {
3186     *err = libssh2_session_error_to_CURLE((int)nread);
3187   }
3188   return nread;
3189 }
3190
3191 /* The get_pathname() function is being borrowed from OpenSSH sftp.c
3192    version 4.6p1. */
3193 /*
3194  * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
3195  *
3196  * Permission to use, copy, modify, and distribute this software for any
3197  * purpose with or without fee is hereby granted, provided that the above
3198  * copyright notice and this permission notice appear in all copies.
3199  *
3200  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
3201  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
3202  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
3203  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
3204  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
3205  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
3206  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
3207  */
3208 static CURLcode
3209 get_pathname(const char **cpp, char **path)
3210 {
3211   const char *cp = *cpp, *end;
3212   char quot;
3213   unsigned int i, j;
3214   static const char WHITESPACE[] = " \t\r\n";
3215
3216   cp += strspn(cp, WHITESPACE);
3217   if(!*cp) {
3218     *cpp = cp;
3219     *path = NULL;
3220     return CURLE_QUOTE_ERROR;
3221   }
3222
3223   *path = malloc(strlen(cp) + 1);
3224   if(*path == NULL)
3225     return CURLE_OUT_OF_MEMORY;
3226
3227   /* Check for quoted filenames */
3228   if(*cp == '\"' || *cp == '\'') {
3229     quot = *cp++;
3230
3231     /* Search for terminating quote, unescape some chars */
3232     for(i = j = 0; i <= strlen(cp); i++) {
3233       if(cp[i] == quot) {  /* Found quote */
3234         i++;
3235         (*path)[j] = '\0';
3236         break;
3237       }
3238       if(cp[i] == '\0') {  /* End of string */
3239         /*error("Unterminated quote");*/
3240         goto fail;
3241       }
3242       if(cp[i] == '\\') {  /* Escaped characters */
3243         i++;
3244         if(cp[i] != '\'' && cp[i] != '\"' &&
3245             cp[i] != '\\') {
3246           /*error("Bad escaped character '\\%c'",
3247               cp[i]);*/
3248           goto fail;
3249         }
3250       }
3251       (*path)[j++] = cp[i];
3252     }
3253
3254     if(j == 0) {
3255       /*error("Empty quotes");*/
3256       goto fail;
3257     }
3258     *cpp = cp + i + strspn(cp + i, WHITESPACE);
3259   }
3260   else {
3261     /* Read to end of filename */
3262     end = strpbrk(cp, WHITESPACE);
3263     if(end == NULL)
3264       end = strchr(cp, '\0');
3265     *cpp = end + strspn(end, WHITESPACE);
3266
3267     memcpy(*path, cp, end - cp);
3268     (*path)[end - cp] = '\0';
3269   }
3270   return CURLE_OK;
3271
3272   fail:
3273   Curl_safefree(*path);
3274   return CURLE_QUOTE_ERROR;
3275 }
3276
3277
3278 static const char *sftp_libssh2_strerror(int err)
3279 {
3280   switch (err) {
3281     case LIBSSH2_FX_NO_SUCH_FILE:
3282       return "No such file or directory";
3283
3284     case LIBSSH2_FX_PERMISSION_DENIED:
3285       return "Permission denied";
3286
3287     case LIBSSH2_FX_FAILURE:
3288       return "Operation failed";
3289
3290     case LIBSSH2_FX_BAD_MESSAGE:
3291       return "Bad message from SFTP server";
3292
3293     case LIBSSH2_FX_NO_CONNECTION:
3294       return "Not connected to SFTP server";
3295
3296     case LIBSSH2_FX_CONNECTION_LOST:
3297       return "Connection to SFTP server lost";
3298
3299     case LIBSSH2_FX_OP_UNSUPPORTED:
3300       return "Operation not supported by SFTP server";
3301
3302     case LIBSSH2_FX_INVALID_HANDLE:
3303       return "Invalid handle";
3304
3305     case LIBSSH2_FX_NO_SUCH_PATH:
3306       return "No such file or directory";
3307
3308     case LIBSSH2_FX_FILE_ALREADY_EXISTS:
3309       return "File already exists";
3310
3311     case LIBSSH2_FX_WRITE_PROTECT:
3312       return "File is write protected";
3313
3314     case LIBSSH2_FX_NO_MEDIA:
3315       return "No media";
3316
3317     case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM:
3318       return "Disk full";
3319
3320     case LIBSSH2_FX_QUOTA_EXCEEDED:
3321       return "User quota exceeded";
3322
3323     case LIBSSH2_FX_UNKNOWN_PRINCIPLE:
3324       return "Unknown principle";
3325
3326     case LIBSSH2_FX_LOCK_CONFlICT:
3327       return "File lock conflict";
3328
3329     case LIBSSH2_FX_DIR_NOT_EMPTY:
3330       return "Directory not empty";
3331
3332     case LIBSSH2_FX_NOT_A_DIRECTORY:
3333       return "Not a directory";
3334
3335     case LIBSSH2_FX_INVALID_FILENAME:
3336       return "Invalid filename";
3337
3338     case LIBSSH2_FX_LINK_LOOP:
3339       return "Link points to itself";
3340   }
3341   return "Unknown error in libssh2";
3342 }
3343
3344 #endif /* USE_LIBSSH2 */