libssh2.c 125 KB

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