ssh.c 106 KB

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