ssh.c 103 KB

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