libssh2.c 114 KB

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