SftpFileSystem.cpp 142 KB

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