ssh.c 103 KB

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