libssh2.c 121 KB

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