ssh.c 105 KB

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