libssh2.c 114 KB

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