2
0

ssh.c 106 KB

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