libssh2.c 119 KB

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