2
0

libssh2.c 118 KB

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