SftpFileSystem.cpp 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SftpFileSystem.h"
  5. #include "PuttyIntf.h"
  6. #include "Common.h"
  7. #include "Interface.h"
  8. #include "Terminal.h"
  9. #include "TextsCore.h"
  10. #include "HelpCore.h"
  11. #include <memory>
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  16. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  17. //---------------------------------------------------------------------------
  18. #define SSH_FX_OK 0
  19. #define SSH_FX_EOF 1
  20. #define SSH_FX_NO_SUCH_FILE 2
  21. #define SSH_FX_OP_UNSUPPORTED 8
  22. #define SSH_FXP_INIT 1
  23. #define SSH_FXP_VERSION 2
  24. #define SSH_FXP_OPEN 3
  25. #define SSH_FXP_CLOSE 4
  26. #define SSH_FXP_READ 5
  27. #define SSH_FXP_WRITE 6
  28. #define SSH_FXP_LSTAT 7
  29. #define SSH_FXP_FSTAT 8
  30. #define SSH_FXP_SETSTAT 9
  31. #define SSH_FXP_FSETSTAT 10
  32. #define SSH_FXP_OPENDIR 11
  33. #define SSH_FXP_READDIR 12
  34. #define SSH_FXP_REMOVE 13
  35. #define SSH_FXP_MKDIR 14
  36. #define SSH_FXP_RMDIR 15
  37. #define SSH_FXP_REALPATH 16
  38. #define SSH_FXP_STAT 17
  39. #define SSH_FXP_RENAME 18
  40. #define SSH_FXP_READLINK 19
  41. #define SSH_FXP_SYMLINK 20
  42. #define SSH_FXP_STATUS 101
  43. #define SSH_FXP_HANDLE 102
  44. #define SSH_FXP_DATA 103
  45. #define SSH_FXP_NAME 104
  46. #define SSH_FXP_ATTRS 105
  47. #define SSH_FXP_EXTENDED 200
  48. #define SSH_FXP_EXTENDED_REPLY 201
  49. #define SSH_FXP_ATTRS 105
  50. #define SSH_FILEXFER_ATTR_SIZE 0x00000001
  51. #define SSH_FILEXFER_ATTR_UIDGID 0x00000002
  52. #define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004
  53. #define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008
  54. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  55. #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008
  56. #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010
  57. #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020
  58. #define SSH_FILEXFER_ATTR_ACL 0x00000040
  59. #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
  60. #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
  61. #define SSH_FILEXFER_ATTR_BITS 0x00000200
  62. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  63. #define SSH_FILEXFER_ATTR_COMMON \
  64. (SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_OWNERGROUP | \
  65. SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACCESSTIME | \
  66. SSH_FILEXFER_ATTR_MODIFYTIME)
  67. #define SSH_FILEXFER_TYPE_REGULAR 1
  68. #define SSH_FILEXFER_TYPE_DIRECTORY 2
  69. #define SSH_FILEXFER_TYPE_SYMLINK 3
  70. #define SSH_FILEXFER_TYPE_SPECIAL 4
  71. #define SSH_FILEXFER_TYPE_UNKNOWN 5
  72. #define SSH_FXF_READ 0x00000001
  73. #define SSH_FXF_WRITE 0x00000002
  74. #define SSH_FXF_APPEND 0x00000004
  75. #define SSH_FXF_CREAT 0x00000008
  76. #define SSH_FXF_TRUNC 0x00000010
  77. #define SSH_FXF_EXCL 0x00000020
  78. #define SSH_FXF_TEXT 0x00000040
  79. #define SSH_FXF_ACCESS_DISPOSITION 0x00000007
  80. #define SSH_FXF_CREATE_NEW 0x00000000
  81. #define SSH_FXF_CREATE_TRUNCATE 0x00000001
  82. #define SSH_FXF_OPEN_EXISTING 0x00000002
  83. #define SSH_FXF_OPEN_OR_CREATE 0x00000003
  84. #define SSH_FXF_TRUNCATE_EXISTING 0x00000004
  85. #define SSH_FXF_ACCESS_APPEND_DATA 0x00000008
  86. #define SSH_FXF_ACCESS_APPEND_DATA_ATOMIC 0x00000010
  87. #define SSH_FXF_ACCESS_TEXT_MODE 0x00000020
  88. #define SSH_FXF_ACCESS_READ_LOCK 0x00000040
  89. #define SSH_FXF_ACCESS_WRITE_LOCK 0x00000080
  90. #define SSH_FXF_ACCESS_DELETE_LOCK 0x00000100
  91. #define ACE4_READ_DATA 0x00000001
  92. #define ACE4_LIST_DIRECTORY 0x00000001
  93. #define ACE4_WRITE_DATA 0x00000002
  94. #define ACE4_ADD_FILE 0x00000002
  95. #define ACE4_APPEND_DATA 0x00000004
  96. #define ACE4_ADD_SUBDIRECTORY 0x00000004
  97. #define ACE4_READ_NAMED_ATTRS 0x00000008
  98. #define ACE4_WRITE_NAMED_ATTRS 0x00000010
  99. #define ACE4_EXECUTE 0x00000020
  100. #define ACE4_DELETE_CHILD 0x00000040
  101. #define ACE4_READ_ATTRIBUTES 0x00000080
  102. #define ACE4_WRITE_ATTRIBUTES 0x00000100
  103. #define ACE4_DELETE 0x00010000
  104. #define ACE4_READ_ACL 0x00020000
  105. #define ACE4_WRITE_ACL 0x00040000
  106. #define ACE4_WRITE_OWNER 0x00080000
  107. #define ACE4_SYNCHRONIZE 0x00100000
  108. #define SSH_FILEXFER_ATTR_FLAGS_HIDDEN 0x00000004
  109. #define SFTP_MAX_PACKET_LEN 102400
  110. //---------------------------------------------------------------------------
  111. #define SFTP_EXT_OWNER_GROUP "owner-group-query@generic-extensions"
  112. #define SFTP_EXT_OWNER_GROUP_REPLY "owner-group-query-reply@generic-extensions"
  113. #define SFTP_EXT_NEWLINE "newline"
  114. #define SFTP_EXT_SUPPORTED "supported"
  115. #define SFTP_EXT_FSROOTS "[email protected]"
  116. #define SFTP_EXT_VENDOR_ID "vendor-id"
  117. //---------------------------------------------------------------------------
  118. #define OGQ_LIST_OWNERS 0x01
  119. #define OGQ_LIST_GROUPS 0x02
  120. //---------------------------------------------------------------------------
  121. const int SFTPMinVersion = 0;
  122. const int SFTPMaxVersion = 5;
  123. const int SFTPNoMessageNumber = -1;
  124. const int asNo = 0;
  125. const int asOK = 1 << SSH_FX_OK;
  126. const int asEOF = 1 << SSH_FX_EOF;
  127. const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED;
  128. const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE;
  129. const int asAll = 0xFFFF;
  130. const int tfFirstLevel = 0x01;
  131. const int tfNewDirectory = 0x02;
  132. //---------------------------------------------------------------------------
  133. #define GET_32BIT(cp) \
  134. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  135. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  136. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  137. ((unsigned long)(unsigned char)(cp)[3]))
  138. #define PUT_32BIT(cp, value) { \
  139. (cp)[0] = (unsigned char)((value) >> 24); \
  140. (cp)[1] = (unsigned char)((value) >> 16); \
  141. (cp)[2] = (unsigned char)((value) >> 8); \
  142. (cp)[3] = (unsigned char)(value); }
  143. //---------------------------------------------------------------------------
  144. #define SFTP_PACKET_ALLOC_DELTA 256
  145. //---------------------------------------------------------------------------
  146. #pragma warn -inl
  147. //---------------------------------------------------------------------------
  148. struct TSFTPSupport
  149. {
  150. unsigned int AttributeMask;
  151. unsigned int AttributeBits;
  152. unsigned int OpenFlags;
  153. unsigned int AccessMask;
  154. unsigned int MaxReadSize;
  155. TStrings * Extensions;
  156. };
  157. //---------------------------------------------------------------------------
  158. class TSFTPPacket
  159. {
  160. public:
  161. TSFTPPacket()
  162. {
  163. Init();
  164. }
  165. TSFTPPacket(const TSFTPPacket & Source)
  166. {
  167. Init();
  168. *this = Source;
  169. }
  170. TSFTPPacket(unsigned char AType)
  171. {
  172. Init();
  173. ChangeType(AType);
  174. }
  175. TSFTPPacket(const char * Source, unsigned int Len)
  176. {
  177. Init();
  178. FLength = Len;
  179. Capacity = FLength;
  180. memcpy(Data, Source, Len);
  181. }
  182. TSFTPPacket(const AnsiString & Source)
  183. {
  184. Init();
  185. FLength = Source.Length();
  186. Capacity = FLength;
  187. memcpy(Data, Source.c_str(), Source.Length());
  188. }
  189. ~TSFTPPacket()
  190. {
  191. if (FData != NULL)
  192. {
  193. delete[] (FData - FSendPrefixLen);
  194. }
  195. if (FReservedBy) FReservedBy->UnreserveResponse(this);
  196. }
  197. void ChangeType(unsigned char AType)
  198. {
  199. FPosition = 0;
  200. FLength = 0;
  201. Capacity = 0;
  202. FType = AType;
  203. AddByte(FType);
  204. if ((FType != 1) && (FType != SSH_FXP_INIT))
  205. {
  206. AssignNumber();
  207. AddCardinal(FMessageNumber);
  208. }
  209. }
  210. void Reuse()
  211. {
  212. AssignNumber();
  213. assert(Length >= 5);
  214. // duplicated in AddCardinal()
  215. unsigned char Buf[4];
  216. PUT_32BIT(Buf, FMessageNumber);
  217. memcpy(FData + 1, Buf, sizeof(Buf));
  218. }
  219. void AddByte(unsigned char Value)
  220. {
  221. Add(&Value, sizeof(Value));
  222. }
  223. void AddCardinal(unsigned long Value)
  224. {
  225. // duplicated in Reuse()
  226. unsigned char Buf[4];
  227. PUT_32BIT(Buf, Value);
  228. Add(&Buf, sizeof(Buf));
  229. }
  230. void AddInt64(__int64 Value)
  231. {
  232. AddCardinal((unsigned long)(Value >> 32));
  233. AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
  234. }
  235. void AddData(const void * Data, int ALength)
  236. {
  237. AddCardinal(ALength);
  238. Add(Data, ALength);
  239. }
  240. void AddString(const AnsiString Value)
  241. {
  242. AddCardinal(Value.Length());
  243. Add(Value.c_str(), Value.Length());
  244. }
  245. inline void AddUtfString(const AnsiString Value)
  246. {
  247. AddString(TSFTPFileSystem::EncodeUTF(Value));
  248. }
  249. inline void AddString(const AnsiString Value, bool Utf)
  250. {
  251. if (Utf)
  252. {
  253. AddUtfString(Value);
  254. }
  255. else
  256. {
  257. AddString(Value);
  258. }
  259. }
  260. // now purposeless alias to AddString
  261. inline void AddPathString(const AnsiString Value, bool Utf)
  262. {
  263. AddString(Value, Utf);
  264. }
  265. void AddProperties(unsigned short * Rights, AnsiString * Owner,
  266. AnsiString * Group, __int64 * MTime, __int64 * ATime,
  267. __int64 * Size, bool IsDirectory, int Version, bool Utf)
  268. {
  269. int Flags = 0;
  270. if (Size != NULL)
  271. {
  272. Flags |= SSH_FILEXFER_ATTR_SIZE;
  273. }
  274. if ((Owner != NULL) || (Group != NULL))
  275. {
  276. Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
  277. }
  278. if (Rights != NULL)
  279. {
  280. Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
  281. }
  282. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  283. {
  284. Flags |= SSH_FILEXFER_ATTR_ACMODTIME;
  285. }
  286. if ((Version >= 4) && (ATime != NULL))
  287. {
  288. Flags |= SSH_FILEXFER_ATTR_ACCESSTIME;
  289. }
  290. if ((Version >= 4) && (MTime != NULL))
  291. {
  292. Flags |= SSH_FILEXFER_ATTR_MODIFYTIME;
  293. }
  294. AddCardinal(Flags);
  295. if (Version >= 4)
  296. {
  297. AddByte(static_cast<unsigned char>(IsDirectory ?
  298. SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
  299. }
  300. if (Size != NULL)
  301. {
  302. AddInt64(*Size);
  303. }
  304. if ((Owner != NULL) || (Group != NULL))
  305. {
  306. assert(Version >= 4);
  307. AddString(Owner != NULL ? *Owner : AnsiString(), Utf);
  308. AddString(Group != NULL ? *Group : AnsiString(), Utf);
  309. }
  310. if (Rights != NULL)
  311. {
  312. AddCardinal(*Rights);
  313. }
  314. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  315. {
  316. // any way to reflect sbSignedTS here?
  317. // (note that casting __int64 > 2^31 < 2^32 to unsigned long is wrapped,
  318. // thus we never can set time after 2038, even if the server supports it)
  319. AddCardinal(static_cast<unsigned long>(ATime != NULL ? *ATime : *MTime));
  320. AddCardinal(static_cast<unsigned long>(MTime != NULL ? *MTime : *ATime));
  321. }
  322. if ((Version >= 4) && (ATime != NULL))
  323. {
  324. AddInt64(*ATime);
  325. }
  326. if ((Version >= 4) && (MTime != NULL))
  327. {
  328. AddInt64(*MTime);
  329. }
  330. }
  331. void AddProperties(const TRemoteProperties * Properties,
  332. unsigned short BaseRights, bool IsDirectory, int Version, bool Utf)
  333. {
  334. enum { valNone = 0, valRights = 0x01, valOwner = 0x02, valGroup = 0x04,
  335. valMTime = 0x08, valATime = 0x10 } Valid = valNone;
  336. unsigned short RightsNum = 0;
  337. AnsiString Owner;
  338. AnsiString Group;
  339. __int64 MTime;
  340. __int64 ATime;
  341. if (Properties != NULL)
  342. {
  343. if (Properties->Valid.Contains(vpGroup))
  344. {
  345. Valid |= valGroup;
  346. Group = Properties->Group;
  347. }
  348. if (Properties->Valid.Contains(vpOwner))
  349. {
  350. Valid |= valOwner;
  351. Owner = Properties->Owner;
  352. }
  353. if (Properties->Valid.Contains(vpRights))
  354. {
  355. Valid |= valRights;
  356. TRights Rights = BaseRights;
  357. Rights |= Properties->Rights.NumberSet;
  358. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  359. if (IsDirectory && Properties->AddXToDirectories)
  360. {
  361. Rights.AddExecute();
  362. }
  363. RightsNum = Rights;
  364. }
  365. if (Properties->Valid.Contains(vpLastAccess))
  366. {
  367. Valid |= valATime;
  368. ATime = Properties->LastAccess;
  369. }
  370. if (Properties->Valid.Contains(vpModification))
  371. {
  372. Valid |= valMTime;
  373. MTime = Properties->Modification;
  374. }
  375. }
  376. AddProperties(
  377. Valid & valRights ? &RightsNum : NULL,
  378. Valid & valOwner ? &Owner : NULL,
  379. Valid & valGroup ? &Group : NULL,
  380. Valid & valMTime ? &MTime : NULL,
  381. Valid & valATime ? &ATime : NULL,
  382. NULL, IsDirectory, Version, Utf);
  383. }
  384. char GetByte()
  385. {
  386. Need(sizeof(char));
  387. char Result = FData[FPosition];
  388. FPosition++;
  389. return Result;
  390. }
  391. unsigned long GetCardinal()
  392. {
  393. unsigned long Result;
  394. Need(sizeof(Result));
  395. Result = GET_32BIT(FData + FPosition);
  396. FPosition += sizeof(Result);
  397. return Result;
  398. }
  399. __int64 GetInt64()
  400. {
  401. __int64 Hi = GetCardinal();
  402. __int64 Lo = GetCardinal();
  403. return (Hi << 32) + Lo;
  404. }
  405. AnsiString GetString()
  406. {
  407. AnsiString Result;
  408. unsigned long Len = GetCardinal();
  409. Need(Len);
  410. // cannot happen anyway as Need() would raise exception
  411. assert(Len < SFTP_MAX_PACKET_LEN);
  412. Result.SetLength(Len);
  413. memcpy(Result.c_str(), FData + FPosition, Len);
  414. FPosition += Len;
  415. return Result;
  416. }
  417. inline AnsiString GetUtfString()
  418. {
  419. return TSFTPFileSystem::DecodeUTF(GetString());
  420. }
  421. inline AnsiString GetString(bool Utf)
  422. {
  423. return (Utf ? GetUtfString() : GetString());
  424. }
  425. // now purposeless alias to GetString
  426. inline AnsiString GetPathString(bool Utf)
  427. {
  428. return GetString(Utf);
  429. }
  430. void GetFile(TRemoteFile * File, int Version, bool ConsiderDST, bool Utf, bool SignedTS)
  431. {
  432. assert(File);
  433. unsigned int Flags;
  434. AnsiString ListingStr;
  435. unsigned long Permissions;
  436. bool ParsingFailed = false;
  437. if (Type != SSH_FXP_ATTRS)
  438. {
  439. File->FileName = GetPathString(Utf);
  440. if (Version < 4)
  441. {
  442. ListingStr = GetString();
  443. }
  444. }
  445. Flags = GetCardinal();
  446. if (Version >= 4)
  447. {
  448. char FXType = GetByte();
  449. // -:regular, D:directory, L:symlink, S:special, U:unknown
  450. // O:socket, C:char devide, B:block device, F:fifo
  451. static char* Types = "-DLSUOCBF";
  452. if (FXType < 1 || FXType > (char)strlen(Types))
  453. {
  454. throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
  455. }
  456. File->Type = Types[FXType-1];
  457. }
  458. if (Flags & SSH_FILEXFER_ATTR_SIZE)
  459. {
  460. File->Size = GetInt64();
  461. }
  462. // SSH-2.0-3.2.0 F-SECURE SSH - Process Software MultiNet
  463. // sets SSH_FILEXFER_ATTR_UIDGID for v4, but does not include the UID/GUID
  464. if ((Flags & SSH_FILEXFER_ATTR_UIDGID) && (Version < 4))
  465. {
  466. GetCardinal(); // skip UID
  467. GetCardinal(); // skip GUID
  468. }
  469. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  470. {
  471. assert(Version >= 4);
  472. File->Owner = GetString(Utf);
  473. File->Group = GetString(Utf);
  474. }
  475. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  476. {
  477. Permissions = GetCardinal();
  478. }
  479. if (Version < 4)
  480. {
  481. if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
  482. {
  483. File->LastAccess = UnixToDateTime(
  484. SignedTS ?
  485. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  486. static_cast<__int64>(GetCardinal()),
  487. ConsiderDST);
  488. File->Modification = UnixToDateTime(
  489. SignedTS ?
  490. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  491. static_cast<__int64>(GetCardinal()),
  492. ConsiderDST);
  493. }
  494. }
  495. else
  496. {
  497. if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
  498. {
  499. File->LastAccess = UnixToDateTime(GetInt64(), ConsiderDST);
  500. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  501. {
  502. GetCardinal(); // skip access time subseconds
  503. }
  504. }
  505. else
  506. {
  507. File->LastAccess = Now();
  508. }
  509. if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
  510. {
  511. GetInt64(); // skip create time
  512. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  513. {
  514. GetCardinal(); // skip create time subseconds
  515. }
  516. }
  517. if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
  518. {
  519. File->Modification = UnixToDateTime(GetInt64(), ConsiderDST);
  520. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  521. {
  522. GetCardinal(); // skip modification time subseconds
  523. }
  524. }
  525. else
  526. {
  527. File->Modification = Now();
  528. }
  529. }
  530. if (Flags & SSH_FILEXFER_ATTR_ACL)
  531. {
  532. GetString();
  533. }
  534. if (Flags & SSH_FILEXFER_ATTR_BITS)
  535. {
  536. // while SSH_FILEXFER_ATTR_BITS is defined for SFTP5 only, vandyke 2.3.3 sets it
  537. // for SFTP4 as well
  538. unsigned long Bits = GetCardinal();
  539. if (FLAGSET(Bits, SSH_FILEXFER_ATTR_FLAGS_HIDDEN))
  540. {
  541. File->IsHidden = true;
  542. }
  543. }
  544. if ((Version < 4) && (Type != SSH_FXP_ATTRS))
  545. {
  546. try
  547. {
  548. // update permissions and user/group name
  549. // modification time and filename is ignored
  550. File->ListingStr = ListingStr;
  551. }
  552. catch(...)
  553. {
  554. // ignore any error while parsing listing line,
  555. // SFTP specification do not recommend to parse it
  556. ParsingFailed = true;
  557. }
  558. }
  559. if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
  560. {
  561. File->Rights->Number = (unsigned short)(Permissions & TRights::rfAllSpecials);
  562. if (Version < 4)
  563. {
  564. File->Type = (Permissions & TRights::rfDirectory ? FILETYPE_DIRECTORY : '-');
  565. }
  566. }
  567. if (Flags & SSH_FILEXFER_ATTR_EXTENDED)
  568. {
  569. unsigned int ExtendedCount = GetCardinal();
  570. for (unsigned int Index = 0; Index < ExtendedCount; Index++)
  571. {
  572. GetString(); // skip extended_type
  573. GetString(); // skip extended_data
  574. }
  575. }
  576. File->Complete();
  577. }
  578. char * GetNextData(unsigned int Size = 0)
  579. {
  580. if (Size > 0)
  581. {
  582. Need(Size);
  583. }
  584. return FPosition < FLength ? FData + FPosition : NULL;
  585. }
  586. void DataUpdated(int ALength)
  587. {
  588. FPosition = 0;
  589. FLength = ALength;
  590. FType = GetByte();
  591. if (FType != SSH_FXP_VERSION)
  592. {
  593. FMessageNumber = GetCardinal();
  594. }
  595. else
  596. {
  597. FMessageNumber = SFTPNoMessageNumber;
  598. }
  599. }
  600. void LoadFromFile(const AnsiString FileName)
  601. {
  602. TStringList * DumpLines = new TStringList();
  603. AnsiString Dump;
  604. try
  605. {
  606. DumpLines->LoadFromFile(FileName);
  607. Dump = DumpLines->Text;
  608. }
  609. __finally
  610. {
  611. delete DumpLines;
  612. }
  613. Capacity = 20480;
  614. char Byte[3];
  615. memset(Byte, '\0', sizeof(Byte));
  616. int Index = 1;
  617. unsigned int Length = 0;
  618. while (Index < Dump.Length())
  619. {
  620. char C = Dump[Index];
  621. if (((C >= '0') && (C <= '9')) || ((C >= 'A') && (C <= 'Z')))
  622. {
  623. if (Byte[0] == '\0')
  624. {
  625. Byte[0] = C;
  626. }
  627. else
  628. {
  629. Byte[1] = C;
  630. assert(Length < Capacity);
  631. Data[Length] = static_cast<unsigned char>(HexToInt(Byte));
  632. Length++;
  633. memset(Byte, '\0', sizeof(Byte));
  634. }
  635. }
  636. Index++;
  637. }
  638. DataUpdated(Length);
  639. }
  640. AnsiString __fastcall Dump() const
  641. {
  642. AnsiString Result;
  643. for (unsigned int Index = 0; Index < Length; Index++)
  644. {
  645. Result += IntToHex(int((unsigned char)Data[Index]), 2) + ",";
  646. if (((Index + 1) % 25) == 0)
  647. {
  648. Result += "\n";
  649. }
  650. }
  651. return Result;
  652. }
  653. TSFTPPacket & operator = (const TSFTPPacket & Source)
  654. {
  655. Capacity = 0;
  656. Add(Source.Data, Source.Length);
  657. DataUpdated(Source.Length);
  658. FPosition = Source.FPosition;
  659. return *this;
  660. }
  661. __property unsigned int Length = { read = FLength };
  662. __property char * Data = { read = FData };
  663. __property char * SendData = { read = GetSendData };
  664. __property unsigned int SendLength = { read = GetSendLength };
  665. __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
  666. __property unsigned char Type = { read = FType };
  667. __property unsigned char RequestType = { read = GetRequestType };
  668. __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
  669. __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
  670. __property AnsiString TypeName = { read = GetTypeName };
  671. private:
  672. char * FData;
  673. unsigned int FLength;
  674. unsigned int FCapacity;
  675. unsigned int FPosition;
  676. unsigned char FType;
  677. unsigned int FMessageNumber;
  678. TSFTPFileSystem * FReservedBy;
  679. static int FMessageCounter;
  680. static const FSendPrefixLen = 4;
  681. void Init()
  682. {
  683. FData = NULL;
  684. FCapacity = 0;
  685. FLength = 0;
  686. FPosition = 0;
  687. FMessageNumber = SFTPNoMessageNumber;
  688. FType = -1;
  689. FReservedBy = NULL;
  690. }
  691. void AssignNumber()
  692. {
  693. // this is not strictly thread-safe, but as it is accessed from multiple
  694. // threads only for multiple connection, it is not problem if two threads get
  695. // the same number
  696. FMessageNumber = (FMessageCounter << 8) + FType;
  697. FMessageCounter++;
  698. }
  699. unsigned char GetRequestType()
  700. {
  701. if (FMessageNumber != SFTPNoMessageNumber)
  702. {
  703. return (unsigned char)(FMessageNumber & 0xFF);
  704. }
  705. else
  706. {
  707. assert(Type == SSH_FXP_VERSION);
  708. return SSH_FXP_INIT;
  709. }
  710. }
  711. inline void Add(const void * AData, int ALength)
  712. {
  713. if (Length + ALength > Capacity)
  714. {
  715. Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
  716. }
  717. memcpy(FData + Length, AData, ALength);
  718. FLength += ALength;
  719. }
  720. void SetCapacity(unsigned int ACapacity)
  721. {
  722. if (ACapacity != Capacity)
  723. {
  724. FCapacity = ACapacity;
  725. if (FCapacity > 0)
  726. {
  727. char * NData = (new char[FCapacity + FSendPrefixLen]) + FSendPrefixLen;
  728. if (FData)
  729. {
  730. memcpy(NData - FSendPrefixLen, FData - FSendPrefixLen,
  731. (FLength < FCapacity ? FLength : FCapacity) + FSendPrefixLen);
  732. delete[] (FData - FSendPrefixLen);
  733. }
  734. FData = NData;
  735. }
  736. else
  737. {
  738. if (FData) delete[] (FData - FSendPrefixLen);
  739. FData = NULL;
  740. }
  741. if (FLength > FCapacity) FLength = FCapacity;
  742. }
  743. }
  744. AnsiString GetTypeName() const
  745. {
  746. #define TYPE_CASE(TYPE) case TYPE: return #TYPE
  747. switch (Type) {
  748. TYPE_CASE(SSH_FXP_INIT);
  749. TYPE_CASE(SSH_FXP_VERSION);
  750. TYPE_CASE(SSH_FXP_OPEN);
  751. TYPE_CASE(SSH_FXP_CLOSE);
  752. TYPE_CASE(SSH_FXP_READ);
  753. TYPE_CASE(SSH_FXP_WRITE);
  754. TYPE_CASE(SSH_FXP_LSTAT);
  755. TYPE_CASE(SSH_FXP_FSTAT);
  756. TYPE_CASE(SSH_FXP_SETSTAT);
  757. TYPE_CASE(SSH_FXP_FSETSTAT);
  758. TYPE_CASE(SSH_FXP_OPENDIR);
  759. TYPE_CASE(SSH_FXP_READDIR);
  760. TYPE_CASE(SSH_FXP_REMOVE);
  761. TYPE_CASE(SSH_FXP_MKDIR);
  762. TYPE_CASE(SSH_FXP_RMDIR);
  763. TYPE_CASE(SSH_FXP_REALPATH);
  764. TYPE_CASE(SSH_FXP_STAT);
  765. TYPE_CASE(SSH_FXP_RENAME);
  766. TYPE_CASE(SSH_FXP_READLINK);
  767. TYPE_CASE(SSH_FXP_SYMLINK);
  768. TYPE_CASE(SSH_FXP_STATUS);
  769. TYPE_CASE(SSH_FXP_HANDLE);
  770. TYPE_CASE(SSH_FXP_DATA);
  771. TYPE_CASE(SSH_FXP_NAME);
  772. TYPE_CASE(SSH_FXP_ATTRS);
  773. TYPE_CASE(SSH_FXP_EXTENDED);
  774. TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
  775. default:
  776. return FORMAT("Unknown message (%d)", (int(Type)));
  777. }
  778. }
  779. char * GetSendData() const
  780. {
  781. char * Result = FData - FSendPrefixLen;
  782. // this is not strictly const-object operation
  783. PUT_32BIT(Result, Length);
  784. return Result;
  785. }
  786. unsigned int GetSendLength() const
  787. {
  788. return FSendPrefixLen + Length;
  789. }
  790. inline void Need(unsigned int Size)
  791. {
  792. if (FPosition + Size > FLength)
  793. {
  794. throw Exception(FMTLOAD(SFTP_PACKET_ERROR, (int(FPosition), int(Size), int(FLength))));
  795. }
  796. }
  797. };
  798. //---------------------------------------------------------------------------
  799. int TSFTPPacket::FMessageCounter = 0;
  800. //---------------------------------------------------------------------------
  801. class TSFTPQueue
  802. {
  803. public:
  804. __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
  805. {
  806. FFileSystem = AFileSystem;
  807. assert(FFileSystem);
  808. FRequests = new TList();
  809. FResponses = new TList();
  810. FMissedRequests = 0;
  811. }
  812. __fastcall ~TSFTPQueue()
  813. {
  814. try
  815. {
  816. if (FFileSystem->FTerminal->Active)
  817. {
  818. Dispose();
  819. }
  820. }
  821. __finally
  822. {
  823. TSFTPQueuePacket * Request;
  824. TSFTPPacket * Response;
  825. assert(FResponses->Count == FRequests->Count);
  826. for (int Index = 0; Index < FRequests->Count; Index++)
  827. {
  828. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[Index]);
  829. assert(Request);
  830. delete Request;
  831. Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
  832. assert(Response);
  833. delete Response;
  834. }
  835. delete FRequests;
  836. delete FResponses;
  837. }
  838. }
  839. bool __fastcall Init(int QueueLen)
  840. {
  841. bool Result = false;
  842. while ((QueueLen > 0) && SendRequest())
  843. {
  844. Result = true;
  845. QueueLen--;
  846. }
  847. FMissedRequests = QueueLen;
  848. return Result;
  849. }
  850. void __fastcall Dispose()
  851. {
  852. assert(FFileSystem->FTerminal->Active);
  853. TSFTPQueuePacket * Request;
  854. TSFTPPacket * Response;
  855. while (FRequests->Count)
  856. {
  857. assert(FResponses->Count);
  858. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  859. assert(Request);
  860. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  861. assert(Response);
  862. try
  863. {
  864. FFileSystem->ReceiveResponse(Request, Response);
  865. }
  866. catch(Exception & E)
  867. {
  868. if (FFileSystem->FTerminal->Active)
  869. {
  870. FFileSystem->FTerminal->LogEvent("Error while disposing the SFTP queue.");
  871. FFileSystem->FTerminal->DoHandleExtendedException(&E);
  872. }
  873. else
  874. {
  875. FFileSystem->FTerminal->LogEvent("Fatal error while disposing the SFTP queue.");
  876. throw;
  877. }
  878. }
  879. FRequests->Delete(0);
  880. delete Request;
  881. FResponses->Delete(0);
  882. delete Response;
  883. }
  884. }
  885. bool __fastcall ReceivePacket(TSFTPPacket * Packet,
  886. int ExpectedType = -1, int AllowStatus = -1, void ** Token = NULL)
  887. {
  888. assert(FRequests->Count);
  889. bool Result;
  890. TSFTPQueuePacket * Request = NULL;
  891. TSFTPPacket * Response = NULL;
  892. try
  893. {
  894. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  895. FRequests->Delete(0);
  896. assert(Request);
  897. if (Token != NULL)
  898. {
  899. *Token = Request->Token;
  900. }
  901. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  902. FResponses->Delete(0);
  903. assert(Response);
  904. FFileSystem->ReceiveResponse(Request, Response,
  905. ExpectedType, AllowStatus);
  906. if (Packet)
  907. {
  908. *Packet = *Response;
  909. }
  910. Result = !End(Response);
  911. if (Result)
  912. {
  913. FMissedRequests++;
  914. while ((FMissedRequests > 0) && SendRequest())
  915. {
  916. FMissedRequests--;
  917. }
  918. }
  919. }
  920. __finally
  921. {
  922. delete Request;
  923. delete Response;
  924. }
  925. return Result;
  926. }
  927. bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
  928. {
  929. return ReceivePacket(NULL, ExpectedType, AllowStatus);
  930. }
  931. protected:
  932. class TSFTPQueuePacket : public TSFTPPacket
  933. {
  934. public:
  935. TSFTPQueuePacket() :
  936. TSFTPPacket()
  937. {
  938. Token = NULL;
  939. }
  940. void * Token;
  941. };
  942. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request) = 0;
  943. virtual bool __fastcall End(TSFTPPacket * Response) = 0;
  944. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  945. {
  946. FFileSystem->SendPacket(Packet);
  947. }
  948. protected:
  949. TList * FRequests;
  950. TList * FResponses;
  951. TSFTPFileSystem * FFileSystem;
  952. int FMissedRequests;
  953. private:
  954. bool __fastcall SendRequest()
  955. {
  956. TSFTPQueuePacket * Request = NULL;
  957. try
  958. {
  959. Request = new TSFTPQueuePacket();
  960. if (!InitRequest(Request))
  961. {
  962. delete Request;
  963. Request = NULL;
  964. }
  965. }
  966. catch(...)
  967. {
  968. delete Request;
  969. throw;
  970. }
  971. if (Request != NULL)
  972. {
  973. TSFTPPacket * Response = new TSFTPPacket();
  974. FRequests->Add(Request);
  975. FResponses->Add(Response);
  976. SendPacket(Request);
  977. FFileSystem->ReserveResponse(Request, Response);
  978. }
  979. return (Request != NULL);
  980. }
  981. };
  982. //---------------------------------------------------------------------------
  983. class TSFTPTransferQueue : public TSFTPQueue
  984. {
  985. public:
  986. TSFTPTransferQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  987. {
  988. }
  989. protected:
  990. __int64 FTransfered;
  991. AnsiString FHandle;
  992. };
  993. //---------------------------------------------------------------------------
  994. class TSFTPDownloadQueue : public TSFTPTransferQueue
  995. {
  996. public:
  997. TSFTPDownloadQueue(TSFTPFileSystem * AFileSystem) :
  998. TSFTPTransferQueue(AFileSystem)
  999. {
  1000. }
  1001. bool __fastcall Init(int QueueLen, const AnsiString AHandle,__int64 ATransfered,
  1002. TFileOperationProgressType * AOperationProgress)
  1003. {
  1004. FHandle = AHandle;
  1005. FTransfered = ATransfered;
  1006. OperationProgress = AOperationProgress;
  1007. return TSFTPTransferQueue::Init(QueueLen);
  1008. }
  1009. void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
  1010. TSFTPPacket * Packet)
  1011. {
  1012. InitRequest(Packet, Offset, Missing);
  1013. }
  1014. bool __fastcall ReceivePacket(TSFTPPacket * Packet, unsigned long & BlockSize)
  1015. {
  1016. void * Token;
  1017. bool Result = TSFTPTransferQueue::ReceivePacket(Packet, SSH_FXP_DATA, asEOF, &Token);
  1018. BlockSize = reinterpret_cast<unsigned long>(Token);
  1019. return Result;
  1020. }
  1021. protected:
  1022. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1023. {
  1024. unsigned int BlockSize = FFileSystem->DownloadBlockSize(OperationProgress);
  1025. InitRequest(Request, FTransfered, BlockSize);
  1026. Request->Token = reinterpret_cast<void*>(BlockSize);
  1027. FTransfered += BlockSize;
  1028. return true;
  1029. }
  1030. void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
  1031. unsigned long Size)
  1032. {
  1033. Request->ChangeType(SSH_FXP_READ);
  1034. Request->AddString(FHandle);
  1035. Request->AddInt64(Offset);
  1036. Request->AddCardinal(Size);
  1037. }
  1038. virtual bool __fastcall End(TSFTPPacket * Response)
  1039. {
  1040. return (Response->Type != SSH_FXP_DATA);
  1041. }
  1042. private:
  1043. TFileOperationProgressType * OperationProgress;
  1044. };
  1045. //---------------------------------------------------------------------------
  1046. class TSFTPUploadQueue : public TSFTPTransferQueue
  1047. {
  1048. public:
  1049. TSFTPUploadQueue(TSFTPFileSystem * AFileSystem) :
  1050. TSFTPTransferQueue(AFileSystem)
  1051. {
  1052. FFile = NULL;
  1053. OperationProgress = NULL;
  1054. FLastBlockSize = 0;
  1055. FEnd = false;
  1056. }
  1057. bool __fastcall Init(int QueueLen, const AnsiString AFileName,
  1058. HANDLE AFile, TFileOperationProgressType * AOperationProgress,
  1059. const AnsiString AHandle, __int64 ATransfered)
  1060. {
  1061. FFileName = AFileName;
  1062. FFile = AFile;
  1063. OperationProgress = AOperationProgress;
  1064. FHandle = AHandle;
  1065. FTransfered = ATransfered;
  1066. return TSFTPTransferQueue::Init(QueueLen);
  1067. }
  1068. protected:
  1069. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1070. {
  1071. TTerminal * FTerminal = FFileSystem->FTerminal;
  1072. // Buffer for one block of data
  1073. TFileBuffer BlockBuf;
  1074. unsigned long BlockSize = GetBlockSize();
  1075. bool Result = (BlockSize > 0);
  1076. if (Result)
  1077. {
  1078. FILE_OPERATION_LOOP(FMTLOAD(READ_ERROR, (FFileName)),
  1079. BlockBuf.LoadFile(FFile, BlockSize, false);
  1080. );
  1081. FEnd = (BlockBuf.Size == 0);
  1082. Result = !FEnd;
  1083. if (Result)
  1084. {
  1085. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1086. // We do ASCII transfer: convert EOL of current block
  1087. if (OperationProgress->AsciiTransfer)
  1088. {
  1089. __int64 PrevBufSize = BlockBuf.Size;
  1090. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1091. FFileSystem->GetEOL(), cpRemoveCtrlZ);
  1092. // update transfer size with difference arised from EOL conversion
  1093. OperationProgress->ChangeTransferSize(OperationProgress->TransferSize -
  1094. PrevBufSize + BlockBuf.Size);
  1095. }
  1096. Request->ChangeType(SSH_FXP_WRITE);
  1097. Request->AddString(FHandle);
  1098. Request->AddInt64(FTransfered);
  1099. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  1100. FLastBlockSize = BlockBuf.Size;
  1101. FTransfered += BlockBuf.Size;
  1102. }
  1103. }
  1104. return Result;
  1105. }
  1106. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1107. {
  1108. TSFTPTransferQueue::SendPacket(Packet);
  1109. OperationProgress->AddTransfered(FLastBlockSize);
  1110. }
  1111. inline int __fastcall GetBlockSize()
  1112. {
  1113. return FFileSystem->UploadBlockSize(FHandle, OperationProgress);
  1114. }
  1115. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1116. {
  1117. return FEnd;
  1118. }
  1119. private:
  1120. HANDLE FFile;
  1121. TFileOperationProgressType * OperationProgress;
  1122. AnsiString FFileName;
  1123. unsigned long FLastBlockSize;
  1124. bool FEnd;
  1125. };
  1126. //---------------------------------------------------------------------------
  1127. #pragma warn .inl
  1128. //---------------------------------------------------------------------------
  1129. class TSFTPBusy
  1130. {
  1131. public:
  1132. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  1133. {
  1134. FFileSystem = FileSystem;
  1135. assert(FFileSystem != NULL);
  1136. FFileSystem->BusyStart();
  1137. }
  1138. __fastcall ~TSFTPBusy()
  1139. {
  1140. FFileSystem->BusyEnd();
  1141. }
  1142. private:
  1143. TSFTPFileSystem * FFileSystem;
  1144. };
  1145. //===========================================================================
  1146. struct TOpenRemoteFileParams
  1147. {
  1148. int LocalFileAttrs;
  1149. AnsiString RemoteFileName;
  1150. TFileOperationProgressType * OperationProgress;
  1151. const TCopyParamType * CopyParam;
  1152. int Params;
  1153. bool Resume;
  1154. TSFTPOverwriteMode OverwriteMode;
  1155. __int64 DestFileSize; // output
  1156. AnsiString RemoteFileHandle; // output
  1157. TOverwriteFileParams * FileParams;
  1158. bool Confirmed;
  1159. };
  1160. //---------------------------------------------------------------------------
  1161. struct TSinkFileParams
  1162. {
  1163. AnsiString TargetDir;
  1164. const TCopyParamType * CopyParam;
  1165. int Params;
  1166. TFileOperationProgressType * OperationProgress;
  1167. bool Skipped;
  1168. unsigned int Flags;
  1169. };
  1170. //===========================================================================
  1171. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal):
  1172. TCustomFileSystem(ATerminal)
  1173. {
  1174. FPacketReservations = new TList();
  1175. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varInteger);
  1176. FPreviousLoggedPacket = 0;
  1177. FNotLoggedPackets = 0;
  1178. FBusy = 0;
  1179. FAvoidBusy = false;
  1180. FUtfStrings = false;
  1181. FUtfNever = false;
  1182. FSignedTS = false;
  1183. FSupport = new TSFTPSupport();
  1184. FSupport->Extensions = new TStringList();
  1185. FExtensions = new TStringList();
  1186. FFixedPaths = NULL;
  1187. }
  1188. //---------------------------------------------------------------------------
  1189. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  1190. {
  1191. delete FSupport->Extensions;
  1192. delete FSupport;
  1193. // there must be no valid packet reservation at the end
  1194. for (int i = 0; i < FPacketReservations->Count; i++)
  1195. {
  1196. assert(FPacketReservations->Items[i] == NULL);
  1197. }
  1198. delete FPacketReservations;
  1199. delete FExtensions;
  1200. delete FFixedPaths;
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. AnsiString __fastcall TSFTPFileSystem::GetProtocolName() const
  1204. {
  1205. return FMTLOAD(SFTP_PROTOCOL_NAME, (FVersion));
  1206. }
  1207. //---------------------------------------------------------------------------
  1208. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  1209. {
  1210. assert(FTerminal);
  1211. switch (Capability) {
  1212. case fcAnyCommand:
  1213. case fcHardLink:
  1214. case fcRemoteCopy:
  1215. return false;
  1216. case fcModeChanging:
  1217. case fcNewerOnlyUpload:
  1218. case fcTimestampChanging:
  1219. return true;
  1220. case fcRename:
  1221. case fcRemoteMove:
  1222. return (FVersion >= 2);
  1223. case fcSymbolicLink:
  1224. case fcResolveSymlink:
  1225. return (FVersion >= 3);
  1226. case fcOwnerChanging:
  1227. case fcGroupChanging:
  1228. case fcNativeTextMode:
  1229. return (FVersion >= 4);
  1230. case fcTextMode:
  1231. return (FVersion >= 4) ||
  1232. strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
  1233. case fcUserGroupListing:
  1234. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1235. default:
  1236. assert(false);
  1237. return false;
  1238. }
  1239. }
  1240. //---------------------------------------------------------------------------
  1241. bool __fastcall TSFTPFileSystem::SupportsExtension(const AnsiString & Extension) const
  1242. {
  1243. return (FSupport->Extensions->IndexOf(Extension) >= 0);
  1244. }
  1245. //---------------------------------------------------------------------------
  1246. void __fastcall TSFTPFileSystem::KeepAlive()
  1247. {
  1248. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1249. Packet.AddPathString("/", FUtfStrings);
  1250. SendPacketAndReceiveResponse(&Packet, &Packet);
  1251. }
  1252. //---------------------------------------------------------------------------
  1253. void __fastcall TSFTPFileSystem::AdditionalInfo(TStrings * AdditionalInfo,
  1254. bool Initial)
  1255. {
  1256. if (Initial)
  1257. {
  1258. if (!IsCapable(fcRename))
  1259. {
  1260. AdditionalInfo->Add(LoadStr(FS_RENAME_NOT_SUPPORTED));
  1261. AdditionalInfo->Add("");
  1262. }
  1263. if (FExtensions->Count > 0)
  1264. {
  1265. AnsiString Name;
  1266. AnsiString Value;
  1267. AnsiString Line;
  1268. AdditionalInfo->Add(LoadStr(SFTP_EXTENSION_INFO));
  1269. for (int Index = 0; Index < FExtensions->Count; Index++)
  1270. {
  1271. AnsiString Name = FExtensions->Names[Index];
  1272. AnsiString Value = FExtensions->Values[Name];
  1273. AnsiString Line;
  1274. if (Value.IsEmpty())
  1275. {
  1276. Line = Name;
  1277. }
  1278. else
  1279. {
  1280. if (!IsDisplayableStr(Value))
  1281. {
  1282. Value = "0x" + StrToHex(Value);
  1283. }
  1284. Line = FORMAT("%s=%s", (Name, Value));
  1285. }
  1286. AdditionalInfo->Add(FORMAT(" %s", (Line)));;
  1287. }
  1288. }
  1289. else
  1290. {
  1291. AdditionalInfo->Add(LoadStr(SFTP_NO_EXTENSION_INFO));
  1292. }
  1293. }
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. struct TUnicodeEmitParams
  1297. {
  1298. WideString Buffer;
  1299. int Pos;
  1300. int Len;
  1301. };
  1302. //---------------------------------------------------------------------------
  1303. extern "C" void UnicodeEmit(void * AParams, long int Output)
  1304. {
  1305. if (Output == 0xFFFFL) // see Putty's charset\internal.h
  1306. {
  1307. throw Exception(LoadStr(DECODE_UTF_ERROR));
  1308. }
  1309. TUnicodeEmitParams * Params = (TUnicodeEmitParams *)AParams;
  1310. if (Params->Pos >= Params->Len)
  1311. {
  1312. Params->Len += 50;
  1313. Params->Buffer.SetLength(Params->Len);
  1314. }
  1315. Params->Pos++;
  1316. Params->Buffer[Params->Pos] = (wchar_t)Output;
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. AnsiString __fastcall TSFTPFileSystem::DecodeUTF(const AnsiString UTF)
  1320. {
  1321. charset_state State;
  1322. char * Str;
  1323. TUnicodeEmitParams Params;
  1324. AnsiString Result;
  1325. State.s0 = 0;
  1326. Str = UTF.c_str();
  1327. Params.Pos = 0;
  1328. Params.Len = UTF.Length();
  1329. Params.Buffer.SetLength(Params.Len);
  1330. while (*Str)
  1331. {
  1332. read_utf8(NULL, (unsigned char)*Str, &State, UnicodeEmit, &Params);
  1333. Str++;
  1334. }
  1335. Params.Buffer.SetLength(Params.Pos);
  1336. return Params.Buffer;
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. struct TUnicodeEmitParams2
  1340. {
  1341. AnsiString Buffer;
  1342. int Pos;
  1343. int Len;
  1344. };
  1345. //---------------------------------------------------------------------------
  1346. extern "C" void UnicodeEmit2(void * AParams, long int Output)
  1347. {
  1348. if (Output == 0xFFFFL) // see Putty's charset\internal.h
  1349. {
  1350. throw Exception(LoadStr(DECODE_UTF_ERROR));
  1351. }
  1352. TUnicodeEmitParams2 * Params = (TUnicodeEmitParams2 *)AParams;
  1353. if (Params->Pos >= Params->Len)
  1354. {
  1355. Params->Len += 50;
  1356. Params->Buffer.SetLength(Params->Len);
  1357. }
  1358. Params->Pos++;
  1359. Params->Buffer[Params->Pos] = (unsigned char)Output;
  1360. }
  1361. //---------------------------------------------------------------------------
  1362. AnsiString __fastcall TSFTPFileSystem::EncodeUTF(const WideString Source)
  1363. {
  1364. charset_state State;
  1365. wchar_t * Str;
  1366. TUnicodeEmitParams2 Params;
  1367. AnsiString Result;
  1368. State.s0 = 0;
  1369. Str = Source.c_bstr();
  1370. Params.Pos = 0;
  1371. Params.Len = Source.Length();
  1372. Params.Buffer.SetLength(Params.Len);
  1373. while (*Str)
  1374. {
  1375. write_utf8(NULL, (wchar_t)*Str, &State, UnicodeEmit2, &Params);
  1376. Str++;
  1377. }
  1378. Params.Buffer.SetLength(Params.Pos);
  1379. return Params.Buffer;
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. inline void __fastcall TSFTPFileSystem::BusyStart()
  1383. {
  1384. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1385. {
  1386. Busy(true);
  1387. }
  1388. FBusy++;
  1389. assert(FBusy < 10);
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. inline void __fastcall TSFTPFileSystem::BusyEnd()
  1393. {
  1394. assert(FBusy > 0);
  1395. FBusy--;
  1396. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1397. {
  1398. Busy(false);
  1399. }
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  1403. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  1404. {
  1405. const unsigned long MinPacketSize = 4096;
  1406. // size + message number + type
  1407. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  1408. unsigned long AMaxPacketSize = FTerminal->MaxPacketSize();
  1409. unsigned long Result = OperationProgress->CPS();
  1410. if ((MaxPacketSize > 0) && (MaxPacketSize < AMaxPacketSize))
  1411. {
  1412. AMaxPacketSize = MaxPacketSize;
  1413. }
  1414. if (Result == 0)
  1415. {
  1416. Result = OperationProgress->StaticBlockSize();
  1417. }
  1418. if (Result < MinPacketSize)
  1419. {
  1420. Result = MinPacketSize;
  1421. }
  1422. if (AMaxPacketSize > 0)
  1423. {
  1424. AMaxPacketSize -= SFTPPacketOverhead + Overhead;
  1425. if (Result > AMaxPacketSize)
  1426. {
  1427. Result = AMaxPacketSize;
  1428. }
  1429. }
  1430. return Result;
  1431. }
  1432. //---------------------------------------------------------------------------
  1433. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const AnsiString & Handle,
  1434. TFileOperationProgressType * OperationProgress)
  1435. {
  1436. // handle length + offset + data size
  1437. const unsigned long UploadPacketOverhead =
  1438. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  1439. int RemainingSendBuffer = FTerminal->RemainingSendBuffer();
  1440. unsigned long Result;
  1441. if (RemainingSendBuffer <= 0)
  1442. {
  1443. Result = 0;
  1444. }
  1445. else
  1446. {
  1447. Result = TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress,
  1448. RemainingSendBuffer);
  1449. }
  1450. return Result;
  1451. }
  1452. //---------------------------------------------------------------------------
  1453. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  1454. TFileOperationProgressType * OperationProgress)
  1455. {
  1456. return TransferBlockSize(sizeof(unsigned long), OperationProgress);
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  1460. {
  1461. BusyStart();
  1462. try
  1463. {
  1464. if (FTerminal->IsLogging())
  1465. {
  1466. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1467. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1468. (Packet->Type != FPreviousLoggedPacket) ||
  1469. (FTerminal->Configuration->LogProtocol >= 1))
  1470. {
  1471. if (FNotLoggedPackets)
  1472. {
  1473. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1474. (FNotLoggedPackets)));
  1475. FNotLoggedPackets = 0;
  1476. }
  1477. FTerminal->Log->Add(llInput, FORMAT("Type: %s, Size: %d, Number: %d",
  1478. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1479. if (FTerminal->Configuration->LogProtocol >= 2)
  1480. {
  1481. FTerminal->Log->Add(llInput, Packet->Dump());
  1482. }
  1483. FPreviousLoggedPacket = Packet->Type;
  1484. }
  1485. else
  1486. {
  1487. FNotLoggedPackets++;
  1488. }
  1489. }
  1490. FTerminal->Send(Packet->SendData, Packet->SendLength);
  1491. }
  1492. __finally
  1493. {
  1494. BusyEnd();
  1495. }
  1496. }
  1497. //---------------------------------------------------------------------------
  1498. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  1499. int AllowStatus)
  1500. {
  1501. unsigned long Code = Packet->GetCardinal();
  1502. static int Messages[] = {
  1503. SFTP_STATUS_OK,
  1504. SFTP_STATUS_EOF,
  1505. SFTP_STATUS_NO_SUCH_FILE,
  1506. SFTP_STATUS_PERMISSION_DENIED,
  1507. SFTP_STATUS_FAILURE,
  1508. SFTP_STATUS_BAD_MESSAGE,
  1509. SFTP_STATUS_NO_CONNECTION,
  1510. SFTP_STATUS_CONNECTION_LOST,
  1511. SFTP_STATUS_OP_UNSUPPORTED,
  1512. SFTP_STATUS_INVALID_HANDLE,
  1513. SFTP_STATUS_NO_SUCH_PATH,
  1514. SFTP_STATUS_FILE_ALREADY_EXISTS,
  1515. SFTP_STATUS_WRITE_PROTECT,
  1516. SFTP_STATUS_NO_MEDIA,
  1517. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  1518. SFTP_STATUS_QUOTA_EXCEEDED,
  1519. SFTP_STATUS_UNKNOWN_PRINCIPLE
  1520. };
  1521. int Message;
  1522. if ((AllowStatus & (0x01 << Code)) == 0)
  1523. {
  1524. if (Code >= sizeof(Messages) / sizeof(*Messages))
  1525. {
  1526. Message = SFTP_STATUS_UNKNOWN;
  1527. }
  1528. else
  1529. {
  1530. Message = Messages[Code];
  1531. }
  1532. AnsiString ServerMessage;
  1533. AnsiString LanguageTag;
  1534. AnsiString AdditionalInfo;
  1535. if (FVersion >= 3)
  1536. {
  1537. // message is in UTF only since SFTP specification 01 (specification 00
  1538. // is also version 3)
  1539. // (in other words, always use UTF unless server is know to be buggy)
  1540. ServerMessage = Packet->GetString(!FUtfNever);
  1541. LanguageTag = Packet->GetString();
  1542. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPLE))
  1543. {
  1544. while (Packet->GetNextData() != NULL)
  1545. {
  1546. if (!AdditionalInfo.IsEmpty())
  1547. {
  1548. AdditionalInfo += ", ";
  1549. }
  1550. AdditionalInfo += Packet->GetString();
  1551. }
  1552. }
  1553. }
  1554. else
  1555. {
  1556. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  1557. }
  1558. if (FTerminal->IsLogging())
  1559. {
  1560. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d, Message: %d, Server: %s, Language: %s ",
  1561. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  1562. }
  1563. if (!LanguageTag.IsEmpty())
  1564. {
  1565. LanguageTag = FORMAT("(%s)", (LanguageTag));
  1566. }
  1567. AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT, (LoadStr(Message) + AdditionalInfo,
  1568. int(Code), ServerMessage, LanguageTag, int(Packet->RequestType)));
  1569. FTerminal->TerminalError(NULL, Error);
  1570. return 0;
  1571. }
  1572. else
  1573. {
  1574. if (!FNotLoggedPackets || Code)
  1575. {
  1576. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d", ((int)Code)));
  1577. }
  1578. return Code;
  1579. }
  1580. }
  1581. //---------------------------------------------------------------------------
  1582. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  1583. {
  1584. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  1585. {
  1586. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  1587. }
  1588. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  1589. if (Packet)
  1590. {
  1591. assert(Packet->ReservedBy == this);
  1592. Packet->ReservedBy = NULL;
  1593. }
  1594. FPacketReservations->Delete(Reservation);
  1595. }
  1596. //---------------------------------------------------------------------------
  1597. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  1598. int ExpectedType, int AllowStatus)
  1599. {
  1600. TSFTPBusy Busy(this);
  1601. int Result = SSH_FX_OK;
  1602. int Reservation = FPacketReservations->IndexOf(Packet);
  1603. if (Reservation < 0 || Packet->Capacity == 0)
  1604. {
  1605. bool IsReserved;
  1606. do
  1607. {
  1608. IsReserved = false;
  1609. assert(Packet);
  1610. char LenBuf[5];
  1611. LenBuf[sizeof(LenBuf) - 1] = '\0';
  1612. FTerminal->Receive(LenBuf, sizeof(LenBuf) - 1);
  1613. int Length = GET_32BIT(LenBuf);
  1614. if (Length > SFTP_MAX_PACKET_LEN)
  1615. {
  1616. AnsiString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  1617. int(Length), SFTP_MAX_PACKET_LEN));
  1618. if (ExpectedType == SSH_FXP_VERSION)
  1619. {
  1620. AnsiString LenString = LenBuf;
  1621. if (!IsDisplayableStr(LenString))
  1622. {
  1623. LenString = "0x" + StrToHex(LenString);
  1624. }
  1625. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  1626. (Message, LenString));
  1627. }
  1628. FTerminal->FatalError(Message);
  1629. }
  1630. Packet->Capacity = Length;
  1631. FTerminal->Receive(Packet->Data, Length);
  1632. Packet->DataUpdated(Length);
  1633. if (FTerminal->IsLogging())
  1634. {
  1635. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1636. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1637. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  1638. (FTerminal->Configuration->LogProtocol >= 1))
  1639. {
  1640. if (FNotLoggedPackets)
  1641. {
  1642. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1643. (FNotLoggedPackets)));
  1644. FNotLoggedPackets = 0;
  1645. }
  1646. FTerminal->Log->Add(llOutput, FORMAT("Type: %s, Size: %d, Number: %d",
  1647. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1648. if (FTerminal->Configuration->LogProtocol >= 2)
  1649. {
  1650. FTerminal->Log->Add(llOutput, Packet->Dump());
  1651. }
  1652. }
  1653. else
  1654. {
  1655. FNotLoggedPackets++;
  1656. }
  1657. }
  1658. if (Reservation < 0 ||
  1659. Packet->MessageNumber != (unsigned long)FPacketNumbers.GetElement(Reservation))
  1660. {
  1661. TSFTPPacket * ReservedPacket;
  1662. unsigned long MessageNumber;
  1663. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  1664. {
  1665. MessageNumber = FPacketNumbers.GetElement(Index);
  1666. if (MessageNumber == Packet->MessageNumber)
  1667. {
  1668. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  1669. IsReserved = true;
  1670. if (ReservedPacket)
  1671. {
  1672. FTerminal->LogEvent("Storing reserved response");
  1673. *ReservedPacket = *Packet;
  1674. }
  1675. else
  1676. {
  1677. FTerminal->LogEvent("Discarding reserved response");
  1678. RemoveReservation(Index);
  1679. }
  1680. break;
  1681. }
  1682. }
  1683. }
  1684. }
  1685. while (IsReserved);
  1686. }
  1687. // before we removed the reservation after check for packet type,
  1688. // but if it raises exception, removal is unnecessarily
  1689. // postponed until the packet is removed
  1690. // (and it have not worked anyway until recent fix to UnreserveResponse)
  1691. if (Reservation >= 0)
  1692. {
  1693. // order might have changed, when reserved, but no longer needed packet
  1694. // was received in above loop
  1695. Reservation = FPacketReservations->IndexOf(Packet);
  1696. assert(Reservation >= 0);
  1697. assert(Packet->MessageNumber == (unsigned long)FPacketNumbers.GetElement(Reservation));
  1698. RemoveReservation(Reservation);
  1699. }
  1700. if (ExpectedType >= 0)
  1701. {
  1702. if (Packet->Type == SSH_FXP_STATUS)
  1703. {
  1704. if (AllowStatus < 0)
  1705. {
  1706. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  1707. }
  1708. Result = GotStatusPacket(Packet, AllowStatus);
  1709. }
  1710. else if (ExpectedType != Packet->Type)
  1711. {
  1712. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  1713. }
  1714. }
  1715. return Result;
  1716. }
  1717. //---------------------------------------------------------------------------
  1718. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  1719. TSFTPPacket * Response)
  1720. {
  1721. if (Response != NULL)
  1722. {
  1723. assert(FPacketReservations->IndexOf(Response) < 0);
  1724. // mark response as not received yet
  1725. Response->Capacity = 0;
  1726. Response->ReservedBy = this;
  1727. }
  1728. FPacketReservations->Add(Response);
  1729. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  1730. {
  1731. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  1732. }
  1733. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  1737. {
  1738. int Reservation = FPacketReservations->IndexOf(Response);
  1739. if (Response->Capacity != 0)
  1740. {
  1741. // added check for already received packet
  1742. // (it happens when the reserved response is received out of order,
  1743. // unexpectedly soon, and then receivepacket() on the packet
  1744. // is not actually called, due to exception)
  1745. RemoveReservation(Reservation);
  1746. }
  1747. else
  1748. {
  1749. if (Reservation >= 0)
  1750. {
  1751. // we probably do not remove the item at all, because
  1752. // we must remember that the respose was expected, so we skip it
  1753. // in receivepacket()
  1754. FPacketReservations->Items[Reservation] = NULL;
  1755. }
  1756. }
  1757. }
  1758. //---------------------------------------------------------------------------
  1759. int __fastcall TSFTPFileSystem::ReceiveResponse(
  1760. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1761. int AllowStatus)
  1762. {
  1763. int Result;
  1764. unsigned int MessageNumber = Packet->MessageNumber;
  1765. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  1766. try
  1767. {
  1768. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus);
  1769. if (MessageNumber != AResponse->MessageNumber)
  1770. {
  1771. FTerminal->FatalError(FMTLOAD(SFTP_MESSAGE_NUMBER,
  1772. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  1773. }
  1774. }
  1775. __finally
  1776. {
  1777. if (!Response) delete AResponse;
  1778. }
  1779. return Result;
  1780. }
  1781. //---------------------------------------------------------------------------
  1782. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  1783. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1784. int AllowStatus)
  1785. {
  1786. int Result;
  1787. TSFTPBusy Busy(this);
  1788. SendPacket(Packet);
  1789. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  1790. return Result;
  1791. }
  1792. //---------------------------------------------------------------------------
  1793. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
  1794. {
  1795. try
  1796. {
  1797. FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
  1798. (Path)));
  1799. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1800. Packet.AddPathString(Path, FUtfStrings);
  1801. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  1802. if (Packet.GetCardinal() != 1)
  1803. {
  1804. FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  1805. }
  1806. AnsiString RealDir = Packet.GetPathString(FUtfStrings);
  1807. // ignore rest of SSH_FXP_NAME packet
  1808. FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
  1809. return RealDir;
  1810. }
  1811. catch(Exception & E)
  1812. {
  1813. if (FTerminal->Active)
  1814. {
  1815. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  1816. }
  1817. else
  1818. {
  1819. throw;
  1820. }
  1821. }
  1822. }
  1823. //---------------------------------------------------------------------------
  1824. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
  1825. const AnsiString BaseDir)
  1826. {
  1827. AnsiString APath;
  1828. if (TTerminal::IsAbsolutePath(Path))
  1829. {
  1830. APath = Path;
  1831. }
  1832. else
  1833. {
  1834. if (!Path.IsEmpty())
  1835. {
  1836. // this condition/block was outside (before) current block
  1837. // but it dod not work when Path was empty
  1838. if (!BaseDir.IsEmpty())
  1839. {
  1840. APath = UnixIncludeTrailingBackslash(BaseDir);
  1841. }
  1842. APath = APath + Path;
  1843. }
  1844. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
  1845. }
  1846. return RealPath(APath);
  1847. }
  1848. //---------------------------------------------------------------------------
  1849. AnsiString __fastcall TSFTPFileSystem::LocalCanonify(const AnsiString & Path)
  1850. {
  1851. // TODO: improve (handle .. etc.)
  1852. if (TTerminal::IsAbsolutePath(Path)) return Path;
  1853. else
  1854. {
  1855. return UnixIncludeTrailingBackslash(FCurrentDirectory) + Path;
  1856. }
  1857. }
  1858. //---------------------------------------------------------------------------
  1859. AnsiString __fastcall TSFTPFileSystem::Canonify(AnsiString Path)
  1860. {
  1861. // inspired by canonify() from PSFTP.C
  1862. AnsiString Result;
  1863. FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
  1864. Path = LocalCanonify(Path);
  1865. bool TryParent = false;
  1866. try
  1867. {
  1868. Result = RealPath(Path);
  1869. }
  1870. catch(...)
  1871. {
  1872. if (FTerminal->Active)
  1873. {
  1874. TryParent = true;
  1875. }
  1876. else
  1877. {
  1878. throw;
  1879. }
  1880. }
  1881. if (TryParent)
  1882. {
  1883. AnsiString APath = UnixExcludeTrailingBackslash(Path);
  1884. AnsiString Name = UnixExtractFileName(APath);
  1885. if (Name == "." || Name == "..")
  1886. {
  1887. Result = Path;
  1888. }
  1889. else
  1890. {
  1891. AnsiString FPath = UnixExtractFilePath(APath);
  1892. try
  1893. {
  1894. Result = RealPath(FPath);
  1895. Result = UnixIncludeTrailingBackslash(Result) + Name;
  1896. }
  1897. catch(...)
  1898. {
  1899. if (FTerminal->Active)
  1900. {
  1901. Result = Path;
  1902. }
  1903. else
  1904. {
  1905. throw;
  1906. }
  1907. }
  1908. }
  1909. }
  1910. FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
  1911. return Result;
  1912. }
  1913. //---------------------------------------------------------------------------
  1914. AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path)
  1915. {
  1916. return RealPath(Path, CurrentDirectory);
  1917. }
  1918. //---------------------------------------------------------------------------
  1919. AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
  1920. {
  1921. if (FHomeDirectory.IsEmpty())
  1922. {
  1923. FHomeDirectory = RealPath(".");
  1924. }
  1925. return FHomeDirectory;
  1926. }
  1927. //---------------------------------------------------------------------------
  1928. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  1929. TRemoteFile * ALinkedByFile, const AnsiString FileName)
  1930. {
  1931. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  1932. try
  1933. {
  1934. File->Terminal = FTerminal;
  1935. if (!FileName.IsEmpty())
  1936. {
  1937. File->FileName = FileName;
  1938. }
  1939. Packet->GetFile(File, FVersion, FTerminal->SessionData->ConsiderDST, FUtfStrings, FSignedTS);
  1940. }
  1941. catch(...)
  1942. {
  1943. delete File;
  1944. throw;
  1945. }
  1946. return File;
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. void __fastcall TSFTPFileSystem::SetCurrentDirectory(AnsiString value)
  1950. {
  1951. assert(false);
  1952. }
  1953. //---------------------------------------------------------------------------
  1954. AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  1955. {
  1956. return FCurrentDirectory;
  1957. }
  1958. //---------------------------------------------------------------------------
  1959. void __fastcall TSFTPFileSystem::DoStartup()
  1960. {
  1961. TSFTPPacket Packet(SSH_FXP_INIT);
  1962. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  1963. if (MaxVersion > SFTPMaxVersion)
  1964. {
  1965. MaxVersion = SFTPMaxVersion;
  1966. }
  1967. Packet.AddCardinal(MaxVersion);
  1968. try
  1969. {
  1970. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  1971. }
  1972. catch(Exception &E)
  1973. {
  1974. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
  1975. }
  1976. FVersion = Packet.GetCardinal();
  1977. FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
  1978. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  1979. {
  1980. FTerminal->FatalError(FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  1981. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  1982. }
  1983. if (FVersion >= 3)
  1984. {
  1985. FEOL = "\r\n";
  1986. AnsiString ExtensionName;
  1987. AnsiString ExtensionData;
  1988. AnsiString ExtensionDisplayData;
  1989. while (Packet.GetNextData() != NULL)
  1990. {
  1991. ExtensionName = Packet.GetString();
  1992. ExtensionData = Packet.GetString();
  1993. ExtensionDisplayData = IsDisplayableStr(ExtensionData) ? ExtensionData :
  1994. "0x" + StrToHex(ExtensionData);
  1995. if (ExtensionName == SFTP_EXT_NEWLINE)
  1996. {
  1997. FEOL = ExtensionData;
  1998. FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
  1999. (ExtensionDisplayData)));
  2000. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2001. {
  2002. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2003. }
  2004. }
  2005. else if (ExtensionName == SFTP_EXT_SUPPORTED)
  2006. {
  2007. TSFTPPacket SupportedStruct(ExtensionData);
  2008. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2009. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2010. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2011. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2012. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2013. AnsiString Extension;
  2014. FSupport->Extensions->Clear();
  2015. while (SupportedStruct.GetNextData() != NULL)
  2016. {
  2017. Extension = SupportedStruct.GetString();
  2018. FSupport->Extensions->Add(Extension);
  2019. }
  2020. if (FTerminal->IsLogging())
  2021. {
  2022. FTerminal->LogEvent(FORMAT(
  2023. "Server support information:\n"
  2024. " Attribute mask: %s, Attribute bits: %s, Open flags: %s\n"
  2025. " Access mask: %s, Max read size: %s\n"
  2026. " Extensions (%d)\n",
  2027. (IntToHex(__int64(FSupport->AttributeMask), 4),
  2028. IntToHex(__int64(FSupport->AttributeBits), 4),
  2029. IntToHex(__int64(FSupport->OpenFlags), 4),
  2030. IntToHex(__int64(FSupport->AccessMask), 4),
  2031. IntToStr(__int64(FSupport->MaxReadSize)),
  2032. FSupport->Extensions->Count)));
  2033. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2034. {
  2035. FTerminal->LogEvent(
  2036. FORMAT(" %s", (FSupport->Extensions->Strings[Index])));
  2037. }
  2038. }
  2039. }
  2040. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2041. {
  2042. TSFTPPacket VendorIdStruct(ExtensionData);
  2043. AnsiString VendorName(VendorIdStruct.GetString());
  2044. AnsiString ProductName(VendorIdStruct.GetString());
  2045. AnsiString ProductVersion(VendorIdStruct.GetString());
  2046. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2047. FTerminal->LogEvent(FORMAT("Server software: %s %s (%d) by %s",
  2048. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2049. }
  2050. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2051. {
  2052. FTerminal->LogEvent("File system roots:\n");
  2053. assert(FFixedPaths == NULL);
  2054. FFixedPaths = new TStringList();
  2055. try
  2056. {
  2057. TSFTPPacket RootsPacket(ExtensionData);
  2058. while (RootsPacket.GetNextData() != NULL)
  2059. {
  2060. unsigned long Dummy = RootsPacket.GetCardinal();
  2061. if (Dummy != 1)
  2062. {
  2063. break;
  2064. }
  2065. else
  2066. {
  2067. char Drive = RootsPacket.GetByte();
  2068. char MaybeType = RootsPacket.GetByte();
  2069. FTerminal->LogEvent(FORMAT(" %s: (type %d)", (Drive, (int)MaybeType)));
  2070. FFixedPaths->Add(FORMAT("%s:", (Drive)));
  2071. }
  2072. }
  2073. }
  2074. catch(Exception & E)
  2075. {
  2076. FFixedPaths->Clear();
  2077. FTerminal->LogEvent(FORMAT("Failed to decode %s extension",
  2078. (SFTP_EXT_FSROOTS)));
  2079. FTerminal->HandleException(&E);
  2080. }
  2081. }
  2082. else
  2083. {
  2084. FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
  2085. (ExtensionName, ExtensionDisplayData)));
  2086. }
  2087. FExtensions->Values[ExtensionName] = ExtensionData;
  2088. }
  2089. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2090. {
  2091. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2092. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2093. Packet.AddString(FTerminal->Configuration->CompanyName);
  2094. Packet.AddString(FTerminal->Configuration->ProductName);
  2095. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2096. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2097. SendPacket(&Packet);
  2098. // we are not interested in the response, do not wait for it
  2099. ReserveResponse(&Packet, NULL);
  2100. }
  2101. }
  2102. if (FVersion < 4)
  2103. {
  2104. // currently enable the bug for all servers (really known on OpenSSH)
  2105. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2106. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2107. if (FSignedTS)
  2108. {
  2109. FTerminal->LogEvent("We believe the server has signed timestamps bug");
  2110. }
  2111. }
  2112. // use UTF when forced or ...
  2113. // when "auto" and version is at least 4 and the server is not know not to use UTF
  2114. FUtfNever = (FTerminal->SshImplementation.Pos("Foxit-WAC-Server") == 1) ||
  2115. (FTerminal->SessionData->SFTPBug[sbUtf] == asOn);
  2116. FUtfStrings =
  2117. (FTerminal->SessionData->SFTPBug[sbUtf] == asOff) ||
  2118. ((FTerminal->SessionData->SFTPBug[sbUtf] == asAuto) &&
  2119. (FVersion >= 4) && !FUtfNever);
  2120. if (FUtfStrings)
  2121. {
  2122. FTerminal->LogEvent("We will use UTF-8 strings when appropriate");
  2123. }
  2124. else if (FUtfNever)
  2125. {
  2126. FTerminal->LogEvent("We will never use UTF-8 strings");
  2127. }
  2128. else
  2129. {
  2130. FTerminal->LogEvent("We will use UTF-8 strings for status messages only");
  2131. }
  2132. }
  2133. //---------------------------------------------------------------------------
  2134. char * __fastcall TSFTPFileSystem::GetEOL() const
  2135. {
  2136. if (FVersion >= 4)
  2137. {
  2138. assert(!FEOL.IsEmpty());
  2139. return FEOL.c_str();
  2140. }
  2141. else
  2142. {
  2143. return EOLToStr(FTerminal->SessionData->EOLType);
  2144. }
  2145. }
  2146. //---------------------------------------------------------------------------
  2147. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2148. {
  2149. assert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2150. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2151. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2152. TSFTPPacket * Packet;
  2153. TUsersGroupsList * List;
  2154. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2155. TUsersGroupsList * Lists[] = { FTerminal->FUsers, FTerminal->FGroups };
  2156. char ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2157. for (int Index = 0; Index < LENOF(Packets); Index++)
  2158. {
  2159. Packet = Packets[Index];
  2160. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  2161. Packet->AddByte(ListTypes[Index]);
  2162. SendPacket(Packet);
  2163. ReserveResponse(Packet, Packet);
  2164. }
  2165. for (int Index = 0; Index < LENOF(Packets); Index++)
  2166. {
  2167. Packet = Packets[Index];
  2168. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  2169. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  2170. (Packet->GetString() != SFTP_EXT_OWNER_GROUP_REPLY))
  2171. {
  2172. FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  2173. }
  2174. else
  2175. {
  2176. List = Lists[Index];
  2177. unsigned long Count = Packet->GetCardinal();
  2178. List->BeginUpdate();
  2179. try
  2180. {
  2181. List->Clear();
  2182. for (unsigned long Item = 0; Item < Count; Item++)
  2183. {
  2184. List->Add(Packet->GetString(!FUtfNever));
  2185. }
  2186. }
  2187. __finally
  2188. {
  2189. List->EndUpdate();
  2190. }
  2191. }
  2192. }
  2193. }
  2194. //---------------------------------------------------------------------------
  2195. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  2196. {
  2197. if (!FDirectoryToChangeTo.IsEmpty())
  2198. {
  2199. FCurrentDirectory = FDirectoryToChangeTo;
  2200. FDirectoryToChangeTo = "";
  2201. }
  2202. else if (FCurrentDirectory.IsEmpty())
  2203. {
  2204. // this happens only after startup when default remote directory is not specified
  2205. FCurrentDirectory = GetHomeDirectory();
  2206. }
  2207. }
  2208. //---------------------------------------------------------------------------
  2209. void __fastcall TSFTPFileSystem::HomeDirectory()
  2210. {
  2211. ChangeDirectory(GetHomeDirectory());
  2212. }
  2213. //---------------------------------------------------------------------------
  2214. void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
  2215. {
  2216. FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
  2217. TRemoteFile * File;
  2218. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  2219. if (File == NULL)
  2220. {
  2221. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  2222. // Fallback to legacy solution, which in turn does not allow entering
  2223. // traverse-only (chmod 110) directories.
  2224. // This is workaround for http://www.ftpshell.com/
  2225. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2226. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  2227. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2228. AnsiString Handle = Packet.GetString();
  2229. Packet.ChangeType(SSH_FXP_CLOSE);
  2230. Packet.AddString(Handle);
  2231. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  2232. }
  2233. else
  2234. {
  2235. delete File;
  2236. }
  2237. }
  2238. //---------------------------------------------------------------------------
  2239. void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
  2240. {
  2241. AnsiString Path, Current;
  2242. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  2243. Path = RealPath(Directory, Current);
  2244. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  2245. // for invalid paths on some systems, like CygWin)
  2246. TryOpenDirectory(Path);
  2247. // if open dir did not fail, directory exists -> success.
  2248. FDirectoryToChangeTo = Path;
  2249. }
  2250. //---------------------------------------------------------------------------
  2251. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  2252. {
  2253. FDirectoryToChangeTo = Directory;
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  2257. {
  2258. assert(FileList && !FileList->Directory.IsEmpty());
  2259. AnsiString Directory;
  2260. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  2261. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
  2262. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  2263. // old data (e.g. parent directory) when reading fails
  2264. FileList->Clear();
  2265. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2266. AnsiString Handle;
  2267. try
  2268. {
  2269. Packet.AddPathString(Directory, FUtfStrings);
  2270. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2271. Handle = Packet.GetString();
  2272. }
  2273. catch(...)
  2274. {
  2275. if (FTerminal->Active)
  2276. {
  2277. FileList->AddFile(new TRemoteParentDirectory());
  2278. }
  2279. throw;
  2280. }
  2281. TSFTPPacket Response;
  2282. try
  2283. {
  2284. bool isEOF = false;
  2285. int Total = 0;
  2286. TRemoteFile * File;
  2287. Packet.ChangeType(SSH_FXP_READDIR);
  2288. Packet.AddString(Handle);
  2289. SendPacket(&Packet);
  2290. do
  2291. {
  2292. ReceiveResponse(&Packet, &Response);
  2293. if (Response.Type == SSH_FXP_NAME)
  2294. {
  2295. TSFTPPacket ListingPacket = Response;
  2296. Packet.ChangeType(SSH_FXP_READDIR);
  2297. Packet.AddString(Handle);
  2298. SendPacket(&Packet);
  2299. ReserveResponse(&Packet, &Response);
  2300. unsigned int Count = ListingPacket.GetCardinal();
  2301. for (unsigned long Index = 0; Index < Count; Index++)
  2302. {
  2303. File = LoadFile(&ListingPacket, NULL, "");
  2304. // security fix
  2305. // (LastDelimiter works for MBCS)
  2306. if (((File->FileName.Length() > 2) && IsDots(File->FileName)) ||
  2307. (File->FileName.LastDelimiter("/\\") > 0))
  2308. {
  2309. FTerminal->LogEvent(FORMAT("Ignored suspicious file '%s'", (File->FileName)));
  2310. delete File;
  2311. }
  2312. else
  2313. {
  2314. FileList->AddFile(File);
  2315. Total++;
  2316. }
  2317. if (Total % 10 == 0)
  2318. {
  2319. FTerminal->DoReadDirectoryProgress(Total);
  2320. }
  2321. }
  2322. if (Count == 0)
  2323. {
  2324. FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
  2325. isEOF = true;
  2326. }
  2327. }
  2328. else if (Response.Type == SSH_FXP_STATUS)
  2329. {
  2330. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  2331. }
  2332. else
  2333. {
  2334. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  2335. }
  2336. }
  2337. while (!isEOF);
  2338. if (Total == 0)
  2339. {
  2340. // Empty file list -> probably "permision denied", we
  2341. // at least get link to parent directory ("..")
  2342. try
  2343. {
  2344. FTerminal->ExceptionOnFail = true;
  2345. try
  2346. {
  2347. File = NULL;
  2348. FTerminal->ReadFile(
  2349. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  2350. }
  2351. __finally
  2352. {
  2353. FTerminal->ExceptionOnFail = false;
  2354. }
  2355. }
  2356. catch(Exception &E)
  2357. {
  2358. if (E.InheritsFrom(__classid(EFatal))) throw;
  2359. else File = NULL;
  2360. }
  2361. // on some systems even getting ".." fails, we create dummy ".." instead
  2362. bool Failure = (File == NULL);
  2363. if (Failure)
  2364. {
  2365. File = new TRemoteParentDirectory();
  2366. }
  2367. assert(File && File->IsParentDirectory);
  2368. FileList->AddFile(File);
  2369. if (Failure)
  2370. {
  2371. throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
  2372. }
  2373. }
  2374. }
  2375. __finally
  2376. {
  2377. if (FTerminal->Active)
  2378. {
  2379. Packet.ChangeType(SSH_FXP_CLOSE);
  2380. Packet.AddString(Handle);
  2381. SendPacket(&Packet);
  2382. // we are not interested in the response, do not wait for it
  2383. ReserveResponse(&Packet, NULL);
  2384. }
  2385. }
  2386. }
  2387. //---------------------------------------------------------------------------
  2388. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2389. TRemoteFile *& File)
  2390. {
  2391. assert(SymlinkFile && SymlinkFile->IsSymLink);
  2392. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2393. AnsiString FileName = LocalCanonify(SymlinkFile->FileName);
  2394. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  2395. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  2396. SendPacket(&ReadLinkPacket);
  2397. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  2398. // send second request before reading response to first one
  2399. // (performance benefit)
  2400. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  2401. AttrsPacket.AddPathString(FileName, FUtfStrings);
  2402. if (FVersion >= 4)
  2403. {
  2404. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  2405. }
  2406. SendPacket(&AttrsPacket);
  2407. ReserveResponse(&AttrsPacket, &AttrsPacket);
  2408. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  2409. if (ReadLinkPacket.GetCardinal() != 1)
  2410. {
  2411. FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2412. }
  2413. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  2414. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  2415. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  2416. File = LoadFile(&AttrsPacket, SymlinkFile,
  2417. UnixExtractFileName(SymlinkFile->LinkTo));
  2418. }
  2419. //---------------------------------------------------------------------------
  2420. void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
  2421. TRemoteFile *& File)
  2422. {
  2423. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  2424. }
  2425. //---------------------------------------------------------------------------
  2426. bool __fastcall TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
  2427. TRemoteFile ** File)
  2428. {
  2429. bool Result;
  2430. try
  2431. {
  2432. TRemoteFile * AFile;
  2433. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  2434. Result = (AFile != NULL);
  2435. if (Result)
  2436. {
  2437. if (File)
  2438. {
  2439. *File = AFile;
  2440. }
  2441. else
  2442. {
  2443. delete AFile;
  2444. }
  2445. }
  2446. }
  2447. catch(...)
  2448. {
  2449. if (!FTerminal->Active)
  2450. {
  2451. throw;
  2452. }
  2453. Result = false;
  2454. }
  2455. return Result;
  2456. }
  2457. //---------------------------------------------------------------------------
  2458. void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
  2459. TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
  2460. int AllowStatus)
  2461. {
  2462. TSFTPPacket Packet(Type);
  2463. Packet.AddPathString(LocalCanonify(FileName), FUtfStrings);
  2464. if (FVersion >= 4)
  2465. {
  2466. Packet.AddCardinal(SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  2467. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  2468. SSH_FILEXFER_ATTR_OWNERGROUP);
  2469. }
  2470. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS,
  2471. AllowStatus);
  2472. if (Packet.Type == SSH_FXP_ATTRS)
  2473. {
  2474. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  2475. }
  2476. else
  2477. {
  2478. assert(AllowStatus > 0);
  2479. File = NULL;
  2480. }
  2481. }
  2482. //---------------------------------------------------------------------------
  2483. void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
  2484. const TRemoteFile * File, bool Recursive)
  2485. {
  2486. char Type;
  2487. AnsiString RealFileName = LocalCanonify(FileName);
  2488. if (File && File->IsDirectory && !File->IsSymLink)
  2489. {
  2490. if (Recursive)
  2491. {
  2492. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Recursive);
  2493. }
  2494. Type = SSH_FXP_RMDIR;
  2495. }
  2496. else
  2497. {
  2498. Type = SSH_FXP_REMOVE;
  2499. }
  2500. TSFTPPacket Packet(Type);
  2501. Packet.AddPathString(RealFileName, FUtfStrings);
  2502. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2503. }
  2504. //---------------------------------------------------------------------------
  2505. void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
  2506. const AnsiString NewName)
  2507. {
  2508. TSFTPPacket Packet(SSH_FXP_RENAME);
  2509. AnsiString RealName = LocalCanonify(FileName);
  2510. Packet.AddPathString(RealName, FUtfStrings);
  2511. AnsiString TargetName;
  2512. if (UnixExtractFilePath(NewName).IsEmpty())
  2513. {
  2514. // rename case (TTerminal::RenameFile)
  2515. TargetName = UnixExtractFilePath(RealName) + NewName;
  2516. }
  2517. else
  2518. {
  2519. TargetName = LocalCanonify(NewName);
  2520. }
  2521. Packet.AddPathString(TargetName, FUtfStrings);
  2522. if (FVersion >= 5)
  2523. {
  2524. Packet.AddCardinal(0);
  2525. }
  2526. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. void __fastcall TSFTPFileSystem::CopyFile(const AnsiString /*FileName*/,
  2530. const AnsiString /*NewName*/)
  2531. {
  2532. assert(false);
  2533. }
  2534. //---------------------------------------------------------------------------
  2535. void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName,
  2536. const TRemoteProperties * Properties)
  2537. {
  2538. TSFTPPacket Packet(SSH_FXP_MKDIR);
  2539. AnsiString CanonifiedName = Canonify(DirName);
  2540. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2541. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings);
  2542. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2543. // explicitly set permissions after directory creation,
  2544. // permissions specified in SSH_FXP_MKDIR are ignored at least by OpenSSH
  2545. Packet.ChangeType(SSH_FXP_SETSTAT);
  2546. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2547. Packet.AddProperties(Properties, 0, true, FVersion, FUtfStrings);
  2548. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2549. }
  2550. //---------------------------------------------------------------------------
  2551. void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
  2552. const AnsiString PointTo, bool Symbolic)
  2553. {
  2554. USEDPARAM(Symbolic);
  2555. assert(Symbolic); // only symlinks are supported by SFTP
  2556. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2557. TSFTPPacket Packet(SSH_FXP_SYMLINK);
  2558. bool Buggy = (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn) ||
  2559. ((FTerminal->SessionData->SFTPBug[sbSymlink] == asAuto) &&
  2560. (FTerminal->SshImplementation.Pos("OpenSSH") == 1));
  2561. if (!Buggy)
  2562. {
  2563. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  2564. Packet.AddPathString(PointTo, FUtfStrings);
  2565. }
  2566. else
  2567. {
  2568. FTerminal->LogEvent("We believe the server has SFTP symlink bug");
  2569. Packet.AddPathString(PointTo, FUtfStrings);
  2570. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  2571. }
  2572. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2573. }
  2574. //---------------------------------------------------------------------------
  2575. void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
  2576. const TRemoteFile * /*File*/, const TRemoteProperties * Properties)
  2577. {
  2578. assert(Properties);
  2579. TRemoteFile * File;
  2580. AnsiString RealFileName = LocalCanonify(FileName);
  2581. ReadFile(RealFileName, File);
  2582. try
  2583. {
  2584. assert(File);
  2585. if (File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  2586. {
  2587. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  2588. (void*)Properties);
  2589. }
  2590. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  2591. Packet.AddPathString(RealFileName, FUtfStrings);
  2592. Packet.AddProperties(Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings);
  2593. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2594. }
  2595. __finally
  2596. {
  2597. delete File;
  2598. }
  2599. }
  2600. //---------------------------------------------------------------------------
  2601. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  2602. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  2603. TLogAddLineEvent /*OutputEvent*/)
  2604. {
  2605. assert(false);
  2606. }
  2607. //---------------------------------------------------------------------------
  2608. void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/)
  2609. {
  2610. assert(false);
  2611. }
  2612. //---------------------------------------------------------------------------
  2613. AnsiString __fastcall TSFTPFileSystem::FileUrl(const AnsiString FileName)
  2614. {
  2615. assert(FileName.Length() > 0);
  2616. return AnsiString("sftp://") + FTerminal->SessionData->SessionName +
  2617. (FileName[1] == '/' ? "" : "/") + FileName;
  2618. }
  2619. //---------------------------------------------------------------------------
  2620. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  2621. {
  2622. return FFixedPaths;
  2623. }
  2624. //---------------------------------------------------------------------------
  2625. // transfer protocol
  2626. //---------------------------------------------------------------------------
  2627. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  2628. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  2629. int Params, TFileOperationProgressType * OperationProgress,
  2630. bool & DisconnectWhenComplete)
  2631. {
  2632. assert(FilesToCopy && OperationProgress);
  2633. AnsiString FileName, FileNameOnly;
  2634. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  2635. int Index = 0;
  2636. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  2637. {
  2638. bool Success = false;
  2639. FileName = FilesToCopy->Strings[Index];
  2640. FileNameOnly = ExtractFileName(FileName);
  2641. assert(!FAvoidBusy);
  2642. FAvoidBusy = true;
  2643. try
  2644. {
  2645. try
  2646. {
  2647. if (FTerminal->SessionData->CacheDirectories)
  2648. {
  2649. FTerminal->DirectoryModified(TargetDir, false);
  2650. if (DirectoryExists(FileName))
  2651. {
  2652. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  2653. FileNameOnly, true);
  2654. }
  2655. }
  2656. SFTPSource(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  2657. tfFirstLevel);
  2658. Success = true;
  2659. }
  2660. catch(EScpSkipFile & E)
  2661. {
  2662. SUSPEND_OPERATION (
  2663. if (!FTerminal->HandleException(&E)) throw;
  2664. );
  2665. }
  2666. }
  2667. __finally
  2668. {
  2669. FAvoidBusy = false;
  2670. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  2671. }
  2672. Index++;
  2673. }
  2674. }
  2675. //---------------------------------------------------------------------------
  2676. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(const AnsiString FileName,
  2677. bool TargetBiggerThanSource, TFileOperationProgressType * OperationProgress,
  2678. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  2679. {
  2680. bool CanAlternateResume = !TargetBiggerThanSource && !OperationProgress->AsciiTransfer;
  2681. if (OperationProgress->NoToAll)
  2682. {
  2683. THROW_SKIP_FILE_NULL;
  2684. }
  2685. else if (CanAlternateResume && OperationProgress->AlternateResumeAlways)
  2686. {
  2687. OverwriteMode = omResume;
  2688. }
  2689. else
  2690. {
  2691. int Answer;
  2692. SUSPEND_OPERATION
  2693. (
  2694. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  2695. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  2696. {
  2697. Answers |= qaRetry;
  2698. }
  2699. TQueryButtonAlias Aliases[2];
  2700. Aliases[0].Button = qaRetry;
  2701. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  2702. Aliases[1].Button = qaAll;
  2703. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  2704. TQueryParams Params(qpNeverAskAgainCheck);
  2705. Params.Aliases = Aliases;
  2706. Params.AliasesCount = LENOF(Aliases);
  2707. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  2708. Answers, &Params,
  2709. OperationProgress->Side == osLocal ? osRemote : osLocal,
  2710. OperationProgress);
  2711. );
  2712. if (Answer == qaRetry)
  2713. {
  2714. if (!CanAlternateResume)
  2715. {
  2716. OverwriteMode = omAppend;
  2717. }
  2718. else
  2719. {
  2720. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  2721. SUSPEND_OPERATION
  2722. (
  2723. Answer = FTerminal->DoQueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
  2724. qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  2725. );
  2726. switch (Answer)
  2727. {
  2728. case qaYes:
  2729. OverwriteMode = omAppend;
  2730. break;
  2731. case qaNo:
  2732. OverwriteMode = omResume;
  2733. break;
  2734. case qaNoToAll:
  2735. OverwriteMode = omResume;
  2736. OperationProgress->AlternateResumeAlways = true;
  2737. break;
  2738. default: assert(false); //fallthru
  2739. case qaCancel:
  2740. if (!OperationProgress->Cancel)
  2741. {
  2742. OperationProgress->Cancel = csCancel;
  2743. }
  2744. Abort();
  2745. break;
  2746. }
  2747. }
  2748. }
  2749. else
  2750. {
  2751. OverwriteMode = omOverwrite;
  2752. switch (Answer)
  2753. {
  2754. case qaCancel:
  2755. if (!OperationProgress->Cancel)
  2756. {
  2757. OperationProgress->Cancel = csCancel;
  2758. }
  2759. Abort();
  2760. break;
  2761. case qaNo:
  2762. THROW_SKIP_FILE_NULL;
  2763. }
  2764. }
  2765. }
  2766. }
  2767. //---------------------------------------------------------------------------
  2768. bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
  2769. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  2770. {
  2771. bool ResumeTransfer;
  2772. assert(OperationProgress);
  2773. if (PartialBiggerThanSource)
  2774. {
  2775. int Answer;
  2776. SUSPEND_OPERATION
  2777. (
  2778. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  2779. Answer = FTerminal->DoQueryUser(
  2780. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)),
  2781. qaOK | qaAbort, &Params, qtWarning);
  2782. )
  2783. if (Answer == qaAbort)
  2784. {
  2785. if (!OperationProgress->Cancel)
  2786. {
  2787. OperationProgress->Cancel = csCancel;
  2788. }
  2789. Abort();
  2790. }
  2791. ResumeTransfer = false;
  2792. }
  2793. else if (FTerminal->Configuration->ConfirmResume)
  2794. {
  2795. int Answer;
  2796. SUSPEND_OPERATION
  2797. (
  2798. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  2799. HELP_RESUME_TRANSFER);
  2800. // "abort" replaced with "cancel" to unify with "append/resume" query
  2801. Answer = FTerminal->DoQueryUser(
  2802. FMTLOAD(RESUME_TRANSFER, (DestFileName)), qaYes | qaNo | qaCancel,
  2803. &Params);
  2804. );
  2805. switch (Answer) {
  2806. case qaNeverAskAgain:
  2807. FTerminal->Configuration->ConfirmResume = false;
  2808. case qaYes:
  2809. ResumeTransfer = true;
  2810. break;
  2811. case qaNo:
  2812. ResumeTransfer = false;
  2813. break;
  2814. case qaCancel:
  2815. if (!OperationProgress->Cancel)
  2816. {
  2817. OperationProgress->Cancel = csCancel;
  2818. }
  2819. Abort();
  2820. break;
  2821. }
  2822. }
  2823. else
  2824. {
  2825. ResumeTransfer = true;
  2826. }
  2827. return ResumeTransfer;
  2828. }
  2829. //---------------------------------------------------------------------------
  2830. void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
  2831. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  2832. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  2833. {
  2834. if (FLAGCLEAR(Params, cpDelete) &&
  2835. !CopyParam->AllowTransfer(FileName, osLocal))
  2836. {
  2837. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  2838. THROW_SKIP_FILE_NULL;
  2839. }
  2840. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  2841. OperationProgress->SetFile(FileName);
  2842. TOpenRemoteFileParams OpenParams;
  2843. OpenParams.OverwriteMode = omOverwrite;
  2844. HANDLE File;
  2845. __int64 MTime, ATime;
  2846. __int64 Size;
  2847. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  2848. &File, NULL, &MTime, &ATime, &Size);
  2849. if (OpenParams.LocalFileAttrs & faDirectory)
  2850. {
  2851. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  2852. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  2853. }
  2854. else
  2855. {
  2856. try
  2857. {
  2858. // File is regular file (not directory)
  2859. assert(File);
  2860. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  2861. osLocal, FLAGSET(Flags, tfFirstLevel));
  2862. AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
  2863. AnsiString DestPartinalFullName;
  2864. bool ResumeAllowed;
  2865. bool ResumeTransfer = false;
  2866. bool DestFileExists = false;
  2867. TRights DestRights;
  2868. __int64 ResumeOffset;
  2869. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  2870. OperationProgress->SetLocalSize(Size);
  2871. // Suppose same data size to transfer as to read
  2872. // (not true with ASCII transfer)
  2873. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  2874. OperationProgress->TransferingFile = false;
  2875. // Will we use ASCII of BINARY file tranfer?
  2876. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName, osLocal));
  2877. FTerminal->LogEvent(
  2878. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  2879. " transfer mode selected.");
  2880. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  2881. FLAGCLEAR(Flags, tfNewDirectory) &&
  2882. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  2883. IsCapable(fcRename);
  2884. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  2885. TOverwriteFileParams FileParams;
  2886. FileParams.SourceSize = OperationProgress->LocalSize;
  2887. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  2888. FTerminal->SessionData->ConsiderDST);
  2889. if (ResumeAllowed)
  2890. {
  2891. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  2892. FTerminal->LogEvent("Checking existence of file.");
  2893. TRemoteFile * File = new TRemoteFile();
  2894. DestFileExists = RemoteFileExists(DestFullName, &File);
  2895. if (DestFileExists)
  2896. {
  2897. OpenParams.DestFileSize = File->Size;
  2898. FileParams.DestSize = OpenParams.DestFileSize;
  2899. FileParams.DestTimestamp = File->Modification;
  2900. DestRights = *File->Rights;
  2901. delete File;
  2902. File = NULL;
  2903. }
  2904. FTerminal->LogEvent("Checking existence of partially transfered file.");
  2905. if (RemoteFileExists(DestPartinalFullName, &File))
  2906. {
  2907. ResumeOffset = File->Size;
  2908. delete File;
  2909. File = NULL;
  2910. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  2911. if (FLAGCLEAR(Params, cpNoConfirmation))
  2912. {
  2913. ResumeTransfer = SFTPConfirmResume(DestFileName,
  2914. PartialBiggerThanSource, OperationProgress);
  2915. }
  2916. else
  2917. {
  2918. ResumeTransfer = !PartialBiggerThanSource;
  2919. }
  2920. if (!ResumeTransfer)
  2921. {
  2922. DeleteFile(DestPartinalFullName);
  2923. }
  2924. else
  2925. {
  2926. FTerminal->LogEvent("Resuming file transfer.");
  2927. }
  2928. }
  2929. else
  2930. {
  2931. // partial upload file does not exists, check for full file
  2932. if (DestFileExists &&
  2933. (FLAGSET(Params, cpNewerOnly) ||
  2934. (FTerminal->Configuration->ConfirmOverwriting &&
  2935. !OperationProgress->YesToAll && FLAGCLEAR(Params, cpNoConfirmation))))
  2936. {
  2937. SFTPConfirmOverwrite(DestFileName,
  2938. OpenParams.DestFileSize >= OperationProgress->LocalSize,
  2939. OperationProgress, OpenParams.OverwriteMode, &FileParams);
  2940. }
  2941. }
  2942. }
  2943. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  2944. if (DoResume && DestFileExists)
  2945. {
  2946. FILE_OPERATION_LOOP(FMTLOAD(DELETE_BEFORE_RESUME_ERROR,
  2947. (UnixExtractFileName(DestFullName), DestFullName)),
  2948. DeleteFile(DestFullName);
  2949. );
  2950. }
  2951. OpenParams.RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
  2952. OpenParams.Resume = DoResume;
  2953. OpenParams.OperationProgress = OperationProgress;
  2954. OpenParams.CopyParam = CopyParam;
  2955. OpenParams.Params = Params;
  2956. OpenParams.FileParams = &FileParams;
  2957. OpenParams.Confirmed = false;
  2958. FTerminal->LogEvent("Opening remote file.");
  2959. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  2960. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  2961. &OpenParams);
  2962. bool TransferFinished = false;
  2963. __int64 DestWriteOffset = 0;
  2964. TSFTPPacket CloseRequest;
  2965. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  2966. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  2967. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  2968. TSFTPPacket PropertiesResponse;
  2969. if (SetProperties)
  2970. {
  2971. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  2972. unsigned short Rights = 0;
  2973. if (CopyParam->PreserveRights)
  2974. {
  2975. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  2976. }
  2977. else if (DoResume && DestFileExists)
  2978. {
  2979. Rights = DestRights.NumberSet;
  2980. }
  2981. PropertiesRequest.AddProperties(
  2982. SetRights ? &Rights : NULL, NULL, NULL,
  2983. CopyParam->PreserveTime ? &MTime : NULL,
  2984. CopyParam->PreserveTime ? &ATime : NULL,
  2985. NULL, false, FVersion, FUtfStrings);
  2986. }
  2987. try
  2988. {
  2989. if (OpenParams.OverwriteMode == omAppend)
  2990. {
  2991. FTerminal->LogEvent("Appending file.");
  2992. DestWriteOffset = OpenParams.DestFileSize;
  2993. }
  2994. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  2995. {
  2996. if (OpenParams.OverwriteMode == omResume)
  2997. {
  2998. FTerminal->LogEvent("Resuming file transfer (append style).");
  2999. ResumeOffset = OpenParams.DestFileSize;
  3000. }
  3001. FileSeek((THandle)File, ResumeOffset, 0);
  3002. OperationProgress->AddResumed(ResumeOffset);
  3003. }
  3004. // at end of this block queue is disposed
  3005. {
  3006. TSFTPUploadQueue Queue(this);
  3007. // no need to limit upload queue len by file size, the queue
  3008. // will take care of it itself
  3009. int QueueLen = FTerminal->SessionData->SFTPUploadQueue;
  3010. bool Initialized;
  3011. Initialized = Queue.Init(QueueLen, FileName, File, OperationProgress,
  3012. OpenParams.RemoteFileHandle,
  3013. DestWriteOffset + OperationProgress->TransferedSize);
  3014. if (Initialized)
  3015. {
  3016. while (Queue.Next(SSH_FXP_STATUS))
  3017. {
  3018. if (OperationProgress->Cancel)
  3019. {
  3020. Abort();
  3021. }
  3022. }
  3023. }
  3024. // send close request before waiting for pending read responses
  3025. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3026. OperationProgress, false, true, &CloseRequest);
  3027. OpenParams.RemoteFileHandle = "";
  3028. // when resuming is disabled, we can send "set properties"
  3029. // request before waiting for pending read/close responses
  3030. if (SetProperties && !DoResume)
  3031. {
  3032. SendPacket(&PropertiesRequest);
  3033. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  3034. }
  3035. }
  3036. TransferFinished = true;
  3037. }
  3038. __finally
  3039. {
  3040. if (FTerminal->Active)
  3041. {
  3042. // if file transfer was finished, the close request was already sent
  3043. if (!OpenParams.RemoteFileHandle.IsEmpty())
  3044. {
  3045. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3046. OperationProgress, TransferFinished, true, &CloseRequest);
  3047. }
  3048. // wait for the response
  3049. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3050. OperationProgress, TransferFinished, false, &CloseRequest);
  3051. // delete file if transfer was not completed and resuming is not allowed
  3052. if (!TransferFinished && !DoResume)
  3053. {
  3054. DeleteFile(OpenParams.RemoteFileName);
  3055. }
  3056. }
  3057. }
  3058. // originally this was before CLOSE (last __finally statement),
  3059. // on VShell it failed
  3060. if (DoResume)
  3061. {
  3062. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3063. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  3064. RenameFile(OpenParams.RemoteFileName, DestFileName);
  3065. );
  3066. }
  3067. if (SetProperties)
  3068. {
  3069. // when resuming is enabled, the set properties request was not sent yet
  3070. if (DoResume)
  3071. {
  3072. SendPacket(&PropertiesRequest);
  3073. }
  3074. bool Resend = false;
  3075. FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_PERM_ERROR, (DestFileName)),
  3076. TSFTPPacket DummyResponse;
  3077. TSFTPPacket * Response = &PropertiesResponse;
  3078. if (Resend)
  3079. {
  3080. PropertiesRequest.Reuse();
  3081. SendPacket(&PropertiesRequest);
  3082. // ReceiveResponse currently cannot receive twice into same packet,
  3083. // so DummyResponse is temporary workaround
  3084. Response = &DummyResponse;
  3085. }
  3086. Resend = true;
  3087. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS);
  3088. );
  3089. }
  3090. }
  3091. __finally
  3092. {
  3093. CloseHandle(File);
  3094. }
  3095. }
  3096. /* TODO : Delete also read-only files. */
  3097. /* TODO : Show error message on failure. */
  3098. if (FLAGSET(Params, cpDelete))
  3099. {
  3100. Sysutils::DeleteFile(FileName);
  3101. }
  3102. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  3103. {
  3104. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  3105. THROWIFFALSE(FileSetAttr(FileName, OpenParams.LocalFileAttrs & ~faArchive) == 0);
  3106. )
  3107. }
  3108. }
  3109. //---------------------------------------------------------------------------
  3110. AnsiString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  3111. const AnsiString & FileName, unsigned int OpenType, __int64 Size)
  3112. {
  3113. TSFTPPacket Packet(SSH_FXP_OPEN);
  3114. Packet.AddPathString(FileName, FUtfStrings);
  3115. if (FVersion < 5)
  3116. {
  3117. Packet.AddCardinal(OpenType);
  3118. }
  3119. else
  3120. {
  3121. unsigned long Access =
  3122. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  3123. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  3124. unsigned long Flags;
  3125. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  3126. {
  3127. Flags = SSH_FXF_CREATE_NEW;
  3128. }
  3129. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  3130. {
  3131. Flags = SSH_FXF_CREATE_TRUNCATE;
  3132. }
  3133. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  3134. {
  3135. Flags = SSH_FXF_OPEN_OR_CREATE;
  3136. }
  3137. else
  3138. {
  3139. Flags = SSH_FXF_OPEN_EXISTING;
  3140. }
  3141. Flags |=
  3142. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  3143. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  3144. Packet.AddCardinal(Access);
  3145. Packet.AddCardinal(Flags);
  3146. }
  3147. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  3148. Size >= 0 ? &Size : NULL, false, FVersion, FUtfStrings);
  3149. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3150. return Packet.GetString();
  3151. }
  3152. //---------------------------------------------------------------------------
  3153. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  3154. {
  3155. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  3156. assert(OpenParams);
  3157. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  3158. int OpenType;
  3159. bool Success = false;
  3160. do
  3161. {
  3162. try
  3163. {
  3164. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  3165. if (FTerminal->Configuration->ConfirmOverwriting &&
  3166. !OpenParams->Confirmed && !OperationProgress->YesToAll && !OpenParams->Resume &&
  3167. !(OpenParams->Params & cpNoConfirmation) &&
  3168. (OpenParams->OverwriteMode == omOverwrite))
  3169. {
  3170. OpenType |= SSH_FXF_EXCL;
  3171. }
  3172. if (!OpenParams->Resume && (OpenParams->OverwriteMode == omOverwrite))
  3173. {
  3174. OpenType |= SSH_FXF_TRUNC;
  3175. }
  3176. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  3177. {
  3178. OpenType |= SSH_FXF_TEXT;
  3179. }
  3180. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  3181. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  3182. Success = true;
  3183. }
  3184. catch(...)
  3185. {
  3186. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  3187. {
  3188. bool TargetBiggerThanSource;
  3189. bool ThrowOriginal = false;
  3190. // When exclusive opening of file fails, try to detect if file exists.
  3191. // When file does not exist, failure was probably caused by 'permission denied'
  3192. // or similar error. In this case throw original exception.
  3193. try
  3194. {
  3195. TRemoteFile * File;
  3196. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3197. ReadFile(RealFileName, File);
  3198. OpenParams->DestFileSize = File->Size;
  3199. if (OpenParams->FileParams != NULL)
  3200. {
  3201. OpenParams->FileParams->DestTimestamp = File->Modification;
  3202. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  3203. }
  3204. TargetBiggerThanSource = File->Size >= OperationProgress->LocalSize;
  3205. // file exists (otherwise exception was thrown)
  3206. assert(File);
  3207. SAFE_DESTROY(File);
  3208. }
  3209. catch(...)
  3210. {
  3211. if (!FTerminal->Active)
  3212. {
  3213. throw;
  3214. }
  3215. else
  3216. {
  3217. ThrowOriginal = true;
  3218. }
  3219. }
  3220. if (ThrowOriginal)
  3221. {
  3222. throw;
  3223. }
  3224. // confirmation duplicated in SFTPSource for resumable file transfers.
  3225. SFTPConfirmOverwrite(UnixExtractFileName(OpenParams->RemoteFileName),
  3226. TargetBiggerThanSource, OperationProgress, OpenParams->OverwriteMode,
  3227. OpenParams->FileParams);
  3228. OpenParams->Confirmed = true;
  3229. if (FTerminal->SessionData->OverwrittenToRecycleBin)
  3230. {
  3231. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  3232. }
  3233. }
  3234. else
  3235. {
  3236. throw;
  3237. }
  3238. }
  3239. }
  3240. while (!Success);
  3241. return 0;
  3242. }
  3243. //---------------------------------------------------------------------------
  3244. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
  3245. const AnsiString FileName, TFileOperationProgressType * OperationProgress,
  3246. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  3247. {
  3248. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  3249. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
  3250. try
  3251. {
  3252. TSFTPPacket CloseRequest;
  3253. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  3254. if (Request)
  3255. {
  3256. P->ChangeType(SSH_FXP_CLOSE);
  3257. P->AddString(Handle);
  3258. SendPacket(P);
  3259. ReserveResponse(P, Packet);
  3260. }
  3261. else
  3262. {
  3263. assert(Packet != NULL);
  3264. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  3265. }
  3266. }
  3267. catch(...)
  3268. {
  3269. if (!FTerminal->Active || TransferFinished)
  3270. {
  3271. throw;
  3272. }
  3273. }
  3274. );
  3275. }
  3276. //---------------------------------------------------------------------------
  3277. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
  3278. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  3279. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3280. {
  3281. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  3282. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  3283. FLAGSET(Flags, tfFirstLevel));
  3284. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  3285. OperationProgress->SetFile(DirectoryName);
  3286. bool CreateDir = false;
  3287. try
  3288. {
  3289. TryOpenDirectory(DestFullName);
  3290. }
  3291. catch(...)
  3292. {
  3293. if (FTerminal->Active)
  3294. {
  3295. // opening directory failed, it probably does not exists, try to
  3296. // create it
  3297. CreateDir = true;
  3298. }
  3299. else
  3300. {
  3301. throw;
  3302. }
  3303. }
  3304. if (CreateDir)
  3305. {
  3306. TRemoteProperties Properties;
  3307. if (CopyParam->PreserveRights)
  3308. {
  3309. Properties.Valid = TValidProperties() << vpRights;
  3310. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  3311. }
  3312. FTerminal->CreateDirectory(DestFullName, &Properties);
  3313. Flags |= tfNewDirectory;
  3314. }
  3315. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  3316. TSearchRec SearchRec;
  3317. bool FindOK;
  3318. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  3319. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  3320. FindAttrs, SearchRec) == 0);
  3321. );
  3322. while (FindOK && !OperationProgress->Cancel)
  3323. {
  3324. AnsiString FileName = DirectoryName + SearchRec.Name;
  3325. try
  3326. {
  3327. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  3328. {
  3329. SFTPSource(FileName, DestFullName, CopyParam, Params, OperationProgress,
  3330. Flags & ~tfFirstLevel);
  3331. }
  3332. }
  3333. catch (EScpSkipFile &E)
  3334. {
  3335. // If ESkipFile occurs, just log it and continue with next file
  3336. SUSPEND_OPERATION (
  3337. // here a message to user was displayed, which was not appropriate
  3338. // when user refused to overwrite the file in subdirectory.
  3339. // hopefuly it won't be missing in other situations.
  3340. if (!FTerminal->HandleException(&E)) throw;
  3341. );
  3342. }
  3343. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  3344. FindOK = (FindNext(SearchRec) == 0);
  3345. );
  3346. };
  3347. FindClose(SearchRec);
  3348. /* TODO : Delete also read-only directories. */
  3349. /* TODO : Show error message on failure. */
  3350. if (!OperationProgress->Cancel)
  3351. {
  3352. if (FLAGSET(Params, cpDelete))
  3353. {
  3354. RemoveDir(DirectoryName);
  3355. }
  3356. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  3357. {
  3358. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  3359. THROWIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  3360. )
  3361. }
  3362. }
  3363. }
  3364. //---------------------------------------------------------------------------
  3365. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  3366. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  3367. int Params, TFileOperationProgressType * OperationProgress,
  3368. bool & DisconnectWhenComplete)
  3369. {
  3370. assert(FilesToCopy && OperationProgress);
  3371. AnsiString FileName, FileNameOnly;
  3372. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  3373. const TRemoteFile * File;
  3374. bool Success;
  3375. int Index = 0;
  3376. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3377. {
  3378. Success = false;
  3379. FileName = FilesToCopy->Strings[Index];
  3380. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  3381. assert(!FAvoidBusy);
  3382. FAvoidBusy = true;
  3383. try
  3384. {
  3385. try
  3386. {
  3387. SFTPSink(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  3388. Params, OperationProgress, tfFirstLevel);
  3389. Success = true;
  3390. }
  3391. catch(EScpSkipFile & E)
  3392. {
  3393. SUSPEND_OPERATION (
  3394. if (!FTerminal->HandleException(&E)) throw;
  3395. );
  3396. }
  3397. catch(...)
  3398. {
  3399. throw;
  3400. }
  3401. }
  3402. __finally
  3403. {
  3404. FAvoidBusy = false;
  3405. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  3406. }
  3407. Index++;
  3408. }
  3409. }
  3410. //---------------------------------------------------------------------------
  3411. void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
  3412. const TRemoteFile * File, const AnsiString TargetDir,
  3413. const TCopyParamType * CopyParam, int Params,
  3414. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3415. {
  3416. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  3417. if (FLAGCLEAR(Params, cpDelete) &&
  3418. !CopyParam->AllowTransfer(FileName, osRemote))
  3419. {
  3420. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  3421. THROW_SKIP_FILE_NULL;
  3422. }
  3423. assert(File);
  3424. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  3425. OperationProgress->SetFile(OnlyFileName);
  3426. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  3427. osRemote, FLAGSET(Flags, tfFirstLevel));
  3428. AnsiString DestFullName = TargetDir + DestFileName;
  3429. if (File->IsDirectory)
  3430. {
  3431. if (!File->IsSymLink)
  3432. {
  3433. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  3434. int Attrs = FileGetAttr(DestFullName);
  3435. if ((Attrs & faDirectory) == 0) EXCEPTION;
  3436. );
  3437. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  3438. if (!ForceDirectories(DestFullName)) EXCEPTION;
  3439. );
  3440. TSinkFileParams SinkFileParams;
  3441. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  3442. SinkFileParams.CopyParam = CopyParam;
  3443. SinkFileParams.Params = Params;
  3444. SinkFileParams.OperationProgress = OperationProgress;
  3445. SinkFileParams.Skipped = false;
  3446. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  3447. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  3448. // Do not delete directory if some of its files were skip.
  3449. // Throw "skip file" for the directory to avoid attempt to deletion
  3450. // of any parent directory
  3451. if ((Params & cpDelete) && SinkFileParams.Skipped)
  3452. {
  3453. THROW_SKIP_FILE_NULL;
  3454. }
  3455. }
  3456. else
  3457. {
  3458. // file is symlink to directory, currently do nothing, but it should be
  3459. // reported to user
  3460. }
  3461. }
  3462. else
  3463. {
  3464. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  3465. AnsiString DestPartinalFullName;
  3466. bool ResumeAllowed;
  3467. bool ResumeTransfer = false;
  3468. __int64 ResumeOffset;
  3469. // Will we use ASCII of BINARY file tranfer?
  3470. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName, osRemote));
  3471. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  3472. " transfer mode selected.");
  3473. // Suppose same data size to transfer as to write
  3474. // (not true with ASCII transfer)
  3475. OperationProgress->SetTransferSize(File->Size);
  3476. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  3477. // resume has no sense for temporary downloads
  3478. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  3479. !OperationProgress->AsciiTransfer &&
  3480. CopyParam->AllowResume(OperationProgress->TransferSize);
  3481. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  3482. int Attrs;
  3483. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  3484. Attrs = FileGetAttr(DestFullName);
  3485. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  3486. );
  3487. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  3488. HANDLE LocalHandle = NULL;
  3489. TStream * FileStream = NULL;
  3490. bool DeleteLocalFile = false;
  3491. AnsiString RemoteHandle;
  3492. AnsiString LocalFileName = DestFullName;
  3493. try
  3494. {
  3495. if (ResumeAllowed)
  3496. {
  3497. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3498. LocalFileName = DestPartinalFullName;
  3499. FTerminal->LogEvent("Checking existence of partially transfered file.");
  3500. if (FileExists(DestPartinalFullName))
  3501. {
  3502. FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
  3503. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  3504. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  3505. if (FLAGCLEAR(Params, cpNoConfirmation))
  3506. {
  3507. ResumeTransfer = SFTPConfirmResume(DestFileName,
  3508. PartialBiggerThanSource, OperationProgress);
  3509. }
  3510. else
  3511. {
  3512. ResumeTransfer = !PartialBiggerThanSource;
  3513. }
  3514. if (!ResumeTransfer)
  3515. {
  3516. CloseHandle(LocalHandle);
  3517. LocalHandle = NULL;
  3518. Sysutils::DeleteFile(DestPartinalFullName);
  3519. }
  3520. else
  3521. {
  3522. FTerminal->LogEvent("Resuming file transfer.");
  3523. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  3524. OperationProgress->AddResumed(ResumeOffset);
  3525. }
  3526. }
  3527. }
  3528. if ((Attrs >= 0) && !ResumeTransfer &&
  3529. (FLAGSET(Params, cpNewerOnly) ||
  3530. (FTerminal->Configuration->ConfirmOverwriting &&
  3531. !OperationProgress->YesToAll &&
  3532. FLAGCLEAR(Params, cpNoConfirmation))))
  3533. {
  3534. __int64 DestFileSize;
  3535. __int64 MTime;
  3536. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  3537. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  3538. FTerminal->LogEvent("Checking existence of file.");
  3539. TSFTPOverwriteMode OverwriteMode;
  3540. TOverwriteFileParams FileParams;
  3541. FileParams.SourceSize = OperationProgress->TransferSize;
  3542. FileParams.SourceTimestamp = File->Modification;
  3543. FileParams.DestTimestamp = UnixToDateTime(MTime,
  3544. FTerminal->SessionData->ConsiderDST);
  3545. FileParams.DestSize = DestFileSize;
  3546. SFTPConfirmOverwrite(DestFileName, (DestFileSize >= OperationProgress->TransferSize),
  3547. OperationProgress, OverwriteMode, &FileParams);
  3548. if (OverwriteMode == omOverwrite)
  3549. {
  3550. // is NULL when overwritting read-only file
  3551. if (LocalHandle)
  3552. {
  3553. CloseHandle(LocalHandle);
  3554. LocalHandle = NULL;
  3555. }
  3556. }
  3557. else
  3558. {
  3559. // is NULL when overwritting read-only file, so following will
  3560. // probably fail anyway
  3561. if (LocalHandle == NULL)
  3562. {
  3563. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  3564. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  3565. }
  3566. ResumeAllowed = false;
  3567. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  3568. if (OverwriteMode == omAppend)
  3569. {
  3570. FTerminal->LogEvent("Appending to file.");
  3571. }
  3572. else
  3573. {
  3574. FTerminal->LogEvent("Resuming file transfer (append style).");
  3575. assert(OverwriteMode == omResume);
  3576. OperationProgress->AddResumed(DestFileSize);
  3577. }
  3578. }
  3579. }
  3580. // if not already opened (resume, append...), create new empty file
  3581. if (!LocalHandle)
  3582. {
  3583. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress, &LocalHandle))
  3584. {
  3585. THROW_SKIP_FILE_NULL;
  3586. }
  3587. }
  3588. assert(LocalHandle);
  3589. DeleteLocalFile = true;
  3590. FTerminal->LogEvent("Opening remote file.");
  3591. FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
  3592. int OpenType = SSH_FXF_READ;
  3593. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  3594. {
  3595. OpenType |= SSH_FXF_TEXT;
  3596. }
  3597. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  3598. );
  3599. FileStream = new THandleStream((THandle)LocalHandle);
  3600. // at end of this block queue is disposed
  3601. {
  3602. TSFTPDownloadQueue Queue(this);
  3603. TSFTPPacket DataPacket;
  3604. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  3605. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  3606. (QueueLen < 0))
  3607. {
  3608. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  3609. }
  3610. if (QueueLen < 1)
  3611. {
  3612. QueueLen = 1;
  3613. }
  3614. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferedSize,
  3615. OperationProgress);
  3616. bool Eof = false;
  3617. bool PrevIncomplete = false;
  3618. int GapFillCount = 0;
  3619. int GapCount = 0;
  3620. unsigned long Missing = 0;
  3621. unsigned long DataLen = 0;
  3622. unsigned long BlockSize;
  3623. while (!Eof)
  3624. {
  3625. if (Missing > 0)
  3626. {
  3627. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  3628. &DataPacket);
  3629. GapFillCount++;
  3630. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  3631. SSH_FXP_DATA, asEOF);
  3632. }
  3633. else
  3634. {
  3635. Queue.ReceivePacket(&DataPacket, BlockSize);
  3636. }
  3637. if (DataPacket.Type == SSH_FXP_STATUS)
  3638. {
  3639. // must be SSH_FX_EOF, any other status packet would raise exception
  3640. Eof = true;
  3641. // close file right away, before waiting for pending responses
  3642. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  3643. true, true, NULL);
  3644. RemoteHandle = ""; // do not close file again in __finally block
  3645. }
  3646. if (!Eof)
  3647. {
  3648. if ((Missing == 0) && PrevIncomplete)
  3649. {
  3650. // This can happen only if last request returned less bytes
  3651. // than expected, but exacly number of bytes missing to last
  3652. // known file size, but actually EOF was not reached.
  3653. // Can happen only when filesize has changed since directory
  3654. // listing and server returns less bytes than requested and
  3655. // file has some special file size.
  3656. FTerminal->LogEvent(FORMAT(
  3657. "Received incomplete data packet before end of file, "
  3658. "offset: %s, size: %d, requested: %d",
  3659. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  3660. int(BlockSize))));
  3661. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  3662. }
  3663. // Buffer for one block of data
  3664. TFileBuffer BlockBuf;
  3665. DataLen = DataPacket.GetCardinal();
  3666. PrevIncomplete = false;
  3667. if (Missing > 0)
  3668. {
  3669. assert(DataLen <= Missing);
  3670. Missing -= DataLen;
  3671. }
  3672. else if (DataLen < BlockSize)
  3673. {
  3674. if (OperationProgress->TransferedSize + DataLen !=
  3675. OperationProgress->TransferSize)
  3676. {
  3677. // with native text transfer mode (SFTP>=4), do not bother about
  3678. // getting less than requested, read offset is ignored anyway
  3679. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  3680. {
  3681. GapCount++;
  3682. Missing = BlockSize - DataLen;
  3683. }
  3684. }
  3685. else
  3686. {
  3687. PrevIncomplete = true;
  3688. }
  3689. }
  3690. assert(DataLen <= BlockSize);
  3691. BlockBuf.Insert(0, DataPacket.GetNextData(DataLen), DataLen);
  3692. OperationProgress->AddTransfered(DataLen);
  3693. if (OperationProgress->AsciiTransfer)
  3694. {
  3695. assert(!ResumeTransfer && !ResumeAllowed);
  3696. unsigned int PrevBlockSize = BlockBuf.Size;
  3697. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
  3698. OperationProgress->SetLocalSize(
  3699. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  3700. }
  3701. FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
  3702. try
  3703. {
  3704. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  3705. }
  3706. catch(...)
  3707. {
  3708. RaiseLastOSError();
  3709. }
  3710. );
  3711. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  3712. }
  3713. if (OperationProgress->Cancel == csCancel)
  3714. {
  3715. Abort();
  3716. }
  3717. };
  3718. if (GapCount > 0)
  3719. {
  3720. FTerminal->LogEvent(FORMAT(
  3721. "%d requests to fill %d data gaps were issued.",
  3722. (GapFillCount, GapCount)));
  3723. }
  3724. }
  3725. if (CopyParam->PreserveTime)
  3726. {
  3727. FILETIME AcTime = DateTimeToFileTime(File->LastAccess,
  3728. FTerminal->SessionData->ConsiderDST);
  3729. FILETIME WrTime = DateTimeToFileTime(File->Modification,
  3730. FTerminal->SessionData->ConsiderDST);
  3731. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  3732. }
  3733. CloseHandle(LocalHandle);
  3734. LocalHandle = NULL;
  3735. if (ResumeAllowed)
  3736. {
  3737. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3738. (ExtractFileName(DestPartinalFullName), DestFileName)),
  3739. if (FileExists(DestFullName))
  3740. {
  3741. if (!Sysutils::DeleteFile(DestFullName)) EXCEPTION;
  3742. }
  3743. if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
  3744. {
  3745. EXCEPTION;
  3746. }
  3747. );
  3748. }
  3749. DeleteLocalFile = false;
  3750. if (Attrs == -1)
  3751. {
  3752. Attrs = faArchive;
  3753. }
  3754. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  3755. if ((NewAttrs & Attrs) != NewAttrs)
  3756. {
  3757. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  3758. FileSetAttr(DestFullName, Attrs | NewAttrs);
  3759. );
  3760. }
  3761. }
  3762. __finally
  3763. {
  3764. if (LocalHandle) CloseHandle(LocalHandle);
  3765. if (FileStream) delete FileStream;
  3766. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0))
  3767. {
  3768. Sysutils::DeleteFile(LocalFileName);
  3769. }
  3770. // if the transfer was finished, the file is closed already
  3771. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  3772. {
  3773. // do not wait for response
  3774. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  3775. true, true, NULL);
  3776. }
  3777. }
  3778. }
  3779. if (Params & cpDelete)
  3780. {
  3781. // If file is directory, do not delete it recursively, because it should be
  3782. // empty already. If not, it should not be deleted (some files were
  3783. // skipped or some new files were copied to it, while we were downloading)
  3784. bool Recursive = false;
  3785. FTerminal->DeleteFile(FileName, File, &Recursive);
  3786. }
  3787. }
  3788. //---------------------------------------------------------------------------
  3789. void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
  3790. const TRemoteFile * File, void * Param)
  3791. {
  3792. TSinkFileParams * Params = (TSinkFileParams *)Param;
  3793. assert(Params->OperationProgress);
  3794. try
  3795. {
  3796. SFTPSink(FileName, File, Params->TargetDir, Params->CopyParam,
  3797. Params->Params, Params->OperationProgress, Params->Flags);
  3798. }
  3799. catch(EScpSkipFile & E)
  3800. {
  3801. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  3802. Params->Skipped = true;
  3803. SUSPEND_OPERATION (
  3804. if (!FTerminal->HandleException(&E)) throw;
  3805. );
  3806. if (OperationProgress->Cancel)
  3807. {
  3808. Abort();
  3809. }
  3810. }
  3811. }