Artifactspublic-v0

curl

master
ply4 git calls30 ms314 KiB3 cachedprotocol v2
3972 lines122 KiBRaw
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 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 https://curl.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 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24#include "curl_setup.h"
26#ifdef USE_LIBSSH2
28/* #define CURL_LIBSSH2_DEBUG */
30#ifdef HAVE_NETINET_IN_H
31#include <netinet/in.h>
32#endif
33#ifdef HAVE_ARPA_INET_H
34#include <arpa/inet.h>
35#endif
36#ifdef HAVE_NETDB_H
37#include <netdb.h>
38#endif
39#ifdef __VMS
40#include <in.h>
41#include <inet.h>
42#endif
44#include "urldata.h"
45#include "sendf.h"
46#include "curl_trc.h"
47#include "progress.h"
48#include "transfer.h"
49#include "vssh/ssh.h"
50#include "url.h"
51#include "cfilters.h"
52#include "connect.h"
53#include "parsedate.h" /* for the week day and month names */
54#include "multiif.h"
55#include "select.h"
56#include "curlx/win32-fopen.h"
57#include "vssh/vssh.h"
58#include "curlx/strparse.h"
59#include "curlx/base64.h" /* for curlx_base64_encode() */
61static const char *sftp_libssh2_strerror(unsigned long err)
63 switch(err) {
64 case LIBSSH2_FX_NO_SUCH_FILE:
65 return "No such file or directory";
67 case LIBSSH2_FX_PERMISSION_DENIED:
68 return "Permission denied";
70 case LIBSSH2_FX_FAILURE:
71 return "Operation failed";
73 case LIBSSH2_FX_BAD_MESSAGE:
74 return "Bad message from SFTP server";
76 case LIBSSH2_FX_NO_CONNECTION:
77 return "Not connected to SFTP server";
79 case LIBSSH2_FX_CONNECTION_LOST:
80 return "Connection to SFTP server lost";
82 case LIBSSH2_FX_OP_UNSUPPORTED:
83 return "Operation not supported by SFTP server";
85 case LIBSSH2_FX_INVALID_HANDLE:
86 return "Invalid handle";
88 case LIBSSH2_FX_NO_SUCH_PATH:
89 return "No such file or directory";
91 case LIBSSH2_FX_FILE_ALREADY_EXISTS:
92 return "File already exists";
94 case LIBSSH2_FX_WRITE_PROTECT:
95 return "File is write protected";
97 case LIBSSH2_FX_NO_MEDIA:
98 return "No media";
100 case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM:
101 return "Disk full";
103 case LIBSSH2_FX_QUOTA_EXCEEDED:
104 return "User quota exceeded";
106 case LIBSSH2_FX_UNKNOWN_PRINCIPAL:
107 return "Unknown principal";
109 case LIBSSH2_FX_LOCK_CONFLICT:
110 return "File lock conflict";
112 case LIBSSH2_FX_DIR_NOT_EMPTY:
113 return "Directory not empty";
115 case LIBSSH2_FX_NOT_A_DIRECTORY:
116 return "Not a directory";
118 case LIBSSH2_FX_INVALID_FILENAME:
119 return "Invalid filename";
121 case LIBSSH2_FX_LINK_LOOP:
122 return "Link points to itself";
123 }
124 return "Unknown error in libssh2";
127static void kbd_callback(const char *name, int name_len,
128 const char *instruction, int instruction_len,
129 int num_prompts,
130 const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
131 LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
132 void **abstract)
134 struct Curl_easy *data = (struct Curl_easy *)*abstract;
136#ifdef CURL_LIBSSH2_DEBUG
137 curl_mfprintf(stderr, "name=%s\n", name);
138 curl_mfprintf(stderr, "name_len=%d\n", name_len);
139 curl_mfprintf(stderr, "instruction=%s\n", instruction);
140 curl_mfprintf(stderr, "instruction_len=%d\n", instruction_len);
141 curl_mfprintf(stderr, "num_prompts=%d\n", num_prompts);
142#else
143 (void)name;
144 (void)name_len;
145 (void)instruction;
146 (void)instruction_len;
147#endif /* CURL_LIBSSH2_DEBUG */
148 if(num_prompts == 1) {
149 struct connectdata *conn = data->conn;
150 const char *passwd = Curl_creds_passwd(conn->creds);
151 /* this function must allocate memory that can be freed by libssh2, which
152 uses the LIBSSH2_FREE_FUNC callback */
153 responses[0].text = Curl_cstrdup(passwd);
154 responses[0].length = responses[0].text ? curlx_uztoui(strlen(passwd)) : 0;
155 }
156 (void)prompts;
157} /* kbd_callback */
159static CURLcode sftp_libssh2_error_to_CURLE(unsigned long err)
161 switch(err) {
162 case LIBSSH2_FX_OK:
163 return CURLE_OK;
165 case LIBSSH2_FX_NO_SUCH_FILE:
166 case LIBSSH2_FX_NO_SUCH_PATH:
167 return CURLE_REMOTE_FILE_NOT_FOUND;
169 case LIBSSH2_FX_PERMISSION_DENIED:
170 case LIBSSH2_FX_WRITE_PROTECT:
171 case LIBSSH2_FX_LOCK_CONFLICT:
172 return CURLE_REMOTE_ACCESS_DENIED;
174 case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM:
175 case LIBSSH2_FX_QUOTA_EXCEEDED:
176 return CURLE_REMOTE_DISK_FULL;
178 case LIBSSH2_FX_FILE_ALREADY_EXISTS:
179 return CURLE_REMOTE_FILE_EXISTS;
181 case LIBSSH2_FX_DIR_NOT_EMPTY:
182 return CURLE_QUOTE_ERROR;
184 default:
185 break;
186 }
188 return CURLE_SSH;
191static CURLcode libssh2_session_error_to_CURLE(int err)
193 switch(err) {
194 /* Ordered by order of appearance in libssh2.h */
195 case LIBSSH2_ERROR_NONE:
196 return CURLE_OK;
198 /* This is the error returned by libssh2_scp_recv2
199 * on unknown file */
200 case LIBSSH2_ERROR_SCP_PROTOCOL:
201 return CURLE_REMOTE_FILE_NOT_FOUND;
203 case LIBSSH2_ERROR_SOCKET_NONE:
204 return CURLE_COULDNT_CONNECT;
206 case LIBSSH2_ERROR_ALLOC:
207 return CURLE_OUT_OF_MEMORY;
209 case LIBSSH2_ERROR_SOCKET_SEND:
210 return CURLE_SEND_ERROR;
212 case LIBSSH2_ERROR_HOSTKEY_INIT:
213 case LIBSSH2_ERROR_HOSTKEY_SIGN:
214 case LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED:
215 case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED:
216 return CURLE_PEER_FAILED_VERIFICATION;
218 case LIBSSH2_ERROR_PASSWORD_EXPIRED:
219 return CURLE_LOGIN_DENIED;
221 case LIBSSH2_ERROR_SOCKET_TIMEOUT:
222 case LIBSSH2_ERROR_TIMEOUT:
223 return CURLE_OPERATION_TIMEDOUT;
225 case LIBSSH2_ERROR_EAGAIN:
226 return CURLE_AGAIN;
227 }
229 return CURLE_SSH;
232/* These functions are made to use the libcurl memory functions - NOT the
233 debugmem functions, as that leads us to trigger on libssh2 memory leaks
234 that are not ours to care for */
236static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc)
238 (void)abstract;
239 return Curl_cmalloc(count);
242static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc)
244 (void)abstract;
245 return Curl_crealloc(ptr, count);
248static LIBSSH2_FREE_FUNC(my_libssh2_free)
250 (void)abstract;
251 if(ptr) /* ssh2 agent sometimes call free with null ptr */
252 Curl_cfree(ptr);
255static int sshkeycallback(CURL *easy,
256 const struct curl_khkey *knownkey, /* known */
257 const struct curl_khkey *foundkey, /* found */
258 enum curl_khmatch match,
259 void *clientp)
261 (void)easy;
262 (void)knownkey;
263 (void)foundkey;
264 (void)clientp;
266 /* we only allow perfect matches, and we reject everything else */
267 return (match != CURLKHMATCH_OK) ? CURLKHSTAT_REJECT : CURLKHSTAT_FINE;
270static enum curl_khtype convert_ssh2_keytype(int sshkeytype)
272 enum curl_khtype keytype = CURLKHTYPE_UNKNOWN;
273 switch(sshkeytype) {
274 case LIBSSH2_HOSTKEY_TYPE_RSA:
275 keytype = CURLKHTYPE_RSA;
276 break;
277#ifdef LIBSSH2_HOSTKEY_TYPE_DSS
278 case LIBSSH2_HOSTKEY_TYPE_DSS: /* deprecated upstream */
279 keytype = CURLKHTYPE_DSS;
280 break;
281#endif
282#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_256
283 case LIBSSH2_HOSTKEY_TYPE_ECDSA_256:
284 keytype = CURLKHTYPE_ECDSA;
285 break;
286#endif
287#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_384
288 case LIBSSH2_HOSTKEY_TYPE_ECDSA_384:
289 keytype = CURLKHTYPE_ECDSA;
290 break;
291#endif
292#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_521
293 case LIBSSH2_HOSTKEY_TYPE_ECDSA_521:
294 keytype = CURLKHTYPE_ECDSA;
295 break;
296#endif
297#ifdef LIBSSH2_HOSTKEY_TYPE_ED25519
298 case LIBSSH2_HOSTKEY_TYPE_ED25519:
299 keytype = CURLKHTYPE_ED25519;
300 break;
301#endif
302 }
303 return keytype;
306static CURLcode ssh_knownhost(struct Curl_easy *data,
307 struct ssh_conn *sshc)
309 struct connectdata *conn = data->conn;
310 struct libssh2_knownhost *host = NULL;
311 const char *remotekey = NULL;
312 int keycheck = LIBSSH2_KNOWNHOST_CHECK_FAILURE;
313 int keybit = 0;
314 int sshkeytype = 0;
315 size_t keylen = 0;
316 int rc = 0;
317 CURLcode result = CURLE_OK;
319 if(!CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)) {
320 infof(data, "SSH: no knownhosts file configured");
321 return CURLE_OK;
322 }
324 remotekey = libssh2_session_hostkey(sshc->ssh_session,
325 &keylen, &sshkeytype);
326 if(remotekey) {
327 /*
328 * A subject to figure out is what hostname we need to pass in here.
329 * What hostname does OpenSSH store in its file if an IDN name is
330 * used?
331 */
332 struct Curl_mapi_guard guard;
333 enum curl_khmatch keymatch;
334 curl_sshkeycallback func =
335 data->set.ssh_keyfunc ? data->set.ssh_keyfunc : sshkeycallback;
336 struct curl_khkey knownkey;
337 struct curl_khkey *knownkeyp = NULL;
338 struct curl_khkey foundkey;
340 switch(sshkeytype) {
341 case LIBSSH2_HOSTKEY_TYPE_RSA:
342 keybit = LIBSSH2_KNOWNHOST_KEY_SSHRSA;
343 break;
344#ifdef LIBSSH2_HOSTKEY_TYPE_DSS
345 case LIBSSH2_HOSTKEY_TYPE_DSS: /* deprecated upstream */
346 keybit = LIBSSH2_KNOWNHOST_KEY_SSHDSS;
347 break;
348#endif
349 case LIBSSH2_HOSTKEY_TYPE_ECDSA_256:
350 keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_256;
351 break;
352 case LIBSSH2_HOSTKEY_TYPE_ECDSA_384:
353 keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_384;
354 break;
355 case LIBSSH2_HOSTKEY_TYPE_ECDSA_521:
356 keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_521;
357 break;
358 case LIBSSH2_HOSTKEY_TYPE_ED25519:
359 keybit = LIBSSH2_KNOWNHOST_KEY_ED25519;
360 break;
361 default:
362 infof(data, "SSH: unsupported host key type for knownhosts check");
363 keybit = 0;
364 break;
365 }
366 if(!keybit)
367 /* no check means failure! */
368 rc = CURLKHSTAT_REJECT;
369 else {
370 keycheck = libssh2_knownhost_checkp(sshc->kh,
371 conn->origin->hostname,
372 (conn->origin->port != PORT_SSH) ?
373 conn->origin->port : -1,
374 remotekey, keylen,
375 LIBSSH2_KNOWNHOST_TYPE_PLAIN |
376 LIBSSH2_KNOWNHOST_KEYENC_RAW |
377 keybit,
378 &host);
380 infof(data, "SSH: host check %d, key: %s", keycheck,
381 (keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) ?
382 host->key : "<none>");
384 /* setup 'knownkey' */
385 if(keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) {
386 knownkey.key = host->key;
387 knownkey.len = 0;
388 knownkey.keytype = convert_ssh2_keytype(sshkeytype);
389 knownkeyp = &knownkey;
390 }
392 /* setup 'foundkey' */
393 foundkey.key = remotekey;
394 foundkey.len = keylen;
395 foundkey.keytype = convert_ssh2_keytype(sshkeytype);
397 /*
398 * if any of the LIBSSH2_KNOWNHOST_CHECK_* defines and the
399 * curl_khmatch enum are ever modified, we need to introduce a
400 * translation table here!
401 */
402 keymatch = (enum curl_khmatch)keycheck;
404 /* Ask the callback how to behave */
405 CURL_CBAPI_START(&guard, data, easy_ssh_keyfunc);
406 rc = func(data, knownkeyp, /* from the knownhosts file */
407 &foundkey, /* from the remote host */
408 keymatch, data->set.ssh_keyfunc_userp);
409 CURL_CBAPI_END(&guard);
410 }
411 }
412 else {
413 /* no remotekey means failure! */
414 infof(data, "SSH: host offers no public key");
415 rc = CURLKHSTAT_REJECT;
416 }
418 switch(rc) {
419 default: /* unknown return codes is the same as reject */
420 case CURLKHSTAT_REJECT:
421 infof(data, "SSH: knownhost check failed");
422 myssh_to(data, sshc, SSH_SESSION_FREE);
423 FALLTHROUGH();
424 case CURLKHSTAT_DEFER:
425 /* DEFER means bail out but keep the SSH_HOSTKEY state */
426 result = CURLE_PEER_FAILED_VERIFICATION;
427 break;
428 case CURLKHSTAT_FINE_REPLACE:
429 /* remove old host+key that does not match */
430 if(host)
431 libssh2_knownhost_del(sshc->kh, host);
432 FALLTHROUGH();
433 case CURLKHSTAT_FINE:
434 case CURLKHSTAT_FINE_ADD_TO_FILE:
435 /* proceed */
436 if(keycheck != LIBSSH2_KNOWNHOST_CHECK_MATCH) {
437 int addrc;
438 const char *hostbuf;
439 char *hostport = NULL;
440 if(conn->origin->port != PORT_SSH) {
441 hostbuf = hostport = curl_maprintf("[%s]:%u", conn->origin->hostname,
442 conn->origin->port);
443 if(!hostbuf)
444 infof(data, "WARNING: failed allocating buffer for [host]:port");
445 }
446 else
447 hostbuf = conn->origin->hostname;
448 if(hostbuf) {
449 /* the found host+key did not match but has been told to be fine
450 anyway so we add it in memory */
451 addrc = libssh2_knownhost_addc(sshc->kh, hostbuf, NULL,
452 remotekey, keylen, NULL, 0,
453 LIBSSH2_KNOWNHOST_TYPE_PLAIN |
454 LIBSSH2_KNOWNHOST_KEYENC_RAW |
455 keybit, NULL);
456 if(addrc)
457 infof(data, "WARNING: adding the known host %s failed", hostbuf);
458 else if(rc == CURLKHSTAT_FINE_ADD_TO_FILE ||
459 rc == CURLKHSTAT_FINE_REPLACE) {
460 /* now we write the entire in-memory list of known hosts to the
461 known_hosts file */
462 int wrc =
463 libssh2_knownhost_writefile(
464 sshc->kh, CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS),
465 LIBSSH2_KNOWNHOST_FILE_OPENSSH);
466 if(wrc) {
467 infof(data, "WARNING: writing %s failed",
468 CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS));
469 }
470 }
471 }
472 curlx_free(hostport);
473 }
474 else
475 infof(data, "SSH: knownhost entry matches host key");
476 break;
477 }
478 return result;
481static CURLcode ssh_check_fingerprint(struct Curl_easy *data,
482 struct ssh_conn *sshc)
484 const char *pubkey_md5 =
485 CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5);
486 const char *pubkey_sha256 =
487 CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256);
489 if(pubkey_sha256) {
490 const char *fingerprint = NULL;
491 char *fingerprint_b64 = NULL;
492 size_t fingerprint_b64_len;
493 size_t pub_pos = 0;
494 size_t b64_pos = 0;
496 infof(data, "SSH: SHA256 public key '%s'", pubkey_sha256);
497 /* The fingerprint points to static storage (!), do not free() it. */
498 fingerprint = libssh2_hostkey_hash(sshc->ssh_session,
499 LIBSSH2_HOSTKEY_HASH_SHA256);
500 if(!fingerprint) {
501 failf(data,
502 "Denied establishing ssh session: SHA256 fingerprint "
503 "not available");
504 myssh_to(data, sshc, SSH_SESSION_FREE);
505 return CURLE_PEER_FAILED_VERIFICATION;
506 }
508 /* The length of fingerprint is 32 bytes for SHA256.
509 * See libssh2_hostkey_hash documentation. */
510 if(curlx_base64_encode((const uint8_t *)fingerprint, 32, &fingerprint_b64,
511 &fingerprint_b64_len) != CURLE_OK) {
512 myssh_to(data, sshc, SSH_SESSION_FREE);
513 return CURLE_PEER_FAILED_VERIFICATION;
514 }
516 if(!fingerprint_b64) {
517 failf(data, "SHA256 fingerprint could not be encoded");
518 myssh_to(data, sshc, SSH_SESSION_FREE);
519 return CURLE_PEER_FAILED_VERIFICATION;
520 }
522 infof(data, "SSH: SHA256 fingerprint '%s'", fingerprint_b64);
524 /* Find the position of any = padding characters in the public key */
525 while((pubkey_sha256[pub_pos] != '=') && pubkey_sha256[pub_pos]) {
526 pub_pos++;
527 }
529 /* Find the position of any = padding characters in the base64 coded
530 * hostkey fingerprint */
531 while((fingerprint_b64[b64_pos] != '=') && fingerprint_b64[b64_pos]) {
532 b64_pos++;
533 }
535 /* Before we authenticate we check the hostkey's SHA256 fingerprint
536 * against a known fingerprint, if available.
537 */
538 if((pub_pos != b64_pos) ||
539 strncmp(fingerprint_b64, pubkey_sha256, pub_pos)) {
540 failf(data,
541 "Denied establishing ssh session: mismatch SHA256 fingerprint. "
542 "Remote %s is not equal to %s", fingerprint_b64, pubkey_sha256);
543 curlx_free(fingerprint_b64);
544 myssh_to(data, sshc, SSH_SESSION_FREE);
545 return CURLE_PEER_FAILED_VERIFICATION;
546 }
548 curlx_free(fingerprint_b64);
550 infof(data, "SSH: SHA256 checksum match");
551 }
553 if(pubkey_md5) {
554 char md5buffer[33];
555 const char *fingerprint;
557 infof(data, "SSH: MD5 public key '%s'", pubkey_md5);
558 fingerprint = libssh2_hostkey_hash(sshc->ssh_session,
559 LIBSSH2_HOSTKEY_HASH_MD5);
561 if(fingerprint) {
562 /* The fingerprint points to static storage (!), do not free() it. */
563 int i;
564 for(i = 0; i < 16; i++) {
565 curl_msnprintf(&md5buffer[i * 2], 3, "%02x",
566 (unsigned char)fingerprint[i]);
567 }
569 infof(data, "SSH: MD5 fingerprint '%s'", md5buffer);
570 }
572 /* This does NOT verify the length of 'pubkey_md5' separately, which
573 makes the comparison below fail unless it is exactly 32 characters */
574 if(!fingerprint || !curl_strequal(md5buffer, pubkey_md5)) {
575 if(fingerprint) {
576 failf(data,
577 "Denied establishing ssh session: mismatch MD5 fingerprint. "
578 "Remote %s is not equal to %s", md5buffer, pubkey_md5);
579 }
580 else {
581 failf(data,
582 "Denied establishing ssh session: MD5 fingerprint "
583 "not available");
584 }
585 myssh_to(data, sshc, SSH_SESSION_FREE);
586 return CURLE_PEER_FAILED_VERIFICATION;
587 }
588 infof(data, "SSH: MD5 checksum match");
589 }
591 if(!pubkey_md5 && !pubkey_sha256) {
592 if(data->set.ssh_hostkeyfunc) {
593 size_t keylen = 0;
594 int sshkeytype = 0;
595 int rc = 0;
596 /* we handle the process to the callback */
597 const char *remotekey = libssh2_session_hostkey(sshc->ssh_session,
598 &keylen, &sshkeytype);
599 if(remotekey) {
600 struct Curl_mapi_guard guard;
601 enum curl_khtype keytype = convert_ssh2_keytype(sshkeytype);
602 CURL_CBAPI_START(&guard, data, easy_ssh_hostkeyfunc);
603 rc = data->set.ssh_hostkeyfunc(data->set.ssh_hostkeyfunc_userp,
604 (int)keytype, remotekey, keylen);
605 CURL_CBAPI_END(&guard);
606 if(rc != CURLKHMATCH_OK) {
607 myssh_to(data, sshc, SSH_SESSION_FREE);
608 failf(data, "SSH: callback failed host public key verification");
609 return CURLE_PEER_FAILED_VERIFICATION;
610 }
611 infof(data, "SSH: verified public key via callback");
612 }
613 else {
614 myssh_to(data, sshc, SSH_SESSION_FREE);
615 return CURLE_PEER_FAILED_VERIFICATION;
616 }
617 return CURLE_OK;
618 }
619 else {
620 CURL_TRC_SSH(data, "no host key checksum given, checking knownhosts");
621 return ssh_knownhost(data, sshc);
622 }
623 }
624 else {
625 /* as we already matched, we skip the check for known hosts */
626 return CURLE_OK;
627 }
630/*
631 * ssh_force_knownhost_key_type() checks the known hosts file and try to
632 * force a specific public key type from the server if an entry is found.
633 */
634static CURLcode ssh_force_knownhost_key_type(struct Curl_easy *data,
635 struct ssh_conn *sshc)
637 CURLcode result = CURLE_OK;
639 static const char hostkey_method_ssh_ed25519[] = "ssh-ed25519";
640 static const char hostkey_method_ssh_ecdsa_521[] = "ecdsa-sha2-nistp521";
641 static const char hostkey_method_ssh_ecdsa_384[] = "ecdsa-sha2-nistp384";
642 static const char hostkey_method_ssh_ecdsa_256[] = "ecdsa-sha2-nistp256";
643 static const char hostkey_method_ssh_rsa_all[] =
644 "rsa-sha2-256,rsa-sha2-512,ssh-rsa";
645#ifdef LIBSSH2_KNOWNHOST_KEY_SSHDSS
646 static const char hostkey_method_ssh_dss[] = "ssh-dss";
647#endif
648 bool found = FALSE;
650 if(sshc->kh &&
651 !CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5) &&
652 !CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256)) {
653 struct libssh2_knownhost *store = NULL;
654 struct connectdata *conn = data->conn;
655 /* key types already confirmed absent for this host, so repeat hashed
656 entries of the same type do not each force a fresh checkp() scan
657 of the whole known_hosts set. one slot per possible key type (indexed
658 by the type shifted down) so no entry ordering can overflow it */
659 bool absent_type[(LIBSSH2_KNOWNHOST_KEY_MASK >>
660 LIBSSH2_KNOWNHOST_KEY_SHIFT) + 1] = { FALSE };
661 /* lets try to find our host in the known hosts file */
662 while(!libssh2_knownhost_get(sshc->kh, &store, store)) {
663 /* For non-standard ports, the name is enclosed in */
664 /* square brackets, followed by a colon and the port */
665 if(store) {
666 if(store->name) {
667 if(store->name[0] == '[') {
668 curl_off_t port;
669 size_t kh_name_size = 0;
670 const char *p;
671 const char *kh_name_end = strstr(store->name, "]:");
672 if(!kh_name_end) {
673 infof(data, "SSH: invalid host pattern %s in %s",
674 store->name,
675 CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS));
676 continue;
677 }
678 p = kh_name_end + 2; /* start of port number */
679 if(!curlx_str_number(&p, &port, 0xffff) &&
680 (kh_name_end && (port == conn->origin->port))) {
681 kh_name_size = strlen(store->name) - 1 - strlen(kh_name_end);
682 if((kh_name_size == strlen(conn->origin->hostname)) &&
683 !strncmp(store->name + 1, conn->origin->hostname,
684 kh_name_size)) {
685 found = TRUE;
686 break;
687 }
688 }
689 }
690 else if(!strcmp(store->name, conn->origin->hostname)) {
691 found = TRUE;
692 break;
693 }
694 }
695 else if(store->key) {
696 unsigned int type = (store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK)
697 >> LIBSSH2_KNOWNHOST_KEY_SHIFT;
698 if(!absent_type[type]) {
699 int keycheck = libssh2_knownhost_checkp(
700 sshc->kh, conn->origin->hostname,
701 (conn->origin->port != PORT_SSH) ? conn->origin->port : -1,
702 store->key, strlen(store->key),
703 LIBSSH2_KNOWNHOST_TYPE_PLAIN |
704 LIBSSH2_KNOWNHOST_KEYENC_BASE64 |
705 (store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK),
706 NULL);
707 if(keycheck == LIBSSH2_KNOWNHOST_CHECK_MATCH) {
708 found = TRUE;
709 break;
710 }
711 else if(keycheck == LIBSSH2_KNOWNHOST_CHECK_NOTFOUND)
712 absent_type[type] = TRUE;
713 }
714 }
715 }
716 }
718 if(found) {
719 int rc;
720 const char *hostkey_method = NULL;
721 infof(data, "SSH: found host '%s' in '%s'",
722 conn->origin->hostname,
723 CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS));
725 switch(store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK) {
726 case LIBSSH2_KNOWNHOST_KEY_ED25519:
727 hostkey_method = hostkey_method_ssh_ed25519;
728 break;
729 case LIBSSH2_KNOWNHOST_KEY_ECDSA_521:
730 hostkey_method = hostkey_method_ssh_ecdsa_521;
731 break;
732 case LIBSSH2_KNOWNHOST_KEY_ECDSA_384:
733 hostkey_method = hostkey_method_ssh_ecdsa_384;
734 break;
735 case LIBSSH2_KNOWNHOST_KEY_ECDSA_256:
736 hostkey_method = hostkey_method_ssh_ecdsa_256;
737 break;
738 case LIBSSH2_KNOWNHOST_KEY_SSHRSA:
739 hostkey_method = hostkey_method_ssh_rsa_all;
740 break;
741#ifdef LIBSSH2_KNOWNHOST_KEY_SSHDSS
742 case LIBSSH2_KNOWNHOST_KEY_SSHDSS: /* deprecated upstream */
743 hostkey_method = hostkey_method_ssh_dss;
744 break;
745#endif
746 case LIBSSH2_KNOWNHOST_KEY_RSA1:
747 failf(data, "Found host key type RSA1 which is not supported");
748 return CURLE_SSH;
749 default:
750 failf(data, "Unknown host key type: %d",
751 (store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK));
752 return CURLE_SSH;
753 }
755 infof(data, "SSH: set '%s' as hostkey type", hostkey_method);
756 rc = libssh2_session_method_pref(sshc->ssh_session,
757 LIBSSH2_METHOD_HOSTKEY, hostkey_method);
758 if(rc) {
759 char *err_msg = NULL;
760 int errlen;
761 libssh2_session_last_error(sshc->ssh_session, &err_msg, &errlen, 0);
762 failf(data, "libssh2 method '%s' failed: %s", hostkey_method, err_msg);
763 result = libssh2_session_error_to_CURLE(rc);
764 }
765 }
766 else {
767 infof(data, "SSH: did not find host '%s' in '%s'",
768 conn->origin->hostname,
769 CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS));
770 }
771 }
773 return result;
776static CURLcode quote_error(struct Curl_easy *data,
777 struct ssh_conn *sshc)
779 failf(data, "Suspicious data after the command line");
780 curlx_safefree(sshc->quote_path1);
781 curlx_safefree(sshc->quote_path2);
782 return CURLE_QUOTE_ERROR;
785static CURLcode sftp_quote(struct Curl_easy *data,
786 struct ssh_conn *sshc,
787 struct SSHPROTO *sshp)
789 const char *cp;
790 CURLcode result = CURLE_OK;
792 /*
793 * Support some of the "FTP" commands
794 *
795 * 'sshc->quote_item' is already verified to be non-NULL before it
796 * switched to this state.
797 */
798 const char *cmd = sshc->quote_item->data;
799 sshc->acceptfail = FALSE;
801 /* if a command starts with an asterisk, which a legal SFTP command never
802 can, the command is allowed to fail without it causing any
803 aborts or cancels etc. It causes libcurl to act as if the command
804 is successful, whatever the server responds. */
806 if(cmd[0] == '*') {
807 cmd++;
808 sshc->acceptfail = TRUE;
809 }
811 if(curl_strequal("pwd", cmd)) {
812 /* output debug output if that is requested */
813 char *tmp = curl_maprintf("257 \"%s\" is current directory.\n",
814 sshp->path);
815 if(!tmp)
816 return CURLE_OUT_OF_MEMORY;
817 Curl_debug(data, CURLINFO_HEADER_OUT, "PWD\n", 4);
818 Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp));
820 /* this sends an FTP-like "header" to the header callback so that
821 the current directory can be read similar to how it is read when
822 using ordinary FTP. */
823 result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp));
824 curlx_free(tmp);
825 if(!result)
826 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
827 return result;
828 }
830 /*
831 * the arguments following the command must be separated from the
832 * command with a space so we can check for it unconditionally
833 */
834 cp = strchr(cmd, ' ');
835 if(!cp) {
836 failf(data, "Syntax error command '%s', missing parameter", cmd);
837 return CURLE_QUOTE_ERROR;
838 }
840 /*
841 * also, every command takes at least one argument so we get that
842 * first argument right now
843 */
844 result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir);
845 if(result) {
846 if(result != CURLE_OUT_OF_MEMORY)
847 failf(data, "Syntax error: Bad first parameter to '%s'", cmd);
848 return result;
849 }
851 /*
852 * SFTP is a binary protocol, so we do not send text commands to the server.
853 * Instead, we scan for commands used by OpenSSH's sftp program and call the
854 * appropriate libssh2 functions.
855 */
856 if(!strncmp(cmd, "chgrp ", 6) ||
857 !strncmp(cmd, "chmod ", 6) ||
858 !strncmp(cmd, "chown ", 6) ||
859 !strncmp(cmd, "atime ", 6) ||
860 !strncmp(cmd, "mtime ", 6)) {
861 /* attribute change */
863 /* sshc->quote_path1 contains the mode to set */
864 /* get the destination */
865 result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir);
866 if(result) {
867 if(result != CURLE_OUT_OF_MEMORY)
868 failf(data, "Syntax error in %s: Bad second parameter", cmd);
869 curlx_safefree(sshc->quote_path1);
870 return result;
871 }
872 if(*cp)
873 return quote_error(data, sshc);
875 memset(&sshp->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES));
876 myssh_to(data, sshc, SSH_SFTP_QUOTE_STAT);
877 return result;
878 }
879 if(!strncmp(cmd, "ln ", 3) ||
880 !strncmp(cmd, "symlink ", 8)) {
881 /* symbolic linking */
882 /* sshc->quote_path1 is the source */
883 /* get the destination */
884 result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir);
885 if(result) {
886 if(result != CURLE_OUT_OF_MEMORY)
887 failf(data, "Syntax error in ln/symlink: Bad second parameter");
888 curlx_safefree(sshc->quote_path1);
889 return result;
890 }
891 if(*cp)
892 return quote_error(data, sshc);
893 myssh_to(data, sshc, SSH_SFTP_QUOTE_SYMLINK);
894 return result;
895 }
896 else if(!strncmp(cmd, "mkdir ", 6)) {
897 if(*cp)
898 return quote_error(data, sshc);
899 /* create directory */
900 myssh_to(data, sshc, SSH_SFTP_QUOTE_MKDIR);
901 return result;
902 }
903 else if(!strncmp(cmd, "rename ", 7)) {
904 /* rename file */
905 /* first param is the source path */
906 /* second param is the dest. path */
907 result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir);
908 if(result) {
909 if(result != CURLE_OUT_OF_MEMORY)
910 failf(data, "Syntax error in rename: Bad second parameter");
911 curlx_safefree(sshc->quote_path1);
912 return result;
913 }
914 if(*cp)
915 return quote_error(data, sshc);
916 myssh_to(data, sshc, SSH_SFTP_QUOTE_RENAME);
917 return result;
918 }
919 else if(!strncmp(cmd, "rmdir ", 6)) {
920 if(*cp)
921 return quote_error(data, sshc);
922 /* delete directory */
923 myssh_to(data, sshc, SSH_SFTP_QUOTE_RMDIR);
924 return result;
925 }
926 else if(!strncmp(cmd, "rm ", 3)) {
927 if(*cp)
928 return quote_error(data, sshc);
929 myssh_to(data, sshc, SSH_SFTP_QUOTE_UNLINK);
930 return result;
931 }
932 else if(!strncmp(cmd, "statvfs ", 8)) {
933 if(*cp)
934 return quote_error(data, sshc);
935 myssh_to(data, sshc, SSH_SFTP_QUOTE_STATVFS);
936 return result;
937 }
939 failf(data, "Unknown SFTP command");
940 curlx_safefree(sshc->quote_path1);
941 curlx_safefree(sshc->quote_path2);
942 return CURLE_QUOTE_ERROR;
945static CURLcode sftp_upload_init(struct Curl_easy *data,
946 struct ssh_conn *sshc,
947 struct SSHPROTO *sshp,
948 bool *blockp)
950 unsigned long flags;
952 /*
953 * NOTE!!! libssh2 requires that the destination path is a full path
954 * that includes the destination file and name OR ends in a "/"
955 * If this is not done the destination file is named the
956 * same name as the last directory in the path.
957 */
959 if(data->state.resume_from) {
960 LIBSSH2_SFTP_ATTRIBUTES attrs;
961 if(data->state.resume_from < 0) {
962 int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path,
963 curlx_uztoui(strlen(sshp->path)),
964 LIBSSH2_SFTP_STAT, &attrs);
965 if(rc == LIBSSH2_ERROR_EAGAIN) {
966 *blockp = TRUE;
967 return CURLE_OK;
968 }
969 if(rc) {
970 data->state.resume_from = 0;
971 }
972 else {
973 curl_off_t size = attrs.filesize;
974 if(size < 0) {
975 failf(data, "Bad file size (%" FMT_OFF_T ")", size);
976 return CURLE_BAD_DOWNLOAD_RESUME;
977 }
978 data->state.resume_from = attrs.filesize;
979 }
980 }
981 }
983 if(data->set.remote_append) {
984 /* True append mode: create if nonexisting */
985 flags = LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_APPEND;
986 }
987 else if(data->state.resume_from > 0) {
988 /*
989 * Resume MUST NOT use APPEND; some servers force writes to EOF when
990 * APPEND is set, ignoring a prior seek().
991 */
992 flags = LIBSSH2_FXF_WRITE;
993 }
994 else {
995 /* Clear file before writing (normal behavior) */
996 flags = LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC;
997 }
999 sshc->sftp_handle =
1000 libssh2_sftp_open_ex(sshc->sftp_session, sshp->path,
1001 curlx_uztoui(strlen(sshp->path)),
1002 flags, (long)data->set.new_file_perms,
1003 LIBSSH2_SFTP_OPENFILE);
1005 if(!sshc->sftp_handle) {
1006 CURLcode result;
1007 unsigned long sftperr;
1008 int rc = libssh2_session_last_errno(sshc->ssh_session);
1010 if(LIBSSH2_ERROR_EAGAIN == rc) {
1011 *blockp = TRUE;
1012 return CURLE_OK;
1015 if(LIBSSH2_ERROR_SFTP_PROTOCOL == rc)
1016 /* only when there was an SFTP protocol error can we extract
1017 the sftp error! */
1018 sftperr = libssh2_sftp_last_error(sshc->sftp_session);
1019 else
1020 sftperr = LIBSSH2_FX_OK; /* not an sftp error at all */
1022 if(sshc->secondCreateDirs) {
1023 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1024 failf(data, "Creating the dir/file failed: %s",
1025 sftp_libssh2_strerror(sftperr));
1026 return sftp_libssh2_error_to_CURLE(sftperr);
1028 if((sftperr == LIBSSH2_FX_NO_SUCH_FILE ||
1029 sftperr == LIBSSH2_FX_FAILURE ||
1030 sftperr == LIBSSH2_FX_NO_SUCH_PATH) &&
1031 data->set.ftp_create_missing_dirs &&
1032 (strlen(sshp->path) > 1)) {
1033 /* try to create the path remotely */
1034 sshc->secondCreateDirs = 1;
1035 myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS_INIT);
1036 return CURLE_OK;
1038 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1039 result = sftp_libssh2_error_to_CURLE(sftperr);
1040 if(!result) {
1041 /* Sometimes, for some reason libssh2_sftp_last_error() returns zero
1042 even though libssh2_sftp_open() failed previously! We need to
1043 work around that! */
1044 result = CURLE_SSH;
1045 sftperr = LIBSSH2_FX_OK;
1047 failf(data, "Upload failed: %s (%lu/%d)",
1048 sftperr != LIBSSH2_FX_OK ?
1049 sftp_libssh2_strerror(sftperr) : "ssh error",
1050 sftperr, rc);
1051 return result;
1054 /* If we have a restart point then we need to seek to the correct
1055 Skip if in explicit remote append mode. */
1056 if(data->state.resume_from > 0 && !data->set.remote_append) {
1057 int seekerr = CURL_SEEKFUNC_OK;
1058 /* Let's read off the proper amount of bytes from the input. */
1059 if(data->set.seek_func) {
1060 struct Curl_mapi_guard guard;
1061 CURL_CBAPI_START(&guard, data, easy_seek_func);
1062 seekerr = data->set.seek_func(data->set.seek_client,
1063 data->state.resume_from, SEEK_SET);
1064 CURL_CBAPI_END(&guard);
1067 if(seekerr != CURL_SEEKFUNC_OK) {
1068 curl_off_t passed = 0;
1070 if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
1071 failf(data, "Could not seek stream");
1072 return CURLE_FTP_COULDNT_USE_REST;
1074 /* seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */
1075 do {
1076 struct Curl_mapi_guard guard;
1077 char scratch[4 * 1024];
1078 size_t readthisamountnow =
1079 (data->state.resume_from - passed >
1080 (curl_off_t)sizeof(scratch)) ?
1081 sizeof(scratch) : curlx_sotouz(data->state.resume_from - passed);
1083 size_t actuallyread;
1084 CURL_CBAPI_START(&guard, data, easy_fread_func);
1085 actuallyread = data->state.fread_func(scratch, 1,
1086 readthisamountnow,
1087 data->state.in);
1088 CURL_CBAPI_END(&guard);
1090 passed += actuallyread;
1091 if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
1092 /* this checks for greater-than only to make sure that the
1093 CURL_READFUNC_ABORT return code still aborts */
1094 failf(data, "Failed to read data");
1095 return CURLE_FTP_COULDNT_USE_REST;
1097 } while(passed < data->state.resume_from);
1100 /* now, decrease the size of the read */
1101 if(data->state.infilesize > 0) {
1102 data->state.infilesize -= data->state.resume_from;
1103 data->req.size = data->state.infilesize;
1104 Curl_pgrsSetUploadSize(data, data->state.infilesize);
1107 libssh2_sftp_seek64(sshc->sftp_handle,
1108 (libssh2_uint64_t)data->state.resume_from);
1110 if(data->state.infilesize > 0) {
1111 data->req.size = data->state.infilesize;
1112 Curl_pgrsSetUploadSize(data, data->state.infilesize);
1114 /* upload data */
1115 Curl_xfer_setup_send(data, FIRSTSOCKET);
1117 /* not set by Curl_xfer_setup to preserve io_flags */
1118 data->conn->recv_idx = FIRSTSOCKET;
1120 /* since we do not really wait for anything at this point, we want the
1121 state machine to move on as soon as possible so mark this as dirty */
1122 Curl_multi_mark_dirty(data);
1124 myssh_to(data, sshc, SSH_STOP);
1125 return CURLE_OK;
1128static void ssh_state_pkey_init(struct Curl_easy *data, struct ssh_conn *sshc)
1130 /*
1131 * Check the supported auth types in the order I feel is most secure
1132 * with the requested type of authentication
1133 */
1134 sshc->authed = FALSE;
1136 if((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) &&
1137 strstr(sshc->authlist, "publickey")) {
1138 if(sshc->pub_key)
1139 infof(data, "SSH: trying public key file '%s'", sshc->pub_key);
1140 infof(data, "SSH: trying private key file '%s'", sshc->priv_key);
1141 myssh_to(data, sshc, SSH_AUTH_PKEY);
1143 else
1144 myssh_to(data, sshc, SSH_AUTH_PASS_INIT);
1147static CURLcode sftp_quote_stat(struct Curl_easy *data,
1148 struct ssh_conn *sshc,
1149 struct SSHPROTO *sshp,
1150 bool *blockp)
1152 const char *cmd = sshc->quote_item->data;
1153 sshc->acceptfail = FALSE;
1155 /* if a command starts with an asterisk, which a legal SFTP command never
1156 can, the command is allowed to fail without it causing any aborts or
1157 cancels etc. It causes libcurl to act as if the command is
1158 successful, whatever the server responds. */
1160 if(cmd[0] == '*') {
1161 cmd++;
1162 sshc->acceptfail = TRUE;
1165 if(strncmp(cmd, "chmod", 5)) {
1166 /* Since chown and chgrp only set owner OR group but libssh2 wants to set
1167 * them both at once, we need to obtain the current ownership first. This
1168 * takes an extra protocol round trip.
1169 */
1170 int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2,
1171 curlx_uztoui(strlen(sshc->quote_path2)),
1172 LIBSSH2_SFTP_STAT,
1173 &sshp->quote_attrs);
1174 if(rc == LIBSSH2_ERROR_EAGAIN) {
1175 *blockp = TRUE;
1176 return CURLE_OK;
1178 if(rc && !sshc->acceptfail) { /* get those attributes */
1179 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
1180 failf(data, "Attempt to get SFTP stats failed: %s",
1181 sftp_libssh2_strerror(sftperr));
1182 goto fail;
1186 /* Now set the new attributes... */
1187 if(!strncmp(cmd, "chgrp", 5)) {
1188 const char *p = sshc->quote_path1;
1189 curl_off_t gid;
1190 if(!curlx_str_number(&p, &gid, ULONG_MAX)) {
1191 sshp->quote_attrs.gid = (unsigned long)gid;
1192 sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID;
1194 else if(!sshc->acceptfail) {
1195 failf(data, "Syntax error: chgrp gid not a number");
1196 goto fail;
1199 else if(!strncmp(cmd, "chmod", 5)) {
1200 curl_off_t perms;
1201 const char *p = sshc->quote_path1;
1202 /* permissions are octal */
1203 if(curlx_str_octal(&p, &perms, 07777)) {
1204 failf(data, "Syntax error: chmod permissions not a number");
1205 goto fail;
1208 sshp->quote_attrs.permissions = (unsigned long)perms;
1209 sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS;
1211 else if(!strncmp(cmd, "chown", 5)) {
1212 const char *p = sshc->quote_path1;
1213 curl_off_t uid;
1214 if(!curlx_str_number(&p, &uid, ULONG_MAX)) {
1215 sshp->quote_attrs.uid = (unsigned long)uid;
1216 sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID;
1218 else if(!sshc->acceptfail) {
1219 failf(data, "Syntax error: chown uid not a number");
1220 goto fail;
1223 else if(!strncmp(cmd, "atime", 5) ||
1224 !strncmp(cmd, "mtime", 5)) {
1225 time_t date;
1226 bool fail = FALSE;
1228 if(Curl_getdate_capped(sshc->quote_path1, &date)) {
1229 failf(data, "incorrect date format for %.*s", 5, cmd);
1230 fail = TRUE;
1232#if SIZEOF_TIME_T > SIZEOF_LONG
1233 if(date > 0xffffffff) {
1234 /* if 'long' cannot hold >32-bit, this date cannot be sent */
1235 failf(data, "date overflow");
1236 fail = TRUE;
1238#endif
1239 if(fail)
1240 goto fail;
1241 if(!strncmp(cmd, "atime", 5))
1242 sshp->quote_attrs.atime = (unsigned long)date;
1243 else /* mtime */
1244 sshp->quote_attrs.mtime = (unsigned long)date;
1246 sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_ACMODTIME;
1249 /* Now send the completed structure... */
1250 myssh_to(data, sshc, SSH_SFTP_QUOTE_SETSTAT);
1251 return CURLE_OK;
1252fail:
1253 curlx_safefree(sshc->quote_path1);
1254 curlx_safefree(sshc->quote_path2);
1255 return CURLE_QUOTE_ERROR;
1258static CURLcode sftp_download_stat(struct Curl_easy *data,
1259 struct ssh_conn *sshc,
1260 struct SSHPROTO *sshp,
1261 bool *blockp)
1263 LIBSSH2_SFTP_ATTRIBUTES attrs;
1264 int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path,
1265 curlx_uztoui(strlen(sshp->path)),
1266 LIBSSH2_SFTP_STAT, &attrs);
1267 if(rc == LIBSSH2_ERROR_EAGAIN) {
1268 *blockp = TRUE;
1269 return CURLE_OK;
1271 if(rc ||
1272 !(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) ||
1273 (attrs.filesize == 0)) {
1274 /*
1275 * libssh2_sftp_open() did not return an error, so maybe the server
1276 * does not support stat()
1277 * OR the server does not return a file size with a stat()
1278 * OR file size is 0
1279 */
1280 data->req.size = -1;
1281 data->req.maxdownload = -1;
1282 Curl_pgrsSetDownloadSize(data, -1);
1283 attrs.filesize = 0; /* might be uninitialized but is read below */
1285 else {
1286 curl_off_t size = attrs.filesize;
1288 if(size < 0) {
1289 failf(data, "Bad file size (%" FMT_OFF_T ")", size);
1290 return CURLE_BAD_DOWNLOAD_RESUME;
1292 if(data->state.use_range) {
1293 curl_off_t from;
1294 CURLcode result = Curl_ssh_range(data, data->state.range, size,
1295 &from, &size);
1296 if(result)
1297 return result;
1299 libssh2_sftp_seek64(sshc->sftp_handle, (libssh2_uint64_t)from);
1301 data->req.size = size;
1302 data->req.maxdownload = size;
1303 Curl_pgrsSetDownloadSize(data, size);
1306 /* We can resume if we can seek to the resume position */
1307 if(data->state.resume_from) {
1308 if(data->state.resume_from < 0) {
1309 /* We are supposed to download the last abs(from) bytes */
1310 if((curl_off_t)attrs.filesize < -data->state.resume_from) {
1311 failf(data, "Offset (%" FMT_OFF_T ") was beyond file size (%"
1312 FMT_OFF_T ")",
1313 data->state.resume_from, (curl_off_t)attrs.filesize);
1314 return CURLE_BAD_DOWNLOAD_RESUME;
1316 /* download from where? */
1317 data->state.resume_from += attrs.filesize;
1319 else {
1320 if((curl_off_t)attrs.filesize < data->state.resume_from) {
1321 failf(data, "Offset (%" FMT_OFF_T
1322 ") was beyond file size (%" FMT_OFF_T ")",
1323 data->state.resume_from, (curl_off_t)attrs.filesize);
1324 return CURLE_BAD_DOWNLOAD_RESUME;
1327 /* Now store the number of bytes we are expected to download */
1328 data->req.size = attrs.filesize - data->state.resume_from;
1329 data->req.maxdownload = attrs.filesize - data->state.resume_from;
1330 Curl_pgrsSetDownloadSize(data, attrs.filesize - data->state.resume_from);
1331 libssh2_sftp_seek64(sshc->sftp_handle,
1332 (libssh2_uint64_t)data->state.resume_from);
1335 /* Setup the actual download */
1336 if(data->req.size == 0) {
1337 /* no data to transfer */
1338 Curl_xfer_setup_nop(data);
1339 infof(data, "SSH: file already completely downloaded");
1340 myssh_to(data, sshc, SSH_STOP);
1341 return CURLE_OK;
1343 Curl_xfer_setup_recv(data, FIRSTSOCKET, data->req.size);
1345 /* not set by Curl_xfer_setup to preserve io_flags */
1346 data->conn->send_idx = 0;
1348 myssh_to(data, sshc, SSH_STOP);
1350 return CURLE_OK;
1353static CURLcode sftp_readdir(struct Curl_easy *data,
1354 struct ssh_conn *sshc,
1355 struct SSHPROTO *sshp,
1356 bool *blockp)
1358 CURLcode result = CURLE_OK;
1359 int rc = libssh2_sftp_readdir_ex(sshc->sftp_handle,
1360 sshp->readdir_filename, CURL_PATH_MAX,
1361 sshp->readdir_longentry, CURL_PATH_MAX,
1362 &sshp->readdir_attrs);
1363 if(rc == LIBSSH2_ERROR_EAGAIN) {
1364 *blockp = TRUE;
1365 return result;
1367 if(rc > 0) {
1368 size_t readdir_len = (size_t)rc;
1369 sshp->readdir_filename[readdir_len] = '\0';
1371 if(data->set.list_only) {
1372 result = Curl_client_write(data, CLIENTWRITE_BODY,
1373 sshp->readdir_filename,
1374 readdir_len);
1375 if(!result)
1376 result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1);
1377 if(result)
1378 return result;
1380 else {
1381 result = curlx_dyn_add(&sshp->readdir, sshp->readdir_longentry);
1383 if(!result) {
1384 if((sshp->readdir_attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) &&
1385 ((sshp->readdir_attrs.permissions & LIBSSH2_SFTP_S_IFMT) ==
1386 LIBSSH2_SFTP_S_IFLNK)) {
1387 result = curlx_dyn_addf(&sshp->readdir_link, "%s%s", sshp->path,
1388 sshp->readdir_filename);
1389 myssh_to(data, sshc, SSH_SFTP_READDIR_LINK);
1391 else {
1392 myssh_to(data, sshc, SSH_SFTP_READDIR_BOTTOM);
1395 return result;
1398 else if(!rc) {
1399 myssh_to(data, sshc, SSH_SFTP_READDIR_DONE);
1401 else {
1402 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
1403 result = sftperr ? sftp_libssh2_error_to_CURLE(sftperr) : CURLE_SSH;
1404 failf(data, "Could not open remote file for reading: %s :: %d",
1405 sftp_libssh2_strerror(sftperr),
1406 libssh2_session_last_errno(sshc->ssh_session));
1407 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1409 return result;
1412static CURLcode ssh_state_init(struct Curl_easy *data,
1413 struct ssh_conn *sshc)
1415 CURLcode result;
1416 sshc->secondCreateDirs = 0;
1417 sshc->nextstate = SSH_NO_STATE;
1419 /* Set libssh2 to non-blocking, since everything internally is
1420 non-blocking */
1421 libssh2_session_set_blocking(sshc->ssh_session, 0);
1423 result = ssh_force_knownhost_key_type(data, sshc);
1424 if(result)
1425 myssh_to(data, sshc, SSH_SESSION_FREE);
1426 else
1427 myssh_to(data, sshc, SSH_S_STARTUP);
1428 return result;
1431static CURLcode ssh_state_startup(struct Curl_easy *data,
1432 struct ssh_conn *sshc)
1434 struct connectdata *conn = data->conn;
1435 int rc = libssh2_session_handshake(sshc->ssh_session,
1436 conn->sock[FIRSTSOCKET]);
1437 if(rc == LIBSSH2_ERROR_EAGAIN)
1438 return CURLE_AGAIN;
1440 if(rc) {
1441 char *err_msg = NULL;
1442 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
1443 failf(data, "Failure establishing ssh session: %d, %s", rc, err_msg);
1445 myssh_to(data, sshc, SSH_SESSION_FREE);
1446 return CURLE_FAILED_INIT;
1449 myssh_to(data, sshc, SSH_HOSTKEY);
1450 return CURLE_OK;
1453static CURLcode ssh_state_hostkey(struct Curl_easy *data,
1454 struct ssh_conn *sshc)
1456 /*
1457 * Before we authenticate we should check the hostkey's fingerprint
1458 * against our known hosts. How that is handled (reading from file,
1459 * whatever) is up to us.
1460 */
1461 CURLcode result = ssh_check_fingerprint(data, sshc);
1462 if(!result)
1463 myssh_to(data, sshc, SSH_AUTHLIST);
1464 return result;
1467static CURLcode ssh_state_authlist(struct Curl_easy *data,
1468 struct ssh_conn *sshc)
1470 /*
1471 * Figure out authentication methods
1472 * NB: As soon as we have provided a username to an openssh server we
1473 * must never change it later. Thus, always specify the correct username
1474 * here, even though the libssh2 docs kind of indicate that it should be
1475 * possible to get a 'generic' list (not user-specific) of authentication
1476 * methods, presumably with a blank username. That does not work in my
1477 * experience.
1478 * Therefore always specify it here.
1479 */
1480 struct connectdata *conn = data->conn;
1481 const char *user = Curl_creds_user(conn->creds);
1482 sshc->authlist = libssh2_userauth_list(sshc->ssh_session,
1483 user, curlx_uztoui(strlen(user)));
1485 if(!sshc->authlist) {
1486 int rc;
1487 if(libssh2_userauth_authenticated(sshc->ssh_session)) {
1488 sshc->authed = TRUE;
1489 infof(data, "SSH: user accepted with no authentication");
1490 myssh_to(data, sshc, SSH_AUTH_DONE);
1491 return CURLE_OK;
1493 rc = libssh2_session_last_errno(sshc->ssh_session);
1494 if(rc == LIBSSH2_ERROR_EAGAIN)
1495 return CURLE_AGAIN;
1497 myssh_to(data, sshc, SSH_SESSION_FREE);
1498 return libssh2_session_error_to_CURLE(rc);
1500 infof(data, "SSH: host offers authentication via: %s", sshc->authlist);
1502 myssh_to(data, sshc, SSH_AUTH_PKEY_INIT);
1503 return CURLE_OK;
1506static CURLcode ssh_state_auth_pkey(struct Curl_easy *data,
1507 struct ssh_conn *sshc)
1509 /* The function below checks if the files exists, no need to stat() here.
1510 */
1511 struct connectdata *conn = data->conn;
1512 const char *user = Curl_creds_user(conn->creds);
1513 int rc = libssh2_userauth_publickey_fromfile_ex(
1514 sshc->ssh_session, user, curlx_uztoui(strlen(user)),
1515 sshc->pub_key, sshc->priv_key, sshc->passphrase ? sshc->passphrase : "");
1516 if(rc == LIBSSH2_ERROR_EAGAIN)
1517 return CURLE_AGAIN;
1519 if(rc == 0) {
1520 sshc->authed = TRUE;
1521 infof(data, "SSH: authenticated via publickey");
1522 myssh_to(data, sshc, SSH_AUTH_DONE);
1524 else {
1525 char *err_msg = NULL;
1526 char unknown[] = "Reason unknown (-1)";
1527 if(rc == -1) {
1528 /* No error message has been set and the last set error message, if
1529 any, is from a previous error so ignore it. #11837 */
1530 err_msg = unknown;
1532 else {
1533 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
1535 infof(data, "SSH: publickey authentication denied: %s", err_msg);
1536 myssh_to(data, sshc, SSH_AUTH_PASS_INIT);
1538 return CURLE_OK;
1541static CURLcode ssh_state_auth_pass_init(struct Curl_easy *data,
1542 struct ssh_conn *sshc)
1544 if((data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) &&
1545 strstr(sshc->authlist, "password")) {
1546 myssh_to(data, sshc, SSH_AUTH_PASS);
1548 else {
1549 myssh_to(data, sshc, SSH_AUTH_HOST_INIT);
1551 return CURLE_OK;
1554static CURLcode ssh_state_auth_pass(struct Curl_easy *data,
1555 struct ssh_conn *sshc)
1557 struct connectdata *conn = data->conn;
1558 const char *user = Curl_creds_user(conn->creds);
1559 const char *passwd = Curl_creds_passwd(conn->creds);
1560 int rc =
1561 libssh2_userauth_password_ex(sshc->ssh_session, user,
1562 curlx_uztoui(strlen(user)),
1563 passwd,
1564 curlx_uztoui(strlen(passwd)),
1565 NULL);
1566 if(rc == LIBSSH2_ERROR_EAGAIN) {
1567 return CURLE_AGAIN;
1569 if(rc == 0) {
1570 sshc->authed = TRUE;
1571 infof(data, "SSH: initialized password authentication");
1572 myssh_to(data, sshc, SSH_AUTH_DONE);
1574 else {
1575 myssh_to(data, sshc, SSH_AUTH_HOST_INIT);
1577 return CURLE_OK;
1580static CURLcode ssh_state_auth_host_init(struct Curl_easy *data,
1581 struct ssh_conn *sshc)
1583 if((data->set.ssh_auth_types & CURLSSH_AUTH_HOST) &&
1584 strstr(sshc->authlist, "hostbased")) {
1585 myssh_to(data, sshc, SSH_AUTH_HOST);
1587 else {
1588 myssh_to(data, sshc, SSH_AUTH_AGENT_INIT);
1590 return CURLE_OK;
1593static CURLcode ssh_state_auth_agent_init(struct Curl_easy *data,
1594 struct ssh_conn *sshc)
1596 int rc = 0;
1597 if((data->set.ssh_auth_types & CURLSSH_AUTH_AGENT) &&
1598 strstr(sshc->authlist, "publickey")) {
1600 infof(data, "SSH: trying publickey authentication via agent");
1601 /* Connect to the ssh-agent */
1602 /* The agent could be shared by a curl thread i believe
1603 but nothing obvious as keys can be added/removed at any time */
1604 if(!sshc->ssh_agent) {
1605 sshc->ssh_agent = libssh2_agent_init(sshc->ssh_session);
1606 if(!sshc->ssh_agent) {
1607 infof(data, "SSH: could not create agent object");
1609 myssh_to(data, sshc, SSH_AUTH_KEY_INIT);
1610 return CURLE_OK;
1614 rc = libssh2_agent_connect(sshc->ssh_agent);
1615 if(rc == LIBSSH2_ERROR_EAGAIN)
1616 return CURLE_AGAIN;
1617 if(rc < 0) {
1618 infof(data, "SSH: failure connecting to agent");
1619 myssh_to(data, sshc, SSH_AUTH_KEY_INIT);
1621 else {
1622 myssh_to(data, sshc, SSH_AUTH_AGENT_LIST);
1625 else
1626 myssh_to(data, sshc, SSH_AUTH_KEY_INIT);
1627 return CURLE_OK;
1630static CURLcode ssh_state_auth_agent_list(struct Curl_easy *data,
1631 struct ssh_conn *sshc)
1633 int rc = libssh2_agent_list_identities(sshc->ssh_agent);
1635 if(rc == LIBSSH2_ERROR_EAGAIN)
1636 return CURLE_AGAIN;
1637 if(rc < 0) {
1638 infof(data, "SSH: failure requesting identities to agent");
1639 myssh_to(data, sshc, SSH_AUTH_KEY_INIT);
1641 else {
1642 myssh_to(data, sshc, SSH_AUTH_AGENT);
1643 sshc->sshagent_prev_identity = NULL;
1645 return CURLE_OK;
1648static CURLcode ssh_state_auth_agent(struct Curl_easy *data,
1649 struct ssh_conn *sshc)
1651 /* as prev_identity evolves only after an identity user auth finished we
1652 can safely request it again as long as EAGAIN is returned here or by
1653 libssh2_agent_userauth */
1654 int rc = libssh2_agent_get_identity(sshc->ssh_agent,
1655 &sshc->sshagent_identity,
1656 sshc->sshagent_prev_identity);
1657 if(rc == LIBSSH2_ERROR_EAGAIN)
1658 return CURLE_AGAIN;
1660 if(rc == 0) {
1661 CURL_TRC_SSH(data, "[SSH_AUTH_AGENT_LIST] auth user '%s' for key '%s'",
1662 Curl_creds_user(data->conn->creds),
1663 sshc->sshagent_identity->comment);
1664 rc = libssh2_agent_userauth(sshc->ssh_agent,
1665 Curl_creds_user(data->conn->creds),
1666 sshc->sshagent_identity);
1668 if(rc < 0) {
1669 if(rc != LIBSSH2_ERROR_EAGAIN) {
1670 /* tried and failed? go to next identity */
1671 sshc->sshagent_prev_identity = sshc->sshagent_identity;
1672 return CURLE_OK;
1674 return CURLE_AGAIN;
1678 if(rc < 0)
1679 infof(data, "SSH: failure requesting identities to agent");
1680 else if(rc == 1)
1681 infof(data, "SSH: no agent identity would match");
1683 if(rc == LIBSSH2_ERROR_NONE) {
1684 sshc->authed = TRUE;
1685 infof(data, "SSH: agent authenticated user '%s' with key '%s'",
1686 Curl_creds_user(data->conn->creds),
1687 sshc->sshagent_identity->comment);
1688 myssh_to(data, sshc, SSH_AUTH_DONE);
1690 else {
1691 myssh_to(data, sshc, SSH_AUTH_KEY_INIT);
1693 return CURLE_OK;
1696static CURLcode ssh_state_auth_key_init(struct Curl_easy *data,
1697 struct ssh_conn *sshc)
1699 if((data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) &&
1700 strstr(sshc->authlist, "keyboard-interactive")) {
1701 myssh_to(data, sshc, SSH_AUTH_KEY);
1703 else {
1704 myssh_to(data, sshc, SSH_AUTH_DONE);
1706 return CURLE_OK;
1709static CURLcode ssh_state_auth_key(struct Curl_easy *data,
1710 struct ssh_conn *sshc)
1712 /* Authentication failed. Continue with keyboard-interactive now. */
1713 struct connectdata *conn = data->conn;
1714 const char *user = Curl_creds_user(conn->creds);
1715 int rc =
1716 libssh2_userauth_keyboard_interactive_ex(sshc->ssh_session,
1717 user, curlx_uztoui(strlen(user)),
1718 &kbd_callback);
1719 if(rc == LIBSSH2_ERROR_EAGAIN)
1720 return CURLE_AGAIN;
1722 if(rc == 0) {
1723 sshc->authed = TRUE;
1724 infof(data, "SSH: initialized keyboard interactive authentication");
1725 myssh_to(data, sshc, SSH_AUTH_DONE);
1726 return CURLE_OK;
1728 return CURLE_LOGIN_DENIED;
1731static CURLcode ssh_state_auth_done(struct Curl_easy *data,
1732 struct ssh_conn *sshc)
1734 struct connectdata *conn = data->conn;
1735 if(!sshc->authed) {
1736 failf(data, "Authentication failure");
1737 myssh_to(data, sshc, SSH_SESSION_FREE);
1738 return CURLE_LOGIN_DENIED;
1741 /*
1742 * At this point we have an authenticated ssh session.
1743 */
1744 infof(data, "SSH: authentication complete");
1746 Curl_pgrsTime(data, TIMER_APPCONNECT); /* SSH is connected */
1748 data->conn->recv_idx = FIRSTSOCKET;
1749 conn->send_idx = -1;
1751 if(conn->scheme->protocol == CURLPROTO_SFTP) {
1752 myssh_to(data, sshc, SSH_SFTP_INIT);
1753 return CURLE_OK;
1755 infof(data, "SSH: connection established");
1756 myssh_to(data, sshc, SSH_STOP);
1757 return CURLE_OK;
1760static CURLcode ssh_state_sftp_init(struct Curl_easy *data,
1761 struct ssh_conn *sshc)
1763 /*
1764 * Start the libssh2 sftp session
1765 */
1766 sshc->sftp_session = libssh2_sftp_init(sshc->ssh_session);
1767 if(!sshc->sftp_session) {
1768 char *err_msg = NULL;
1769 if(libssh2_session_last_errno(sshc->ssh_session) ==
1770 LIBSSH2_ERROR_EAGAIN)
1771 return CURLE_AGAIN;
1773 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
1774 failf(data, "Failure initializing sftp session: %s", err_msg);
1775 myssh_to(data, sshc, SSH_SESSION_FREE);
1776 return CURLE_FAILED_INIT;
1778 myssh_to(data, sshc, SSH_SFTP_REALPATH);
1779 return CURLE_OK;
1782static CURLcode ssh_state_sftp_realpath(struct Curl_easy *data,
1783 struct ssh_conn *sshc,
1784 struct SSHPROTO *sshp)
1786 /*
1787 * Get the "home" directory
1788 */
1789 int rc;
1791 if(!sshp)
1792 return CURLE_FAILED_INIT;
1794 rc = libssh2_sftp_symlink_ex(sshc->sftp_session, ".",
1795 curlx_uztoui(CURL_CSTRLEN(".")),
1796 sshp->readdir_filename, CURL_PATH_MAX,
1797 LIBSSH2_SFTP_REALPATH);
1798 if(rc == LIBSSH2_ERROR_EAGAIN)
1799 return CURLE_AGAIN;
1801 myssh_to(data, sshc, SSH_STOP);
1802 if(rc > 0) {
1803 curlx_free(sshc->homedir);
1804 sshc->homedir = curlx_strdup(sshp->readdir_filename);
1805 if(!sshc->homedir)
1806 return CURLE_OUT_OF_MEMORY;
1807 curlx_free(data->state.most_recent_ftp_entrypath);
1808 data->state.most_recent_ftp_entrypath = curlx_strdup(sshc->homedir);
1809 if(!data->state.most_recent_ftp_entrypath)
1810 return CURLE_OUT_OF_MEMORY;
1812 else {
1813 /* Return the error type */
1814 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
1815 CURLcode result;
1816 if(sftperr)
1817 result = sftp_libssh2_error_to_CURLE(sftperr);
1818 else
1819 /* in this case, the error was not in the SFTP level but for example a
1820 time-out or similar */
1821 result = CURLE_SSH;
1822 CURL_TRC_SSH(data, "error = %lu makes libcurl = %d", sftperr, (int)result);
1823 return result;
1826 /* This is the last step in the SFTP connect phase. Do note that while we
1827 get the homedir here, we get the "workingpath" in the DO action since the
1828 homedir remains the same between request but the working path does not. */
1829 CURL_TRC_SSH(data, "CONNECT phase done");
1830 return CURLE_OK;
1833static CURLcode ssh_state_sftp_quote_init(struct Curl_easy *data,
1834 struct ssh_conn *sshc,
1835 struct SSHPROTO *sshp)
1837 CURLcode result;
1839 if(!sshp)
1840 return CURLE_FAILED_INIT;
1842 result = Curl_getworkingpath(data, sshc->homedir, &sshp->path);
1843 if(result) {
1844 myssh_to(data, sshc, SSH_STOP);
1845 return result;
1848 if(data->set.quote) {
1849 infof(data, "SSH: sending quote commands");
1850 sshc->quote_item = data->set.quote;
1851 myssh_to(data, sshc, SSH_SFTP_QUOTE);
1853 else {
1854 myssh_to(data, sshc, SSH_SFTP_GETINFO);
1856 return CURLE_OK;
1859static CURLcode ssh_state_sftp_postquote_init(struct Curl_easy *data,
1860 struct ssh_conn *sshc)
1862 if(data->set.postquote) {
1863 infof(data, "SSH: sending quote commands");
1864 sshc->quote_item = data->set.postquote;
1865 myssh_to(data, sshc, SSH_SFTP_QUOTE);
1867 else {
1868 myssh_to(data, sshc, SSH_STOP);
1870 return CURLE_OK;
1873static CURLcode ssh_state_sftp_quote(struct Curl_easy *data,
1874 struct ssh_conn *sshc,
1875 struct SSHPROTO *sshp)
1877 /* Send quote commands */
1878 CURLcode result;
1880 if(!sshp)
1881 return CURLE_FAILED_INIT;
1883 result = sftp_quote(data, sshc, sshp);
1884 if(result) {
1885 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1886 sshc->nextstate = SSH_NO_STATE;
1888 return result;
1891static CURLcode ssh_state_sftp_next_quote(struct Curl_easy *data,
1892 struct ssh_conn *sshc)
1894 curlx_safefree(sshc->quote_path1);
1895 curlx_safefree(sshc->quote_path2);
1897 sshc->quote_item = sshc->quote_item->next;
1899 if(sshc->quote_item) {
1900 myssh_to(data, sshc, SSH_SFTP_QUOTE);
1902 else {
1903 if(sshc->nextstate != SSH_NO_STATE) {
1904 myssh_to(data, sshc, sshc->nextstate);
1905 sshc->nextstate = SSH_NO_STATE;
1907 else {
1908 myssh_to(data, sshc, SSH_SFTP_GETINFO);
1911 return CURLE_OK;
1914static CURLcode ssh_state_sftp_quote_stat(struct Curl_easy *data,
1915 struct ssh_conn *sshc,
1916 struct SSHPROTO *sshp,
1917 bool *blockp)
1919 CURLcode result;
1921 if(!sshp)
1922 return CURLE_FAILED_INIT;
1924 result = sftp_quote_stat(data, sshc, sshp, blockp);
1925 if(result) {
1926 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1927 sshc->nextstate = SSH_NO_STATE;
1929 return result;
1932static CURLcode ssh_state_sftp_quote_setstat(struct Curl_easy *data,
1933 struct ssh_conn *sshc,
1934 struct SSHPROTO *sshp)
1936 int rc;
1938 if(!sshp)
1939 return CURLE_FAILED_INIT;
1941 rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2,
1942 curlx_uztoui(strlen(sshc->quote_path2)),
1943 LIBSSH2_SFTP_SETSTAT,
1944 &sshp->quote_attrs);
1945 if(rc == LIBSSH2_ERROR_EAGAIN)
1946 return CURLE_AGAIN;
1948 if(rc && !sshc->acceptfail) {
1949 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
1950 failf(data, "Attempt to set SFTP stats for \"%s\" failed: %s",
1951 sshc->quote_path2, sftp_libssh2_strerror(sftperr));
1952 curlx_safefree(sshc->quote_path1);
1953 curlx_safefree(sshc->quote_path2);
1954 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1955 sshc->nextstate = SSH_NO_STATE;
1956 return CURLE_QUOTE_ERROR;
1958 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
1959 return CURLE_OK;
1962static CURLcode ssh_state_sftp_quote_symlink(struct Curl_easy *data,
1963 struct ssh_conn *sshc)
1965 int rc =
1966 libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->quote_path1,
1967 curlx_uztoui(strlen(sshc->quote_path1)),
1968 sshc->quote_path2,
1969 curlx_uztoui(strlen(sshc->quote_path2)),
1970 LIBSSH2_SFTP_SYMLINK);
1971 if(rc == LIBSSH2_ERROR_EAGAIN)
1972 return CURLE_AGAIN;
1974 if(rc && !sshc->acceptfail) {
1975 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
1976 failf(data, "symlink \"%s\" to \"%s\" failed: %s",
1977 sshc->quote_path1, sshc->quote_path2,
1978 sftp_libssh2_strerror(sftperr));
1979 curlx_safefree(sshc->quote_path1);
1980 curlx_safefree(sshc->quote_path2);
1981 myssh_to(data, sshc, SSH_SFTP_CLOSE);
1982 sshc->nextstate = SSH_NO_STATE;
1983 return CURLE_QUOTE_ERROR;
1985 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
1986 return CURLE_OK;
1989static CURLcode ssh_state_sftp_quote_mkdir(struct Curl_easy *data,
1990 struct ssh_conn *sshc)
1992 int rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshc->quote_path1,
1993 curlx_uztoui(strlen(sshc->quote_path1)),
1994 (long)data->set.new_directory_perms);
1995 if(rc == LIBSSH2_ERROR_EAGAIN)
1996 return CURLE_AGAIN;
1998 if(rc && !sshc->acceptfail) {
1999 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2000 failf(data, "mkdir \"%s\" failed: %s",
2001 sshc->quote_path1, sftp_libssh2_strerror(sftperr));
2002 curlx_safefree(sshc->quote_path1);
2003 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2004 sshc->nextstate = SSH_NO_STATE;
2005 return CURLE_QUOTE_ERROR;
2007 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
2008 return CURLE_OK;
2011static CURLcode ssh_state_sftp_quote_rename(struct Curl_easy *data,
2012 struct ssh_conn *sshc)
2014 int rc =
2015 libssh2_sftp_rename_ex(sshc->sftp_session, sshc->quote_path1,
2016 curlx_uztoui(strlen(sshc->quote_path1)),
2017 sshc->quote_path2,
2018 curlx_uztoui(strlen(sshc->quote_path2)),
2019 LIBSSH2_SFTP_RENAME_OVERWRITE |
2020 LIBSSH2_SFTP_RENAME_ATOMIC |
2021 LIBSSH2_SFTP_RENAME_NATIVE);
2023 if(rc == LIBSSH2_ERROR_EAGAIN)
2024 return CURLE_AGAIN;
2026 if(rc && !sshc->acceptfail) {
2027 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2028 failf(data, "rename \"%s\" to \"%s\" failed: %s",
2029 sshc->quote_path1, sshc->quote_path2,
2030 sftp_libssh2_strerror(sftperr));
2031 curlx_safefree(sshc->quote_path1);
2032 curlx_safefree(sshc->quote_path2);
2033 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2034 sshc->nextstate = SSH_NO_STATE;
2035 return CURLE_QUOTE_ERROR;
2037 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
2038 return CURLE_OK;
2041static CURLcode ssh_state_sftp_quote_rmdir(struct Curl_easy *data,
2042 struct ssh_conn *sshc)
2044 int rc = libssh2_sftp_rmdir_ex(sshc->sftp_session, sshc->quote_path1,
2045 curlx_uztoui(strlen(sshc->quote_path1)));
2046 if(rc == LIBSSH2_ERROR_EAGAIN)
2047 return CURLE_AGAIN;
2049 if(rc && !sshc->acceptfail) {
2050 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2051 failf(data, "rmdir \"%s\" failed: %s",
2052 sshc->quote_path1, sftp_libssh2_strerror(sftperr));
2053 curlx_safefree(sshc->quote_path1);
2054 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2055 sshc->nextstate = SSH_NO_STATE;
2056 return CURLE_QUOTE_ERROR;
2058 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
2059 return CURLE_OK;
2062static CURLcode ssh_state_sftp_quote_unlink(struct Curl_easy *data,
2063 struct ssh_conn *sshc)
2065 int rc = libssh2_sftp_unlink_ex(sshc->sftp_session, sshc->quote_path1,
2066 curlx_uztoui(strlen(sshc->quote_path1)));
2067 if(rc == LIBSSH2_ERROR_EAGAIN)
2068 return CURLE_AGAIN;
2070 if(rc && !sshc->acceptfail) {
2071 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2072 failf(data, "rm \"%s\" failed: %s",
2073 sshc->quote_path1, sftp_libssh2_strerror(sftperr));
2074 curlx_safefree(sshc->quote_path1);
2075 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2076 sshc->nextstate = SSH_NO_STATE;
2077 return CURLE_QUOTE_ERROR;
2079 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
2080 return CURLE_OK;
2083static CURLcode ssh_state_sftp_quote_statvfs(struct Curl_easy *data,
2084 struct ssh_conn *sshc)
2086 LIBSSH2_SFTP_STATVFS statvfs;
2087 int rc = libssh2_sftp_statvfs(sshc->sftp_session, sshc->quote_path1,
2088 curlx_uztoui(strlen(sshc->quote_path1)),
2089 &statvfs);
2091 if(rc == LIBSSH2_ERROR_EAGAIN)
2092 return CURLE_AGAIN;
2094 if(rc && !sshc->acceptfail) {
2095 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2096 failf(data, "statvfs \"%s\" failed: %s",
2097 sshc->quote_path1, sftp_libssh2_strerror(sftperr));
2098 curlx_safefree(sshc->quote_path1);
2099 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2100 sshc->nextstate = SSH_NO_STATE;
2101 return CURLE_QUOTE_ERROR;
2103 else if(rc == 0) {
2104#ifdef _MSC_VER
2105#define CURL_LIBSSH2_VFS_SIZE_MASK "I64u"
2106#else
2107#define CURL_LIBSSH2_VFS_SIZE_MASK "llu"
2108#endif
2109 CURLcode result;
2110 char *tmp = curl_maprintf("statvfs:\n"
2111 "f_bsize: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2112 "f_frsize: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2113 "f_blocks: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2114 "f_bfree: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2115 "f_bavail: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2116 "f_files: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2117 "f_ffree: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2118 "f_favail: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2119 "f_fsid: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2120 "f_flag: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n"
2121 "f_namemax: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n",
2122 statvfs.f_bsize, statvfs.f_frsize,
2123 statvfs.f_blocks, statvfs.f_bfree,
2124 statvfs.f_bavail, statvfs.f_files,
2125 statvfs.f_ffree, statvfs.f_favail,
2126 statvfs.f_fsid, statvfs.f_flag,
2127 statvfs.f_namemax);
2128 if(!tmp) {
2129 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2130 sshc->nextstate = SSH_NO_STATE;
2131 return CURLE_OUT_OF_MEMORY;
2134 result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp));
2135 curlx_free(tmp);
2136 if(result) {
2137 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2138 sshc->nextstate = SSH_NO_STATE;
2139 return result;
2142 myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE);
2143 return CURLE_OK;
2146static CURLcode ssh_state_sftp_create_dirs_mkdir(struct Curl_easy *data,
2147 struct ssh_conn *sshc,
2148 struct SSHPROTO *sshp)
2150 /* 'mode' - parameter is preliminary - default to 0644 */
2151 int rc;
2153 if(!sshp)
2154 return CURLE_FAILED_INIT;
2156 rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshp->path,
2157 curlx_uztoui(strlen(sshp->path)),
2158 (long)data->set.new_directory_perms);
2159 if(rc == LIBSSH2_ERROR_EAGAIN)
2160 return CURLE_AGAIN;
2162 *sshc->slash_pos = '/';
2163 ++sshc->slash_pos;
2164 if(rc < 0) {
2165 /*
2166 * Abort if failure was not that the directory already exists or
2167 * the permission was denied (creation might succeed further down
2168 * the path) - retry on unspecific FAILURE also
2169 */
2170 unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2171 if((sftperr != LIBSSH2_FX_FILE_ALREADY_EXISTS) &&
2172 (sftperr != LIBSSH2_FX_FAILURE) &&
2173 (sftperr != LIBSSH2_FX_PERMISSION_DENIED)) {
2174 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2175 return sftp_libssh2_error_to_CURLE(sftperr);
2178 myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS);
2179 return CURLE_OK;
2182static CURLcode ssh_state_sftp_readdir_init(struct Curl_easy *data,
2183 struct ssh_conn *sshc,
2184 struct SSHPROTO *sshp)
2186 if(!sshp)
2187 return CURLE_FAILED_INIT;
2189 Curl_pgrsSetDownloadSize(data, -1);
2190 if(data->req.no_body) {
2191 myssh_to(data, sshc, SSH_STOP);
2192 return CURLE_OK;
2195 /*
2196 * This is a directory that we are trying to get, so produce a directory
2197 * listing
2198 */
2199 sshc->sftp_handle =
2200 libssh2_sftp_open_ex(sshc->sftp_session, sshp->path,
2201 curlx_uztoui(strlen(sshp->path)),
2202 0, 0, LIBSSH2_SFTP_OPENDIR);
2203 if(!sshc->sftp_handle) {
2204 unsigned long sftperr;
2205 if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN)
2206 return CURLE_AGAIN;
2208 sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2209 failf(data, "Could not open directory for reading: %s",
2210 sftp_libssh2_strerror(sftperr));
2211 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2212 return sftp_libssh2_error_to_CURLE(sftperr);
2214 myssh_to(data, sshc, SSH_SFTP_READDIR);
2215 return CURLE_OK;
2218static CURLcode ssh_state_sftp_readdir_link(struct Curl_easy *data,
2219 struct ssh_conn *sshc,
2220 struct SSHPROTO *sshp)
2222 CURLcode result;
2223 int rc;
2224 if(!sshp)
2225 return CURLE_FAILED_INIT;
2227 rc = libssh2_sftp_symlink_ex(sshc->sftp_session,
2228 curlx_dyn_ptr(&sshp->readdir_link),
2229 (unsigned int)
2230 curlx_dyn_len(&sshp->readdir_link),
2231 sshp->readdir_filename,
2232 CURL_PATH_MAX, LIBSSH2_SFTP_READLINK);
2233 if(rc == LIBSSH2_ERROR_EAGAIN)
2234 return CURLE_AGAIN;
2236 curlx_dyn_free(&sshp->readdir_link);
2238 if(rc < 0)
2239 return CURLE_OUT_OF_MEMORY;
2241 /* append filename and extra output */
2242 result = curlx_dyn_addf(&sshp->readdir, " -> %s", sshp->readdir_filename);
2243 if(result)
2244 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2245 else
2246 myssh_to(data, sshc, SSH_SFTP_READDIR_BOTTOM);
2247 return result;
2250static CURLcode ssh_state_scp_download_init(struct Curl_easy *data,
2251 struct ssh_conn *sshc,
2252 struct SSHPROTO *sshp)
2254 curl_off_t bytecount;
2255 libssh2_struct_stat sb;
2257 if(!sshp)
2258 return CURLE_FAILED_INIT;
2259 /*
2260 * We must check the remote file; if it is a directory no values are
2261 * be set in sb
2262 */
2264 /*
2265 * If support for >2GB files exists, use it.
2266 */
2268 /* get a fresh new channel from the ssh layer */
2269 memset(&sb, 0, sizeof(libssh2_struct_stat));
2270 sshc->ssh_channel = libssh2_scp_recv2(sshc->ssh_session, sshp->path, &sb);
2271 if(!sshc->ssh_channel) {
2272 int ssh_err;
2273 char *err_msg = NULL;
2275 if(libssh2_session_last_errno(sshc->ssh_session) ==
2276 LIBSSH2_ERROR_EAGAIN)
2277 return CURLE_AGAIN;
2279 ssh_err = libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2280 failf(data, "%s", err_msg);
2281 myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE);
2282 return libssh2_session_error_to_CURLE(ssh_err);
2285 /* download data */
2286 bytecount = (curl_off_t)sb.st_size;
2287 data->req.maxdownload = (curl_off_t)sb.st_size;
2288 Curl_xfer_setup_recv(data, FIRSTSOCKET, bytecount);
2290 /* not set by Curl_xfer_setup to preserve io_flags */
2291 data->conn->send_idx = 0;
2293 myssh_to(data, sshc, SSH_STOP);
2294 return CURLE_OK;
2297static CURLcode ssh_state_sftp_close(struct Curl_easy *data,
2298 struct ssh_conn *sshc,
2299 struct SSHPROTO *sshp)
2301 int rc = 0;
2302 if(!sshp)
2303 return CURLE_FAILED_INIT;
2304 if(sshc->sftp_handle) {
2305 rc = libssh2_sftp_close(sshc->sftp_handle);
2306 if(rc == LIBSSH2_ERROR_EAGAIN)
2307 return CURLE_AGAIN;
2309 if(rc < 0) {
2310 char *err_msg = NULL;
2311 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2312 infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg);
2314 sshc->sftp_handle = NULL;
2317 curlx_safefree(sshp->path);
2319 CURL_TRC_SSH(data, "SFTP DONE done");
2321 /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT
2322 After nextstate is executed, the control should come back to
2323 SSH_SFTP_CLOSE to pass the correct result back */
2324 if(sshc->nextstate != SSH_NO_STATE &&
2325 sshc->nextstate != SSH_SFTP_CLOSE) {
2326 myssh_to(data, sshc, sshc->nextstate);
2327 sshc->nextstate = SSH_SFTP_CLOSE;
2329 else
2330 myssh_to(data, sshc, SSH_STOP);
2332 return CURLE_OK;
2335static CURLcode ssh_state_sftp_shutdown(struct Curl_easy *data,
2336 struct ssh_conn *sshc)
2338 /* during times we get here due to a broken transfer and then the
2339 sftp_handle might not have been taken down so make sure that is done
2340 before we proceed */
2341 int rc = 0;
2342 if(sshc->sftp_handle) {
2343 rc = libssh2_sftp_close(sshc->sftp_handle);
2344 if(rc == LIBSSH2_ERROR_EAGAIN)
2345 return CURLE_AGAIN;
2347 if(rc < 0) {
2348 char *err_msg = NULL;
2349 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2350 infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg);
2352 sshc->sftp_handle = NULL;
2354 if(sshc->sftp_session) {
2355 rc = libssh2_sftp_shutdown(sshc->sftp_session);
2356 if(rc == LIBSSH2_ERROR_EAGAIN)
2357 return CURLE_AGAIN;
2359 if(rc < 0) {
2360 infof(data, "Failed to stop libssh2 sftp subsystem");
2362 sshc->sftp_session = NULL;
2365 curlx_safefree(sshc->homedir);
2367 myssh_to(data, sshc, SSH_SESSION_DISCONNECT);
2368 return CURLE_OK;
2371static CURLcode ssh_state_sftp_download_init(struct Curl_easy *data,
2372 struct ssh_conn *sshc,
2373 struct SSHPROTO *sshp)
2375 if(!sshp)
2376 return CURLE_FAILED_INIT;
2377 /*
2378 * Work on getting the specified file
2379 */
2380 sshc->sftp_handle =
2381 libssh2_sftp_open_ex(sshc->sftp_session, sshp->path,
2382 curlx_uztoui(strlen(sshp->path)),
2383 LIBSSH2_FXF_READ, (long)data->set.new_file_perms,
2384 LIBSSH2_SFTP_OPENFILE);
2385 if(!sshc->sftp_handle) {
2386 unsigned long sftperr;
2387 if(libssh2_session_last_errno(sshc->ssh_session) ==
2388 LIBSSH2_ERROR_EAGAIN) {
2389 return CURLE_AGAIN;
2391 sftperr = libssh2_sftp_last_error(sshc->sftp_session);
2392 failf(data, "Could not open remote file for reading: %s",
2393 sftp_libssh2_strerror(sftperr));
2394 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2395 return sftp_libssh2_error_to_CURLE(sftperr);
2397 myssh_to(data, sshc, SSH_SFTP_DOWNLOAD_STAT);
2398 return CURLE_OK;
2401static CURLcode ssh_state_scp_upload_init(struct Curl_easy *data,
2402 struct ssh_conn *sshc,
2403 struct SSHPROTO *sshp)
2405 if(!sshp)
2406 return CURLE_FAILED_INIT;
2407 /*
2408 * libssh2 requires that the destination path is a full path that
2409 * includes the destination file and name OR ends in a "/" . If this is
2410 * not done the destination file is named the same name as the last
2411 * directory in the path.
2412 */
2413 sshc->ssh_channel =
2414 libssh2_scp_send64(sshc->ssh_session, sshp->path,
2415 (int)data->set.new_file_perms,
2416 (libssh2_int64_t)data->state.infilesize, 0, 0);
2417 if(!sshc->ssh_channel) {
2418 int ssh_err;
2419 char *err_msg = NULL;
2420 CURLcode result;
2421 if(libssh2_session_last_errno(sshc->ssh_session) ==
2422 LIBSSH2_ERROR_EAGAIN)
2423 return CURLE_AGAIN;
2425 ssh_err = libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2426 failf(data, "%s", err_msg);
2427 myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE);
2428 result = libssh2_session_error_to_CURLE(ssh_err);
2430 /* Map generic errors to upload failed */
2431 if(result == CURLE_SSH ||
2432 result == CURLE_REMOTE_FILE_NOT_FOUND)
2433 result = CURLE_UPLOAD_FAILED;
2434 return result;
2437 /* upload data */
2438 data->req.size = data->state.infilesize;
2439 Curl_pgrsSetUploadSize(data, data->state.infilesize);
2440 Curl_xfer_setup_send(data, FIRSTSOCKET);
2442 /* not set by Curl_xfer_setup to preserve io_flags */
2443 data->conn->recv_idx = FIRSTSOCKET;
2445 myssh_to(data, sshc, SSH_STOP);
2447 return CURLE_OK;
2450static CURLcode ssh_state_session_disconnect(struct Curl_easy *data,
2451 struct ssh_conn *sshc)
2453 /* during weird times when we have been prematurely aborted, the channel
2454 is still alive when we reach this state and we MUST kill the channel
2455 properly first */
2456 int rc = 0;
2457 if(sshc->ssh_channel) {
2458 rc = libssh2_channel_free(sshc->ssh_channel);
2459 if(rc == LIBSSH2_ERROR_EAGAIN)
2460 return CURLE_AGAIN;
2462 if(rc < 0) {
2463 char *err_msg = NULL;
2464 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2465 infof(data, "Failed to free libssh2 scp subsystem: %d %s", rc, err_msg);
2467 sshc->ssh_channel = NULL;
2470 if(sshc->ssh_session) {
2471 rc = libssh2_session_disconnect(sshc->ssh_session, "Shutdown");
2472 if(rc == LIBSSH2_ERROR_EAGAIN)
2473 return CURLE_AGAIN;
2475 if(rc < 0) {
2476 char *err_msg = NULL;
2477 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2478 infof(data, "Failed to disconnect libssh2 session: %d %s", rc, err_msg);
2482 curlx_safefree(sshc->homedir);
2484 myssh_to(data, sshc, SSH_SESSION_FREE);
2485 return CURLE_OK;
2488static CURLcode sshc_cleanup(struct ssh_conn *sshc, struct Curl_easy *data,
2489 bool block)
2491 int rc;
2493 if(sshc->kh) {
2494 libssh2_knownhost_free(sshc->kh);
2495 sshc->kh = NULL;
2498 if(sshc->ssh_agent) {
2499 rc = libssh2_agent_disconnect(sshc->ssh_agent);
2500 if((rc < 0) && data) {
2501 char *err_msg = NULL;
2502 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2503 infof(data, "Failed to disconnect from libssh2 agent: %d %s",
2504 rc, err_msg);
2506 if(!block && (rc == LIBSSH2_ERROR_EAGAIN))
2507 return CURLE_AGAIN;
2509 libssh2_agent_free(sshc->ssh_agent);
2510 sshc->ssh_agent = NULL;
2512 /* NB: there is no need to free identities, they are part of internal
2513 agent stuff */
2514 sshc->sshagent_identity = NULL;
2515 sshc->sshagent_prev_identity = NULL;
2518 if(sshc->sftp_handle) {
2519 rc = libssh2_sftp_close(sshc->sftp_handle);
2520 if((rc < 0) && data) {
2521 char *err_msg = NULL;
2522 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2523 infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg);
2525 if(!block && (rc == LIBSSH2_ERROR_EAGAIN))
2526 return CURLE_AGAIN;
2528 sshc->sftp_handle = NULL;
2531 if(sshc->ssh_channel) {
2532 rc = libssh2_channel_free(sshc->ssh_channel);
2533 if((rc < 0) && data) {
2534 char *err_msg = NULL;
2535 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2536 infof(data, "Failed to free libssh2 scp subsystem: %d %s", rc, err_msg);
2538 if(!block && (rc == LIBSSH2_ERROR_EAGAIN))
2539 return CURLE_AGAIN;
2541 sshc->ssh_channel = NULL;
2544 if(sshc->sftp_session) {
2545 rc = libssh2_sftp_shutdown(sshc->sftp_session);
2546 if((rc < 0) && data) {
2547 char *err_msg = NULL;
2548 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2549 infof(data, "Failed to stop libssh2 sftp subsystem: %d %s", rc, err_msg);
2551 if(!block && (rc == LIBSSH2_ERROR_EAGAIN))
2552 return CURLE_AGAIN;
2554 sshc->sftp_session = NULL;
2557 if(sshc->ssh_session) {
2558 rc = libssh2_session_free(sshc->ssh_session);
2559 if((rc < 0) && data) {
2560 char *err_msg = NULL;
2561 (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0);
2562 infof(data, "Failed to free libssh2 session: %d %s", rc, err_msg);
2564 if(!block && (rc == LIBSSH2_ERROR_EAGAIN))
2565 return CURLE_AGAIN;
2567 sshc->ssh_session = NULL;
2570 /* worst-case scenario cleanup */
2571 DEBUGASSERT(!sshc->ssh_session);
2572 DEBUGASSERT(!sshc->ssh_channel);
2573 DEBUGASSERT(!sshc->sftp_session);
2574 DEBUGASSERT(!sshc->sftp_handle);
2575 DEBUGASSERT(!sshc->kh);
2576 DEBUGASSERT(!sshc->ssh_agent);
2578 curlx_safefree(sshc->passphrase);
2579 curlx_safefree(sshc->pub_key);
2580 curlx_safefree(sshc->priv_key);
2581 curlx_safefree(sshc->quote_path1);
2582 curlx_safefree(sshc->quote_path2);
2583 curlx_safefree(sshc->homedir);
2585 return CURLE_OK;
2588static CURLcode ssh_state_sftp_getinfo(struct Curl_easy *data,
2589 struct ssh_conn *sshc)
2591 if(data->set.get_filetime)
2592 myssh_to(data, sshc, SSH_SFTP_FILETIME);
2593 else
2594 myssh_to(data, sshc, SSH_SFTP_TRANS_INIT);
2595 return CURLE_OK;
2598static CURLcode ssh_state_sftp_filetime(struct Curl_easy *data,
2599 struct ssh_conn *sshc,
2600 struct SSHPROTO *sshp)
2602 LIBSSH2_SFTP_ATTRIBUTES attrs;
2603 int rc;
2605 if(!sshp)
2606 return CURLE_FAILED_INIT;
2608 rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path,
2609 curlx_uztoui(strlen(sshp->path)),
2610 LIBSSH2_SFTP_STAT, &attrs);
2611 if(rc == LIBSSH2_ERROR_EAGAIN)
2612 return CURLE_AGAIN;
2614 if(rc == 0)
2615 data->info.filetime = (time_t)attrs.mtime;
2617 myssh_to(data, sshc, SSH_SFTP_TRANS_INIT);
2618 return CURLE_OK;
2621static CURLcode ssh_state_sftp_trans_init(struct Curl_easy *data,
2622 struct ssh_conn *sshc,
2623 struct SSHPROTO *sshp)
2625 if(data->state.upload)
2626 myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT);
2627 else if(sshp) {
2628 size_t plen = strlen(sshp->path);
2629 if(plen && (sshp->path[plen - 1] == '/'))
2630 myssh_to(data, sshc, SSH_SFTP_READDIR_INIT);
2631 else
2632 myssh_to(data, sshc, SSH_SFTP_DOWNLOAD_INIT);
2634 else
2635 return CURLE_FAILED_INIT;
2636 return CURLE_OK;
2639static CURLcode ssh_state_sftp_upload_init(struct Curl_easy *data,
2640 struct ssh_conn *sshc,
2641 struct SSHPROTO *sshp,
2642 bool *block)
2644 CURLcode result;
2645 if(!sshp)
2646 return CURLE_FAILED_INIT;
2647 result = sftp_upload_init(data, sshc, sshp, block);
2648 if(result) {
2649 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2650 sshc->nextstate = SSH_NO_STATE;
2652 return result;
2655static CURLcode ssh_state_sftp_create_dirs_init(struct Curl_easy *data,
2656 struct ssh_conn *sshc,
2657 struct SSHPROTO *sshp)
2659 if(!sshp)
2660 return CURLE_FAILED_INIT;
2661 if(strlen(sshp->path) > 1) {
2662 sshc->slash_pos = sshp->path + 1; /* ignore the leading '/' */
2663 myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS);
2665 else
2666 myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT);
2667 return CURLE_OK;
2670static CURLcode ssh_state_sftp_create_dirs(struct Curl_easy *data,
2671 struct ssh_conn *sshc,
2672 struct SSHPROTO *sshp)
2674 if(!sshp)
2675 return CURLE_FAILED_INIT;
2676 sshc->slash_pos = strchr(sshc->slash_pos, '/');
2677 if(sshc->slash_pos) {
2678 *sshc->slash_pos = 0;
2679 infof(data, "SFTP: creating directory '%s'", sshp->path);
2680 myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS_MKDIR);
2681 return CURLE_OK;
2683 myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT);
2684 return CURLE_OK;
2687static CURLcode ssh_state_sftp_readdir(struct Curl_easy *data,
2688 struct ssh_conn *sshc,
2689 struct SSHPROTO *sshp,
2690 bool *block)
2692 CURLcode result;
2693 if(!sshp)
2694 return CURLE_FAILED_INIT;
2695 result = sftp_readdir(data, sshc, sshp, block);
2696 if(result)
2697 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2698 return result;
2701static CURLcode ssh_state_sftp_readdir_bottom(struct Curl_easy *data,
2702 struct ssh_conn *sshc,
2703 struct SSHPROTO *sshp)
2705 CURLcode result;
2706 if(!sshp)
2707 return CURLE_FAILED_INIT;
2709 result = curlx_dyn_addn(&sshp->readdir, "\n", 1);
2710 if(!result)
2711 result = Curl_client_write(data, CLIENTWRITE_BODY,
2712 curlx_dyn_ptr(&sshp->readdir),
2713 curlx_dyn_len(&sshp->readdir));
2714 if(result) {
2715 curlx_dyn_free(&sshp->readdir);
2716 myssh_to(data, sshc, SSH_STOP);
2718 else {
2719 curlx_dyn_reset(&sshp->readdir);
2720 myssh_to(data, sshc, SSH_SFTP_READDIR);
2722 return result;
2725static CURLcode ssh_state_sftp_readdir_done(struct Curl_easy *data,
2726 struct ssh_conn *sshc)
2728 if(libssh2_sftp_closedir(sshc->sftp_handle) ==
2729 LIBSSH2_ERROR_EAGAIN)
2730 return CURLE_AGAIN;
2732 sshc->sftp_handle = NULL;
2734 /* no data to transfer */
2735 Curl_xfer_setup_nop(data);
2736 myssh_to(data, sshc, SSH_STOP);
2737 return CURLE_OK;
2740static CURLcode ssh_state_sftp_download_stat(struct Curl_easy *data,
2741 struct ssh_conn *sshc,
2742 struct SSHPROTO *sshp,
2743 bool *block)
2745 CURLcode result;
2746 if(!sshp)
2747 return CURLE_FAILED_INIT;
2748 result = sftp_download_stat(data, sshc, sshp, block);
2749 if(result) {
2750 myssh_to(data, sshc, SSH_SFTP_CLOSE);
2751 sshc->nextstate = SSH_NO_STATE;
2753 return result;
2756static CURLcode ssh_state_scp_trans_init(struct Curl_easy *data,
2757 struct ssh_conn *sshc,
2758 struct SSHPROTO *sshp)
2760 CURLcode result;
2761 if(!sshp)
2762 return CURLE_FAILED_INIT;
2763 result = Curl_getworkingpath(data, sshc->homedir,
2764 &sshp->path);
2765 if(result) {
2766 myssh_to(data, sshc, SSH_STOP);
2767 return result;
2770 if(data->state.upload) {
2771 if(data->state.infilesize < 0) {
2772 failf(data, "SCP requires a known file size for upload");
2773 myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE);
2774 return CURLE_UPLOAD_FAILED;
2776 myssh_to(data, sshc, SSH_SCP_UPLOAD_INIT);
2778 else
2779 myssh_to(data, sshc, SSH_SCP_DOWNLOAD_INIT);
2780 return CURLE_OK;
2783static CURLcode ssh_state_scp_done(struct Curl_easy *data,
2784 struct ssh_conn *sshc)
2786 if(data->state.upload)
2787 myssh_to(data, sshc, SSH_SCP_SEND_EOF);
2788 else
2789 myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE);
2790 return CURLE_OK;
2793static CURLcode ssh_state_scp_send_eof(struct Curl_easy *data,
2794 struct ssh_conn *sshc)
2796 if(sshc->ssh_channel) {
2797 int rc = libssh2_channel_send_eof(sshc->ssh_channel);
2798 if(rc == LIBSSH2_ERROR_EAGAIN)
2799 return CURLE_AGAIN;
2800 if(rc) {
2801 char *err_msg = NULL;
2802 (void)libssh2_session_last_error(sshc->ssh_session,
2803 &err_msg, NULL, 0);
2804 infof(data, "Failed to send libssh2 channel EOF: %d %s",
2805 rc, err_msg);
2808 myssh_to(data, sshc, SSH_SCP_WAIT_EOF);
2809 return CURLE_OK;
2812static CURLcode ssh_state_scp_wait_eof(struct Curl_easy *data,
2813 struct ssh_conn *sshc)
2815 if(sshc->ssh_channel) {
2816 int rc = libssh2_channel_wait_eof(sshc->ssh_channel);
2817 if(rc == LIBSSH2_ERROR_EAGAIN)
2818 return CURLE_AGAIN;
2819 if(rc) {
2820 char *err_msg = NULL;
2821 (void)libssh2_session_last_error(sshc->ssh_session,
2822 &err_msg, NULL, 0);
2823 infof(data, "Failed to get channel EOF: %d %s", rc, err_msg);
2826 myssh_to(data, sshc, SSH_SCP_WAIT_CLOSE);
2827 return CURLE_OK;
2830static CURLcode ssh_state_scp_wait_close(struct Curl_easy *data,
2831 struct ssh_conn *sshc)
2833 if(sshc->ssh_channel) {
2834 int rc =
2835 libssh2_channel_wait_closed(sshc->ssh_channel);
2836 if(rc == LIBSSH2_ERROR_EAGAIN)
2837 return CURLE_AGAIN;
2838 if(rc) {
2839 char *err_msg = NULL;
2840 (void)libssh2_session_last_error(sshc->ssh_session,
2841 &err_msg, NULL, 0);
2842 infof(data, "Channel failed to close: %d %s", rc, err_msg);
2845 myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE);
2846 return CURLE_OK;
2849static CURLcode ssh_state_scp_channel_free(
2850 struct Curl_easy *data,
2851 struct ssh_conn *sshc)
2853 if(sshc->ssh_channel) {
2854 int rc = libssh2_channel_free(sshc->ssh_channel);
2855 if(rc == LIBSSH2_ERROR_EAGAIN)
2856 return CURLE_AGAIN;
2857 if(rc < 0) {
2858 char *err_msg = NULL;
2859 (void)libssh2_session_last_error(sshc->ssh_session,
2860 &err_msg, NULL, 0);
2861 infof(data, "Failed to free libssh2 scp subsystem: %d %s", rc, err_msg);
2863 sshc->ssh_channel = NULL;
2865 CURL_TRC_SSH(data, "SCP DONE phase complete");
2866 myssh_to(data, sshc, SSH_STOP);
2867 return CURLE_OK;
2870static CURLcode ssh_state_session_free(struct Curl_easy *data,
2871 struct ssh_conn *sshc)
2873 CURLcode result = sshc_cleanup(sshc, data, FALSE);
2874 struct connectdata *conn = data->conn;
2875 if(result)
2876 return result;
2877 memset(sshc, 0, sizeof(struct ssh_conn));
2878 connclose(conn);
2879 sshc->state = SSH_SESSION_FREE; /* current */
2880 myssh_to(data, sshc, SSH_STOP);
2881 return CURLE_OK;
2885 * ssh_statemachine() runs the SSH state machine as far as it can without
2886 * blocking and without reaching the end. The data the pointer 'block' points
2887 * to is set to TRUE if the libssh2 function returns LIBSSH2_ERROR_EAGAIN
2888 * meaning it wants to be called again when the socket is ready
2889 */
2890static CURLcode ssh_statemachine(struct Curl_easy *data,
2891 struct ssh_conn *sshc,
2892 struct SSHPROTO *sshp,
2893 bool *block)
2895 CURLcode result = CURLE_OK;
2896 *block = 0; /* we are not blocking by default */
2898 do {
2899 switch(sshc->state) {
2900 case SSH_INIT:
2901 result = ssh_state_init(data, sshc);
2902 if(result)
2903 break;
2904 FALLTHROUGH();
2906 case SSH_S_STARTUP:
2907 result = ssh_state_startup(data, sshc);
2908 if(result)
2909 break;
2910 FALLTHROUGH();
2912 case SSH_HOSTKEY:
2913 result = ssh_state_hostkey(data, sshc);
2914 break;
2916 case SSH_AUTHLIST:
2917 result = ssh_state_authlist(data, sshc);
2918 break;
2920 case SSH_AUTH_PKEY_INIT:
2921 ssh_state_pkey_init(data, sshc);
2922 break;
2924 case SSH_AUTH_PKEY:
2925 result = ssh_state_auth_pkey(data, sshc);
2926 break;
2928 case SSH_AUTH_PASS_INIT:
2929 result = ssh_state_auth_pass_init(data, sshc);
2930 break;
2932 case SSH_AUTH_PASS:
2933 result = ssh_state_auth_pass(data, sshc);
2934 break;
2936 case SSH_AUTH_HOST_INIT:
2937 result = ssh_state_auth_host_init(data, sshc);
2938 break;
2940 case SSH_AUTH_HOST:
2941 myssh_to(data, sshc, SSH_AUTH_AGENT_INIT);
2942 break;
2944 case SSH_AUTH_AGENT_INIT:
2945 result = ssh_state_auth_agent_init(data, sshc);
2946 break;
2948 case SSH_AUTH_AGENT_LIST:
2949 result = ssh_state_auth_agent_list(data, sshc);
2950 break;
2952 case SSH_AUTH_AGENT:
2953 result = ssh_state_auth_agent(data, sshc);
2954 break;
2956 case SSH_AUTH_KEY_INIT:
2957 result = ssh_state_auth_key_init(data, sshc);
2958 break;
2960 case SSH_AUTH_KEY:
2961 result = ssh_state_auth_key(data, sshc);
2962 break;
2964 case SSH_AUTH_DONE:
2965 result = ssh_state_auth_done(data, sshc);
2966 break;
2968 case SSH_SFTP_INIT:
2969 result = ssh_state_sftp_init(data, sshc);
2970 break;
2972 case SSH_SFTP_REALPATH:
2973 result = ssh_state_sftp_realpath(data, sshc, sshp);
2974 break;
2976 case SSH_SFTP_QUOTE_INIT:
2977 result = ssh_state_sftp_quote_init(data, sshc, sshp);
2978 break;
2980 case SSH_SFTP_POSTQUOTE_INIT:
2981 result = ssh_state_sftp_postquote_init(data, sshc);
2982 break;
2984 case SSH_SFTP_QUOTE:
2985 result = ssh_state_sftp_quote(data, sshc, sshp);
2986 break;
2988 case SSH_SFTP_NEXT_QUOTE:
2989 result = ssh_state_sftp_next_quote(data, sshc);
2990 break;
2992 case SSH_SFTP_QUOTE_STAT:
2993 result = ssh_state_sftp_quote_stat(data, sshc, sshp, block);
2994 break;
2996 case SSH_SFTP_QUOTE_SETSTAT:
2997 result = ssh_state_sftp_quote_setstat(data, sshc, sshp);
2998 break;
3000 case SSH_SFTP_QUOTE_SYMLINK:
3001 result = ssh_state_sftp_quote_symlink(data, sshc);
3002 break;
3004 case SSH_SFTP_QUOTE_MKDIR:
3005 result = ssh_state_sftp_quote_mkdir(data, sshc);
3006 break;
3008 case SSH_SFTP_QUOTE_RENAME:
3009 result = ssh_state_sftp_quote_rename(data, sshc);
3010 break;
3012 case SSH_SFTP_QUOTE_RMDIR:
3013 result = ssh_state_sftp_quote_rmdir(data, sshc);
3014 break;
3016 case SSH_SFTP_QUOTE_UNLINK:
3017 result = ssh_state_sftp_quote_unlink(data, sshc);
3018 break;
3020 case SSH_SFTP_QUOTE_STATVFS:
3021 result = ssh_state_sftp_quote_statvfs(data, sshc);
3022 break;
3024 case SSH_SFTP_GETINFO:
3025 result = ssh_state_sftp_getinfo(data, sshc);
3026 break;
3028 case SSH_SFTP_FILETIME:
3029 result = ssh_state_sftp_filetime(data, sshc, sshp);
3030 break;
3032 case SSH_SFTP_TRANS_INIT:
3033 result = ssh_state_sftp_trans_init(data, sshc, sshp);
3034 break;
3036 case SSH_SFTP_UPLOAD_INIT:
3037 result = ssh_state_sftp_upload_init(data, sshc, sshp, block);
3038 break;
3040 case SSH_SFTP_CREATE_DIRS_INIT:
3041 result = ssh_state_sftp_create_dirs_init(data, sshc, sshp);
3042 break;
3044 case SSH_SFTP_CREATE_DIRS:
3045 result = ssh_state_sftp_create_dirs(data, sshc, sshp);
3046 break;
3048 case SSH_SFTP_CREATE_DIRS_MKDIR:
3049 result = ssh_state_sftp_create_dirs_mkdir(data, sshc, sshp);
3050 break;
3052 case SSH_SFTP_READDIR_INIT:
3053 result = ssh_state_sftp_readdir_init(data, sshc, sshp);
3054 break;
3056 case SSH_SFTP_READDIR:
3057 result = ssh_state_sftp_readdir(data, sshc, sshp, block);
3058 break;
3060 case SSH_SFTP_READDIR_LINK:
3061 result = ssh_state_sftp_readdir_link(data, sshc, sshp);
3062 break;
3064 case SSH_SFTP_READDIR_BOTTOM:
3065 result = ssh_state_sftp_readdir_bottom(data, sshc, sshp);
3066 break;
3068 case SSH_SFTP_READDIR_DONE:
3069 result = ssh_state_sftp_readdir_done(data, sshc);
3070 break;
3072 case SSH_SFTP_DOWNLOAD_INIT:
3073 result = ssh_state_sftp_download_init(data, sshc, sshp);
3074 break;
3076 case SSH_SFTP_DOWNLOAD_STAT:
3077 result = ssh_state_sftp_download_stat(data, sshc, sshp, block);
3078 break;
3080 case SSH_SFTP_CLOSE:
3081 result = ssh_state_sftp_close(data, sshc, sshp);
3082 break;
3084 case SSH_SFTP_SHUTDOWN:
3085 result = ssh_state_sftp_shutdown(data, sshc);
3086 break;
3088 case SSH_SCP_TRANS_INIT:
3089 result = ssh_state_scp_trans_init(data, sshc, sshp);
3090 break;
3092 case SSH_SCP_UPLOAD_INIT:
3093 result = ssh_state_scp_upload_init(data, sshc, sshp);
3094 break;
3096 case SSH_SCP_DOWNLOAD_INIT:
3097 result = ssh_state_scp_download_init(data, sshc, sshp);
3098 break;
3100 case SSH_SCP_DONE:
3101 result = ssh_state_scp_done(data, sshc);
3102 break;
3104 case SSH_SCP_SEND_EOF:
3105 result = ssh_state_scp_send_eof(data, sshc);
3106 break;
3108 case SSH_SCP_WAIT_EOF:
3109 result = ssh_state_scp_wait_eof(data, sshc);
3110 break;
3112 case SSH_SCP_WAIT_CLOSE:
3113 result = ssh_state_scp_wait_close(data, sshc);
3114 break;
3116 case SSH_SCP_CHANNEL_FREE:
3117 result = ssh_state_scp_channel_free(data, sshc);
3118 break;
3120 case SSH_SESSION_DISCONNECT:
3121 result = ssh_state_session_disconnect(data, sshc);
3122 break;
3124 case SSH_SESSION_FREE:
3125 result = ssh_state_session_free(data, sshc);
3126 break;
3128 case SSH_QUIT:
3129 default:
3130 /* internal error */
3131 myssh_to(data, sshc, SSH_STOP);
3132 break;
3135 } while(!result && (sshc->state != SSH_STOP) && !*block);
3137 if(result == CURLE_AGAIN) {
3138 /* we would block, we need to wait for the socket to be ready (in the
3139 right direction too)! */
3140 *block = TRUE;
3141 result = CURLE_OK;
3143 CURL_TRC_SSH(data, "[%s] statemachine() -> %d, block=%d",
3144 Curl_ssh_statename(sshc->state), (int)result, *block);
3146 return result;
3150 * When one of the libssh2 functions has returned LIBSSH2_ERROR_EAGAIN this
3151 * function is used to figure out in what direction and stores this info so
3152 * that the multi interface can take advantage of it. Make sure to call this
3153 * function in all cases so that when it _does not_ return EAGAIN we can
3154 * restore the default wait bits.
3155 */
3156static void ssh_block2waitfor(struct Curl_easy *data,
3157 struct ssh_conn *sshc,
3158 bool block)
3160 int dir = 0;
3161 (void)data;
3162 if(block) {
3163 dir = libssh2_session_block_directions(sshc->ssh_session);
3164 if(dir) {
3165 /* translate the libssh2 define bits into our own bit defines */
3166 sshc->waitfor =
3167 ((dir & LIBSSH2_SESSION_BLOCK_INBOUND) ? REQ_IO_RECV : 0) |
3168 ((dir & LIBSSH2_SESSION_BLOCK_OUTBOUND) ? REQ_IO_SEND : 0);
3171 if(!dir)
3172 sshc->waitfor = 0;
3175/* called repeatedly until done from multi.c */
3176static CURLcode ssh_multi_statemach(struct Curl_easy *data, bool *done)
3178 struct connectdata *conn = data->conn;
3179 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3180 struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY);
3181 CURLcode result = CURLE_OK;
3182 bool block; /* we store the status and use that to provide
3183 a Curl_ssh_pollset() implementation */
3184 if(!sshc || !sshp)
3185 return CURLE_FAILED_INIT;
3187 do {
3188 result = ssh_statemachine(data, sshc, sshp, &block);
3189 *done = (sshc->state == SSH_STOP);
3190 /* if there is no error, it is not done and it did not EWOULDBLOCK, then
3191 try again */
3192 } while(!result && !*done && !block);
3193 ssh_block2waitfor(data, sshc, block);
3195 return result;
3198static CURLcode ssh_block_statemach(struct Curl_easy *data,
3199 struct ssh_conn *sshc,
3200 struct SSHPROTO *sshp,
3201 bool disconnect)
3203 CURLcode result = CURLE_OK;
3204 struct curltime start = *Curl_pgrs_now(data);
3206 while((sshc->state != SSH_STOP) && !result) {
3207 bool block;
3208 timediff_t left_ms = 1000;
3210 result = ssh_statemachine(data, sshc, sshp, &block);
3211 if(result)
3212 break;
3214 if(!disconnect) {
3215 result = Curl_pgrsCheck(data);
3216 if(result)
3217 break;
3219 left_ms = Curl_timeleft_ms(data);
3220 if(left_ms < 0) {
3221 failf(data, "Operation timed out");
3222 return CURLE_OPERATION_TIMEDOUT;
3225 else if(curlx_ptimediff_ms(Curl_pgrs_now(data), &start) > 1000) {
3226 /* disconnect timeout */
3227 failf(data, "Disconnect timed out");
3228 result = CURLE_OK;
3229 break;
3232 if(block) {
3233 int dir = libssh2_session_block_directions(sshc->ssh_session);
3234 curl_socket_t sock = data->conn->sock[FIRSTSOCKET];
3235 curl_socket_t fd_read = CURL_SOCKET_BAD;
3236 curl_socket_t fd_write = CURL_SOCKET_BAD;
3237 if(LIBSSH2_SESSION_BLOCK_INBOUND & dir)
3238 fd_read = sock;
3239 if(LIBSSH2_SESSION_BLOCK_OUTBOUND & dir)
3240 fd_write = sock;
3241 /* wait for the socket to become ready */
3242 (void)Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write,
3243 (!left_ms || left_ms > 1000) ? 1000 : left_ms);
3247 return result;
3250static void myssh_easy_dtor(const void *key, size_t klen, void *entry)
3252 struct SSHPROTO *sshp = entry;
3253 (void)key;
3254 (void)klen;
3255 curlx_safefree(sshp->path);
3256 curlx_dyn_free(&sshp->readdir);
3257 curlx_dyn_free(&sshp->readdir_link);
3258 curlx_free(sshp);
3261static void myssh_conn_dtor(const void *key, size_t klen, void *entry)
3263 struct ssh_conn *sshc = entry;
3264 (void)key;
3265 (void)klen;
3266 sshc_cleanup(sshc, NULL, TRUE);
3267 curlx_free(sshc);
3271 * SSH setup and connection
3272 */
3273static CURLcode ssh_setup_connection(struct Curl_easy *data,
3274 struct connectdata *conn)
3276 struct ssh_conn *sshc;
3277 struct SSHPROTO *sshp;
3278 (void)conn;
3280 sshc = curlx_calloc(1, sizeof(*sshc));
3281 if(!sshc)
3282 return CURLE_OUT_OF_MEMORY;
3284 if(Curl_conn_meta_set(conn, CURL_META_SSH_CONN, sshc, myssh_conn_dtor))
3285 return CURLE_OUT_OF_MEMORY;
3287 sshp = curlx_calloc(1, sizeof(*sshp));
3288 if(!sshp)
3289 return CURLE_OUT_OF_MEMORY;
3291 curlx_dyn_init(&sshp->readdir, CURL_PATH_MAX * 2);
3292 curlx_dyn_init(&sshp->readdir_link, CURL_PATH_MAX);
3293 if(Curl_meta_set(data, CURL_META_SSH_EASY, sshp, myssh_easy_dtor))
3294 return CURLE_OUT_OF_MEMORY;
3296 return Curl_ssh_setup_pkey(data, sshc);
3299static Curl_recv scp_recv, sftp_recv;
3300static Curl_send scp_send, sftp_send;
3302#ifndef CURL_DISABLE_PROXY
3303static ssize_t ssh_tls_recv(libssh2_socket_t sock, void *buffer,
3304 size_t length, int flags, void **abstract)
3306 struct Curl_easy *data = (struct Curl_easy *)*abstract;
3307 int8_t sockindex = Curl_conn_sockindex(data, sock);
3308 size_t nread;
3309 CURLcode result;
3310 struct connectdata *conn = data->conn;
3311 Curl_recv *backup = conn->recv[sockindex];
3312 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3313 (void)flags;
3315 if(!sshc)
3316 return -1;
3318 /* swap in the TLS reader function for this call only, and then swap back
3319 the SSH one again */
3320 conn->recv[sockindex] = sshc->tls_recv;
3321 result = Curl_conn_recv(data, sockindex, buffer, length, &nread);
3322 conn->recv[sockindex] = backup;
3323 if(result == CURLE_AGAIN)
3324 return -EAGAIN; /* magic return code for libssh2 */
3325 else if(result)
3326 return -1; /* generic error */
3327 Curl_debug(data, CURLINFO_DATA_IN, (const char *)buffer, nread);
3328 return (ssize_t)nread;
3331static ssize_t ssh_tls_send(libssh2_socket_t sock, const void *buffer,
3332 size_t length, int flags, void **abstract)
3334 struct Curl_easy *data = (struct Curl_easy *)*abstract;
3335 int8_t sockindex = Curl_conn_sockindex(data, sock);
3336 size_t nwrite;
3337 CURLcode result;
3338 struct connectdata *conn = data->conn;
3339 Curl_send *backup = conn->send[sockindex];
3340 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3341 (void)flags;
3343 if(!sshc)
3344 return -1;
3346 /* swap in the TLS writer function for this call only, and then swap back
3347 the SSH one again */
3348 conn->send[sockindex] = sshc->tls_send;
3349 result = Curl_conn_send(data, sockindex, buffer, length, FALSE, &nwrite);
3350 conn->send[sockindex] = backup;
3351 if(result == CURLE_AGAIN)
3352 return -EAGAIN; /* magic return code for libssh2 */
3353 else if(result)
3354 return -1; /* error */
3355 Curl_debug(data, CURLINFO_DATA_OUT, (const char *)buffer, nwrite);
3356 return (ssize_t)nwrite;
3358#endif
3361 * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to
3362 * do protocol-specific actions at connect-time.
3363 */
3364static CURLcode ssh_connect(struct Curl_easy *data, bool *done)
3366#ifdef CURL_LIBSSH2_DEBUG
3367 curl_socket_t sock;
3368#endif
3369 struct connectdata *conn = data->conn;
3370 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3371 CURLcode result;
3373#if LIBSSH2_VERSION_NUM >= 0x010b00
3375 const char *crypto_str;
3376 switch(libssh2_crypto_engine()) {
3377 case libssh2_gcrypt:
3378 crypto_str = "libgcrypt";
3379 break;
3380 case libssh2_mbedtls:
3381 crypto_str = "mbedTLS";
3382 break;
3383 case libssh2_openssl:
3384 crypto_str = "openssl compatible";
3385 break;
3386 case libssh2_os400qc3:
3387 crypto_str = "OS400QC3";
3388 break;
3389 case libssh2_wincng:
3390 crypto_str = "WinCNG";
3391 break;
3392 default:
3393 crypto_str = NULL;
3394 break;
3396 if(crypto_str)
3397 infof(data, "SSH: libssh2 cryptography backend: %s", crypto_str);
3399#endif
3401 if(!sshc)
3402 return CURLE_FAILED_INIT;
3404 infof(data, "SSH: user '%s'", Curl_creds_user(conn->creds));
3405#ifdef CURL_LIBSSH2_DEBUG
3406 infof(data, "SSH: password %s", Curl_creds_passwd(conn->creds));
3407 sock = conn->sock[FIRSTSOCKET];
3408#endif /* CURL_LIBSSH2_DEBUG */
3410 /* libcurl MUST set custom memory functions so that the kbd_callback
3411 function's memory allocations can be properly freed */
3412 sshc->ssh_session = libssh2_session_init_ex(my_libssh2_malloc,
3413 my_libssh2_free,
3414 my_libssh2_realloc, data);
3416 if(!sshc->ssh_session) {
3417 failf(data, "Failure initializing ssh session");
3418 return CURLE_FAILED_INIT;
3421 /* Set the packet read timeout if the libssh2 version supports it */
3422#if LIBSSH2_VERSION_NUM >= 0x010B00
3423 if(data->set.server_response_timeout > 0) {
3424 libssh2_session_set_read_timeout(sshc->ssh_session,
3425 (long)(data->set.server_response_timeout / 1000));
3427#endif
3429#ifndef CURL_DISABLE_PROXY
3430 if(conn->http_proxy.proxytype == CURLPROXY_HTTPS) {
3431 /* Setup libssh2 callbacks to make it read/write TLS from the socket.
3433 ssize_t
3434 recvcb(libssh2_socket_t sock, void *buffer, size_t length,
3435 int flags, void **abstract);
3437 ssize_t
3438 sendcb(libssh2_socket_t sock, const void *buffer, size_t length,
3439 int flags, void **abstract);
3440 */
3441#if LIBSSH2_VERSION_NUM >= 0x010b01
3442 infof(data, "SSH: using HTTPS proxy");
3443#if defined(__clang__) && __clang_major__ >= 16
3444#pragma clang diagnostic push
3445#pragma clang diagnostic ignored "-Wcast-function-type-strict"
3446#endif
3447 libssh2_session_callback_set2(sshc->ssh_session,
3448 LIBSSH2_CALLBACK_RECV,
3449 (libssh2_cb_generic *)ssh_tls_recv);
3450 libssh2_session_callback_set2(sshc->ssh_session,
3451 LIBSSH2_CALLBACK_SEND,
3452 (libssh2_cb_generic *)ssh_tls_send);
3453#if defined(__clang__) && __clang_major__ >= 16
3454#pragma clang diagnostic pop
3455#endif
3456#else
3457 /*
3458 * This crazy union dance is here to avoid assigning a void pointer a
3459 * function pointer as it is invalid C. The problem is of course that
3460 * libssh2 has such an API...
3461 */
3462 union receive {
3463 void *recvp;
3464 ssize_t (*recvptr)(libssh2_socket_t, void *, size_t, int, void **);
3465 };
3466 union transfer {
3467 void *sendp;
3468 ssize_t (*sendptr)(libssh2_socket_t, const void *, size_t, int, void **);
3469 };
3470 union receive sshrecv;
3471 union transfer sshsend;
3473 sshrecv.recvptr = ssh_tls_recv;
3474 sshsend.sendptr = ssh_tls_send;
3476 infof(data, "SSH: using HTTPS proxy");
3477 libssh2_session_callback_set(sshc->ssh_session,
3478 LIBSSH2_CALLBACK_RECV, sshrecv.recvp);
3479 libssh2_session_callback_set(sshc->ssh_session,
3480 LIBSSH2_CALLBACK_SEND, sshsend.sendp);
3481#endif
3483 /* Store the underlying TLS recv/send function pointers to be used when
3484 reading from the proxy */
3485 sshc->tls_recv = conn->recv[FIRSTSOCKET];
3486 sshc->tls_send = conn->send[FIRSTSOCKET];
3489#endif /* CURL_DISABLE_PROXY */
3490 if(conn->scheme->protocol & CURLPROTO_SCP) {
3491 conn->recv[FIRSTSOCKET] = scp_recv;
3492 conn->send[FIRSTSOCKET] = scp_send;
3494 else {
3495 conn->recv[FIRSTSOCKET] = sftp_recv;
3496 conn->send[FIRSTSOCKET] = sftp_send;
3499 if(data->set.ssh_compression &&
3500 libssh2_session_flag(sshc->ssh_session, LIBSSH2_FLAG_COMPRESS, 1) < 0) {
3501 infof(data, "SSH: failed to enable compression for session");
3504 if(CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)) {
3505 int rc;
3506 sshc->kh = libssh2_knownhost_init(sshc->ssh_session);
3507 if(!sshc->kh) {
3508 libssh2_session_free(sshc->ssh_session);
3509 sshc->ssh_session = NULL;
3510 return CURLE_FAILED_INIT;
3513 /* read all known hosts from there */
3514 rc = libssh2_knownhost_readfile(
3515 sshc->kh, CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS),
3516 LIBSSH2_KNOWNHOST_FILE_OPENSSH);
3517 if(rc < 0)
3518 infof(data, "SSH: failed to read known hosts from %s",
3519 CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS));
3522#ifdef CURL_LIBSSH2_DEBUG
3523 libssh2_trace(sshc->ssh_session, ~0);
3524 infof(data, "SSH: socket %d", (int)sock);
3525#endif
3527 myssh_to(data, sshc, SSH_INIT);
3529 result = ssh_multi_statemach(data, done);
3531 return result;
3535 ***********************************************************************
3537 * scp_perform()
3539 * This is the actual DO function for SCP. Get a file according to
3540 * the options previously setup.
3541 */
3543static CURLcode scp_perform(struct Curl_easy *data,
3544 bool *connected,
3545 bool *dophase_done)
3547 struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN);
3548 CURLcode result = CURLE_OK;
3550 CURL_TRC_SSH(data, "DO phase starts");
3552 *dophase_done = FALSE; /* not done yet */
3553 if(!sshc)
3554 return CURLE_FAILED_INIT;
3556 /* start the first command in the DO phase */
3557 myssh_to(data, sshc, SSH_SCP_TRANS_INIT);
3559 /* run the state-machine */
3560 result = ssh_multi_statemach(data, dophase_done);
3562 *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET);
3564 if(*dophase_done) {
3565 CURL_TRC_SSH(data, "DO phase is complete");
3568 return result;
3571/* called from multi.c while DOing */
3572static CURLcode scp_doing(struct Curl_easy *data,
3573 bool *dophase_done)
3575 CURLcode result;
3576 result = ssh_multi_statemach(data, dophase_done);
3578 if(*dophase_done) {
3579 CURL_TRC_SSH(data, "DO phase is complete");
3581 return result;
3584/* BLOCKING, but the function is using the state machine so the only reason
3585 this is still blocking is that the multi interface code has no support for
3586 disconnecting operations that takes a while */
3587static CURLcode scp_disconnect(struct Curl_easy *data,
3588 struct connectdata *conn,
3589 bool dead_connection)
3591 CURLcode result = CURLE_OK;
3592 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3593 struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY);
3594 (void)dead_connection;
3596 if(sshc && sshc->ssh_session) {
3597 /* only if there is a session still around to use! */
3598 myssh_to(data, sshc, SSH_SESSION_DISCONNECT);
3599 result = ssh_block_statemach(data, sshc, sshp, TRUE);
3602 if(sshc)
3603 return sshc_cleanup(sshc, data, TRUE);
3604 return result;
3607/* generic done function for both SCP and SFTP called from their specific
3608 done functions */
3609static CURLcode ssh_done(struct Curl_easy *data, CURLcode status)
3611 struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN);
3612 struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY);
3613 CURLcode result = CURLE_OK;
3615 if(!sshc || !sshp)
3616 return CURLE_FAILED_INIT;
3618 if(!status)
3619 /* run the state-machine */
3620 result = ssh_block_statemach(data, sshc, sshp, FALSE);
3621 else
3622 result = status;
3624 if(Curl_pgrsDone(data, Curl_pgrs_now(data)))
3625 return CURLE_ABORTED_BY_CALLBACK;
3627 CURL_REQ_CLEAR_IO(data);
3628 return result;
3631static CURLcode scp_done(struct Curl_easy *data, CURLcode status,
3632 bool premature)
3634 struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN);
3635 (void)premature;
3637 if(sshc && !status)
3638 myssh_to(data, sshc, SSH_SCP_DONE);
3640 return ssh_done(data, status);
3643static CURLcode scp_send(struct Curl_easy *data, int8_t sockindex,
3644 const uint8_t *mem, size_t len, bool eos,
3645 size_t *pnwritten)
3647 struct connectdata *conn = data->conn;
3648 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3649 CURLcode result = CURLE_OK;
3650 ssize_t nwritten;
3652 (void)sockindex; /* we only support SCP on the fixed known primary socket */
3653 (void)eos;
3654 *pnwritten = 0;
3656 if(!sshc)
3657 return CURLE_FAILED_INIT;
3659 /* libssh2_channel_write() returns int! */
3660 nwritten = (ssize_t)libssh2_channel_write(sshc->ssh_channel,
3661 (const char *)mem, len);
3663 ssh_block2waitfor(data, sshc, (nwritten == LIBSSH2_ERROR_EAGAIN));
3665 if(nwritten == LIBSSH2_ERROR_EAGAIN)
3666 result = CURLE_AGAIN;
3667 else if(nwritten < LIBSSH2_ERROR_NONE)
3668 result = libssh2_session_error_to_CURLE((int)nwritten);
3669 else
3670 *pnwritten = (size_t)nwritten;
3672 return result;
3675static CURLcode scp_recv(struct Curl_easy *data, int8_t sockindex,
3676 char *mem, size_t len, size_t *pnread)
3678 struct connectdata *conn = data->conn;
3679 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3680 CURLcode result = CURLE_OK;
3681 ssize_t nread;
3683 (void)sockindex; /* we only support SCP on the fixed known primary socket */
3684 *pnread = 0;
3686 if(!sshc)
3687 return CURLE_FAILED_INIT;
3689 /* libssh2_channel_read() returns int */
3690 nread = (ssize_t)libssh2_channel_read(sshc->ssh_channel, mem, len);
3692 ssh_block2waitfor(data, sshc, (nread == LIBSSH2_ERROR_EAGAIN));
3693 if(nread == LIBSSH2_ERROR_EAGAIN)
3694 return CURLE_AGAIN;
3695 else if(nread < LIBSSH2_ERROR_NONE)
3696 result = libssh2_session_error_to_CURLE((int)nread);
3697 else
3698 *pnread = (size_t)nread;
3700 return result;
3704 * =============== SFTP ===============
3705 */
3708 ***********************************************************************
3710 * sftp_perform()
3712 * This is the actual DO function for SFTP. Get a file/directory according to
3713 * the options previously setup.
3714 */
3716static CURLcode sftp_perform(struct Curl_easy *data,
3717 bool *connected,
3718 bool *dophase_done)
3720 struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN);
3721 CURLcode result = CURLE_OK;
3723 CURL_TRC_SSH(data, "DO phase starts");
3725 *dophase_done = FALSE; /* not done yet */
3726 if(!sshc)
3727 return CURLE_FAILED_INIT;
3729 /* start the first command in the DO phase */
3730 myssh_to(data, sshc, SSH_SFTP_QUOTE_INIT);
3732 /* run the state-machine */
3733 result = ssh_multi_statemach(data, dophase_done);
3735 *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET);
3737 if(*dophase_done) {
3738 CURL_TRC_SSH(data, "DO phase is complete");
3741 return result;
3744/* called from multi.c while DOing */
3745static CURLcode sftp_doing(struct Curl_easy *data,
3746 bool *dophase_done)
3748 CURLcode result = ssh_multi_statemach(data, dophase_done);
3750 if(*dophase_done) {
3751 CURL_TRC_SSH(data, "DO phase is complete");
3753 return result;
3756/* BLOCKING, but the function is using the state machine so the only reason
3757 this is still blocking is that the multi interface code has no support for
3758 disconnecting operations that takes a while */
3759static CURLcode sftp_disconnect(struct Curl_easy *data,
3760 struct connectdata *conn, bool dead_connection)
3762 CURLcode result = CURLE_OK;
3763 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3764 struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY);
3765 (void)dead_connection;
3767 if(sshc) {
3768 if(sshc->ssh_session) {
3769 /* only if there is a session still around to use! */
3770 CURL_TRC_SSH(data, "DISCONNECT starts now");
3771 myssh_to(data, sshc, SSH_SFTP_SHUTDOWN);
3772 result = ssh_block_statemach(data, sshc, sshp, TRUE);
3773 CURL_TRC_SSH(data, "DISCONNECT is done -> %d", (int)result);
3775 sshc_cleanup(sshc, data, TRUE);
3777 return result;
3780static CURLcode sftp_done(struct Curl_easy *data, CURLcode status,
3781 bool premature)
3783 struct connectdata *conn = data->conn;
3784 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3786 if(!sshc)
3787 return CURLE_FAILED_INIT;
3789 if(!status) {
3790 /* Post quote commands are executed after the SFTP_CLOSE state to avoid
3791 errors that could happen due to open file handles during POSTQUOTE
3792 operation */
3793 if(!premature && data->set.postquote && !conn->bits.retry)
3794 sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT;
3795 myssh_to(data, sshc, SSH_SFTP_CLOSE);
3797 return ssh_done(data, status);
3800/* return number of sent bytes */
3801static CURLcode sftp_send(struct Curl_easy *data, int8_t sockindex,
3802 const uint8_t *mem, size_t len, bool eos,
3803 size_t *pnwritten)
3805 struct connectdata *conn = data->conn;
3806 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3807 ssize_t nwrite;
3809 (void)sockindex;
3810 (void)eos;
3811 *pnwritten = 0;
3813 if(!sshc)
3814 return CURLE_FAILED_INIT;
3816 nwrite = libssh2_sftp_write(sshc->sftp_handle, (const char *)mem, len);
3818 ssh_block2waitfor(data, sshc, (nwrite == LIBSSH2_ERROR_EAGAIN));
3820 if(nwrite == LIBSSH2_ERROR_EAGAIN)
3821 return CURLE_AGAIN;
3822 else if(nwrite < LIBSSH2_ERROR_NONE)
3823 return libssh2_session_error_to_CURLE((int)nwrite);
3824 *pnwritten = (size_t)nwrite;
3825 return CURLE_OK;
3829 * Return number of received (decrypted) bytes
3830 * or <0 on error
3831 */
3832static CURLcode sftp_recv(struct Curl_easy *data, int8_t sockindex,
3833 char *mem, size_t len, size_t *pnread)
3835 struct connectdata *conn = data->conn;
3836 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3837 ssize_t nread;
3839 (void)sockindex;
3840 *pnread = 0;
3842 if(!sshc)
3843 return CURLE_FAILED_INIT;
3845 nread = libssh2_sftp_read(sshc->sftp_handle, mem, len);
3847 ssh_block2waitfor(data, sshc, (nread == LIBSSH2_ERROR_EAGAIN));
3849 if(nread == LIBSSH2_ERROR_EAGAIN)
3850 return CURLE_AGAIN;
3851 else if(nread < 0)
3852 return libssh2_session_error_to_CURLE((int)nread);
3854 *pnread = (size_t)nread;
3855 return CURLE_OK;
3859 * The DO function is generic for both protocols. There was previously two
3860 * separate ones but this way means less duplicated code.
3861 */
3862static CURLcode ssh_do(struct Curl_easy *data, bool *done)
3864 CURLcode result;
3865 bool connected = FALSE;
3866 struct connectdata *conn = data->conn;
3867 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3869 *done = FALSE; /* default to false */
3870 if(!sshc)
3871 return CURLE_FAILED_INIT;
3873 data->req.size = -1; /* make sure this is unknown at this point */
3874 sshc->secondCreateDirs = 0; /* reset the create directory attempt state
3875 variable */
3877 Curl_pgrsReset(data);
3879 if(conn->scheme->protocol & CURLPROTO_SCP)
3880 result = scp_perform(data, &connected, done);
3881 else
3882 result = sftp_perform(data, &connected, done);
3884 return result;
3887CURLcode Curl_ssh_init(void)
3889 if(libssh2_init(0)) {
3890 DEBUGF(curl_mfprintf(stderr, "Error: libssh2_init failed\n"));
3891 return CURLE_FAILED_INIT;
3893 return CURLE_OK;
3896void Curl_ssh_cleanup(void)
3898 libssh2_exit();
3901void Curl_ssh_version(char *buffer, size_t buflen)
3903 (void)curl_msnprintf(buffer, buflen, "libssh2/%s", libssh2_version(0));
3906/* The SSH session is associated with the *CONNECTION* but the callback user
3907 * pointer is an easy handle pointer. This function allows us to reassign the
3908 * user pointer to the *CURRENT* (new) easy handle.
3909 */
3910static void ssh_attach(struct Curl_easy *data, struct connectdata *conn)
3912 DEBUGASSERT(data);
3913 DEBUGASSERT(conn);
3914 if(conn->scheme->protocol & PROTO_FAMILY_SSH) {
3915 struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN);
3916 if(sshc && sshc->ssh_session) {
3917 /* only re-attach if the session already exists */
3918 void **abstract = libssh2_session_abstract(sshc->ssh_session);
3919 *abstract = data;
3925 * SCP protocol handler.
3926 */
3927const struct Curl_protocol Curl_protocol_scp = {
3928 ssh_setup_connection, /* setup_connection */
3929 ZERO_NULL, /* setup_filters */
3930 ssh_do, /* do_it */
3931 scp_done, /* done */
3932 ZERO_NULL, /* do_more */
3933 ssh_connect, /* connect_it */
3934 ssh_multi_statemach, /* connecting */
3935 scp_doing, /* doing */
3936 Curl_ssh_pollset, /* proto_pollset */
3937 Curl_ssh_pollset, /* doing_pollset */
3938 ZERO_NULL, /* domore_pollset */
3939 Curl_ssh_pollset, /* perform_pollset */
3940 scp_disconnect, /* disconnect */
3941 ZERO_NULL, /* write_resp */
3942 ZERO_NULL, /* write_resp_hd */
3943 ZERO_NULL, /* connection_is_dead */
3944 ssh_attach, /* attach */
3945 ZERO_NULL, /* follow */
3949 * SFTP protocol handler.
3950 */
3951const struct Curl_protocol Curl_protocol_sftp = {
3952 ssh_setup_connection, /* setup_connection */
3953 ZERO_NULL, /* setup_filters */
3954 ssh_do, /* do_it */
3955 sftp_done, /* done */
3956 ZERO_NULL, /* do_more */
3957 ssh_connect, /* connect_it */
3958 ssh_multi_statemach, /* connecting */
3959 sftp_doing, /* doing */
3960 Curl_ssh_pollset, /* proto_pollset */
3961 Curl_ssh_pollset, /* doing_pollset */
3962 ZERO_NULL, /* domore_pollset */
3963 Curl_ssh_pollset, /* perform_pollset */
3964 sftp_disconnect, /* disconnect */
3965 ZERO_NULL, /* write_resp */
3966 ZERO_NULL, /* write_resp_hd */
3967 ZERO_NULL, /* connection_is_dead */
3968 ssh_attach, /* attach */
3969 ZERO_NULL, /* follow */
3972#endif /* USE_LIBSSH2 */
Diagnostics4 git calls · 30 ms
CallStatusSizeTime030 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=149
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=149
git.pkt.payload.max=78
git.ls_refs.count=2
git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=293470
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=10
git.pkt.data=8
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=293470
git.pkt.payload.max=65516
git.sideband.band1.bytes=293354
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=87
git.pack.bytes=293354
git.pack.ofs_delta=0
git.pack.ref_delta=1
git.pack.chain.max=1
git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0
git.pack.full=86
Open pack map
fetch20027 KiB · hit24 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=23
git.response.bytes=27981
git.response.cache=HIT
git.response.duration_ms=24
git.fetch.wants=630c881b86c440dcc4dda7e66df8a3937caa56ac
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=27981
git.pkt.payload.max=27960
git.sideband.band1.bytes=27959
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
Ref
refs/heads/master
Commit
31c911efe5652725e930f4d2e60c9060e5f6646d
cf-ray
a5e276b68f9ad806
Request
8eb22e60…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format