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