PageRenderTime 57ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/curl-7.28.0/lib/ssh.c

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