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