libssh2.c 120 KB

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