libssh2.c 121 KB

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