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