libssh2.c 116 KB

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