libssh2.c 119 KB

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