2
0

libssh2.c 121 KB

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