libssh2.c 118 KB

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