SftpFileSystem.cpp 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SftpFileSystem.h"
  5. #include "PuttyTools.h"
  6. #include "Common.h"
  7. #include "Exceptions.h"
  8. #include "Interface.h"
  9. #include "Terminal.h"
  10. #include "TextsCore.h"
  11. #include "HelpCore.h"
  12. #include "SecureShell.h"
  13. #include "Cryptography.h"
  14. #include <WideStrUtils.hpp>
  15. #include <limits>
  16. #include <memory>
  17. //---------------------------------------------------------------------------
  18. #pragma package(smart_init)
  19. //---------------------------------------------------------------------------
  20. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  21. //---------------------------------------------------------------------------
  22. #define SSH_FX_OK 0
  23. #define SSH_FX_EOF 1
  24. #define SSH_FX_NO_SUCH_FILE 2
  25. #define SSH_FX_PERMISSION_DENIED 3
  26. #define SSH_FX_FAILURE 4
  27. #define SSH_FX_OP_UNSUPPORTED 8
  28. #define SSH_FXP_INIT 1
  29. #define SSH_FXP_VERSION 2
  30. #define SSH_FXP_OPEN 3
  31. #define SSH_FXP_CLOSE 4
  32. #define SSH_FXP_READ 5
  33. #define SSH_FXP_WRITE 6
  34. #define SSH_FXP_LSTAT 7
  35. #define SSH_FXP_FSTAT 8
  36. #define SSH_FXP_SETSTAT 9
  37. #define SSH_FXP_FSETSTAT 10
  38. #define SSH_FXP_OPENDIR 11
  39. #define SSH_FXP_READDIR 12
  40. #define SSH_FXP_REMOVE 13
  41. #define SSH_FXP_MKDIR 14
  42. #define SSH_FXP_RMDIR 15
  43. #define SSH_FXP_REALPATH 16
  44. #define SSH_FXP_STAT 17
  45. #define SSH_FXP_RENAME 18
  46. #define SSH_FXP_READLINK 19
  47. #define SSH_FXP_SYMLINK 20
  48. #define SSH_FXP_LINK 21
  49. #define SSH_FXP_STATUS 101
  50. #define SSH_FXP_HANDLE 102
  51. #define SSH_FXP_DATA 103
  52. #define SSH_FXP_NAME 104
  53. #define SSH_FXP_ATTRS 105
  54. #define SSH_FXP_EXTENDED 200
  55. #define SSH_FXP_EXTENDED_REPLY 201
  56. #define SSH_FXP_ATTRS 105
  57. #define SSH_FILEXFER_ATTR_SIZE 0x00000001
  58. #define SSH_FILEXFER_ATTR_UIDGID 0x00000002
  59. #define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004
  60. #define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008
  61. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  62. #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008
  63. #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010
  64. #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020
  65. #define SSH_FILEXFER_ATTR_ACL 0x00000040
  66. #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
  67. #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
  68. #define SSH_FILEXFER_ATTR_BITS 0x00000200
  69. #define SSH_FILEXFER_ATTR_ALLOCATION_SIZE 0x00000400
  70. #define SSH_FILEXFER_ATTR_TEXT_HINT 0x00000800
  71. #define SSH_FILEXFER_ATTR_MIME_TYPE 0x00001000
  72. #define SSH_FILEXFER_ATTR_LINK_COUNT 0x00002000
  73. #define SSH_FILEXFER_ATTR_UNTRANSLATED_NAME 0x00004000
  74. #define SSH_FILEXFER_ATTR_CTIME 0x00008000
  75. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  76. #define SSH_FILEXFER_ATTR_COMMON \
  77. (SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_OWNERGROUP | \
  78. SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACCESSTIME | \
  79. SSH_FILEXFER_ATTR_MODIFYTIME)
  80. #define SSH_FILEXFER_TYPE_REGULAR 1
  81. #define SSH_FILEXFER_TYPE_DIRECTORY 2
  82. #define SSH_FILEXFER_TYPE_SYMLINK 3
  83. #define SSH_FILEXFER_TYPE_SPECIAL 4
  84. #define SSH_FILEXFER_TYPE_UNKNOWN 5
  85. #define SSH_FXF_READ 0x00000001
  86. #define SSH_FXF_WRITE 0x00000002
  87. #define SSH_FXF_APPEND 0x00000004
  88. #define SSH_FXF_CREAT 0x00000008
  89. #define SSH_FXF_TRUNC 0x00000010
  90. #define SSH_FXF_EXCL 0x00000020
  91. #define SSH_FXF_TEXT 0x00000040
  92. #define SSH_FXF_ACCESS_DISPOSITION 0x00000007
  93. #define SSH_FXF_CREATE_NEW 0x00000000
  94. #define SSH_FXF_CREATE_TRUNCATE 0x00000001
  95. #define SSH_FXF_OPEN_EXISTING 0x00000002
  96. #define SSH_FXF_OPEN_OR_CREATE 0x00000003
  97. #define SSH_FXF_TRUNCATE_EXISTING 0x00000004
  98. #define SSH_FXF_ACCESS_APPEND_DATA 0x00000008
  99. #define SSH_FXF_ACCESS_APPEND_DATA_ATOMIC 0x00000010
  100. #define SSH_FXF_ACCESS_TEXT_MODE 0x00000020
  101. #define ACE4_READ_DATA 0x00000001
  102. #define ACE4_LIST_DIRECTORY 0x00000001
  103. #define ACE4_WRITE_DATA 0x00000002
  104. #define ACE4_ADD_FILE 0x00000002
  105. #define ACE4_APPEND_DATA 0x00000004
  106. #define ACE4_ADD_SUBDIRECTORY 0x00000004
  107. #define ACE4_READ_NAMED_ATTRS 0x00000008
  108. #define ACE4_WRITE_NAMED_ATTRS 0x00000010
  109. #define ACE4_EXECUTE 0x00000020
  110. #define ACE4_DELETE_CHILD 0x00000040
  111. #define ACE4_READ_ATTRIBUTES 0x00000080
  112. #define ACE4_WRITE_ATTRIBUTES 0x00000100
  113. #define ACE4_DELETE 0x00010000
  114. #define ACE4_READ_ACL 0x00020000
  115. #define ACE4_WRITE_ACL 0x00040000
  116. #define ACE4_WRITE_OWNER 0x00080000
  117. #define ACE4_SYNCHRONIZE 0x00100000
  118. #define SSH_FILEXFER_ATTR_FLAGS_HIDDEN 0x00000004
  119. #define SSH_FXP_REALPATH_NO_CHECK 0x00000001
  120. #define SSH_FXP_REALPATH_STAT_IF 0x00000002
  121. #define SSH_FXP_REALPATH_STAT_ALWAYS 0x00000003
  122. #define SFTP_MAX_PACKET_LEN 1024000
  123. //---------------------------------------------------------------------------
  124. #define SFTP_EXT_OWNER_GROUP "owner-group-query@generic-extensions"
  125. #define SFTP_EXT_OWNER_GROUP_REPLY "owner-group-query-reply@generic-extensions"
  126. #define SFTP_EXT_NEWLINE "newline"
  127. #define SFTP_EXT_SUPPORTED "supported"
  128. #define SFTP_EXT_SUPPORTED2 "supported2"
  129. #define SFTP_EXT_FSROOTS "[email protected]"
  130. #define SFTP_EXT_VENDOR_ID "vendor-id"
  131. #define SFTP_EXT_VERSIONS "versions"
  132. #define SFTP_EXT_SPACE_AVAILABLE "space-available"
  133. #define SFTP_EXT_CHECK_FILE "check-file"
  134. #define SFTP_EXT_CHECK_FILE_NAME "check-file-name"
  135. #define SFTP_EXT_STATVFS "[email protected]"
  136. #define SFTP_EXT_STATVFS_VALUE_V2 L"2"
  137. #define SFTP_EXT_STATVFS_ST_RDONLY 0x1
  138. #define SFTP_EXT_STATVFS_ST_NOSUID 0x2
  139. #define SFTP_EXT_HARDLINK "[email protected]"
  140. #define SFTP_EXT_HARDLINK_VALUE_V1 L"1"
  141. #define SFTP_EXT_COPY_FILE "copy-file"
  142. //---------------------------------------------------------------------------
  143. #define OGQ_LIST_OWNERS 0x01
  144. #define OGQ_LIST_GROUPS 0x02
  145. //---------------------------------------------------------------------------
  146. const int SFTPMinVersion = 0;
  147. const int SFTPMaxVersion = 6;
  148. const unsigned int SFTPNoMessageNumber = static_cast<unsigned int>(-1);
  149. const int asNo = 0;
  150. const int asOK = 1 << SSH_FX_OK;
  151. const int asEOF = 1 << SSH_FX_EOF;
  152. const int asPermDenied = 1 << SSH_FX_PERMISSION_DENIED;
  153. const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED;
  154. const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE;
  155. const int asAll = 0xFFFF;
  156. //---------------------------------------------------------------------------
  157. #define GET_32BIT(cp) \
  158. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  159. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  160. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  161. ((unsigned long)(unsigned char)(cp)[3]))
  162. #define PUT_32BIT(cp, value) { \
  163. (cp)[0] = (unsigned char)((value) >> 24); \
  164. (cp)[1] = (unsigned char)((value) >> 16); \
  165. (cp)[2] = (unsigned char)((value) >> 8); \
  166. (cp)[3] = (unsigned char)(value); }
  167. //---------------------------------------------------------------------------
  168. #define SFTP_PACKET_ALLOC_DELTA 256
  169. //---------------------------------------------------------------------------
  170. #pragma warn -inl
  171. //---------------------------------------------------------------------------
  172. struct TSFTPSupport
  173. {
  174. TSFTPSupport() :
  175. AttribExtensions(new TStringList()),
  176. Extensions(new TStringList())
  177. {
  178. Reset();
  179. }
  180. ~TSFTPSupport()
  181. {
  182. delete AttribExtensions;
  183. delete Extensions;
  184. }
  185. void Reset()
  186. {
  187. AttributeMask = 0;
  188. AttributeBits = 0;
  189. OpenFlags = 0;
  190. AccessMask = 0;
  191. MaxReadSize = 0;
  192. OpenBlockVector = 0;
  193. BlockVector = 0;
  194. AttribExtensions->Clear();
  195. Extensions->Clear();
  196. Loaded = false;
  197. }
  198. unsigned int AttributeMask;
  199. unsigned int AttributeBits;
  200. unsigned int OpenFlags;
  201. unsigned int AccessMask;
  202. unsigned int MaxReadSize;
  203. unsigned int OpenBlockVector;
  204. unsigned int BlockVector;
  205. TStrings * AttribExtensions;
  206. TStrings * Extensions;
  207. bool Loaded;
  208. };
  209. //---------------------------------------------------------------------------
  210. class TSFTPPacket
  211. {
  212. public:
  213. TSFTPPacket()
  214. {
  215. Init();
  216. }
  217. TSFTPPacket(const TSFTPPacket & Source)
  218. {
  219. Init();
  220. *this = Source;
  221. }
  222. TSFTPPacket(unsigned char AType)
  223. {
  224. Init();
  225. ChangeType(AType);
  226. }
  227. TSFTPPacket(const unsigned char * Source, unsigned int Len)
  228. {
  229. Init();
  230. FLength = Len;
  231. Capacity = FLength;
  232. memcpy(Data, Source, Len);
  233. }
  234. TSFTPPacket(const RawByteString & Source)
  235. {
  236. Init();
  237. FLength = Source.Length();
  238. Capacity = FLength;
  239. memcpy(Data, Source.c_str(), Source.Length());
  240. }
  241. ~TSFTPPacket()
  242. {
  243. if (FData != NULL)
  244. {
  245. delete[] (FData - FSendPrefixLen);
  246. }
  247. if (FReservedBy) FReservedBy->UnreserveResponse(this);
  248. }
  249. void ChangeType(unsigned char AType)
  250. {
  251. FPosition = 0;
  252. FLength = 0;
  253. Capacity = 0;
  254. FType = AType;
  255. AddByte(FType);
  256. if ((FType != 1) && (FType != SSH_FXP_INIT))
  257. {
  258. AssignNumber();
  259. AddCardinal(FMessageNumber);
  260. }
  261. }
  262. void Reuse()
  263. {
  264. AssignNumber();
  265. DebugAssert(Length >= 5);
  266. // duplicated in AddCardinal()
  267. unsigned char Buf[4];
  268. PUT_32BIT(Buf, FMessageNumber);
  269. memcpy(FData + 1, Buf, sizeof(Buf));
  270. }
  271. void AddByte(unsigned char Value)
  272. {
  273. Add(&Value, sizeof(Value));
  274. }
  275. void AddBool(bool Value)
  276. {
  277. AddByte(Value ? 1 : 0);
  278. }
  279. void AddCardinal(unsigned long Value)
  280. {
  281. // duplicated in Reuse()
  282. unsigned char Buf[4];
  283. PUT_32BIT(Buf, Value);
  284. Add(&Buf, sizeof(Buf));
  285. }
  286. void AddInt64(__int64 Value)
  287. {
  288. AddCardinal((unsigned long)(Value >> 32));
  289. AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
  290. }
  291. void AddData(const void * Data, int ALength)
  292. {
  293. AddCardinal(ALength);
  294. Add(Data, ALength);
  295. }
  296. void AddString(const RawByteString & Value)
  297. {
  298. AddCardinal(Value.Length());
  299. Add(Value.c_str(), Value.Length());
  300. }
  301. inline void AddUtfString(const UTF8String & Value)
  302. {
  303. AddString(Value);
  304. }
  305. inline void AddUtfString(const UnicodeString & Value)
  306. {
  307. AddUtfString(UTF8String(Value));
  308. }
  309. inline void AddString(const UnicodeString Value, TAutoSwitch Utf)
  310. {
  311. // asAuto: Using UTF until we receive non-UTF string from the server
  312. if ((Utf == asOn) || (Utf == asAuto))
  313. {
  314. AddUtfString(Value);
  315. }
  316. else
  317. {
  318. AddString(RawByteString(AnsiString(Value)));
  319. }
  320. }
  321. // now purposeless alias to AddString
  322. inline void AddPathString(const UnicodeString & Value, TAutoSwitch Utf)
  323. {
  324. AddString(Value, Utf);
  325. }
  326. unsigned int AllocationSizeAttribute(int Version)
  327. {
  328. return (Version >= 6) ? SSH_FILEXFER_ATTR_ALLOCATION_SIZE : SSH_FILEXFER_ATTR_SIZE;
  329. }
  330. void AddProperties(unsigned short * Rights, TRemoteToken * Owner,
  331. TRemoteToken * Group, __int64 * MTime, __int64 * ATime,
  332. __int64 * Size, bool IsDirectory, int Version, TAutoSwitch Utf)
  333. {
  334. int Flags = 0;
  335. if (Size != NULL)
  336. {
  337. Flags |= AllocationSizeAttribute(Version);
  338. }
  339. // both or neither
  340. DebugAssert((Owner != NULL) == (Group != NULL));
  341. if ((Owner != NULL) && (Group != NULL))
  342. {
  343. if (Version < 4)
  344. {
  345. DebugAssert(Owner->IDValid && Group->IDValid);
  346. Flags |= SSH_FILEXFER_ATTR_UIDGID;
  347. }
  348. else
  349. {
  350. DebugAssert(Owner->NameValid && Group->NameValid);
  351. Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
  352. }
  353. }
  354. if (Rights != NULL)
  355. {
  356. Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
  357. }
  358. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  359. {
  360. Flags |= SSH_FILEXFER_ATTR_ACMODTIME;
  361. }
  362. if ((Version >= 4) && (ATime != NULL))
  363. {
  364. Flags |= SSH_FILEXFER_ATTR_ACCESSTIME;
  365. }
  366. if ((Version >= 4) && (MTime != NULL))
  367. {
  368. Flags |= SSH_FILEXFER_ATTR_MODIFYTIME;
  369. }
  370. AddCardinal(Flags);
  371. if (Version >= 4)
  372. {
  373. AddByte(static_cast<unsigned char>(IsDirectory ?
  374. SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
  375. }
  376. if (Size != NULL)
  377. {
  378. // this is SSH_FILEXFER_ATTR_SIZE for version <= 5, but
  379. // SSH_FILEXFER_ATTR_ALLOCATION_SIZE for version >= 6
  380. AddInt64(*Size);
  381. }
  382. if ((Owner != NULL) && (Group != NULL))
  383. {
  384. if (Version < 4)
  385. {
  386. DebugAssert(Owner->IDValid && Group->IDValid);
  387. AddCardinal(Owner->ID);
  388. AddCardinal(Group->ID);
  389. }
  390. else
  391. {
  392. DebugAssert(Owner->NameValid && Group->NameValid);
  393. AddString(Owner->Name, Utf);
  394. AddString(Group->Name, Utf);
  395. }
  396. }
  397. if (Rights != NULL)
  398. {
  399. AddCardinal(*Rights);
  400. }
  401. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  402. {
  403. // any way to reflect sbSignedTS here?
  404. // (note that casting __int64 > 2^31 < 2^32 to unsigned long is wrapped,
  405. // thus we never can set time after 2038, even if the server supports it)
  406. AddCardinal(static_cast<unsigned long>(ATime != NULL ? *ATime : *MTime));
  407. AddCardinal(static_cast<unsigned long>(MTime != NULL ? *MTime : *ATime));
  408. }
  409. if ((Version >= 4) && (ATime != NULL))
  410. {
  411. AddInt64(*ATime);
  412. }
  413. if ((Version >= 4) && (MTime != NULL))
  414. {
  415. AddInt64(*MTime);
  416. }
  417. }
  418. void AddProperties(const TRemoteProperties * Properties,
  419. unsigned short BaseRights, bool IsDirectory, int Version, TAutoSwitch Utf,
  420. TChmodSessionAction * Action)
  421. {
  422. enum TValid { valNone = 0, valRights = 0x01, valOwner = 0x02, valGroup = 0x04,
  423. valMTime = 0x08, valATime = 0x10 } Valid = valNone;
  424. unsigned short RightsNum = 0;
  425. TRemoteToken Owner;
  426. TRemoteToken Group;
  427. __int64 MTime;
  428. __int64 ATime;
  429. if (Properties != NULL)
  430. {
  431. if (Properties->Valid.Contains(vpGroup))
  432. {
  433. Valid = (TValid)(Valid | valGroup);
  434. Group = Properties->Group;
  435. }
  436. if (Properties->Valid.Contains(vpOwner))
  437. {
  438. Valid = (TValid)(Valid | valOwner);
  439. Owner = Properties->Owner;
  440. }
  441. if (Properties->Valid.Contains(vpRights))
  442. {
  443. Valid = (TValid)(Valid | valRights);
  444. TRights Rights = BaseRights;
  445. Rights |= Properties->Rights.NumberSet;
  446. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  447. if (IsDirectory && Properties->AddXToDirectories)
  448. {
  449. Rights.AddExecute();
  450. }
  451. RightsNum = Rights;
  452. if (Action != NULL)
  453. {
  454. Action->Rights(Rights);
  455. }
  456. }
  457. if (Properties->Valid.Contains(vpLastAccess))
  458. {
  459. Valid = (TValid)(Valid | valATime);
  460. ATime = Properties->LastAccess;
  461. }
  462. if (Properties->Valid.Contains(vpModification))
  463. {
  464. Valid = (TValid)(Valid | valMTime);
  465. MTime = Properties->Modification;
  466. }
  467. }
  468. AddProperties(
  469. Valid & valRights ? &RightsNum : NULL,
  470. Valid & valOwner ? &Owner : NULL,
  471. Valid & valGroup ? &Group : NULL,
  472. Valid & valMTime ? &MTime : NULL,
  473. Valid & valATime ? &ATime : NULL,
  474. NULL, IsDirectory, Version, Utf);
  475. }
  476. unsigned char GetByte()
  477. {
  478. Need(sizeof(unsigned char));
  479. unsigned char Result = FData[FPosition];
  480. DataConsumed(sizeof(unsigned char));
  481. return Result;
  482. }
  483. bool GetBool()
  484. {
  485. return (GetByte() != 0);
  486. }
  487. bool CanGetBool()
  488. {
  489. return (RemainingLength >= sizeof(unsigned char));
  490. }
  491. unsigned long GetCardinal()
  492. {
  493. unsigned long Result = PeekCardinal();
  494. DataConsumed(sizeof(Result));
  495. return Result;
  496. }
  497. bool CanGetCardinal()
  498. {
  499. return (RemainingLength >= sizeof(unsigned long));
  500. }
  501. unsigned long GetSmallCardinal()
  502. {
  503. unsigned long Result;
  504. Need(2);
  505. Result = (FData[FPosition] << 8) + FData[FPosition + 1];
  506. DataConsumed(2);
  507. return Result;
  508. }
  509. bool CanGetSmallCardinal()
  510. {
  511. return (RemainingLength >= 2);
  512. }
  513. __int64 GetInt64()
  514. {
  515. __int64 Hi = GetCardinal();
  516. __int64 Lo = GetCardinal();
  517. return (Hi << 32) + Lo;
  518. }
  519. RawByteString GetRawByteString()
  520. {
  521. RawByteString Result;
  522. unsigned long Len = GetCardinal();
  523. Need(Len);
  524. // cannot happen anyway as Need() would raise exception
  525. DebugAssert(Len < SFTP_MAX_PACKET_LEN);
  526. Result.SetLength(Len);
  527. memcpy(Result.c_str(), FData + FPosition, Len);
  528. DataConsumed(Len);
  529. return Result;
  530. }
  531. bool CanGetString(unsigned int & Size)
  532. {
  533. bool Result = CanGetCardinal();
  534. if (Result)
  535. {
  536. unsigned long Len = PeekCardinal();
  537. Size = (sizeof(Len) + Len);
  538. Result = (Size <= RemainingLength);
  539. }
  540. return Result;
  541. }
  542. // For reading strings that are character strings (not byte strings as
  543. // as file handles), and SFTP spec does not say explicitly that they
  544. // are in UTF. For most of them it actually does not matter as
  545. // the content should be pure ASCII (e.g. extension names, etc.)
  546. inline UnicodeString GetAnsiString()
  547. {
  548. return AnsiToString(GetRawByteString());
  549. }
  550. inline RawByteString GetFileHandle()
  551. {
  552. return GetRawByteString();
  553. }
  554. inline UnicodeString GetString(TAutoSwitch & Utf)
  555. {
  556. if (Utf != asOff)
  557. {
  558. return GetUtfString(Utf);
  559. }
  560. else
  561. {
  562. return GetAnsiString();
  563. }
  564. }
  565. // now purposeless alias to GetString(bool)
  566. inline UnicodeString GetPathString(TAutoSwitch & Utf)
  567. {
  568. return GetString(Utf);
  569. }
  570. void GetFile(TRemoteFile * File, int Version, TDSTMode DSTMode, TAutoSwitch & Utf, bool SignedTS, bool Complete)
  571. {
  572. DebugAssert(File);
  573. unsigned int Flags;
  574. UnicodeString ListingStr;
  575. unsigned long Permissions = 0;
  576. bool ParsingFailed = false;
  577. if (Type != SSH_FXP_ATTRS)
  578. {
  579. File->FileName = GetPathString(Utf);
  580. if (Version < 4)
  581. {
  582. ListingStr = GetString(Utf);
  583. }
  584. }
  585. Flags = GetCardinal();
  586. if (Version >= 4)
  587. {
  588. unsigned char FXType = GetByte();
  589. // -:regular, D:directory, L:symlink, S:special, U:unknown
  590. // O:socket, C:char device, B:block device, F:fifo
  591. // SSH-2.0-cryptlib returns file type 0 in response to SSH_FXP_LSTAT,
  592. // handle this undefined value as "unknown"
  593. static wchar_t * Types = L"U-DLSUOCBF";
  594. if (FXType > (unsigned char)wcslen(Types))
  595. {
  596. throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
  597. }
  598. File->Type = Types[FXType];
  599. }
  600. if (Flags & SSH_FILEXFER_ATTR_SIZE)
  601. {
  602. File->Size = GetInt64();
  603. }
  604. // SFTP-6 only
  605. if (Flags & SSH_FILEXFER_ATTR_ALLOCATION_SIZE)
  606. {
  607. GetInt64(); // skip
  608. }
  609. // SSH-2.0-3.2.0 F-SECURE SSH - Process Software MultiNet
  610. // sets SSH_FILEXFER_ATTR_UIDGID for v4, but does not include the UID/GUID
  611. if ((Flags & SSH_FILEXFER_ATTR_UIDGID) && (Version < 4))
  612. {
  613. File->Owner.ID = GetCardinal();
  614. File->Group.ID = GetCardinal();
  615. }
  616. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  617. {
  618. DebugAssert(Version >= 4);
  619. File->Owner.Name = GetString(Utf);
  620. File->Group.Name = GetString(Utf);
  621. }
  622. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  623. {
  624. Permissions = GetCardinal();
  625. }
  626. if (Version < 4)
  627. {
  628. if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
  629. {
  630. File->LastAccess = UnixToDateTime(
  631. SignedTS ?
  632. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  633. static_cast<__int64>(GetCardinal()),
  634. DSTMode);
  635. File->Modification = UnixToDateTime(
  636. SignedTS ?
  637. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  638. static_cast<__int64>(GetCardinal()),
  639. DSTMode);
  640. }
  641. }
  642. else
  643. {
  644. if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
  645. {
  646. File->LastAccess = UnixToDateTime(GetInt64(), DSTMode);
  647. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  648. {
  649. GetCardinal(); // skip access time subseconds
  650. }
  651. }
  652. if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
  653. {
  654. GetInt64(); // skip create time
  655. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  656. {
  657. GetCardinal(); // skip create time subseconds
  658. }
  659. }
  660. if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
  661. {
  662. File->Modification = UnixToDateTime(GetInt64(), DSTMode);
  663. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  664. {
  665. GetCardinal(); // skip modification time subseconds
  666. }
  667. }
  668. // SFTP-6
  669. if (Flags & SSH_FILEXFER_ATTR_CTIME)
  670. {
  671. GetInt64(); // skip attribute modification time
  672. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  673. {
  674. GetCardinal(); // skip attribute modification time subseconds
  675. }
  676. }
  677. }
  678. if (Flags & SSH_FILEXFER_ATTR_ACL)
  679. {
  680. GetRawByteString();
  681. }
  682. if (Flags & SSH_FILEXFER_ATTR_BITS)
  683. {
  684. // while SSH_FILEXFER_ATTR_BITS is defined for SFTP5 only, vandyke 2.3.3 sets it
  685. // for SFTP4 as well
  686. unsigned long Bits = GetCardinal();
  687. if (Version >= 6)
  688. {
  689. unsigned long BitsValid = GetCardinal();
  690. Bits = Bits & BitsValid;
  691. }
  692. if (FLAGSET(Bits, SSH_FILEXFER_ATTR_FLAGS_HIDDEN))
  693. {
  694. File->IsHidden = true;
  695. }
  696. }
  697. // skip some SFTP-6 only fields
  698. if (Flags & SSH_FILEXFER_ATTR_TEXT_HINT)
  699. {
  700. GetByte();
  701. }
  702. if (Flags & SSH_FILEXFER_ATTR_MIME_TYPE)
  703. {
  704. GetAnsiString();
  705. }
  706. if (Flags & SSH_FILEXFER_ATTR_LINK_COUNT)
  707. {
  708. GetCardinal();
  709. }
  710. if (Flags & SSH_FILEXFER_ATTR_UNTRANSLATED_NAME)
  711. {
  712. GetPathString(Utf);
  713. }
  714. if ((Version < 4) && (Type != SSH_FXP_ATTRS))
  715. {
  716. try
  717. {
  718. // update permissions and user/group name
  719. // modification time and filename is ignored
  720. File->ListingStr = ListingStr;
  721. }
  722. catch(...)
  723. {
  724. // ignore any error while parsing listing line,
  725. // SFTP specification do not recommend to parse it
  726. ParsingFailed = true;
  727. }
  728. }
  729. if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
  730. {
  731. wchar_t Type = FILETYPE_DEFAULT;
  732. if (FLAGSET(Flags, SSH_FILEXFER_ATTR_PERMISSIONS))
  733. {
  734. File->Rights->Number = (unsigned short)(Permissions & TRights::rfAllSpecials);
  735. if (FLAGSET(Permissions, TRights::rfDirectory))
  736. {
  737. Type = FILETYPE_DIRECTORY;
  738. }
  739. }
  740. if (Version < 4)
  741. {
  742. File->Type = Type;
  743. }
  744. }
  745. if (Flags & SSH_FILEXFER_ATTR_EXTENDED)
  746. {
  747. unsigned int ExtendedCount = GetCardinal();
  748. for (unsigned int Index = 0; Index < ExtendedCount; Index++)
  749. {
  750. GetRawByteString(); // skip extended_type
  751. GetRawByteString(); // skip extended_data
  752. }
  753. }
  754. if (Complete)
  755. {
  756. File->Complete();
  757. }
  758. }
  759. unsigned char * GetNextData(unsigned int Size = 0)
  760. {
  761. if (Size > 0)
  762. {
  763. Need(Size);
  764. }
  765. return FPosition < FLength ? FData + FPosition : NULL;
  766. }
  767. void DataConsumed(unsigned int Size)
  768. {
  769. FPosition += Size;
  770. }
  771. void DataUpdated(int ALength)
  772. {
  773. FPosition = 0;
  774. FLength = ALength;
  775. FType = GetByte();
  776. if (FType != SSH_FXP_VERSION)
  777. {
  778. FMessageNumber = GetCardinal();
  779. }
  780. else
  781. {
  782. FMessageNumber = SFTPNoMessageNumber;
  783. }
  784. }
  785. void LoadFromFile(const UnicodeString FileName)
  786. {
  787. TStringList * DumpLines = new TStringList();
  788. RawByteString Dump;
  789. try
  790. {
  791. DumpLines->LoadFromFile(FileName);
  792. Dump = RawByteString(AnsiString(DumpLines->Text));
  793. }
  794. __finally
  795. {
  796. delete DumpLines;
  797. }
  798. Capacity = 20480;
  799. unsigned char Byte[3];
  800. memset(Byte, '\0', sizeof(Byte));
  801. int Index = 1;
  802. unsigned int Length = 0;
  803. while (Index < Dump.Length())
  804. {
  805. char C = Dump[Index];
  806. if (IsHex(C))
  807. {
  808. if (Byte[0] == '\0')
  809. {
  810. Byte[0] = C;
  811. }
  812. else
  813. {
  814. Byte[1] = C;
  815. DebugAssert(Length < Capacity);
  816. Data[Length] = HexToByte(UnicodeString(reinterpret_cast<char *>(Byte)));
  817. Length++;
  818. memset(Byte, '\0', sizeof(Byte));
  819. }
  820. }
  821. Index++;
  822. }
  823. DataUpdated(Length);
  824. }
  825. UnicodeString __fastcall Dump() const
  826. {
  827. UnicodeString Result;
  828. for (unsigned int Index = 0; Index < Length; Index++)
  829. {
  830. Result += ByteToHex(Data[Index]) + L",";
  831. if (((Index + 1) % 25) == 0)
  832. {
  833. Result += L"\n";
  834. }
  835. }
  836. return Result;
  837. }
  838. TSFTPPacket & operator = (const TSFTPPacket & Source)
  839. {
  840. Capacity = 0;
  841. Add(Source.Data, Source.Length);
  842. DataUpdated(Source.Length);
  843. FPosition = Source.FPosition;
  844. return *this;
  845. }
  846. __property unsigned int Length = { read = FLength };
  847. __property unsigned int RemainingLength = { read = GetRemainingLength };
  848. __property unsigned char * Data = { read = FData };
  849. __property unsigned char * SendData = { read = GetSendData };
  850. __property unsigned int SendLength = { read = GetSendLength };
  851. __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
  852. __property unsigned char Type = { read = FType };
  853. __property unsigned char RequestType = { read = GetRequestType };
  854. __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
  855. __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
  856. __property UnicodeString TypeName = { read = GetTypeName };
  857. private:
  858. unsigned char * FData;
  859. unsigned int FLength;
  860. unsigned int FCapacity;
  861. unsigned int FPosition;
  862. unsigned char FType;
  863. unsigned int FMessageNumber;
  864. TSFTPFileSystem * FReservedBy;
  865. static int FMessageCounter;
  866. static const FSendPrefixLen = 4;
  867. void Init()
  868. {
  869. FData = NULL;
  870. FCapacity = 0;
  871. FLength = 0;
  872. FPosition = 0;
  873. FMessageNumber = SFTPNoMessageNumber;
  874. FType = -1;
  875. FReservedBy = NULL;
  876. }
  877. void AssignNumber()
  878. {
  879. // this is not strictly thread-safe, but as it is accessed from multiple
  880. // threads only for multiple connection, it is not problem if two threads get
  881. // the same number
  882. FMessageNumber = (FMessageCounter << 8) + FType;
  883. FMessageCounter++;
  884. }
  885. unsigned char GetRequestType()
  886. {
  887. if (FMessageNumber != SFTPNoMessageNumber)
  888. {
  889. return (unsigned char)(FMessageNumber & 0xFF);
  890. }
  891. else
  892. {
  893. DebugAssert(Type == SSH_FXP_VERSION);
  894. return SSH_FXP_INIT;
  895. }
  896. }
  897. inline void Add(const void * AData, int ALength)
  898. {
  899. if (Length + ALength > Capacity)
  900. {
  901. Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
  902. }
  903. memcpy(FData + Length, AData, ALength);
  904. FLength += ALength;
  905. }
  906. void SetCapacity(unsigned int ACapacity)
  907. {
  908. if (ACapacity != Capacity)
  909. {
  910. FCapacity = ACapacity;
  911. if (FCapacity > 0)
  912. {
  913. unsigned char * NData = (new unsigned char[FCapacity + FSendPrefixLen]) + FSendPrefixLen;
  914. if (FData)
  915. {
  916. memcpy(NData - FSendPrefixLen, FData - FSendPrefixLen,
  917. (FLength < FCapacity ? FLength : FCapacity) + FSendPrefixLen);
  918. delete[] (FData - FSendPrefixLen);
  919. }
  920. FData = NData;
  921. }
  922. else
  923. {
  924. if (FData) delete[] (FData - FSendPrefixLen);
  925. FData = NULL;
  926. }
  927. if (FLength > FCapacity) FLength = FCapacity;
  928. }
  929. }
  930. UnicodeString GetTypeName() const
  931. {
  932. #define TYPE_CASE(TYPE) case TYPE: return TEXT(#TYPE)
  933. switch (Type) {
  934. TYPE_CASE(SSH_FXP_INIT);
  935. TYPE_CASE(SSH_FXP_VERSION);
  936. TYPE_CASE(SSH_FXP_OPEN);
  937. TYPE_CASE(SSH_FXP_CLOSE);
  938. TYPE_CASE(SSH_FXP_READ);
  939. TYPE_CASE(SSH_FXP_WRITE);
  940. TYPE_CASE(SSH_FXP_LSTAT);
  941. TYPE_CASE(SSH_FXP_FSTAT);
  942. TYPE_CASE(SSH_FXP_SETSTAT);
  943. TYPE_CASE(SSH_FXP_FSETSTAT);
  944. TYPE_CASE(SSH_FXP_OPENDIR);
  945. TYPE_CASE(SSH_FXP_READDIR);
  946. TYPE_CASE(SSH_FXP_REMOVE);
  947. TYPE_CASE(SSH_FXP_MKDIR);
  948. TYPE_CASE(SSH_FXP_RMDIR);
  949. TYPE_CASE(SSH_FXP_REALPATH);
  950. TYPE_CASE(SSH_FXP_STAT);
  951. TYPE_CASE(SSH_FXP_RENAME);
  952. TYPE_CASE(SSH_FXP_READLINK);
  953. TYPE_CASE(SSH_FXP_SYMLINK);
  954. TYPE_CASE(SSH_FXP_LINK);
  955. TYPE_CASE(SSH_FXP_STATUS);
  956. TYPE_CASE(SSH_FXP_HANDLE);
  957. TYPE_CASE(SSH_FXP_DATA);
  958. TYPE_CASE(SSH_FXP_NAME);
  959. TYPE_CASE(SSH_FXP_ATTRS);
  960. TYPE_CASE(SSH_FXP_EXTENDED);
  961. TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
  962. default:
  963. return FORMAT(L"Unknown message (%d)", (int(Type)));
  964. }
  965. }
  966. unsigned char * GetSendData() const
  967. {
  968. unsigned char * Result = FData - FSendPrefixLen;
  969. // this is not strictly const-object operation
  970. PUT_32BIT(Result, Length);
  971. return Result;
  972. }
  973. unsigned int GetSendLength() const
  974. {
  975. return FSendPrefixLen + Length;
  976. }
  977. unsigned int GetRemainingLength() const
  978. {
  979. return Length - FPosition;
  980. }
  981. inline void Need(unsigned int Size)
  982. {
  983. if (Size > RemainingLength)
  984. {
  985. throw Exception(FMTLOAD(SFTP_PACKET_ERROR, (int(FPosition), int(Size), int(FLength))));
  986. }
  987. }
  988. unsigned long PeekCardinal()
  989. {
  990. unsigned long Result;
  991. Need(sizeof(Result));
  992. Result = GET_32BIT(FData + FPosition);
  993. return Result;
  994. }
  995. inline UnicodeString GetUtfString(TAutoSwitch & Utf)
  996. {
  997. DebugAssert(Utf != asOff);
  998. UnicodeString Result;
  999. RawByteString S = GetRawByteString();
  1000. if (Utf == asAuto)
  1001. {
  1002. TEncodeType EncodeType = DetectUTF8Encoding(S);
  1003. if (EncodeType == etANSI)
  1004. {
  1005. Utf = asOff;
  1006. Result = AnsiToString(S);
  1007. }
  1008. }
  1009. if (Utf != asOff)
  1010. {
  1011. Result = UTF8ToString(S);
  1012. }
  1013. return Result;
  1014. }
  1015. };
  1016. //---------------------------------------------------------------------------
  1017. int TSFTPPacket::FMessageCounter = 0;
  1018. //---------------------------------------------------------------------------
  1019. class TSFTPQueue
  1020. {
  1021. public:
  1022. __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
  1023. {
  1024. FFileSystem = AFileSystem;
  1025. DebugAssert(FFileSystem);
  1026. FRequests = new TList();
  1027. FResponses = new TList();
  1028. }
  1029. virtual __fastcall ~TSFTPQueue()
  1030. {
  1031. TSFTPQueuePacket * Request;
  1032. TSFTPPacket * Response;
  1033. DebugAssert(FResponses->Count == FRequests->Count);
  1034. for (int Index = 0; Index < FRequests->Count; Index++)
  1035. {
  1036. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[Index]);
  1037. DebugAssert(Request);
  1038. delete Request;
  1039. Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
  1040. DebugAssert(Response);
  1041. delete Response;
  1042. }
  1043. delete FRequests;
  1044. delete FResponses;
  1045. }
  1046. bool __fastcall Init()
  1047. {
  1048. return SendRequests();
  1049. }
  1050. virtual void __fastcall Dispose(int ExpectedType, int AllowStatus)
  1051. {
  1052. DebugAssert(FFileSystem->FTerminal->Active);
  1053. while (FRequests->Count)
  1054. {
  1055. DebugAssert(FResponses->Count);
  1056. std::unique_ptr<TSFTPQueuePacket> Request(DebugNotNull(static_cast<TSFTPQueuePacket*>(FRequests->Items[0])));
  1057. std::unique_ptr<TSFTPPacket> Response(DebugNotNull(static_cast<TSFTPPacket*>(FResponses->Items[0])));
  1058. // Particularly when ExpectedType >= 0, the ReceiveResponse may throw, and we have to remove the packets from queue
  1059. FRequests->Delete(0);
  1060. FResponses->Delete(0);
  1061. try
  1062. {
  1063. ReceiveResponse(Request.get(), Response.get(), ExpectedType, AllowStatus);
  1064. }
  1065. catch(Exception & E)
  1066. {
  1067. if (ExpectedType < 0)
  1068. {
  1069. if (FFileSystem->FTerminal->Active)
  1070. {
  1071. FFileSystem->FTerminal->LogEvent(L"Error while disposing the SFTP queue.");
  1072. FFileSystem->FTerminal->Log->AddException(&E);
  1073. }
  1074. else
  1075. {
  1076. FFileSystem->FTerminal->LogEvent(L"Fatal error while disposing the SFTP queue.");
  1077. throw;
  1078. }
  1079. }
  1080. else
  1081. {
  1082. throw;
  1083. }
  1084. }
  1085. }
  1086. }
  1087. void __fastcall DisposeSafe(int ExpectedType = -1, int AllowStatus = -1)
  1088. {
  1089. if (FFileSystem->FTerminal->Active)
  1090. {
  1091. Dispose(ExpectedType, AllowStatus);
  1092. }
  1093. }
  1094. bool __fastcall ReceivePacket(TSFTPPacket * Packet,
  1095. int ExpectedType = -1, int AllowStatus = -1, void ** Token = NULL, bool TryOnly = false)
  1096. {
  1097. DebugAssert(FRequests->Count);
  1098. bool Result;
  1099. TSFTPQueuePacket * Request = NULL;
  1100. TSFTPPacket * Response = NULL;
  1101. try
  1102. {
  1103. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  1104. FRequests->Delete(0);
  1105. DebugAssert(Request);
  1106. if (Token != NULL)
  1107. {
  1108. *Token = Request->Token;
  1109. }
  1110. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  1111. FResponses->Delete(0);
  1112. DebugAssert(Response);
  1113. ReceiveResponse(Request, Response, ExpectedType, AllowStatus, TryOnly);
  1114. if ((Response->Capacity == 0) && DebugAlwaysTrue(TryOnly))
  1115. {
  1116. FRequests->Insert(0, Request);
  1117. Request = NULL;
  1118. FResponses->Insert(0, Response);
  1119. Response = NULL;
  1120. Result = true;
  1121. }
  1122. else
  1123. {
  1124. if (Packet)
  1125. {
  1126. *Packet = *Response;
  1127. }
  1128. Result = !End(Response);
  1129. if (Result)
  1130. {
  1131. SendRequests();
  1132. }
  1133. }
  1134. }
  1135. __finally
  1136. {
  1137. delete Request;
  1138. delete Response;
  1139. }
  1140. return Result;
  1141. }
  1142. bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
  1143. {
  1144. return ReceivePacket(NULL, ExpectedType, AllowStatus);
  1145. }
  1146. protected:
  1147. TList * FRequests;
  1148. TList * FResponses;
  1149. TSFTPFileSystem * FFileSystem;
  1150. class TSFTPQueuePacket : public TSFTPPacket
  1151. {
  1152. public:
  1153. TSFTPQueuePacket() :
  1154. TSFTPPacket()
  1155. {
  1156. Token = NULL;
  1157. }
  1158. void * Token;
  1159. };
  1160. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request) = 0;
  1161. virtual bool __fastcall End(TSFTPPacket * Response) = 0;
  1162. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1163. {
  1164. FFileSystem->SendPacket(Packet);
  1165. }
  1166. virtual void __fastcall ReceiveResponse(
  1167. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1168. int AllowStatus, bool TryOnly = false)
  1169. {
  1170. FFileSystem->ReceiveResponse(Packet, Response, ExpectedType, AllowStatus, TryOnly);
  1171. }
  1172. // sends as many requests as allowed by implementation
  1173. virtual bool SendRequests() = 0;
  1174. virtual bool __fastcall SendRequest()
  1175. {
  1176. TSFTPQueuePacket * Request = NULL;
  1177. try
  1178. {
  1179. Request = new TSFTPQueuePacket();
  1180. if (!InitRequest(Request))
  1181. {
  1182. delete Request;
  1183. Request = NULL;
  1184. }
  1185. }
  1186. catch(...)
  1187. {
  1188. delete Request;
  1189. throw;
  1190. }
  1191. if (Request != NULL)
  1192. {
  1193. TSFTPPacket * Response = new TSFTPPacket();
  1194. FRequests->Add(Request);
  1195. FResponses->Add(Response);
  1196. // make sure the response is reserved before actually ending the message
  1197. // as we may receive response asynchronously before SendPacket finishes
  1198. FFileSystem->ReserveResponse(Request, Response);
  1199. SendPacket(Request);
  1200. }
  1201. return (Request != NULL);
  1202. }
  1203. };
  1204. //---------------------------------------------------------------------------
  1205. class TSFTPFixedLenQueue : public TSFTPQueue
  1206. {
  1207. public:
  1208. __fastcall TSFTPFixedLenQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1209. {
  1210. FMissedRequests = 0;
  1211. }
  1212. virtual __fastcall ~TSFTPFixedLenQueue(){}
  1213. bool Init(int QueueLen)
  1214. {
  1215. FMissedRequests = QueueLen - 1;
  1216. return TSFTPQueue::Init();
  1217. }
  1218. protected:
  1219. int FMissedRequests;
  1220. // sends as many requests as allowed by implementation
  1221. virtual bool SendRequests()
  1222. {
  1223. bool Result = false;
  1224. FMissedRequests++;
  1225. while ((FMissedRequests > 0) && SendRequest())
  1226. {
  1227. Result = true;
  1228. FMissedRequests--;
  1229. }
  1230. return Result;
  1231. }
  1232. };
  1233. //---------------------------------------------------------------------------
  1234. class TSFTPAsynchronousQueue : public TSFTPQueue
  1235. {
  1236. public:
  1237. __fastcall TSFTPAsynchronousQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1238. {
  1239. FFileSystem->FSecureShell->RegisterReceiveHandler(ReceiveHandler);
  1240. FReceiveHandlerRegistered = true;
  1241. }
  1242. virtual __fastcall ~TSFTPAsynchronousQueue()
  1243. {
  1244. UnregisterReceiveHandler();
  1245. }
  1246. virtual void __fastcall Dispose(int ExpectedType, int AllowStatus)
  1247. {
  1248. // we do not want to receive asynchronous notifications anymore,
  1249. // while waiting synchronously for pending responses
  1250. UnregisterReceiveHandler();
  1251. TSFTPQueue::Dispose(ExpectedType, AllowStatus);
  1252. }
  1253. bool __fastcall Continue()
  1254. {
  1255. return SendRequest();
  1256. }
  1257. protected:
  1258. // event handler for incoming data
  1259. void __fastcall ReceiveHandler(TObject * /*Sender*/)
  1260. {
  1261. while (// optimization only as we call ReceivePacket with TryOnly anyway
  1262. FFileSystem->PeekPacket() &&
  1263. ReceivePacketAsynchronously())
  1264. {
  1265. // loop
  1266. }
  1267. }
  1268. virtual bool __fastcall ReceivePacketAsynchronously() = 0;
  1269. // sends as many requests as allowed by implementation
  1270. virtual bool SendRequests()
  1271. {
  1272. // noop
  1273. return true;
  1274. }
  1275. void __fastcall UnregisterReceiveHandler()
  1276. {
  1277. if (FReceiveHandlerRegistered)
  1278. {
  1279. FReceiveHandlerRegistered = false;
  1280. FFileSystem->FSecureShell->UnregisterReceiveHandler(ReceiveHandler);
  1281. }
  1282. }
  1283. private:
  1284. bool FReceiveHandlerRegistered;
  1285. };
  1286. //---------------------------------------------------------------------------
  1287. class TSFTPDownloadQueue : public TSFTPFixedLenQueue
  1288. {
  1289. public:
  1290. TSFTPDownloadQueue(TSFTPFileSystem * AFileSystem) :
  1291. TSFTPFixedLenQueue(AFileSystem)
  1292. {
  1293. }
  1294. virtual __fastcall ~TSFTPDownloadQueue(){}
  1295. bool __fastcall Init(int QueueLen, const RawByteString & AHandle,__int64 ATransferred,
  1296. TFileOperationProgressType * AOperationProgress)
  1297. {
  1298. FHandle = AHandle;
  1299. FTransferred = ATransferred;
  1300. OperationProgress = AOperationProgress;
  1301. return TSFTPFixedLenQueue::Init(QueueLen);
  1302. }
  1303. void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
  1304. TSFTPPacket * Packet)
  1305. {
  1306. InitRequest(Packet, Offset, Missing);
  1307. }
  1308. bool __fastcall ReceivePacket(TSFTPPacket * Packet, unsigned long & BlockSize)
  1309. {
  1310. void * Token;
  1311. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_DATA, asEOF, &Token);
  1312. BlockSize = reinterpret_cast<unsigned long>(Token);
  1313. return Result;
  1314. }
  1315. protected:
  1316. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1317. {
  1318. unsigned int BlockSize = FFileSystem->DownloadBlockSize(OperationProgress);
  1319. InitRequest(Request, FTransferred, BlockSize);
  1320. Request->Token = reinterpret_cast<void*>(BlockSize);
  1321. FTransferred += BlockSize;
  1322. return true;
  1323. }
  1324. void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
  1325. unsigned long Size)
  1326. {
  1327. Request->ChangeType(SSH_FXP_READ);
  1328. Request->AddString(FHandle);
  1329. Request->AddInt64(Offset);
  1330. Request->AddCardinal(Size);
  1331. }
  1332. virtual bool __fastcall End(TSFTPPacket * Response)
  1333. {
  1334. return (Response->Type != SSH_FXP_DATA);
  1335. }
  1336. private:
  1337. TFileOperationProgressType * OperationProgress;
  1338. __int64 FTransferred;
  1339. RawByteString FHandle;
  1340. };
  1341. //---------------------------------------------------------------------------
  1342. class TSFTPUploadQueue : public TSFTPAsynchronousQueue
  1343. {
  1344. public:
  1345. TSFTPUploadQueue(TSFTPFileSystem * AFileSystem, TEncryption * Encryption) :
  1346. TSFTPAsynchronousQueue(AFileSystem),
  1347. FEncryption(Encryption)
  1348. {
  1349. FStream = NULL;
  1350. OperationProgress = NULL;
  1351. FLastBlockSize = 0;
  1352. FEnd = false;
  1353. FConvertToken = false;
  1354. }
  1355. virtual __fastcall ~TSFTPUploadQueue()
  1356. {
  1357. delete FStream;
  1358. }
  1359. bool __fastcall Init(const UnicodeString AFileName,
  1360. HANDLE AFile, TFileOperationProgressType * AOperationProgress,
  1361. const RawByteString AHandle, __int64 ATransferred,
  1362. int ConvertParams)
  1363. {
  1364. FFileName = AFileName;
  1365. FStream = new TSafeHandleStream((THandle)AFile);
  1366. OperationProgress = AOperationProgress;
  1367. FHandle = AHandle;
  1368. FTransferred = ATransferred;
  1369. FConvertParams = ConvertParams;
  1370. return TSFTPAsynchronousQueue::Init();
  1371. }
  1372. void __fastcall DisposeSafeWithErrorHandling()
  1373. {
  1374. DisposeSafe(SSH_FXP_STATUS);
  1375. }
  1376. protected:
  1377. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1378. {
  1379. TTerminal * FTerminal = FFileSystem->FTerminal;
  1380. // Buffer for one block of data
  1381. TFileBuffer BlockBuf;
  1382. unsigned long BlockSize = GetBlockSize();
  1383. bool Result = (BlockSize > 0);
  1384. if (Result)
  1385. {
  1386. FILE_OPERATION_LOOP_BEGIN
  1387. {
  1388. BlockBuf.LoadStream(FStream, BlockSize, false);
  1389. }
  1390. FILE_OPERATION_LOOP_END(FMTLOAD(READ_ERROR, (FFileName)));
  1391. FEnd = (BlockBuf.Size == 0);
  1392. Result = !FEnd;
  1393. if (Result)
  1394. {
  1395. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  1396. // We do ASCII transfer: convert EOL of current block
  1397. if (OperationProgress->AsciiTransfer)
  1398. {
  1399. __int64 PrevBufSize = BlockBuf.Size;
  1400. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1401. FFileSystem->GetEOL(), FConvertParams, FConvertToken);
  1402. // update transfer size with difference arised from EOL conversion
  1403. OperationProgress->ChangeTransferSize(OperationProgress->TransferSize -
  1404. PrevBufSize + BlockBuf.Size);
  1405. }
  1406. if (FFileSystem->FTerminal->Configuration->ActualLogProtocol >= 1)
  1407. {
  1408. FFileSystem->FTerminal->LogEvent(FORMAT(L"Write request offset: %d, len: %d",
  1409. (int(FTransferred), int(BlockBuf.Size))));
  1410. }
  1411. if (FEncryption != NULL)
  1412. {
  1413. FEncryption->Encrypt(BlockBuf, (FStream->Position >= FStream->Size));
  1414. }
  1415. Request->ChangeType(SSH_FXP_WRITE);
  1416. Request->AddString(FHandle);
  1417. Request->AddInt64(FTransferred);
  1418. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  1419. FLastBlockSize = BlockBuf.Size;
  1420. FTransferred += BlockBuf.Size;
  1421. }
  1422. }
  1423. return Result;
  1424. }
  1425. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1426. {
  1427. TSFTPAsynchronousQueue::SendPacket(Packet);
  1428. OperationProgress->AddTransferred(FLastBlockSize);
  1429. }
  1430. virtual void __fastcall ReceiveResponse(
  1431. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1432. int AllowStatus, bool TryOnly)
  1433. {
  1434. TSFTPAsynchronousQueue::ReceiveResponse(Packet, Response, ExpectedType, AllowStatus, TryOnly);
  1435. if (Response->Capacity > 0)
  1436. {
  1437. // particularly when uploading a file that completelly fits into send buffer
  1438. // over slow line, we may end up seemingly completing the transfer immediatelly
  1439. // but hanging the application for a long time waiting for responses
  1440. // (common is that the progress window would not even manage to draw itself,
  1441. // showing that upload finished, before the application "hangs")
  1442. FFileSystem->Progress(OperationProgress);
  1443. }
  1444. else
  1445. {
  1446. DebugAssert(TryOnly);
  1447. }
  1448. }
  1449. virtual bool __fastcall ReceivePacketAsynchronously()
  1450. {
  1451. // do not read response to close request
  1452. bool Result = (FRequests->Count > 0);
  1453. if (Result)
  1454. {
  1455. // Try only: We cannot read from the socket here as we are already called
  1456. // from TSecureShell::HandleNetworkEvents as it would cause a recursion
  1457. // that would potentially make PuTTY code process the SSH packets in wrong order.
  1458. ReceivePacket(NULL, SSH_FXP_STATUS, -1, NULL, true);
  1459. }
  1460. return Result;
  1461. }
  1462. inline int __fastcall GetBlockSize()
  1463. {
  1464. return FFileSystem->UploadBlockSize(FHandle, OperationProgress);
  1465. }
  1466. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1467. {
  1468. return FEnd;
  1469. }
  1470. private:
  1471. TStream * FStream;
  1472. TFileOperationProgressType * OperationProgress;
  1473. UnicodeString FFileName;
  1474. unsigned long FLastBlockSize;
  1475. bool FEnd;
  1476. __int64 FTransferred;
  1477. RawByteString FHandle;
  1478. bool FConvertToken;
  1479. int FConvertParams;
  1480. TEncryption * FEncryption;
  1481. };
  1482. //---------------------------------------------------------------------------
  1483. class TSFTPLoadFilesPropertiesQueue : public TSFTPFixedLenQueue
  1484. {
  1485. public:
  1486. TSFTPLoadFilesPropertiesQueue(TSFTPFileSystem * AFileSystem) :
  1487. TSFTPFixedLenQueue(AFileSystem)
  1488. {
  1489. FIndex = 0;
  1490. }
  1491. virtual __fastcall ~TSFTPLoadFilesPropertiesQueue(){}
  1492. bool __fastcall Init(int QueueLen, TStrings * FileList)
  1493. {
  1494. FFileList = FileList;
  1495. return TSFTPFixedLenQueue::Init(QueueLen);
  1496. }
  1497. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1498. {
  1499. void * Token;
  1500. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_ATTRS, asAll, &Token);
  1501. File = static_cast<TRemoteFile *>(Token);
  1502. return Result;
  1503. }
  1504. protected:
  1505. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1506. {
  1507. bool Result = false;
  1508. while (!Result && (FIndex < FFileList->Count))
  1509. {
  1510. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1511. FIndex++;
  1512. bool MissingRights =
  1513. (FFileSystem->FSupport->Loaded &&
  1514. FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS) &&
  1515. File->Rights->Unknown);
  1516. bool MissingOwnerGroup =
  1517. (FFileSystem->FSecureShell->SshImplementation == sshiBitvise) ||
  1518. (FFileSystem->FSupport->Loaded &&
  1519. FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP) &&
  1520. !File->Owner.IsSet || !File->Group.IsSet);
  1521. Result = (MissingRights || MissingOwnerGroup);
  1522. if (Result)
  1523. {
  1524. Request->ChangeType(SSH_FXP_LSTAT);
  1525. FFileSystem->AddPathString(*Request, FFileSystem->LocalCanonify(File->FileName));
  1526. if (FFileSystem->FVersion >= 4)
  1527. {
  1528. Request->AddCardinal(
  1529. FLAGMASK(MissingRights, SSH_FILEXFER_ATTR_PERMISSIONS) |
  1530. FLAGMASK(MissingOwnerGroup, SSH_FILEXFER_ATTR_OWNERGROUP));
  1531. }
  1532. Request->Token = File;
  1533. }
  1534. }
  1535. return Result;
  1536. }
  1537. virtual bool __fastcall SendRequest()
  1538. {
  1539. bool Result =
  1540. (FIndex < FFileList->Count) &&
  1541. TSFTPFixedLenQueue::SendRequest();
  1542. return Result;
  1543. }
  1544. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1545. {
  1546. return (FRequests->Count == 0);
  1547. }
  1548. private:
  1549. TStrings * FFileList;
  1550. int FIndex;
  1551. };
  1552. //---------------------------------------------------------------------------
  1553. class TSFTPCalculateFilesChecksumQueue : public TSFTPFixedLenQueue
  1554. {
  1555. public:
  1556. TSFTPCalculateFilesChecksumQueue(TSFTPFileSystem * AFileSystem) :
  1557. TSFTPFixedLenQueue(AFileSystem)
  1558. {
  1559. FIndex = 0;
  1560. }
  1561. virtual __fastcall ~TSFTPCalculateFilesChecksumQueue(){}
  1562. bool __fastcall Init(int QueueLen, const UnicodeString & Alg, TStrings * FileList)
  1563. {
  1564. FAlg = Alg;
  1565. FFileList = FileList;
  1566. return TSFTPFixedLenQueue::Init(QueueLen);
  1567. }
  1568. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1569. {
  1570. void * Token;
  1571. bool Result;
  1572. try
  1573. {
  1574. Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_EXTENDED_REPLY, asNo, &Token);
  1575. }
  1576. __finally
  1577. {
  1578. File = static_cast<TRemoteFile *>(Token);
  1579. }
  1580. return Result;
  1581. }
  1582. protected:
  1583. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1584. {
  1585. bool Result = false;
  1586. while (!Result && (FIndex < FFileList->Count))
  1587. {
  1588. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1589. DebugAssert(File != NULL);
  1590. FIndex++;
  1591. Result = !File->IsDirectory;
  1592. if (Result)
  1593. {
  1594. DebugAssert(IsRealFile(File->FileName));
  1595. Request->ChangeType(SSH_FXP_EXTENDED);
  1596. Request->AddString(SFTP_EXT_CHECK_FILE_NAME);
  1597. FFileSystem->AddPathString(*Request, FFileSystem->LocalCanonify(File->FullFileName));
  1598. Request->AddString(FAlg);
  1599. Request->AddInt64(0); // offset
  1600. Request->AddInt64(0); // length (0 = till end)
  1601. Request->AddCardinal(0); // block size (0 = no blocks or "one block")
  1602. Request->Token = File;
  1603. }
  1604. }
  1605. return Result;
  1606. }
  1607. virtual bool __fastcall SendRequest()
  1608. {
  1609. bool Result =
  1610. (FIndex < FFileList->Count) &&
  1611. TSFTPFixedLenQueue::SendRequest();
  1612. return Result;
  1613. }
  1614. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1615. {
  1616. return (FRequests->Count == 0);
  1617. }
  1618. private:
  1619. UnicodeString FAlg;
  1620. TStrings * FFileList;
  1621. int FIndex;
  1622. };
  1623. //---------------------------------------------------------------------------
  1624. #pragma warn .inl
  1625. //---------------------------------------------------------------------------
  1626. class TSFTPBusy
  1627. {
  1628. public:
  1629. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  1630. {
  1631. FFileSystem = FileSystem;
  1632. DebugAssert(FFileSystem != NULL);
  1633. FFileSystem->BusyStart();
  1634. }
  1635. __fastcall ~TSFTPBusy()
  1636. {
  1637. FFileSystem->BusyEnd();
  1638. }
  1639. private:
  1640. TSFTPFileSystem * FFileSystem;
  1641. };
  1642. //===========================================================================
  1643. struct TOpenRemoteFileParams
  1644. {
  1645. UnicodeString FileName;
  1646. UnicodeString RemoteFileName;
  1647. TFileOperationProgressType * OperationProgress;
  1648. const TCopyParamType * CopyParam;
  1649. int Params;
  1650. bool Resume;
  1651. bool Resuming;
  1652. TSFTPOverwriteMode OverwriteMode;
  1653. __int64 DestFileSize; // output
  1654. RawByteString RemoteFileHandle; // output
  1655. TOverwriteFileParams * FileParams;
  1656. bool Confirmed;
  1657. };
  1658. //===========================================================================
  1659. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal,
  1660. TSecureShell * SecureShell):
  1661. TCustomFileSystem(ATerminal)
  1662. {
  1663. FSecureShell = SecureShell;
  1664. FPacketReservations = new TList();
  1665. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varLongWord);
  1666. FPreviousLoggedPacket = 0;
  1667. FNotLoggedPackets = 0;
  1668. FBusy = 0;
  1669. FAvoidBusy = false;
  1670. FUtfStrings = asOff;
  1671. FUtfDisablingAnnounced = true;
  1672. FSignedTS = false;
  1673. FSupport = new TSFTPSupport();
  1674. FExtensions = new TStringList();
  1675. FFixedPaths = NULL;
  1676. FFileSystemInfoValid = false;
  1677. FChecksumAlgs.reset(new TStringList());
  1678. FChecksumSftpAlgs.reset(new TStringList());
  1679. // List as defined by draft-ietf-secsh-filexfer-extensions-00
  1680. // MD5 moved to the back
  1681. RegisterChecksumAlg(Sha1ChecksumAlg, L"sha1");
  1682. RegisterChecksumAlg(Sha224ChecksumAlg, L"sha224");
  1683. RegisterChecksumAlg(Sha256ChecksumAlg, L"sha256");
  1684. RegisterChecksumAlg(Sha384ChecksumAlg, L"sha384");
  1685. RegisterChecksumAlg(Sha512ChecksumAlg, L"sha512");
  1686. RegisterChecksumAlg(Md5ChecksumAlg, L"md5");
  1687. RegisterChecksumAlg(Crc32ChecksumAlg, L"crc32");
  1688. }
  1689. //---------------------------------------------------------------------------
  1690. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  1691. {
  1692. delete FSupport;
  1693. ResetConnection();
  1694. delete FPacketReservations;
  1695. delete FExtensions;
  1696. delete FFixedPaths;
  1697. delete FSecureShell;
  1698. }
  1699. //---------------------------------------------------------------------------
  1700. void __fastcall TSFTPFileSystem::Open()
  1701. {
  1702. // this is used for reconnects only
  1703. FSecureShell->Open();
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. void __fastcall TSFTPFileSystem::Close()
  1707. {
  1708. FSecureShell->Close();
  1709. }
  1710. //---------------------------------------------------------------------------
  1711. bool __fastcall TSFTPFileSystem::GetActive()
  1712. {
  1713. return FSecureShell->Active;
  1714. }
  1715. //---------------------------------------------------------------------------
  1716. void __fastcall TSFTPFileSystem::CollectUsage()
  1717. {
  1718. FSecureShell->CollectUsage();
  1719. UnicodeString VersionCounter;
  1720. switch (FVersion)
  1721. {
  1722. case 0:
  1723. VersionCounter = L"OpenedSessionsSFTP0";
  1724. break;
  1725. case 1:
  1726. VersionCounter = L"OpenedSessionsSFTP1";
  1727. break;
  1728. case 2:
  1729. VersionCounter = L"OpenedSessionsSFTP2";
  1730. break;
  1731. case 3:
  1732. VersionCounter = L"OpenedSessionsSFTP3";
  1733. break;
  1734. case 4:
  1735. VersionCounter = L"OpenedSessionsSFTP4";
  1736. break;
  1737. case 5:
  1738. VersionCounter = L"OpenedSessionsSFTP5";
  1739. break;
  1740. case 6:
  1741. VersionCounter = L"OpenedSessionsSFTP6";
  1742. break;
  1743. default:
  1744. DebugFail();
  1745. }
  1746. FTerminal->Configuration->Usage->Inc(VersionCounter);
  1747. }
  1748. //---------------------------------------------------------------------------
  1749. const TSessionInfo & __fastcall TSFTPFileSystem::GetSessionInfo()
  1750. {
  1751. return FSecureShell->GetSessionInfo();
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. const TFileSystemInfo & __fastcall TSFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1755. {
  1756. if (!FFileSystemInfoValid)
  1757. {
  1758. FFileSystemInfo.AdditionalInfo = L"";
  1759. if (!IsCapable(fcRename))
  1760. {
  1761. FFileSystemInfo.AdditionalInfo += LoadStr(FS_RENAME_NOT_SUPPORTED) + L"\r\n\r\n";
  1762. }
  1763. if (FExtensions->Count > 0)
  1764. {
  1765. UnicodeString Name;
  1766. UnicodeString Value;
  1767. UnicodeString Line;
  1768. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_EXTENSION_INFO) + L"\r\n";
  1769. for (int Index = 0; Index < FExtensions->Count; Index++)
  1770. {
  1771. UnicodeString Name = FExtensions->Names[Index];
  1772. UnicodeString Value = FExtensions->Values[Name];
  1773. UnicodeString Line;
  1774. if (Value.IsEmpty())
  1775. {
  1776. Line = Name;
  1777. }
  1778. else
  1779. {
  1780. Line = FORMAT(L"%s=%s", (Name, Value));
  1781. }
  1782. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (Line));
  1783. }
  1784. }
  1785. else
  1786. {
  1787. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_NO_EXTENSION_INFO) + L"\r\n";
  1788. }
  1789. FFileSystemInfo.ProtocolBaseName = L"SFTP";
  1790. FFileSystemInfo.ProtocolName = FMTLOAD(SFTP_PROTOCOL_NAME2, (FVersion));
  1791. FTerminal->SaveCapabilities(FFileSystemInfo);
  1792. FFileSystemInfoValid = true;
  1793. }
  1794. return FFileSystemInfo;
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. bool __fastcall TSFTPFileSystem::TemporaryTransferFile(const UnicodeString & FileName)
  1798. {
  1799. return SameText(UnixExtractFileExt(FileName), PARTIAL_EXT);
  1800. }
  1801. //---------------------------------------------------------------------------
  1802. bool __fastcall TSFTPFileSystem::GetStoredCredentialsTried()
  1803. {
  1804. return FSecureShell->GetStoredCredentialsTried();
  1805. }
  1806. //---------------------------------------------------------------------------
  1807. UnicodeString __fastcall TSFTPFileSystem::GetUserName()
  1808. {
  1809. return FSecureShell->UserName;
  1810. }
  1811. //---------------------------------------------------------------------------
  1812. void __fastcall TSFTPFileSystem::Idle()
  1813. {
  1814. // Keep session alive
  1815. if ((FTerminal->SessionData->PingType != ptOff) &&
  1816. (Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
  1817. {
  1818. if ((FTerminal->SessionData->PingType == ptDummyCommand) &&
  1819. FSecureShell->Ready)
  1820. {
  1821. FTerminal->LogEvent(L"Sending dummy command to keep session alive.");
  1822. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1823. AddPathString(Packet, L"/");
  1824. SendPacketAndReceiveResponse(&Packet, &Packet);
  1825. }
  1826. else
  1827. {
  1828. FSecureShell->KeepAlive();
  1829. }
  1830. }
  1831. FSecureShell->Idle();
  1832. }
  1833. //---------------------------------------------------------------------------
  1834. void __fastcall TSFTPFileSystem::ResetConnection()
  1835. {
  1836. // there must be no valid packet reservation at the end
  1837. for (int i = 0; i < FPacketReservations->Count; i++)
  1838. {
  1839. DebugAssert(FPacketReservations->Items[i] == NULL);
  1840. delete (TSFTPPacket *)FPacketReservations->Items[i];
  1841. }
  1842. FPacketReservations->Clear();
  1843. FPacketNumbers.Clear();
  1844. }
  1845. //---------------------------------------------------------------------------
  1846. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  1847. {
  1848. DebugAssert(FTerminal);
  1849. switch (Capability) {
  1850. case fcAnyCommand:
  1851. case fcShellAnyCommand:
  1852. return false;
  1853. case fcNewerOnlyUpload:
  1854. case fcTimestampChanging:
  1855. case fcIgnorePermErrors:
  1856. case fcPreservingTimestampUpload:
  1857. case fcSecondaryShell:
  1858. case fcRemoveCtrlZUpload:
  1859. case fcRemoveBOMUpload:
  1860. case fcPreservingTimestampDirs:
  1861. return true;
  1862. case fcMoveToQueue:
  1863. case fcResumeSupport:
  1864. case fsSkipTransfer:
  1865. case fsParallelTransfers:
  1866. return !FTerminal->IsEncryptingFiles();
  1867. case fcRename:
  1868. case fcRemoteMove:
  1869. return (FVersion >= 2);
  1870. case fcSymbolicLink:
  1871. case fcResolveSymlink:
  1872. return (FVersion >= 3) && !FTerminal->IsEncryptingFiles();
  1873. case fcModeChanging:
  1874. case fcModeChangingUpload:
  1875. return !FSupport->Loaded ||
  1876. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS);
  1877. case fcGroupOwnerChangingByID:
  1878. return (FVersion <= 3);
  1879. case fcOwnerChanging:
  1880. case fcGroupChanging:
  1881. return
  1882. (FVersion <= 3) ||
  1883. ((FVersion >= 4) &&
  1884. (!FSupport->Loaded ||
  1885. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP)));
  1886. case fcNativeTextMode:
  1887. return !FTerminal->IsEncryptingFiles() && (FVersion >= 4);
  1888. case fcTextMode:
  1889. return
  1890. !FTerminal->IsEncryptingFiles() &&
  1891. ((FVersion >= 4) ||
  1892. (strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0));
  1893. case fcUserGroupListing:
  1894. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1895. case fcLoadingAdditionalProperties:
  1896. // We allow loading properties only, if "supported" extension is supported and
  1897. // the server supports "permissions" and/or "owner/group" attributes
  1898. // (no other attributes are loaded).
  1899. // This is here only because of VShell
  1900. // (it supports owner/group, but does not include them into response to
  1901. // SSH_FXP_READDIR)
  1902. // and Bitwise (the same as VShell, but it does not even bother to provide "supported" extension until 6.21)
  1903. // No other use is known.
  1904. return
  1905. (FSupport->Loaded &&
  1906. ((FSupport->AttributeMask &
  1907. (SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_OWNERGROUP)) != 0)) ||
  1908. (FSecureShell->SshImplementation == sshiBitvise);
  1909. case fcCheckingSpaceAvailable:
  1910. return
  1911. // extension announced in extension list of by
  1912. // SFTP_EXT_SUPPORTED/SFTP_EXT_SUPPORTED2 extension
  1913. // (SFTP version 5 and newer only)
  1914. SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  1915. // extension announced by proprietary SFTP_EXT_STATVFS extension
  1916. FSupportsStatVfsV2 ||
  1917. // Bitwise (until 6.21) fails to report it's supported extensions.
  1918. (FSecureShell->SshImplementation == sshiBitvise);
  1919. case fcCalculatingChecksum:
  1920. return
  1921. !FTerminal->IsEncryptingFiles() &&
  1922. (// Specification says that "check-file" should be announced,
  1923. // yet Vandyke VShell (as of 4.0.3) announce "check-file-name"
  1924. // https://forums.vandyke.com/showthread.php?t=11597
  1925. SupportsExtension(SFTP_EXT_CHECK_FILE) ||
  1926. SupportsExtension(SFTP_EXT_CHECK_FILE_NAME) ||
  1927. // see above
  1928. (FSecureShell->SshImplementation == sshiBitvise));
  1929. case fcRemoteCopy:
  1930. return
  1931. SupportsExtension(SFTP_EXT_COPY_FILE) ||
  1932. // see above
  1933. (FSecureShell->SshImplementation == sshiBitvise);
  1934. case fcHardLink:
  1935. return
  1936. (FVersion >= 6) ||
  1937. FSupportsHardlink;
  1938. case fcLocking:
  1939. return false;
  1940. case fcChangePassword:
  1941. return FSecureShell->CanChangePassword();
  1942. default:
  1943. DebugFail();
  1944. return false;
  1945. }
  1946. }
  1947. //---------------------------------------------------------------------------
  1948. bool __fastcall TSFTPFileSystem::SupportsExtension(const UnicodeString & Extension) const
  1949. {
  1950. return FSupport->Loaded && (FSupport->Extensions->IndexOf(Extension) >= 0);
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. inline void __fastcall TSFTPFileSystem::BusyStart()
  1954. {
  1955. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1956. {
  1957. FBusyToken = ::BusyStart();
  1958. }
  1959. FBusy++;
  1960. DebugAssert(FBusy < 10);
  1961. }
  1962. //---------------------------------------------------------------------------
  1963. inline void __fastcall TSFTPFileSystem::BusyEnd()
  1964. {
  1965. DebugAssert(FBusy > 0);
  1966. FBusy--;
  1967. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1968. {
  1969. ::BusyEnd(FBusyToken);
  1970. FBusyToken = NULL;
  1971. }
  1972. }
  1973. //---------------------------------------------------------------------------
  1974. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  1975. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  1976. {
  1977. const unsigned long MinPacketSize = 32768;
  1978. // size + message number + type
  1979. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  1980. unsigned long AMaxPacketSize = FSecureShell->MaxPacketSize();
  1981. bool MaxPacketSizeValid = (AMaxPacketSize > 0);
  1982. unsigned long CPSRounded = TEncryption::RoundToBlock(OperationProgress->CPS());
  1983. unsigned long Result = CPSRounded;
  1984. if ((MaxPacketSize > 0) &&
  1985. ((MaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1986. {
  1987. AMaxPacketSize = MaxPacketSize;
  1988. MaxPacketSizeValid = true;
  1989. }
  1990. if ((FMaxPacketSize > 0) &&
  1991. ((FMaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1992. {
  1993. AMaxPacketSize = FMaxPacketSize;
  1994. MaxPacketSizeValid = true;
  1995. }
  1996. if (Result == 0)
  1997. {
  1998. Result = OperationProgress->StaticBlockSize();
  1999. }
  2000. if (Result < MinPacketSize)
  2001. {
  2002. Result = MinPacketSize;
  2003. }
  2004. if (MaxPacketSizeValid)
  2005. {
  2006. Overhead += SFTPPacketOverhead;
  2007. if (AMaxPacketSize < Overhead)
  2008. {
  2009. // do not send another request
  2010. // (generally should happen only if upload buffer is full)
  2011. Result = 0;
  2012. }
  2013. else
  2014. {
  2015. AMaxPacketSize -= Overhead;
  2016. if (Result > AMaxPacketSize)
  2017. {
  2018. unsigned int MaxPacketSizeRounded = TEncryption::RoundToBlockDown(AMaxPacketSize);
  2019. if (MaxPacketSizeRounded > 0)
  2020. {
  2021. AMaxPacketSize = MaxPacketSizeRounded;
  2022. }
  2023. Result = AMaxPacketSize;
  2024. }
  2025. }
  2026. }
  2027. Result = OperationProgress->AdjustToCPSLimit(Result);
  2028. return Result;
  2029. }
  2030. //---------------------------------------------------------------------------
  2031. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const RawByteString & Handle,
  2032. TFileOperationProgressType * OperationProgress)
  2033. {
  2034. // handle length + offset + data size
  2035. const unsigned long UploadPacketOverhead =
  2036. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  2037. return TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress);
  2038. }
  2039. //---------------------------------------------------------------------------
  2040. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  2041. TFileOperationProgressType * OperationProgress)
  2042. {
  2043. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  2044. if (FSupport->Loaded && (FSupport->MaxReadSize > 0) &&
  2045. (Result > FSupport->MaxReadSize))
  2046. {
  2047. Result = FSupport->MaxReadSize;
  2048. }
  2049. return Result;
  2050. }
  2051. //---------------------------------------------------------------------------
  2052. void __fastcall TSFTPFileSystem::Progress(TFileOperationProgressType * OperationProgress)
  2053. {
  2054. FTerminal->Progress(OperationProgress);
  2055. }
  2056. //---------------------------------------------------------------------------
  2057. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  2058. {
  2059. // putting here for a lack of better place
  2060. if (!FUtfDisablingAnnounced && (FUtfStrings == asOff))
  2061. {
  2062. FTerminal->LogEvent(L"Strings received in non-UTF-8 encoding in a previous packet, will not use UTF-8 anymore");
  2063. FUtfDisablingAnnounced = true;
  2064. }
  2065. BusyStart();
  2066. try
  2067. {
  2068. if (FTerminal->Log->Logging && (FTerminal->Configuration->ActualLogProtocol >= 0))
  2069. {
  2070. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2071. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2072. (Packet->Type != FPreviousLoggedPacket) ||
  2073. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2074. {
  2075. if (FNotLoggedPackets)
  2076. {
  2077. FTerminal->LogEvent(FORMAT(L"%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  2078. (FNotLoggedPackets)));
  2079. FNotLoggedPackets = 0;
  2080. }
  2081. FTerminal->Log->Add(llInput, FORMAT(L"Type: %s, Size: %d, Number: %d",
  2082. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2083. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2084. {
  2085. FTerminal->Log->Add(llInput, Packet->Dump());
  2086. }
  2087. FPreviousLoggedPacket = Packet->Type;
  2088. }
  2089. else
  2090. {
  2091. FNotLoggedPackets++;
  2092. }
  2093. }
  2094. FSecureShell->Send(Packet->SendData, Packet->SendLength);
  2095. }
  2096. __finally
  2097. {
  2098. BusyEnd();
  2099. }
  2100. }
  2101. //---------------------------------------------------------------------------
  2102. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  2103. int AllowStatus)
  2104. {
  2105. unsigned long Code = Packet->GetCardinal();
  2106. static int Messages[] = {
  2107. SFTP_STATUS_OK,
  2108. SFTP_STATUS_EOF,
  2109. SFTP_STATUS_NO_SUCH_FILE,
  2110. SFTP_STATUS_PERMISSION_DENIED,
  2111. SFTP_STATUS_FAILURE,
  2112. SFTP_STATUS_BAD_MESSAGE,
  2113. SFTP_STATUS_NO_CONNECTION,
  2114. SFTP_STATUS_CONNECTION_LOST,
  2115. SFTP_STATUS_OP_UNSUPPORTED,
  2116. SFTP_STATUS_INVALID_HANDLE,
  2117. SFTP_STATUS_NO_SUCH_PATH,
  2118. SFTP_STATUS_FILE_ALREADY_EXISTS,
  2119. SFTP_STATUS_WRITE_PROTECT,
  2120. SFTP_STATUS_NO_MEDIA,
  2121. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  2122. SFTP_STATUS_QUOTA_EXCEEDED,
  2123. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  2124. SFTP_STATUS_LOCK_CONFLICT,
  2125. SFTP_STATUS_DIR_NOT_EMPTY,
  2126. SFTP_STATUS_NOT_A_DIRECTORY,
  2127. SFTP_STATUS_INVALID_FILENAME,
  2128. SFTP_STATUS_LINK_LOOP,
  2129. SFTP_STATUS_CANNOT_DELETE,
  2130. SFTP_STATUS_INVALID_PARAMETER,
  2131. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  2132. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  2133. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  2134. SFTP_STATUS_DELETE_PENDING,
  2135. SFTP_STATUS_FILE_CORRUPT,
  2136. SFTP_STATUS_OWNER_INVALID,
  2137. SFTP_STATUS_GROUP_INVALID,
  2138. SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK
  2139. };
  2140. int Message;
  2141. if ((AllowStatus & (0x01 << Code)) == 0)
  2142. {
  2143. if (Code >= LENOF(Messages))
  2144. {
  2145. Message = SFTP_STATUS_UNKNOWN;
  2146. }
  2147. else
  2148. {
  2149. Message = Messages[Code];
  2150. }
  2151. UnicodeString MessageStr = LoadStr(Message);
  2152. UnicodeString ServerMessage;
  2153. UnicodeString LanguageTag;
  2154. if ((FVersion >= 3) ||
  2155. // if version is not decided yet (i.e. this is status response
  2156. // to the init request), go on, only if there are any more data
  2157. ((FVersion < 0) && (Packet->RemainingLength > 0)))
  2158. {
  2159. // message is in UTF only since SFTP specification 01 (specification 00
  2160. // is also version 3)
  2161. // (in other words, always use UTF unless server is known to be buggy)
  2162. ServerMessage = Packet->GetString(FUtfStrings);
  2163. // SSH-2.0-Maverick_SSHD and SSH-2.0-CIGNA SFTP Server Ready! omit the language tag
  2164. // and I believe I've seen one more server doing the same.
  2165. if (Packet->RemainingLength > 0)
  2166. {
  2167. LanguageTag = Packet->GetAnsiString();
  2168. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  2169. {
  2170. UnicodeString Principals;
  2171. while (Packet->GetNextData() != NULL)
  2172. {
  2173. if (!Principals.IsEmpty())
  2174. {
  2175. Principals += L", ";
  2176. }
  2177. Principals += Packet->GetAnsiString();
  2178. }
  2179. MessageStr = FORMAT(MessageStr, (Principals));
  2180. }
  2181. }
  2182. }
  2183. else
  2184. {
  2185. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  2186. }
  2187. if (FTerminal->Log->Logging &&
  2188. (FTerminal->Configuration->ActualLogProtocol >= 0))
  2189. {
  2190. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d, Message: %d, Server: %s, Language: %s ",
  2191. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  2192. }
  2193. if (!LanguageTag.IsEmpty())
  2194. {
  2195. LanguageTag = FORMAT(L" (%s)", (LanguageTag));
  2196. }
  2197. UnicodeString HelpKeyword;
  2198. switch (Code)
  2199. {
  2200. case SSH_FX_FAILURE:
  2201. HelpKeyword = HELP_SFTP_STATUS_FAILURE;
  2202. break;
  2203. case SSH_FX_PERMISSION_DENIED:
  2204. HelpKeyword = HELP_SFTP_STATUS_PERMISSION_DENIED;
  2205. break;
  2206. }
  2207. UnicodeString Error = FMTLOAD(SFTP_ERROR_FORMAT3, (MessageStr,
  2208. int(Code), LanguageTag, ServerMessage));
  2209. if (Code == SSH_FX_FAILURE)
  2210. {
  2211. FTerminal->Configuration->Usage->Inc(L"SftpFailureErrors");
  2212. Error += L"\n\n" + LoadStr(SFTP_STATUS_4);
  2213. }
  2214. FTerminal->TerminalError(NULL, Error, HelpKeyword);
  2215. return 0;
  2216. }
  2217. else
  2218. {
  2219. if (!FNotLoggedPackets || Code)
  2220. {
  2221. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2222. {
  2223. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d", ((int)Code)));
  2224. }
  2225. }
  2226. return Code;
  2227. }
  2228. }
  2229. //---------------------------------------------------------------------------
  2230. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  2231. {
  2232. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  2233. {
  2234. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  2235. }
  2236. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  2237. if (Packet)
  2238. {
  2239. DebugAssert(Packet->ReservedBy == this);
  2240. Packet->ReservedBy = NULL;
  2241. }
  2242. FPacketReservations->Delete(Reservation);
  2243. }
  2244. //---------------------------------------------------------------------------
  2245. inline int __fastcall TSFTPFileSystem::PacketLength(unsigned char * LenBuf, int ExpectedType)
  2246. {
  2247. int Length = GET_32BIT(LenBuf);
  2248. if (Length > SFTP_MAX_PACKET_LEN)
  2249. {
  2250. UnicodeString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  2251. int(Length), SFTP_MAX_PACKET_LEN));
  2252. if (ExpectedType == SSH_FXP_VERSION)
  2253. {
  2254. RawByteString LenString(reinterpret_cast<char *>(LenBuf), 4);
  2255. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  2256. (Message, DisplayableStr(LenString)));
  2257. }
  2258. FTerminal->FatalError(NULL, Message, HELP_SFTP_PACKET_TOO_BIG);
  2259. }
  2260. return Length;
  2261. }
  2262. //---------------------------------------------------------------------------
  2263. bool __fastcall TSFTPFileSystem::PeekPacket()
  2264. {
  2265. bool Result;
  2266. unsigned char * Buf;
  2267. Result = FSecureShell->Peek(Buf, 4);
  2268. if (Result)
  2269. {
  2270. int Length = PacketLength(Buf, -1);
  2271. Result = FSecureShell->Peek(Buf, 4 + Length);
  2272. }
  2273. return Result;
  2274. }
  2275. //---------------------------------------------------------------------------
  2276. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  2277. int ExpectedType, int AllowStatus, bool TryOnly)
  2278. {
  2279. TSFTPBusy Busy(this);
  2280. int Result = SSH_FX_OK;
  2281. int Reservation = FPacketReservations->IndexOf(Packet);
  2282. if (Reservation < 0 || Packet->Capacity == 0)
  2283. {
  2284. bool IsReserved;
  2285. do
  2286. {
  2287. IsReserved = false;
  2288. DebugAssert(Packet);
  2289. if (TryOnly && !PeekPacket())
  2290. {
  2291. // Reset packet in case it was filled by previous out-of-order
  2292. // reserved packet
  2293. *Packet = TSFTPPacket();
  2294. }
  2295. else
  2296. {
  2297. unsigned char LenBuf[4];
  2298. FSecureShell->Receive(LenBuf, sizeof(LenBuf));
  2299. int Length = PacketLength(LenBuf, ExpectedType);
  2300. Packet->Capacity = Length;
  2301. FSecureShell->Receive(Packet->Data, Length);
  2302. Packet->DataUpdated(Length);
  2303. if (FTerminal->Log->Logging && (FTerminal->Configuration->ActualLogProtocol >= 0))
  2304. {
  2305. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2306. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2307. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  2308. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2309. {
  2310. if (FNotLoggedPackets)
  2311. {
  2312. FTerminal->LogEvent(FORMAT(L"%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  2313. (FNotLoggedPackets)));
  2314. FNotLoggedPackets = 0;
  2315. }
  2316. FTerminal->Log->Add(llOutput, FORMAT(L"Type: %s, Size: %d, Number: %d",
  2317. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2318. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2319. {
  2320. FTerminal->Log->Add(llOutput, Packet->Dump());
  2321. }
  2322. }
  2323. else
  2324. {
  2325. FNotLoggedPackets++;
  2326. }
  2327. }
  2328. if (Reservation < 0 ||
  2329. Packet->MessageNumber != (unsigned int)FPacketNumbers.GetElement(Reservation))
  2330. {
  2331. TSFTPPacket * ReservedPacket;
  2332. unsigned int MessageNumber;
  2333. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  2334. {
  2335. MessageNumber = (unsigned int)FPacketNumbers.GetElement(Index);
  2336. if (MessageNumber == Packet->MessageNumber)
  2337. {
  2338. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  2339. IsReserved = true;
  2340. if (ReservedPacket)
  2341. {
  2342. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2343. {
  2344. FTerminal->LogEvent(L"Storing reserved response");
  2345. }
  2346. *ReservedPacket = *Packet;
  2347. }
  2348. else
  2349. {
  2350. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2351. {
  2352. FTerminal->LogEvent(L"Discarding reserved response");
  2353. }
  2354. RemoveReservation(Index);
  2355. if ((Reservation >= 0) && (Reservation > Index))
  2356. {
  2357. Reservation--;
  2358. DebugAssert(Reservation == FPacketReservations->IndexOf(Packet));
  2359. }
  2360. }
  2361. break;
  2362. }
  2363. }
  2364. }
  2365. }
  2366. }
  2367. while (IsReserved);
  2368. }
  2369. if ((Packet->Capacity == 0) && DebugAlwaysTrue(TryOnly))
  2370. {
  2371. // noop
  2372. }
  2373. else
  2374. {
  2375. // before we removed the reservation after check for packet type,
  2376. // but if it raises exception, removal is unnecessarily
  2377. // postponed until the packet is removed
  2378. // (and it have not worked anyway until recent fix to UnreserveResponse)
  2379. if (Reservation >= 0)
  2380. {
  2381. DebugAssert(Packet->MessageNumber == (unsigned int)FPacketNumbers.GetElement(Reservation));
  2382. RemoveReservation(Reservation);
  2383. }
  2384. if (ExpectedType >= 0)
  2385. {
  2386. if (Packet->Type == SSH_FXP_STATUS)
  2387. {
  2388. if (AllowStatus < 0)
  2389. {
  2390. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  2391. }
  2392. Result = GotStatusPacket(Packet, AllowStatus);
  2393. }
  2394. else if (ExpectedType != Packet->Type)
  2395. {
  2396. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  2397. }
  2398. }
  2399. }
  2400. return Result;
  2401. }
  2402. //---------------------------------------------------------------------------
  2403. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  2404. TSFTPPacket * Response)
  2405. {
  2406. if (Response != NULL)
  2407. {
  2408. DebugAssert(FPacketReservations->IndexOf(Response) < 0);
  2409. // mark response as not received yet
  2410. Response->Capacity = 0;
  2411. Response->ReservedBy = this;
  2412. }
  2413. FPacketReservations->Add(Response);
  2414. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  2415. {
  2416. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  2417. }
  2418. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  2419. }
  2420. //---------------------------------------------------------------------------
  2421. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  2422. {
  2423. int Reservation = FPacketReservations->IndexOf(Response);
  2424. if (Response->Capacity != 0)
  2425. {
  2426. // added check for already received packet
  2427. // (it happens when the reserved response is received out of order,
  2428. // unexpectedly soon, and then receivepacket() on the packet
  2429. // is not actually called, due to exception)
  2430. RemoveReservation(Reservation);
  2431. }
  2432. else
  2433. {
  2434. if (Reservation >= 0)
  2435. {
  2436. // we probably do not remove the item at all, because
  2437. // we must remember that the response was expected, so we skip it
  2438. // in receivepacket()
  2439. FPacketReservations->Items[Reservation] = NULL;
  2440. }
  2441. }
  2442. }
  2443. //---------------------------------------------------------------------------
  2444. int __fastcall TSFTPFileSystem::ReceiveResponse(
  2445. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2446. int AllowStatus, bool TryOnly)
  2447. {
  2448. int Result;
  2449. unsigned int MessageNumber = Packet->MessageNumber;
  2450. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  2451. try
  2452. {
  2453. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus, TryOnly);
  2454. if (MessageNumber != AResponse->MessageNumber)
  2455. {
  2456. FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER,
  2457. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  2458. }
  2459. }
  2460. __finally
  2461. {
  2462. if (!Response)
  2463. {
  2464. delete AResponse;
  2465. }
  2466. }
  2467. return Result;
  2468. }
  2469. //---------------------------------------------------------------------------
  2470. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2471. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2472. int AllowStatus)
  2473. {
  2474. int Result;
  2475. TSFTPBusy Busy(this);
  2476. SendPacket(Packet);
  2477. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2478. return Result;
  2479. }
  2480. //---------------------------------------------------------------------------
  2481. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString Path)
  2482. {
  2483. try
  2484. {
  2485. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2486. {
  2487. FTerminal->LogEvent(FORMAT(L"Getting real path for '%s'", (Path)));
  2488. }
  2489. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2490. AddPathString(Packet, Path);
  2491. // In SFTP-6 new optional field control-byte is added that defaults to
  2492. // SSH_FXP_REALPATH_NO_CHECK=0x01, meaning it won't fail, if the path does not exist.
  2493. // That differs from SFTP-5 recommendation that
  2494. // "The server SHOULD fail the request if the path is not present on the server."
  2495. // Earlier versions had no recommendation, though canonical SFTP-3 implementation
  2496. // in OpenSSH fails.
  2497. // While we really do not care much, we anyway set the flag to ~ & 0x01 to make the request fail.
  2498. // First for consistency.
  2499. // Second to workaround a bug in ProFTPD/mod_sftp version 1.3.5rc1 through 1.3.5-stable
  2500. // that sends a completelly malformed response for non-existing paths,
  2501. // when SSH_FXP_REALPATH_NO_CHECK (even implicitly) is used.
  2502. // See http://bugs.proftpd.org/show_bug.cgi?id=4160
  2503. // Note that earlier drafts of SFTP-6 (filexfer-07 and -08) had optional compose-path field
  2504. // before control-byte field. If we ever use this against a server conforming to those drafts,
  2505. // it may cause trouble.
  2506. if (FVersion >= 6)
  2507. {
  2508. if (FSecureShell->SshImplementation != sshiProFTPD)
  2509. {
  2510. Packet.AddByte(SSH_FXP_REALPATH_STAT_ALWAYS);
  2511. }
  2512. else
  2513. {
  2514. // Cannot use SSH_FXP_REALPATH_STAT_ALWAYS as ProFTPD does wrong bitwise test
  2515. // so it incorrectly evaluates SSH_FXP_REALPATH_STAT_ALWAYS (0x03) as
  2516. // SSH_FXP_REALPATH_NO_CHECK (0x01). The only value conforming to the
  2517. // specification, yet working with ProFTPD is SSH_FXP_REALPATH_STAT_IF (0x02).
  2518. Packet.AddByte(SSH_FXP_REALPATH_STAT_IF);
  2519. }
  2520. }
  2521. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2522. if (Packet.GetCardinal() != 1)
  2523. {
  2524. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2525. }
  2526. UnicodeString RealDir = UnixExcludeTrailingBackslash(Packet.GetPathString(FUtfStrings));
  2527. RealDir = FTerminal->DecryptFileName(RealDir);
  2528. // ignore rest of SSH_FXP_NAME packet
  2529. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2530. {
  2531. FTerminal->LogEvent(FORMAT(L"Real path is '%s'", (RealDir)));
  2532. }
  2533. return RealDir;
  2534. }
  2535. catch(Exception & E)
  2536. {
  2537. if (FTerminal->Active)
  2538. {
  2539. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2540. }
  2541. else
  2542. {
  2543. throw;
  2544. }
  2545. }
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString Path,
  2549. const UnicodeString BaseDir)
  2550. {
  2551. UnicodeString APath;
  2552. if (UnixIsAbsolutePath(Path))
  2553. {
  2554. APath = Path;
  2555. }
  2556. else
  2557. {
  2558. if (!Path.IsEmpty())
  2559. {
  2560. // this condition/block was outside (before) current block
  2561. // but it did not work when Path was empty
  2562. if (!BaseDir.IsEmpty())
  2563. {
  2564. APath = UnixIncludeTrailingBackslash(BaseDir);
  2565. }
  2566. APath = APath + Path;
  2567. }
  2568. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(L".");
  2569. }
  2570. return RealPath(APath);
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. UnicodeString __fastcall TSFTPFileSystem::LocalCanonify(const UnicodeString & Path)
  2574. {
  2575. // TODO: improve (handle .. etc.)
  2576. if (UnixIsAbsolutePath(Path) ||
  2577. (!FCurrentDirectory.IsEmpty() && UnixSamePath(FCurrentDirectory, Path)))
  2578. {
  2579. return Path;
  2580. }
  2581. else
  2582. {
  2583. return ::AbsolutePath(FCurrentDirectory, Path);
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. UnicodeString __fastcall TSFTPFileSystem::Canonify(UnicodeString Path)
  2588. {
  2589. // inspired by canonify() from PSFTP.C
  2590. UnicodeString Result;
  2591. FTerminal->LogEvent(FORMAT(L"Canonifying: \"%s\"", (Path)));
  2592. Path = LocalCanonify(Path);
  2593. bool TryParent = false;
  2594. try
  2595. {
  2596. Result = RealPath(Path);
  2597. }
  2598. catch(...)
  2599. {
  2600. if (FTerminal->Active)
  2601. {
  2602. TryParent = true;
  2603. }
  2604. else
  2605. {
  2606. throw;
  2607. }
  2608. }
  2609. if (TryParent)
  2610. {
  2611. UnicodeString APath = UnixExcludeTrailingBackslash(Path);
  2612. UnicodeString Name = UnixExtractFileName(APath);
  2613. if (!IsRealFile(Name))
  2614. {
  2615. Result = Path;
  2616. }
  2617. else
  2618. {
  2619. UnicodeString FPath = UnixExtractFilePath(APath);
  2620. try
  2621. {
  2622. Result = RealPath(FPath);
  2623. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2624. }
  2625. catch(...)
  2626. {
  2627. if (FTerminal->Active)
  2628. {
  2629. Result = Path;
  2630. }
  2631. else
  2632. {
  2633. throw;
  2634. }
  2635. }
  2636. }
  2637. }
  2638. FTerminal->LogEvent(FORMAT(L"Canonified: \"%s\"", (Result)));
  2639. return Result;
  2640. }
  2641. //---------------------------------------------------------------------------
  2642. UnicodeString __fastcall TSFTPFileSystem::AbsolutePath(UnicodeString Path, bool Local)
  2643. {
  2644. if (Local)
  2645. {
  2646. return LocalCanonify(Path);
  2647. }
  2648. else
  2649. {
  2650. return RealPath(Path, CurrentDirectory);
  2651. }
  2652. }
  2653. //---------------------------------------------------------------------------
  2654. UnicodeString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2655. {
  2656. if (FHomeDirectory.IsEmpty())
  2657. {
  2658. FHomeDirectory = RealPath(L".");
  2659. }
  2660. return FHomeDirectory;
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2664. bool Complete)
  2665. {
  2666. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode, FUtfStrings, FSignedTS, Complete);
  2667. }
  2668. //---------------------------------------------------------------------------
  2669. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2670. TRemoteFile * ALinkedByFile, const UnicodeString FileName,
  2671. TRemoteFileList * TempFileList, bool Complete)
  2672. {
  2673. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2674. try
  2675. {
  2676. File->Terminal = FTerminal;
  2677. if (!FileName.IsEmpty())
  2678. {
  2679. File->FileName = FileName;
  2680. }
  2681. // to get full path for symlink completion
  2682. File->Directory = TempFileList;
  2683. LoadFile(File, Packet, Complete);
  2684. File->Directory = NULL;
  2685. }
  2686. catch(...)
  2687. {
  2688. delete File;
  2689. throw;
  2690. }
  2691. return File;
  2692. }
  2693. //---------------------------------------------------------------------------
  2694. UnicodeString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2695. {
  2696. return FCurrentDirectory;
  2697. }
  2698. //---------------------------------------------------------------------------
  2699. void __fastcall TSFTPFileSystem::DoStartup()
  2700. {
  2701. // do not know yet
  2702. FVersion = -1;
  2703. FFileSystemInfoValid = false;
  2704. TSFTPPacket Packet(SSH_FXP_INIT);
  2705. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2706. if (MaxVersion > SFTPMaxVersion)
  2707. {
  2708. MaxVersion = SFTPMaxVersion;
  2709. }
  2710. Packet.AddCardinal(MaxVersion);
  2711. try
  2712. {
  2713. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2714. }
  2715. catch(Exception &E)
  2716. {
  2717. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR), HELP_SFTP_INITIALIZE_ERROR);
  2718. }
  2719. FVersion = Packet.GetCardinal();
  2720. FTerminal->LogEvent(FORMAT(L"SFTP version %d negotiated.", (FVersion)));
  2721. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2722. {
  2723. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2724. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2725. }
  2726. FExtensions->Clear();
  2727. FEOL = "\r\n";
  2728. FSupport->Loaded = false;
  2729. FSupportsStatVfsV2 = false;
  2730. FSupportsHardlink = false;
  2731. SAFE_DESTROY(FFixedPaths);
  2732. if (FVersion >= 3)
  2733. {
  2734. while (Packet.GetNextData() != NULL)
  2735. {
  2736. UnicodeString ExtensionName = Packet.GetAnsiString();
  2737. RawByteString ExtensionData = Packet.GetRawByteString();
  2738. UnicodeString ExtensionDisplayData = DisplayableStr(ExtensionData);
  2739. if (ExtensionName == SFTP_EXT_NEWLINE)
  2740. {
  2741. FEOL = AnsiString(ExtensionData);
  2742. FTerminal->LogEvent(FORMAT(L"Server requests EOL sequence %s.",
  2743. (ExtensionDisplayData)));
  2744. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2745. {
  2746. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2747. }
  2748. }
  2749. // do not allow "supported" to override "supported2" if both are received
  2750. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2751. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2752. {
  2753. FSupport->Reset();
  2754. TSFTPPacket SupportedStruct(ExtensionData);
  2755. FSupport->Loaded = true;
  2756. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2757. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2758. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2759. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2760. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2761. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2762. {
  2763. while (SupportedStruct.GetNextData() != NULL)
  2764. {
  2765. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2766. }
  2767. }
  2768. else
  2769. {
  2770. // note that supported-open-block-vector, supported-block-vector,
  2771. // attrib-extension-count and attrib-extension-names fields
  2772. // were added only in rev 08, while "supported2" was defined in rev 07
  2773. FSupport->OpenBlockVector = SupportedStruct.GetSmallCardinal();
  2774. FSupport->BlockVector = SupportedStruct.GetSmallCardinal();
  2775. unsigned int ExtensionCount;
  2776. ExtensionCount = SupportedStruct.GetCardinal();
  2777. for (unsigned int i = 0; i < ExtensionCount; i++)
  2778. {
  2779. FSupport->AttribExtensions->Add(SupportedStruct.GetAnsiString());
  2780. }
  2781. ExtensionCount = SupportedStruct.GetCardinal();
  2782. for (unsigned int i = 0; i < ExtensionCount; i++)
  2783. {
  2784. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2785. }
  2786. }
  2787. if (FTerminal->Log->Logging)
  2788. {
  2789. FTerminal->LogEvent(FORMAT(
  2790. L"Server support information (%s):\n"
  2791. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2792. " Access mask: %x, Open block vector: %x, Block vector: %x, Max read size: %d\n",
  2793. (ExtensionName,
  2794. int(FSupport->AttributeMask),
  2795. int(FSupport->AttributeBits),
  2796. int(FSupport->OpenFlags),
  2797. int(FSupport->AccessMask),
  2798. int(FSupport->OpenBlockVector),
  2799. int(FSupport->BlockVector),
  2800. int(FSupport->MaxReadSize))));
  2801. FTerminal->LogEvent(FORMAT(L" Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2802. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2803. {
  2804. FTerminal->LogEvent(
  2805. FORMAT(L" %s", (FSupport->AttribExtensions->Strings[Index])));
  2806. }
  2807. FTerminal->LogEvent(FORMAT(L" Extensions (%d)\n", (FSupport->Extensions->Count)));
  2808. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2809. {
  2810. FTerminal->LogEvent(
  2811. FORMAT(L" %s", (FSupport->Extensions->Strings[Index])));
  2812. }
  2813. }
  2814. }
  2815. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2816. {
  2817. TSFTPPacket VendorIdStruct(ExtensionData);
  2818. UnicodeString VendorName(VendorIdStruct.GetAnsiString());
  2819. UnicodeString ProductName(VendorIdStruct.GetAnsiString());
  2820. UnicodeString ProductVersion(VendorIdStruct.GetAnsiString());
  2821. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2822. FTerminal->LogEvent(FORMAT(L"Server software: %s %s (%d) by %s",
  2823. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2824. }
  2825. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2826. {
  2827. FTerminal->LogEvent(L"File system roots:\n");
  2828. DebugAssert(FFixedPaths == NULL);
  2829. FFixedPaths = new TStringList();
  2830. try
  2831. {
  2832. TSFTPPacket RootsPacket(ExtensionData);
  2833. while (RootsPacket.GetNextData() != NULL)
  2834. {
  2835. unsigned long Dummy = RootsPacket.GetCardinal();
  2836. if (Dummy != 1)
  2837. {
  2838. break;
  2839. }
  2840. else
  2841. {
  2842. unsigned char Drive = RootsPacket.GetByte();
  2843. unsigned char MaybeType = RootsPacket.GetByte();
  2844. FTerminal->LogEvent(FORMAT(L" %s: (type %d)", (static_cast<char>(Drive), (int)MaybeType)));
  2845. FFixedPaths->Add(FORMAT(L"%s:", (static_cast<char>(Drive))));
  2846. }
  2847. }
  2848. }
  2849. catch(Exception & E)
  2850. {
  2851. FFixedPaths->Clear();
  2852. FTerminal->LogEvent(FORMAT(L"Failed to decode %s extension",
  2853. (SFTP_EXT_FSROOTS)));
  2854. FTerminal->HandleException(&E);
  2855. }
  2856. }
  2857. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2858. {
  2859. // first try legacy decoding according to incorrect encoding
  2860. // (structure-like) as of VShell (bug no longer present as of 4.0.3).
  2861. TSFTPPacket VersionsPacket(ExtensionData);
  2862. unsigned int StringSize;
  2863. if (VersionsPacket.CanGetString(StringSize) &&
  2864. (StringSize == VersionsPacket.RemainingLength))
  2865. {
  2866. UnicodeString Versions = VersionsPacket.GetAnsiString();
  2867. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server (VShell format): %s",
  2868. (Versions)));
  2869. }
  2870. else
  2871. {
  2872. // if that fails, fallback to proper decoding
  2873. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server: %s",
  2874. (AnsiToString(ExtensionData))));
  2875. }
  2876. }
  2877. else if (ExtensionName == SFTP_EXT_STATVFS)
  2878. {
  2879. UnicodeString StatVfsVersion = AnsiToString(ExtensionData);
  2880. if (StatVfsVersion == SFTP_EXT_STATVFS_VALUE_V2)
  2881. {
  2882. FSupportsStatVfsV2 = true;
  2883. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2884. }
  2885. else
  2886. {
  2887. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2888. }
  2889. }
  2890. else if (ExtensionName == SFTP_EXT_HARDLINK)
  2891. {
  2892. UnicodeString HardlinkVersion = AnsiToString(ExtensionData);
  2893. if (HardlinkVersion == SFTP_EXT_HARDLINK_VALUE_V1)
  2894. {
  2895. FSupportsHardlink = true;
  2896. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2897. }
  2898. else
  2899. {
  2900. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2901. }
  2902. }
  2903. else
  2904. {
  2905. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2906. {
  2907. FTerminal->LogEvent(FORMAT(L"Unknown server extension %s=%s",
  2908. (ExtensionName, ExtensionDisplayData)));
  2909. }
  2910. }
  2911. FExtensions->Values[ExtensionName] = ExtensionDisplayData;
  2912. }
  2913. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2914. {
  2915. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2916. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2917. Packet.AddString(FTerminal->Configuration->CompanyName);
  2918. Packet.AddString(FTerminal->Configuration->ProductName);
  2919. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2920. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2921. SendPacket(&Packet);
  2922. // we are not interested in the response, do not wait for it
  2923. ReceiveResponse(&Packet, &Packet);
  2924. //ReserveResponse(&Packet, NULL);
  2925. }
  2926. }
  2927. if (FVersion < 4)
  2928. {
  2929. // currently enable the bug for all servers (really known on OpenSSH)
  2930. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2931. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2932. if (FSignedTS)
  2933. {
  2934. FTerminal->LogEvent(L"We believe the server has signed timestamps bug");
  2935. }
  2936. }
  2937. else
  2938. {
  2939. FSignedTS = false;
  2940. }
  2941. switch (FTerminal->SessionData->NotUtf)
  2942. {
  2943. case asOff:
  2944. FUtfStrings = asOn;
  2945. FTerminal->LogEvent(L"We will use UTF-8 strings as configured");
  2946. break;
  2947. default:
  2948. DebugFail();
  2949. case asAuto:
  2950. // Nb, Foxit server does not exist anymore
  2951. if (GetSessionInfo().SshImplementation.Pos(L"Foxit-WAC-Server") == 1)
  2952. {
  2953. FUtfStrings = asOff;
  2954. FTerminal->LogEvent(L"We will not use UTF-8 strings as the server is known not to use them");
  2955. }
  2956. else
  2957. {
  2958. if (FVersion >= 4)
  2959. {
  2960. FTerminal->LogEvent(L"We will use UTF-8 strings as it is mandatory with SFTP version 4 and newer");
  2961. FUtfStrings = asOn;
  2962. }
  2963. else
  2964. {
  2965. FTerminal->LogEvent(L"We will use UTF-8 strings until server sends an invalid UTF-8 string as with SFTP version 3 and older UTF-8 strings are not mandatory");
  2966. FUtfStrings = asAuto;
  2967. FUtfDisablingAnnounced = false;
  2968. }
  2969. }
  2970. break;
  2971. case asOn:
  2972. FTerminal->LogEvent(L"We will not use UTF-8 strings as configured");
  2973. FUtfStrings = asOff;
  2974. break;
  2975. }
  2976. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2977. if (FMaxPacketSize == 0)
  2978. {
  2979. if ((FSecureShell->SshImplementation == sshiOpenSSH) && (FVersion == 3) && !FSupport->Loaded)
  2980. {
  2981. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2982. FTerminal->LogEvent(FORMAT(L"Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  2983. (int(FMaxPacketSize))));
  2984. }
  2985. // full string is "1.77 sshlib: Momentum SSH Server",
  2986. // possibly it is sshlib-related
  2987. else if (GetSessionInfo().SshImplementation.Pos(L"Momentum SSH Server") != 0)
  2988. {
  2989. FMaxPacketSize = 4 + (32 * 1024);
  2990. FTerminal->LogEvent(FORMAT(L"Limiting packet size to Momentum sftp-server limit of %d bytes",
  2991. (int(FMaxPacketSize))));
  2992. }
  2993. }
  2994. }
  2995. //---------------------------------------------------------------------------
  2996. char * __fastcall TSFTPFileSystem::GetEOL() const
  2997. {
  2998. if (FVersion >= 4)
  2999. {
  3000. DebugAssert(!FEOL.IsEmpty());
  3001. return FEOL.c_str();
  3002. }
  3003. else
  3004. {
  3005. return EOLToStr(FTerminal->SessionData->EOLType);
  3006. }
  3007. }
  3008. //---------------------------------------------------------------------------
  3009. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  3010. {
  3011. DebugAssert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  3012. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  3013. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  3014. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  3015. TRemoteTokenList * Lists[] = { &FTerminal->FUsers, &FTerminal->FGroups };
  3016. wchar_t ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  3017. for (size_t Index = 0; Index < LENOF(Packets); Index++)
  3018. {
  3019. TSFTPPacket * Packet = Packets[Index];
  3020. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  3021. Packet->AddByte(ListTypes[Index]);
  3022. SendPacket(Packet);
  3023. ReserveResponse(Packet, Packet);
  3024. }
  3025. for (size_t Index = 0; Index < LENOF(Packets); Index++)
  3026. {
  3027. TSFTPPacket * Packet = Packets[Index];
  3028. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  3029. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  3030. (Packet->GetAnsiString() != SFTP_EXT_OWNER_GROUP_REPLY))
  3031. {
  3032. FTerminal->LogEvent(FORMAT(L"Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  3033. }
  3034. else
  3035. {
  3036. TRemoteTokenList & List = *Lists[Index];
  3037. unsigned long Count = Packet->GetCardinal();
  3038. List.Clear();
  3039. for (unsigned long Item = 0; Item < Count; Item++)
  3040. {
  3041. TRemoteToken Token(Packet->GetString(FUtfStrings));
  3042. List.Add(Token);
  3043. if (&List == &FTerminal->FGroups)
  3044. {
  3045. FTerminal->FMembership.Add(Token);
  3046. }
  3047. }
  3048. }
  3049. }
  3050. }
  3051. //---------------------------------------------------------------------------
  3052. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  3053. {
  3054. if (!FDirectoryToChangeTo.IsEmpty())
  3055. {
  3056. FCurrentDirectory = FDirectoryToChangeTo;
  3057. FDirectoryToChangeTo = L"";
  3058. }
  3059. else if (FCurrentDirectory.IsEmpty())
  3060. {
  3061. // this happens only after startup when default remote directory is not specified
  3062. FCurrentDirectory = GetHomeDirectory();
  3063. }
  3064. }
  3065. //---------------------------------------------------------------------------
  3066. void __fastcall TSFTPFileSystem::HomeDirectory()
  3067. {
  3068. ChangeDirectory(GetHomeDirectory());
  3069. }
  3070. //---------------------------------------------------------------------------
  3071. void __fastcall TSFTPFileSystem::TryOpenDirectory(const UnicodeString Directory)
  3072. {
  3073. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  3074. TRemoteFile * File;
  3075. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  3076. if (File == NULL)
  3077. {
  3078. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  3079. // Fallback to legacy solution, which in turn does not allow entering
  3080. // traverse-only (chmod 110) directories.
  3081. // This is workaround for http://www.ftpshell.com/
  3082. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  3083. AddPathString(Packet, UnixExcludeTrailingBackslash(Directory));
  3084. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3085. RawByteString Handle = Packet.GetFileHandle();
  3086. Packet.ChangeType(SSH_FXP_CLOSE);
  3087. Packet.AddString(Handle);
  3088. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  3089. }
  3090. else
  3091. {
  3092. delete File;
  3093. }
  3094. }
  3095. //---------------------------------------------------------------------------
  3096. void __fastcall TSFTPFileSystem::AnnounceFileListOperation()
  3097. {
  3098. }
  3099. //---------------------------------------------------------------------------
  3100. void __fastcall TSFTPFileSystem::ChangeDirectory(const UnicodeString Directory)
  3101. {
  3102. UnicodeString Path, Current;
  3103. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  3104. Path = RealPath(Directory, Current);
  3105. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  3106. // for invalid paths on some systems, like CygWin)
  3107. TryOpenDirectory(Path);
  3108. // if open dir did not fail, directory exists -> success.
  3109. FDirectoryToChangeTo = Path;
  3110. }
  3111. //---------------------------------------------------------------------------
  3112. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  3113. {
  3114. FDirectoryToChangeTo = UnixExcludeTrailingBackslash(Directory);
  3115. }
  3116. //---------------------------------------------------------------------------
  3117. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  3118. {
  3119. DebugAssert(FileList && !FileList->Directory.IsEmpty());
  3120. UnicodeString Directory;
  3121. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  3122. FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".", (Directory)));
  3123. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  3124. // old data (e.g. parent directory) when reading fails
  3125. FileList->Reset();
  3126. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  3127. RawByteString Handle;
  3128. try
  3129. {
  3130. AddPathString(Packet, Directory);
  3131. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3132. Handle = Packet.GetFileHandle();
  3133. }
  3134. catch(...)
  3135. {
  3136. if (FTerminal->Active)
  3137. {
  3138. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  3139. }
  3140. throw;
  3141. }
  3142. TSFTPPacket Response;
  3143. try
  3144. {
  3145. bool isEOF = false;
  3146. int Total = 0;
  3147. bool HasParentDirectory = false;
  3148. TRemoteFile * File;
  3149. Packet.ChangeType(SSH_FXP_READDIR);
  3150. Packet.AddString(Handle);
  3151. SendPacket(&Packet);
  3152. do
  3153. {
  3154. ReceiveResponse(&Packet, &Response);
  3155. if (Response.Type == SSH_FXP_NAME)
  3156. {
  3157. TSFTPPacket ListingPacket = Response;
  3158. Packet.ChangeType(SSH_FXP_READDIR);
  3159. Packet.AddString(Handle);
  3160. SendPacket(&Packet);
  3161. ReserveResponse(&Packet, &Response);
  3162. unsigned int Count = ListingPacket.GetCardinal();
  3163. int ResolvedLinks = 0;
  3164. for (unsigned long Index = 0; !isEOF && (Index < Count); Index++)
  3165. {
  3166. File = LoadFile(&ListingPacket, NULL, L"", FileList);
  3167. FileList->AddFile(File);
  3168. if (FTerminal->IsEncryptingFiles() && // optimization
  3169. IsRealFile(File->FileName))
  3170. {
  3171. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  3172. UnicodeString FileName = UnixExtractFileName(FTerminal->DecryptFileName(FullFileName));
  3173. if (File->FileName != FileName)
  3174. {
  3175. File->SetEncrypted();
  3176. }
  3177. File->FileName = FileName;
  3178. }
  3179. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3180. {
  3181. FTerminal->LogEvent(FORMAT(L"Read file '%s' from listing", (File->FileName)));
  3182. }
  3183. if (File->LinkedFile != NULL)
  3184. {
  3185. ResolvedLinks++;
  3186. }
  3187. if (File->IsParentDirectory)
  3188. {
  3189. HasParentDirectory = true;
  3190. }
  3191. Total++;
  3192. if (Total % 10 == 0)
  3193. {
  3194. FTerminal->DoReadDirectoryProgress(Total, ResolvedLinks, isEOF);
  3195. if (isEOF)
  3196. {
  3197. FTerminal->DoReadDirectoryProgress(-2, 0, isEOF);
  3198. }
  3199. }
  3200. }
  3201. if ((FVersion >= 6) &&
  3202. // As of 7.0.9 the Cerberus SFTP server always sets the end-of-list to true.
  3203. // Fixed in 7.0.10.
  3204. (FSecureShell->SshImplementation != sshiCerberus) &&
  3205. ListingPacket.CanGetBool())
  3206. {
  3207. isEOF = ListingPacket.GetBool();
  3208. }
  3209. if (Count == 0)
  3210. {
  3211. FTerminal->LogEvent(L"Empty directory listing packet. Aborting directory reading.");
  3212. isEOF = true;
  3213. }
  3214. }
  3215. else if (Response.Type == SSH_FXP_STATUS)
  3216. {
  3217. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  3218. }
  3219. else
  3220. {
  3221. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  3222. }
  3223. }
  3224. while (!isEOF);
  3225. if (Total == 0)
  3226. {
  3227. bool Failure = false;
  3228. // no point reading parent of root directory,
  3229. // moreover CompleteFTP terminates session upon attempt to do so
  3230. if (IsUnixRootPath(FileList->Directory))
  3231. {
  3232. File = NULL;
  3233. }
  3234. else
  3235. {
  3236. // Empty file list -> probably "permission denied", we
  3237. // at least get link to parent directory ("..")
  3238. try
  3239. {
  3240. FTerminal->ExceptionOnFail = true;
  3241. try
  3242. {
  3243. File = NULL;
  3244. FTerminal->ReadFile(
  3245. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  3246. }
  3247. __finally
  3248. {
  3249. FTerminal->ExceptionOnFail = false;
  3250. }
  3251. }
  3252. catch(Exception &E)
  3253. {
  3254. if (E.InheritsFrom(__classid(EFatal)))
  3255. {
  3256. throw;
  3257. }
  3258. else
  3259. {
  3260. File = NULL;
  3261. Failure = true;
  3262. }
  3263. }
  3264. }
  3265. // on some systems even getting ".." fails, we create dummy ".." instead
  3266. if (File == NULL)
  3267. {
  3268. File = new TRemoteParentDirectory(FTerminal);
  3269. }
  3270. DebugAssert(File && File->IsParentDirectory);
  3271. FileList->AddFile(File);
  3272. if (Failure)
  3273. {
  3274. throw ExtException(
  3275. NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
  3276. HELP_EMPTY_DIRECTORY);
  3277. }
  3278. }
  3279. else
  3280. {
  3281. if (!HasParentDirectory)
  3282. {
  3283. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  3284. }
  3285. }
  3286. }
  3287. __finally
  3288. {
  3289. if (FTerminal->Active)
  3290. {
  3291. Packet.ChangeType(SSH_FXP_CLOSE);
  3292. Packet.AddString(Handle);
  3293. SendPacket(&Packet);
  3294. // we are not interested in the response, do not wait for it
  3295. ReserveResponse(&Packet, NULL);
  3296. }
  3297. }
  3298. }
  3299. //---------------------------------------------------------------------------
  3300. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  3301. TRemoteFile *& File)
  3302. {
  3303. DebugAssert(SymlinkFile && SymlinkFile->IsSymLink);
  3304. DebugAssert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  3305. // need to use full filename when resolving links within subdirectory
  3306. // (i.e. for download)
  3307. UnicodeString FileName = LocalCanonify(
  3308. SymlinkFile->Directory != NULL ? SymlinkFile->FullFileName : SymlinkFile->FileName);
  3309. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  3310. AddPathString(ReadLinkPacket, FileName);
  3311. SendPacket(&ReadLinkPacket);
  3312. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  3313. // send second request before reading response to first one
  3314. // (performance benefit)
  3315. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  3316. AddPathString(AttrsPacket, FileName);
  3317. if (FVersion >= 4)
  3318. {
  3319. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  3320. }
  3321. SendPacket(&AttrsPacket);
  3322. ReserveResponse(&AttrsPacket, &AttrsPacket);
  3323. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  3324. if (ReadLinkPacket.GetCardinal() != 1)
  3325. {
  3326. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  3327. }
  3328. SymlinkFile->LinkTo = FTerminal->DecryptFileName(ReadLinkPacket.GetPathString(FUtfStrings));
  3329. FTerminal->LogEvent(FORMAT(L"Link resolved to \"%s\".", (SymlinkFile->LinkTo)));
  3330. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  3331. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  3332. File = LoadFile(&AttrsPacket, SymlinkFile,
  3333. UnixExtractFileName(SymlinkFile->LinkTo));
  3334. }
  3335. //---------------------------------------------------------------------------
  3336. void __fastcall TSFTPFileSystem::ReadFile(const UnicodeString FileName,
  3337. TRemoteFile *& File)
  3338. {
  3339. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  3340. }
  3341. //---------------------------------------------------------------------------
  3342. bool __fastcall TSFTPFileSystem::RemoteFileExists(const UnicodeString FullPath,
  3343. TRemoteFile ** File)
  3344. {
  3345. bool Result;
  3346. try
  3347. {
  3348. TRemoteFile * AFile;
  3349. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  3350. Result = (AFile != NULL);
  3351. if (Result)
  3352. {
  3353. if (File)
  3354. {
  3355. *File = AFile;
  3356. }
  3357. else
  3358. {
  3359. delete AFile;
  3360. }
  3361. }
  3362. }
  3363. catch(...)
  3364. {
  3365. if (!FTerminal->Active)
  3366. {
  3367. throw;
  3368. }
  3369. Result = false;
  3370. }
  3371. return Result;
  3372. }
  3373. //---------------------------------------------------------------------------
  3374. void __fastcall TSFTPFileSystem::SendCustomReadFile(TSFTPPacket * Packet,
  3375. TSFTPPacket * Response, unsigned long Flags)
  3376. {
  3377. if (FVersion >= 4)
  3378. {
  3379. Packet->AddCardinal(Flags);
  3380. }
  3381. SendPacket(Packet);
  3382. ReserveResponse(Packet, Response);
  3383. }
  3384. //---------------------------------------------------------------------------
  3385. void __fastcall TSFTPFileSystem::CustomReadFile(const UnicodeString FileName,
  3386. TRemoteFile *& File, unsigned char Type, TRemoteFile * ALinkedByFile,
  3387. int AllowStatus)
  3388. {
  3389. unsigned long Flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  3390. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  3391. SSH_FILEXFER_ATTR_OWNERGROUP;
  3392. TSFTPPacket Packet(Type);
  3393. AddPathString(Packet, LocalCanonify(FileName));
  3394. SendCustomReadFile(&Packet, &Packet, Flags);
  3395. ReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS, AllowStatus);
  3396. if (Packet.Type == SSH_FXP_ATTRS)
  3397. {
  3398. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  3399. if (FTerminal->IsFileEncrypted(FileName))
  3400. {
  3401. File->SetEncrypted();
  3402. }
  3403. }
  3404. else
  3405. {
  3406. DebugAssert(AllowStatus > 0);
  3407. File = NULL;
  3408. }
  3409. }
  3410. //---------------------------------------------------------------------------
  3411. void __fastcall TSFTPFileSystem::DoDeleteFile(const UnicodeString FileName, unsigned char Type)
  3412. {
  3413. TSFTPPacket Packet(Type);
  3414. UnicodeString RealFileName = LocalCanonify(FileName);
  3415. AddPathString(Packet, RealFileName);
  3416. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3417. }
  3418. //---------------------------------------------------------------------------
  3419. void __fastcall TSFTPFileSystem::DeleteFile(const UnicodeString FileName,
  3420. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3421. {
  3422. unsigned char Type;
  3423. if (FTerminal->DeleteContentsIfDirectory(FileName, File, Params, Action))
  3424. {
  3425. Type = SSH_FXP_RMDIR;
  3426. }
  3427. else
  3428. {
  3429. Type = SSH_FXP_REMOVE;
  3430. }
  3431. DoDeleteFile(FileName, Type);
  3432. }
  3433. //---------------------------------------------------------------------------
  3434. void __fastcall TSFTPFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  3435. const UnicodeString NewName)
  3436. {
  3437. TSFTPPacket Packet(SSH_FXP_RENAME);
  3438. UnicodeString RealName = LocalCanonify(FileName);
  3439. bool Encrypted = FTerminal->IsFileEncrypted(RealName);
  3440. AddPathString(Packet, RealName);
  3441. UnicodeString TargetName;
  3442. if (UnixExtractFilePath(NewName).IsEmpty())
  3443. {
  3444. // rename case (TTerminal::RenameFile)
  3445. TargetName = UnixExtractFilePath(RealName) + NewName;
  3446. }
  3447. else
  3448. {
  3449. TargetName = LocalCanonify(NewName);
  3450. }
  3451. AddPathString(Packet, TargetName, Encrypted);
  3452. if (FVersion >= 5)
  3453. {
  3454. Packet.AddCardinal(0);
  3455. }
  3456. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3457. }
  3458. //---------------------------------------------------------------------------
  3459. void __fastcall TSFTPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  3460. const UnicodeString NewName)
  3461. {
  3462. // Implemented by ProFTPD/mod_sftp and Bitvise WinSSHD (without announcing it)
  3463. DebugAssert(SupportsExtension(SFTP_EXT_COPY_FILE) || (FSecureShell->SshImplementation == sshiBitvise));
  3464. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3465. Packet.AddString(SFTP_EXT_COPY_FILE);
  3466. UnicodeString RealName = Canonify(FileName);
  3467. bool Encrypted = FTerminal->IsFileEncrypted(RealName);
  3468. AddPathString(Packet, RealName);
  3469. AddPathString(Packet, Canonify(NewName), Encrypted);
  3470. Packet.AddBool(false);
  3471. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3472. }
  3473. //---------------------------------------------------------------------------
  3474. void __fastcall TSFTPFileSystem::CreateDirectory(const UnicodeString & DirName, bool Encrypt)
  3475. {
  3476. TSFTPPacket Packet(SSH_FXP_MKDIR);
  3477. UnicodeString CanonifiedName = Canonify(DirName);
  3478. AddPathString(Packet, CanonifiedName, Encrypt);
  3479. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings, NULL);
  3480. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3481. }
  3482. //---------------------------------------------------------------------------
  3483. void __fastcall TSFTPFileSystem::CreateLink(const UnicodeString FileName,
  3484. const UnicodeString PointTo, bool Symbolic)
  3485. {
  3486. // Cerberus server does not even respond to LINK or SYMLINK,
  3487. // Although its log says:
  3488. // Unrecognized SFTP client command: (20)
  3489. // Unknown SFTP packet - Sending Unsupported OP response
  3490. DebugAssert(FVersion >= 3); // links are supported with SFTP version 3 and later
  3491. bool UseLink = (FVersion >= 6);
  3492. bool UseHardlink = !Symbolic && !UseLink && FSupportsHardlink;
  3493. TSFTPPacket Packet(UseHardlink ? SSH_FXP_EXTENDED : (UseLink ? SSH_FXP_LINK : SSH_FXP_SYMLINK));
  3494. if (UseHardlink)
  3495. {
  3496. Packet.AddString(SFTP_EXT_HARDLINK);
  3497. }
  3498. bool Buggy;
  3499. // OpenSSH hardlink extension always uses the "wrong" order
  3500. // as it's defined as such to mimic OpenSSH symlink bug
  3501. if (UseHardlink)
  3502. {
  3503. Buggy = true; //sic
  3504. }
  3505. else
  3506. {
  3507. if (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn)
  3508. {
  3509. Buggy = true;
  3510. FTerminal->LogEvent(L"Forcing workaround for SFTP link bug");
  3511. }
  3512. else if (FTerminal->SessionData->SFTPBug[sbSymlink] == asOff)
  3513. {
  3514. Buggy = false;
  3515. }
  3516. else
  3517. {
  3518. if (UseLink)
  3519. {
  3520. if (FSecureShell->SshImplementation == sshiProFTPD)
  3521. {
  3522. // ProFTPD/mod_sftp followed OpenSSH symlink bug even for link implementation.
  3523. // This will be fixed with the next release with
  3524. // SSH version string bumbed to "mod_sftp/1.0.0"
  3525. // http://bugs.proftpd.org/show_bug.cgi?id=4080
  3526. UnicodeString ProFTPDVerStr = GetSessionInfo().SshImplementation;
  3527. CutToChar(ProFTPDVerStr, L'/', false);
  3528. int ProFTPDMajorVer = StrToIntDef(CutToChar(ProFTPDVerStr, L'.', false), 0);
  3529. Buggy = (ProFTPDMajorVer == 0);
  3530. if (Buggy)
  3531. {
  3532. FTerminal->LogEvent(L"We believe the server has SFTP link bug");
  3533. }
  3534. }
  3535. else
  3536. {
  3537. Buggy = false;
  3538. }
  3539. }
  3540. else
  3541. {
  3542. // ProFTPD/mod_sftp deliberately follows OpenSSH bug.
  3543. // Though we should get here with ProFTPD only when user forced
  3544. // SFTP version < 6 or when connecting to an ancient version of ProFTPD.
  3545. Buggy =
  3546. (FSecureShell->SshImplementation == sshiOpenSSH) ||
  3547. (FSecureShell->SshImplementation == sshiProFTPD);
  3548. if (Buggy)
  3549. {
  3550. FTerminal->LogEvent(L"We believe the server has SFTP symlink bug");
  3551. }
  3552. }
  3553. }
  3554. }
  3555. UnicodeString FinalPointTo = PointTo;
  3556. UnicodeString FinalFileName = Canonify(FileName);
  3557. if (!Symbolic)
  3558. {
  3559. FinalPointTo = Canonify(PointTo);
  3560. }
  3561. // creating symlinks is not allowed when encryption is enabled, so we are not considering encryption here
  3562. if (!Buggy)
  3563. {
  3564. AddPathString(Packet, FinalFileName);
  3565. AddPathString(Packet, FinalPointTo);
  3566. }
  3567. else
  3568. {
  3569. AddPathString(Packet, FinalPointTo);
  3570. AddPathString(Packet, FinalFileName);
  3571. }
  3572. if (UseLink)
  3573. {
  3574. Packet.AddBool(Symbolic);
  3575. }
  3576. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3577. }
  3578. //---------------------------------------------------------------------------
  3579. void __fastcall TSFTPFileSystem::ChangeFileProperties(const UnicodeString FileName,
  3580. const TRemoteFile * /*File*/, const TRemoteProperties * AProperties,
  3581. TChmodSessionAction & Action)
  3582. {
  3583. DebugAssert(AProperties != NULL);
  3584. TRemoteFile * File;
  3585. UnicodeString RealFileName = LocalCanonify(FileName);
  3586. ReadFile(RealFileName, File);
  3587. try
  3588. {
  3589. DebugAssert(File);
  3590. if (File->IsDirectory && FTerminal->CanRecurseToDirectory(File) && AProperties->Recursive)
  3591. {
  3592. try
  3593. {
  3594. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  3595. (void*)AProperties);
  3596. }
  3597. catch(...)
  3598. {
  3599. Action.Cancel();
  3600. throw;
  3601. }
  3602. }
  3603. // SFTP can change owner and group at the same time only, not individually.
  3604. // Fortunately we know current owner/group, so if only one is present,
  3605. // we can supplement the other.
  3606. TRemoteProperties Properties(*AProperties);
  3607. if (Properties.Valid.Contains(vpGroup) &&
  3608. !Properties.Valid.Contains(vpOwner))
  3609. {
  3610. Properties.Owner = File->Owner;
  3611. Properties.Valid << vpOwner;
  3612. }
  3613. else if (Properties.Valid.Contains(vpOwner) &&
  3614. !Properties.Valid.Contains(vpGroup))
  3615. {
  3616. Properties.Group = File->Group;
  3617. Properties.Valid << vpGroup;
  3618. }
  3619. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  3620. AddPathString(Packet, RealFileName);
  3621. Packet.AddProperties(&Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings, &Action);
  3622. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3623. }
  3624. __finally
  3625. {
  3626. delete File;
  3627. }
  3628. }
  3629. //---------------------------------------------------------------------------
  3630. bool __fastcall TSFTPFileSystem::LoadFilesProperties(TStrings * FileList)
  3631. {
  3632. bool Result = false;
  3633. // without knowledge of server's capabilities, this all make no sense
  3634. if (FSupport->Loaded || (FSecureShell->SshImplementation == sshiBitvise))
  3635. {
  3636. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3637. Progress.Start(foGetProperties, osRemote, FileList->Count);
  3638. FTerminal->FOperationProgress = &Progress;
  3639. static int LoadFilesPropertiesQueueLen = 5;
  3640. TSFTPLoadFilesPropertiesQueue Queue(this);
  3641. try
  3642. {
  3643. if (Queue.Init(LoadFilesPropertiesQueueLen, FileList))
  3644. {
  3645. TRemoteFile * File;
  3646. TSFTPPacket Packet;
  3647. bool Next;
  3648. do
  3649. {
  3650. Next = Queue.ReceivePacket(&Packet, File);
  3651. DebugAssert((Packet.Type == SSH_FXP_ATTRS) || (Packet.Type == SSH_FXP_STATUS));
  3652. if (Packet.Type == SSH_FXP_ATTRS)
  3653. {
  3654. DebugAssert(File != NULL);
  3655. Progress.SetFile(File->FileName);
  3656. LoadFile(File, &Packet);
  3657. Result = true;
  3658. TOnceDoneOperation OnceDoneOperation;
  3659. Progress.Finish(File->FileName, true, OnceDoneOperation);
  3660. }
  3661. if (Progress.Cancel != csContinue)
  3662. {
  3663. Next = false;
  3664. }
  3665. }
  3666. while (Next);
  3667. }
  3668. }
  3669. __finally
  3670. {
  3671. Queue.DisposeSafe();
  3672. FTerminal->FOperationProgress = NULL;
  3673. Progress.Stop();
  3674. }
  3675. // queue is discarded here
  3676. }
  3677. return Result;
  3678. }
  3679. //---------------------------------------------------------------------------
  3680. void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(
  3681. const UnicodeString & Alg, const UnicodeString & SftpAlg,
  3682. TStrings * FileList, TStrings * Checksums,
  3683. TCalculatedChecksumEvent OnCalculatedChecksum,
  3684. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  3685. {
  3686. TOnceDoneOperation OnceDoneOperation; // not used
  3687. // recurse into subdirectories only if we have callback function
  3688. if (OnCalculatedChecksum != NULL)
  3689. {
  3690. for (int Index = 0; Index < FileList->Count; Index++)
  3691. {
  3692. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  3693. DebugAssert(File != NULL);
  3694. if (File->IsDirectory && FTerminal->CanRecurseToDirectory(File) &&
  3695. IsRealFile(File->FileName))
  3696. {
  3697. OperationProgress->SetFile(File->FileName);
  3698. TRemoteFileList * SubFiles =
  3699. FTerminal->CustomReadDirectoryListing(File->FullFileName, false);
  3700. if (SubFiles != NULL)
  3701. {
  3702. TStrings * SubFileList = new TStringList();
  3703. bool Success = false;
  3704. try
  3705. {
  3706. OperationProgress->SetFile(File->FileName);
  3707. for (int Index = 0; Index < SubFiles->Count; Index++)
  3708. {
  3709. TRemoteFile * SubFile = SubFiles->Files[Index];
  3710. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  3711. }
  3712. // do not collect checksums for files in subdirectories,
  3713. // only send back checksums via callback
  3714. DoCalculateFilesChecksum(Alg, SftpAlg, SubFileList, NULL,
  3715. OnCalculatedChecksum, OperationProgress, false);
  3716. Success = true;
  3717. }
  3718. __finally
  3719. {
  3720. delete SubFiles;
  3721. delete SubFileList;
  3722. if (FirstLevel)
  3723. {
  3724. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3725. }
  3726. }
  3727. }
  3728. }
  3729. }
  3730. }
  3731. static int CalculateFilesChecksumQueueLen = 5;
  3732. TSFTPCalculateFilesChecksumQueue Queue(this);
  3733. try
  3734. {
  3735. if (Queue.Init(CalculateFilesChecksumQueueLen, SftpAlg, FileList))
  3736. {
  3737. TSFTPPacket Packet;
  3738. bool Next;
  3739. do
  3740. {
  3741. bool Success = false;
  3742. UnicodeString Checksum;
  3743. TRemoteFile * File = NULL;
  3744. try
  3745. {
  3746. TChecksumSessionAction Action(FTerminal->ActionLog);
  3747. try
  3748. {
  3749. Next = Queue.ReceivePacket(&Packet, File);
  3750. DebugAssert(Packet.Type == SSH_FXP_EXTENDED_REPLY);
  3751. OperationProgress->SetFile(File->FileName);
  3752. Action.FileName(FTerminal->AbsolutePath(File->FullFileName, true));
  3753. // skip alg
  3754. Packet.GetAnsiString();
  3755. Checksum = BytesToHex(reinterpret_cast<const unsigned char*>(Packet.GetNextData(Packet.RemainingLength)), Packet.RemainingLength, false);
  3756. if (OnCalculatedChecksum != NULL)
  3757. {
  3758. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  3759. }
  3760. Action.Checksum(Alg, Checksum);
  3761. Success = true;
  3762. }
  3763. catch (Exception & E)
  3764. {
  3765. FTerminal->RollbackAction(Action, OperationProgress, &E);
  3766. // Error formatting expanded from inline to avoid strange exceptions
  3767. UnicodeString Error =
  3768. FMTLOAD(CHECKSUM_ERROR,
  3769. (File != NULL ? File->FullFileName : UnicodeString(L"")));
  3770. FTerminal->CommandError(&E, Error);
  3771. // TODO: retries? resume?
  3772. Next = false;
  3773. }
  3774. if (Checksums != NULL)
  3775. {
  3776. Checksums->Add(Checksum);
  3777. }
  3778. }
  3779. __finally
  3780. {
  3781. if (FirstLevel)
  3782. {
  3783. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3784. }
  3785. }
  3786. if (OperationProgress->Cancel != csContinue)
  3787. {
  3788. Next = false;
  3789. }
  3790. }
  3791. while (Next);
  3792. }
  3793. }
  3794. __finally
  3795. {
  3796. Queue.DisposeSafe();
  3797. }
  3798. // queue is discarded here
  3799. }
  3800. //---------------------------------------------------------------------------
  3801. void __fastcall TSFTPFileSystem::CalculateFilesChecksum(const UnicodeString & Alg,
  3802. TStrings * FileList, TStrings * Checksums,
  3803. TCalculatedChecksumEvent OnCalculatedChecksum)
  3804. {
  3805. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3806. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  3807. UnicodeString NormalizedAlg = FindIdent(Alg, FChecksumAlgs.get());
  3808. UnicodeString SftpAlg;
  3809. int Index = FChecksumAlgs->IndexOf(NormalizedAlg);
  3810. if (Index >= 0)
  3811. {
  3812. SftpAlg = FChecksumSftpAlgs->Strings[Index];
  3813. }
  3814. else
  3815. {
  3816. // try user-specified alg
  3817. SftpAlg = NormalizedAlg;
  3818. }
  3819. FTerminal->FOperationProgress = &Progress;
  3820. try
  3821. {
  3822. DoCalculateFilesChecksum(NormalizedAlg, SftpAlg, FileList, Checksums, OnCalculatedChecksum,
  3823. &Progress, true);
  3824. }
  3825. __finally
  3826. {
  3827. FTerminal->FOperationProgress = NULL;
  3828. Progress.Stop();
  3829. }
  3830. }
  3831. //---------------------------------------------------------------------------
  3832. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  3833. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  3834. TCaptureOutputEvent /*OutputEvent*/)
  3835. {
  3836. DebugFail();
  3837. }
  3838. //---------------------------------------------------------------------------
  3839. void __fastcall TSFTPFileSystem::AnyCommand(const UnicodeString /*Command*/,
  3840. TCaptureOutputEvent /*OutputEvent*/)
  3841. {
  3842. DebugFail();
  3843. }
  3844. //---------------------------------------------------------------------------
  3845. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  3846. {
  3847. return FFixedPaths;
  3848. }
  3849. //---------------------------------------------------------------------------
  3850. void __fastcall TSFTPFileSystem::SpaceAvailable(const UnicodeString Path,
  3851. TSpaceAvailable & ASpaceAvailable)
  3852. {
  3853. if (SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  3854. // See comment in IsCapable
  3855. (FSecureShell->SshImplementation == sshiBitvise))
  3856. {
  3857. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3858. Packet.AddString(SFTP_EXT_SPACE_AVAILABLE);
  3859. AddPathString(Packet, LocalCanonify(Path));
  3860. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3861. ASpaceAvailable.BytesOnDevice = Packet.GetInt64();
  3862. ASpaceAvailable.UnusedBytesOnDevice = Packet.GetInt64();
  3863. ASpaceAvailable.BytesAvailableToUser = Packet.GetInt64();
  3864. ASpaceAvailable.UnusedBytesAvailableToUser = Packet.GetInt64();
  3865. // bytes-per-allocation-unit was added later to the protocol
  3866. // (revision 07, while the extension was defined already in rev 06),
  3867. // be tolerant
  3868. if (Packet.CanGetCardinal())
  3869. {
  3870. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetCardinal();
  3871. }
  3872. else if (Packet.CanGetSmallCardinal())
  3873. {
  3874. // See http://bugs.proftpd.org/show_bug.cgi?id=4079
  3875. FTerminal->LogEvent(L"Assuming ProFTPD/mod_sftp bug of 2-byte bytes-per-allocation-unit field");
  3876. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetSmallCardinal();
  3877. }
  3878. else
  3879. {
  3880. FTerminal->LogEvent(L"Missing bytes-per-allocation-unit field");
  3881. }
  3882. }
  3883. else if (DebugAlwaysTrue(FSupportsStatVfsV2))
  3884. {
  3885. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL
  3886. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3887. Packet.AddString(SFTP_EXT_STATVFS);
  3888. AddPathString(Packet, LocalCanonify(Path));
  3889. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3890. __int64 BlockSize = Packet.GetInt64(); // file system block size
  3891. __int64 FundamentalBlockSize = Packet.GetInt64(); // fundamental fs block size
  3892. __int64 Blocks = Packet.GetInt64(); // number of blocks (unit f_frsize)
  3893. __int64 FreeBlocks = Packet.GetInt64(); // free blocks in file system
  3894. __int64 AvailableBlocks = Packet.GetInt64(); // free blocks for non-root
  3895. __int64 FileINodes = Packet.GetInt64(); // total file inodes
  3896. __int64 FreeFileINodes = Packet.GetInt64(); // free file inodes
  3897. __int64 AvailableFileINodes = Packet.GetInt64(); // free file inodes for to non-root
  3898. __int64 SID = Packet.GetInt64(); // file system id
  3899. __int64 Flags = Packet.GetInt64(); // bit mask of f_flag values
  3900. __int64 NameMax = Packet.GetInt64(); // maximum filename length
  3901. FTerminal->LogEvent(FORMAT(L"Block size: %s", (IntToStr(BlockSize))));
  3902. FTerminal->LogEvent(FORMAT(L"Fundamental block size: %s", (IntToStr(FundamentalBlockSize))));
  3903. FTerminal->LogEvent(FORMAT(L"Total blocks: %s", (IntToStr(Blocks))));
  3904. FTerminal->LogEvent(FORMAT(L"Free blocks: %s", (IntToStr(FreeBlocks))));
  3905. FTerminal->LogEvent(FORMAT(L"Free blocks for non-root: %s", (IntToStr(AvailableBlocks))));
  3906. FTerminal->LogEvent(FORMAT(L"Total file inodes: %s", (IntToStr(FileINodes))));
  3907. FTerminal->LogEvent(FORMAT(L"Free file inodes: %s", (IntToStr(FreeFileINodes))));
  3908. FTerminal->LogEvent(FORMAT(L"Free file inodes for non-root: %s", (IntToStr(AvailableFileINodes))));
  3909. FTerminal->LogEvent(FORMAT(L"File system ID: %s", (BytesToHex(reinterpret_cast<const unsigned char *>(&SID), sizeof(SID)))));
  3910. UnicodeString FlagStr;
  3911. if (FLAGSET(Flags, SFTP_EXT_STATVFS_ST_RDONLY))
  3912. {
  3913. AddToList(FlagStr, L"read-only", L",");
  3914. Flags -= SFTP_EXT_STATVFS_ST_RDONLY;
  3915. }
  3916. if (FLAGSET(Flags, SFTP_EXT_STATVFS_ST_NOSUID))
  3917. {
  3918. AddToList(FlagStr, L"no-setuid", L",");
  3919. Flags -= SFTP_EXT_STATVFS_ST_NOSUID;
  3920. }
  3921. if (Flags != 0)
  3922. {
  3923. AddToList(FlagStr, UnicodeString(L"0x") + IntToHex(Flags, 2), L",");
  3924. }
  3925. if (FlagStr.IsEmpty())
  3926. {
  3927. FlagStr = L"none";
  3928. }
  3929. FTerminal->LogEvent(FORMAT(L"Flags: %s", (FlagStr)));
  3930. FTerminal->LogEvent(FORMAT(L"Max name length: %s", (IntToStr(NameMax))));
  3931. ASpaceAvailable.BytesOnDevice = BlockSize * Blocks;
  3932. ASpaceAvailable.UnusedBytesOnDevice = BlockSize * FreeBlocks;
  3933. ASpaceAvailable.BytesAvailableToUser = 0;
  3934. ASpaceAvailable.UnusedBytesAvailableToUser = BlockSize * AvailableBlocks;
  3935. ASpaceAvailable.BytesPerAllocationUnit =
  3936. (BlockSize > std::numeric_limits<unsigned long>::max()) ? 0 : static_cast<unsigned long>(BlockSize);
  3937. }
  3938. }
  3939. //---------------------------------------------------------------------------
  3940. // transfer protocol
  3941. //---------------------------------------------------------------------------
  3942. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  3943. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  3944. int Params, TFileOperationProgressType * OperationProgress,
  3945. TOnceDoneOperation & OnceDoneOperation)
  3946. {
  3947. TAutoFlag AvoidBusyFlag(FAvoidBusy);
  3948. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  3949. }
  3950. //---------------------------------------------------------------------------
  3951. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(
  3952. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  3953. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  3954. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  3955. {
  3956. bool CanAppend = !FTerminal->IsEncryptingFiles() && ((FVersion < 4) || !OperationProgress->AsciiTransfer);
  3957. unsigned int Answer;
  3958. {
  3959. TSuspendFileOperationProgress Suspend(OperationProgress);
  3960. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  3961. // possibly we can allow alternate resume at least in some cases
  3962. if (CanAppend)
  3963. {
  3964. Answers |= qaRetry;
  3965. }
  3966. TQueryButtonAlias Aliases[5];
  3967. Aliases[0].Button = qaRetry;
  3968. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  3969. Aliases[0].GroupWith = qaNo;
  3970. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  3971. Aliases[1] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  3972. Aliases[2] = TQueryButtonAlias::CreateIgnoreAsRenameGrouppedWithNo();
  3973. Aliases[3] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  3974. Aliases[4] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  3975. TQueryParams QueryParams(qpNeverAskAgainCheck);
  3976. QueryParams.NoBatchAnswers = qaIgnore | qaRetry | qaAll;
  3977. QueryParams.Aliases = Aliases;
  3978. QueryParams.AliasesCount = LENOF(Aliases);
  3979. Answer = FTerminal->ConfirmFileOverwrite(
  3980. SourceFullFileName, TargetFileName, FileParams,
  3981. Answers, &QueryParams,
  3982. ReverseOperationSide(OperationProgress->Side),
  3983. CopyParam, Params, OperationProgress);
  3984. }
  3985. if (CanAppend &&
  3986. ((Answer == qaRetry) || (Answer == qaSkip)))
  3987. {
  3988. OperationProgress->LockUserSelections();
  3989. try
  3990. {
  3991. // duplicated in TTerminal::ConfirmFileOverwrite
  3992. bool CanAlternateResume =
  3993. (FileParams->DestSize < FileParams->SourceSize) && !OperationProgress->AsciiTransfer;
  3994. TBatchOverwrite BatchOverwrite =
  3995. FTerminal->EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  3996. // when mode is forced by batch, never query user
  3997. if (BatchOverwrite == boAppend)
  3998. {
  3999. OverwriteMode = omAppend;
  4000. }
  4001. else if (CanAlternateResume &&
  4002. ((BatchOverwrite == boResume) || (BatchOverwrite == boAlternateResume)))
  4003. {
  4004. OverwriteMode = omResume;
  4005. }
  4006. // no other option, but append
  4007. else if (!CanAlternateResume)
  4008. {
  4009. OverwriteMode = omAppend;
  4010. }
  4011. else
  4012. {
  4013. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  4014. {
  4015. TSuspendFileOperationProgress Suspend(OperationProgress);
  4016. Answer = FTerminal->QueryUser(FORMAT(LoadStr(APPEND_OR_RESUME2), (SourceFullFileName)),
  4017. NULL, qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  4018. }
  4019. switch (Answer)
  4020. {
  4021. case qaYes:
  4022. OverwriteMode = omAppend;
  4023. break;
  4024. case qaNo:
  4025. OverwriteMode = omResume;
  4026. break;
  4027. case qaNoToAll:
  4028. OverwriteMode = omResume;
  4029. OperationProgress->SetBatchOverwrite(boAlternateResume);
  4030. break;
  4031. default: DebugFail(); //fallthru
  4032. case qaCancel:
  4033. OperationProgress->SetCancelAtLeast(csCancel);
  4034. Abort();
  4035. break;
  4036. }
  4037. }
  4038. }
  4039. __finally
  4040. {
  4041. OperationProgress->UnlockUserSelections();
  4042. }
  4043. }
  4044. else if (Answer == qaIgnore)
  4045. {
  4046. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName, LoadStr(RENAME_TITLE), L"",
  4047. LoadStr(RENAME_PROMPT2), true, 0, TargetFileName))
  4048. {
  4049. OverwriteMode = omOverwrite;
  4050. }
  4051. else
  4052. {
  4053. OperationProgress->SetCancelAtLeast(csCancel);
  4054. Abort();
  4055. }
  4056. }
  4057. else
  4058. {
  4059. OverwriteMode = omOverwrite;
  4060. switch (Answer)
  4061. {
  4062. case qaCancel:
  4063. OperationProgress->SetCancelAtLeast(csCancel);
  4064. Abort();
  4065. break;
  4066. case qaNo:
  4067. throw ESkipFile();
  4068. }
  4069. }
  4070. }
  4071. //---------------------------------------------------------------------------
  4072. bool TSFTPFileSystem::SFTPConfirmResume(const UnicodeString DestFileName,
  4073. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  4074. {
  4075. bool ResumeTransfer;
  4076. DebugAssert(OperationProgress);
  4077. if (PartialBiggerThanSource)
  4078. {
  4079. unsigned int Answer;
  4080. {
  4081. TSuspendFileOperationProgress Suspend(OperationProgress);
  4082. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  4083. Answer = FTerminal->QueryUser(
  4084. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  4085. qaOK | qaAbort, &Params, qtWarning);
  4086. }
  4087. if (Answer == qaAbort)
  4088. {
  4089. OperationProgress->SetCancelAtLeast(csCancel);
  4090. Abort();
  4091. }
  4092. ResumeTransfer = false;
  4093. }
  4094. else if (FTerminal->Configuration->ConfirmResume)
  4095. {
  4096. unsigned int Answer;
  4097. {
  4098. TSuspendFileOperationProgress Suspend(OperationProgress);
  4099. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  4100. HELP_RESUME_TRANSFER);
  4101. // "abort" replaced with "cancel" to unify with "append/resume" query
  4102. Answer = FTerminal->QueryUser(
  4103. FMTLOAD(RESUME_TRANSFER2, (DestFileName)), NULL, qaYes | qaNo | qaCancel,
  4104. &Params);
  4105. }
  4106. switch (Answer) {
  4107. case qaNeverAskAgain:
  4108. FTerminal->Configuration->ConfirmResume = false;
  4109. case qaYes:
  4110. ResumeTransfer = true;
  4111. break;
  4112. case qaNo:
  4113. ResumeTransfer = false;
  4114. break;
  4115. case qaCancel:
  4116. OperationProgress->SetCancelAtLeast(csCancel);
  4117. Abort();
  4118. break;
  4119. }
  4120. }
  4121. else
  4122. {
  4123. ResumeTransfer = true;
  4124. }
  4125. return ResumeTransfer;
  4126. }
  4127. //---------------------------------------------------------------------------
  4128. void __fastcall TSFTPFileSystem::Source(
  4129. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  4130. const TCopyParamType * CopyParam, int Params,
  4131. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  4132. TUploadSessionAction & Action, bool & ChildError)
  4133. {
  4134. UnicodeString DestFullName = LocalCanonify(TargetDir + DestFileName);
  4135. UnicodeString DestPartialFullName;
  4136. bool ResumeAllowed;
  4137. bool ResumeTransfer = false;
  4138. bool DestFileExists = false;
  4139. TRights DestRights;
  4140. __int64 ResumeOffset;
  4141. // should we check for interrupted transfer?
  4142. ResumeAllowed =
  4143. !OperationProgress->AsciiTransfer &&
  4144. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  4145. IsCapable(fcRename) &&
  4146. !FTerminal->IsEncryptingFiles();
  4147. TOpenRemoteFileParams OpenParams;
  4148. OpenParams.OverwriteMode = omOverwrite;
  4149. TOverwriteFileParams FileParams;
  4150. FileParams.SourceSize = OperationProgress->LocalSize;
  4151. FileParams.SourceTimestamp = Handle.Modification;
  4152. if (ResumeAllowed)
  4153. {
  4154. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4155. if (FLAGCLEAR(Flags, tfNewDirectory))
  4156. {
  4157. FTerminal->LogEvent(L"Checking existence of file.");
  4158. TRemoteFile * File = NULL;
  4159. DestFileExists = RemoteFileExists(DestFullName, &File);
  4160. OperationProgress->Progress();
  4161. if (DestFileExists)
  4162. {
  4163. FTerminal->LogEvent(FORMAT(L"File exists: %s", (FTerminal->GetRemoteFileInfo(File))));
  4164. OpenParams.DestFileSize = File->Size;
  4165. FileParams.DestSize = OpenParams.DestFileSize;
  4166. FileParams.DestTimestamp = File->Modification;
  4167. DestRights = *File->Rights;
  4168. // If destination file is symlink, never do resumable transfer,
  4169. // as it would delete the symlink.
  4170. if (File->IsSymLink)
  4171. {
  4172. ResumeAllowed = false;
  4173. FTerminal->LogEvent(L"Existing file is symbolic link, not doing resumable transfer.");
  4174. }
  4175. // Also bit of heuristics to detect symlink on SFTP-3 and older
  4176. // (which does not indicate symlink in SSH_FXP_ATTRS).
  4177. // if file has all permissions and is small, then it is likely symlink.
  4178. // also it is not likely that such a small file (if it is not symlink)
  4179. // gets overwritten by large file (that would trigger resumable transfer).
  4180. else if ((FVersion < 4) &&
  4181. ((*File->Rights & TRights::rfAll) == TRights::rfAll) &&
  4182. (File->Size < 100))
  4183. {
  4184. ResumeAllowed = false;
  4185. FTerminal->LogEvent(L"Existing file looks like a symbolic link, not doing resumable transfer.");
  4186. }
  4187. // Also never do resumable transfer for file owned by other user
  4188. // as deleting and recreating the file would change ownership.
  4189. // This won't for work for SFTP-3 (OpenSSH) as it does not provide
  4190. // owner name (only UID) and we know only logged in user name (not UID)
  4191. else if (!File->Owner.Name.IsEmpty() && !SameUserName(File->Owner.Name, FTerminal->UserName))
  4192. {
  4193. ResumeAllowed = false;
  4194. FTerminal->LogEvent(
  4195. FORMAT(L"Existing file is owned by another user [%s], not doing resumable transfer.", (File->Owner.Name)));
  4196. }
  4197. delete File;
  4198. File = NULL;
  4199. }
  4200. if (ResumeAllowed)
  4201. {
  4202. FTerminal->LogEvent(L"Checking existence of partially transferred file.");
  4203. if (RemoteFileExists(DestPartialFullName, &File))
  4204. {
  4205. ResumeOffset = File->Size;
  4206. delete File;
  4207. File = NULL;
  4208. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  4209. if (FLAGCLEAR(Params, cpNoConfirmation) &&
  4210. FLAGCLEAR(Params, cpResume) &&
  4211. !CopyParam->ResumeTransfer(Handle.FileName))
  4212. {
  4213. ResumeTransfer = SFTPConfirmResume(DestFileName,
  4214. PartialBiggerThanSource, OperationProgress);
  4215. }
  4216. else
  4217. {
  4218. ResumeTransfer = !PartialBiggerThanSource;
  4219. }
  4220. if (!ResumeTransfer)
  4221. {
  4222. DoDeleteFile(DestPartialFullName, SSH_FXP_REMOVE);
  4223. OperationProgress->Progress();
  4224. }
  4225. else
  4226. {
  4227. FTerminal->LogEvent(L"Resuming file transfer.");
  4228. }
  4229. }
  4230. else
  4231. {
  4232. // partial upload file does not exists, check for full file
  4233. if (DestFileExists)
  4234. {
  4235. UnicodeString PrevDestFileName = DestFileName;
  4236. SFTPConfirmOverwrite(Handle.FileName, DestFileName,
  4237. CopyParam, Params, OperationProgress, OpenParams.OverwriteMode, &FileParams);
  4238. if (PrevDestFileName != DestFileName)
  4239. {
  4240. // update paths in case user changes the file name
  4241. DestFullName = LocalCanonify(TargetDir + DestFileName);
  4242. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4243. FTerminal->LogEvent(L"Checking existence of new file.");
  4244. DestFileExists = RemoteFileExists(DestFullName, NULL);
  4245. }
  4246. }
  4247. }
  4248. }
  4249. }
  4250. }
  4251. // will the transfer be resumable?
  4252. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  4253. UnicodeString RemoteFileName = DoResume ? DestPartialFullName : DestFullName;
  4254. OpenParams.FileName = Handle.FileName;
  4255. OpenParams.RemoteFileName = RemoteFileName;
  4256. OpenParams.Resume = DoResume;
  4257. OpenParams.Resuming = ResumeTransfer;
  4258. OpenParams.OperationProgress = OperationProgress;
  4259. OpenParams.CopyParam = CopyParam;
  4260. OpenParams.Params = Params;
  4261. OpenParams.FileParams = &FileParams;
  4262. OpenParams.Confirmed = false;
  4263. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  4264. {
  4265. FTerminal->LogEvent(L"Opening remote file.");
  4266. }
  4267. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, folAllowSkip,
  4268. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  4269. &OpenParams);
  4270. OperationProgress->Progress();
  4271. if (OpenParams.RemoteFileName != RemoteFileName)
  4272. {
  4273. DebugAssert(!DoResume);
  4274. DebugAssert(UnixExtractFilePath(OpenParams.RemoteFileName) == UnixExtractFilePath(RemoteFileName));
  4275. DestFullName = OpenParams.RemoteFileName;
  4276. UnicodeString NewFileName = UnixExtractFileName(DestFullName);
  4277. DebugAssert(DestFileName != NewFileName);
  4278. DestFileName = NewFileName;
  4279. }
  4280. Action.Destination(DestFullName);
  4281. bool TransferFinished = false;
  4282. __int64 DestWriteOffset = 0;
  4283. TSFTPPacket CloseRequest;
  4284. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  4285. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  4286. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  4287. TSFTPPacket PropertiesResponse;
  4288. TRights Rights;
  4289. if (SetProperties)
  4290. {
  4291. AddPathString(PropertiesRequest, DestFullName);
  4292. if (CopyParam->PreserveRights)
  4293. {
  4294. Rights = CopyParam->RemoteFileRights(Handle.Attrs);
  4295. }
  4296. else if (DoResume && DestFileExists)
  4297. {
  4298. Rights = DestRights;
  4299. }
  4300. else
  4301. {
  4302. DebugAssert(!SetRights);
  4303. }
  4304. unsigned short RightsNumber = Rights.NumberSet;
  4305. PropertiesRequest.AddProperties(
  4306. SetRights ? &RightsNumber : NULL, NULL, NULL,
  4307. CopyParam->PreserveTime ? &Handle.MTime : NULL,
  4308. NULL, NULL, false, FVersion, FUtfStrings);
  4309. }
  4310. try
  4311. {
  4312. if (OpenParams.OverwriteMode == omAppend)
  4313. {
  4314. FTerminal->LogEvent(L"Appending file.");
  4315. DestWriteOffset = OpenParams.DestFileSize;
  4316. }
  4317. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  4318. {
  4319. if (OpenParams.OverwriteMode == omResume)
  4320. {
  4321. FTerminal->LogEvent(L"Resuming file transfer (append style).");
  4322. ResumeOffset = OpenParams.DestFileSize;
  4323. }
  4324. FileSeek((THandle)Handle.Handle, ResumeOffset, 0);
  4325. OperationProgress->AddResumed(ResumeOffset);
  4326. }
  4327. TEncryption Encryption(FTerminal->GetEncryptKey());
  4328. bool Encrypt = FTerminal->IsFileEncrypted(DestFullName, CopyParam->EncryptNewFiles);
  4329. TSFTPUploadQueue Queue(this, (Encrypt ? &Encryption : NULL));
  4330. try
  4331. {
  4332. int ConvertParams =
  4333. FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
  4334. FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
  4335. Queue.Init(Handle.FileName, Handle.Handle, OperationProgress,
  4336. OpenParams.RemoteFileHandle,
  4337. DestWriteOffset + OperationProgress->TransferredSize,
  4338. ConvertParams);
  4339. while (Queue.Continue())
  4340. {
  4341. if (OperationProgress->Cancel)
  4342. {
  4343. if (OperationProgress->ClearCancelFile())
  4344. {
  4345. throw ESkipFile();
  4346. }
  4347. else
  4348. {
  4349. Abort();
  4350. }
  4351. }
  4352. }
  4353. // send close request before waiting for pending read responses
  4354. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4355. OperationProgress, false, true, &CloseRequest);
  4356. OpenParams.RemoteFileHandle = L"";
  4357. // when resuming is disabled, we can send "set properties"
  4358. // request before waiting for pending read/close responses
  4359. if (SetProperties && !DoResume)
  4360. {
  4361. SendPacket(&PropertiesRequest);
  4362. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  4363. }
  4364. // No error so far, processes pending responses and throw on first error
  4365. Queue.DisposeSafeWithErrorHandling();
  4366. }
  4367. __finally
  4368. {
  4369. // Either queue is empty now (noop call then),
  4370. // or some error occured (in that case, process remaining responses, ignoring other errors)
  4371. Queue.DisposeSafe();
  4372. }
  4373. TransferFinished = true;
  4374. // queue is discarded here
  4375. }
  4376. __finally
  4377. {
  4378. if (FTerminal->Active)
  4379. {
  4380. // if file transfer was finished, the close request was already sent
  4381. if (!OpenParams.RemoteFileHandle.IsEmpty())
  4382. {
  4383. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4384. OperationProgress, TransferFinished, true, &CloseRequest);
  4385. }
  4386. // wait for the response
  4387. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4388. OperationProgress, TransferFinished, false, &CloseRequest);
  4389. // delete file if transfer was not completed, resuming was not allowed and
  4390. // we were not appending (incl. alternate resume),
  4391. // shortly after plain transfer completes (eq. !ResumeAllowed)
  4392. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  4393. {
  4394. DoDeleteFile(OpenParams.RemoteFileName, SSH_FXP_REMOVE);
  4395. }
  4396. }
  4397. }
  4398. OperationProgress->Progress();
  4399. if (DoResume)
  4400. {
  4401. if (DestFileExists)
  4402. {
  4403. FILE_OPERATION_LOOP_BEGIN
  4404. {
  4405. if (FTerminal->SessionData->OverwrittenToRecycleBin &&
  4406. !FTerminal->SessionData->RecycleBinPath.IsEmpty())
  4407. {
  4408. FTerminal->RecycleFile(DestFullName, NULL);
  4409. }
  4410. else
  4411. {
  4412. DoDeleteFile(DestFullName, SSH_FXP_REMOVE);
  4413. }
  4414. }
  4415. FILE_OPERATION_LOOP_END(
  4416. FMTLOAD(DELETE_ON_RESUME_ERROR,
  4417. (UnixExtractFileName(DestFullName), DestFullName)));
  4418. }
  4419. // originally this was before CLOSE (last __finally statement),
  4420. // on VShell it failed
  4421. FILE_OPERATION_LOOP_BEGIN
  4422. {
  4423. RenameFile(OpenParams.RemoteFileName, NULL, DestFileName);
  4424. }
  4425. FILE_OPERATION_LOOP_END_CUSTOM(
  4426. FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  4427. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  4428. folAllowSkip, HELP_RENAME_AFTER_RESUME_ERROR);
  4429. }
  4430. if (SetProperties)
  4431. {
  4432. std::unique_ptr<TTouchSessionAction> TouchAction;
  4433. if (CopyParam->PreserveTime)
  4434. {
  4435. TDateTime MDateTime = UnixToDateTime(Handle.MTime, FTerminal->SessionData->DSTMode);
  4436. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  4437. (StandardTimestamp(MDateTime))));
  4438. TouchAction.reset(new TTouchSessionAction(FTerminal->ActionLog, DestFullName,
  4439. MDateTime));
  4440. }
  4441. std::unique_ptr<TChmodSessionAction> ChmodAction;
  4442. // do record chmod only if it was explicitly requested,
  4443. // not when it was implicitly performed to apply timestamp
  4444. // of overwritten file to new file
  4445. if (CopyParam->PreserveRights)
  4446. {
  4447. ChmodAction.reset(new TChmodSessionAction(FTerminal->ActionLog, DestFullName, Rights));
  4448. }
  4449. try
  4450. {
  4451. // when resuming is enabled, the set properties request was not sent yet
  4452. if (DoResume)
  4453. {
  4454. SendPacket(&PropertiesRequest);
  4455. }
  4456. bool Resend = false;
  4457. FILE_OPERATION_LOOP_BEGIN
  4458. {
  4459. try
  4460. {
  4461. TSFTPPacket DummyResponse;
  4462. TSFTPPacket * Response = &PropertiesResponse;
  4463. if (Resend)
  4464. {
  4465. PropertiesRequest.Reuse();
  4466. SendPacket(&PropertiesRequest);
  4467. // ReceiveResponse currently cannot receive twice into same packet,
  4468. // so DummyResponse is temporary workaround
  4469. Response = &DummyResponse;
  4470. }
  4471. Resend = true;
  4472. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS,
  4473. asOK | FLAGMASK(CopyParam->IgnorePermErrors, asPermDenied));
  4474. }
  4475. catch (...)
  4476. {
  4477. if (FTerminal->Active &&
  4478. (!CopyParam->PreserveRights && !CopyParam->PreserveTime))
  4479. {
  4480. DebugAssert(DoResume);
  4481. FTerminal->LogEvent(L"Ignoring error preserving permissions of overwritten file");
  4482. }
  4483. else
  4484. {
  4485. throw;
  4486. }
  4487. }
  4488. }
  4489. FILE_OPERATION_LOOP_END_CUSTOM(
  4490. FMTLOAD(PRESERVE_TIME_PERM_ERROR3, (DestFileName)),
  4491. folAllowSkip, HELP_PRESERVE_TIME_PERM_ERROR);
  4492. }
  4493. catch(Exception & E)
  4494. {
  4495. if (TouchAction.get() != NULL)
  4496. {
  4497. TouchAction->Rollback(&E);
  4498. }
  4499. if (ChmodAction.get() != NULL)
  4500. {
  4501. ChmodAction->Rollback(&E);
  4502. }
  4503. ChildError = true;
  4504. throw;
  4505. }
  4506. }
  4507. }
  4508. //---------------------------------------------------------------------------
  4509. RawByteString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  4510. const UnicodeString & FileName, unsigned int OpenType, bool EncryptNewFiles, __int64 Size)
  4511. {
  4512. TSFTPPacket Packet(SSH_FXP_OPEN);
  4513. AddPathString(Packet, FileName, EncryptNewFiles);
  4514. if (FVersion < 5)
  4515. {
  4516. Packet.AddCardinal(OpenType);
  4517. }
  4518. else
  4519. {
  4520. unsigned long Access =
  4521. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  4522. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  4523. unsigned long Flags;
  4524. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  4525. {
  4526. Flags = SSH_FXF_CREATE_NEW;
  4527. }
  4528. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  4529. {
  4530. Flags = SSH_FXF_CREATE_TRUNCATE;
  4531. }
  4532. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  4533. {
  4534. Flags = SSH_FXF_OPEN_OR_CREATE;
  4535. }
  4536. else
  4537. {
  4538. Flags = SSH_FXF_OPEN_EXISTING;
  4539. }
  4540. Flags |=
  4541. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  4542. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  4543. Packet.AddCardinal(Access);
  4544. Packet.AddCardinal(Flags);
  4545. }
  4546. bool SendSize =
  4547. (Size >= 0) &&
  4548. FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC) &&
  4549. // Particuarly VanDyke VShell (4.0.3) does not support SSH_FILEXFER_ATTR_ALLOCATION_SIZE
  4550. // (it fails open request when the attribute is included).
  4551. // It's SFTP-6 attribute, so support structure should be available.
  4552. // It's actually not with VShell. But VShell supports the SSH_FILEXFER_ATTR_ALLOCATION_SIZE.
  4553. // All servers should support SSH_FILEXFER_ATTR_SIZE (SFTP < 6)
  4554. (!FSupport->Loaded || FLAGSET(FSupport->AttributeMask, Packet.AllocationSizeAttribute(FVersion)));
  4555. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  4556. SendSize ? &Size : NULL, false, FVersion, FUtfStrings);
  4557. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  4558. return Packet.GetFileHandle();
  4559. }
  4560. //---------------------------------------------------------------------------
  4561. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  4562. {
  4563. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  4564. DebugAssert(OpenParams);
  4565. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  4566. int OpenType;
  4567. bool Success = false;
  4568. bool ConfirmOverwriting;
  4569. do
  4570. {
  4571. try
  4572. {
  4573. ConfirmOverwriting =
  4574. !OpenParams->Confirmed && !OpenParams->Resume &&
  4575. FTerminal->CheckRemoteFile(OpenParams->FileName, OpenParams->CopyParam, OpenParams->Params, OperationProgress);
  4576. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  4577. // when we want to preserve overwritten files, we need to find out that
  4578. // they exist first... even if overwrite confirmation is disabled.
  4579. // but not when we already know we are not going to overwrite (but e.g. to append)
  4580. if ((ConfirmOverwriting || FTerminal->SessionData->OverwrittenToRecycleBin) &&
  4581. (OpenParams->OverwriteMode == omOverwrite))
  4582. {
  4583. OpenType |= SSH_FXF_EXCL;
  4584. }
  4585. if (!OpenParams->Resuming && (OpenParams->OverwriteMode == omOverwrite))
  4586. {
  4587. OpenType |= SSH_FXF_TRUNC;
  4588. }
  4589. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  4590. {
  4591. OpenType |= SSH_FXF_TEXT;
  4592. }
  4593. OpenParams->RemoteFileHandle =
  4594. SFTPOpenRemoteFile(OpenParams->RemoteFileName, OpenType, OpenParams->CopyParam->EncryptNewFiles, OperationProgress->LocalSize);
  4595. Success = true;
  4596. }
  4597. catch(Exception & E)
  4598. {
  4599. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  4600. {
  4601. FTerminal->LogEvent(FORMAT(L"Cannot create new file \"%s\", checking if it exists already", (OpenParams->RemoteFileName)));
  4602. bool ThrowOriginal = false;
  4603. // When exclusive opening of file fails, try to detect if file exists.
  4604. // When file does not exist, failure was probably caused by 'permission denied'
  4605. // or similar error. In this case throw original exception.
  4606. try
  4607. {
  4608. OperationProgress->Progress();
  4609. TRemoteFile * File;
  4610. UnicodeString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4611. ReadFile(RealFileName, File);
  4612. DebugAssert(File);
  4613. OpenParams->DestFileSize = File->Size;
  4614. if (OpenParams->FileParams != NULL)
  4615. {
  4616. OpenParams->FileParams->DestTimestamp = File->Modification;
  4617. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  4618. }
  4619. // file exists (otherwise exception was thrown)
  4620. SAFE_DESTROY(File);
  4621. }
  4622. catch(...)
  4623. {
  4624. if (!FTerminal->Active)
  4625. {
  4626. throw;
  4627. }
  4628. else
  4629. {
  4630. ThrowOriginal = true;
  4631. }
  4632. }
  4633. if (ThrowOriginal)
  4634. {
  4635. throw;
  4636. }
  4637. // we may get here even if confirmation is disabled,
  4638. // when we have preserving of overwritten files enabled
  4639. if (ConfirmOverwriting)
  4640. {
  4641. OperationProgress->Progress();
  4642. // confirmation duplicated in SFTPSource for resumable file transfers.
  4643. UnicodeString RemoteFileNameOnly = UnixExtractFileName(OpenParams->RemoteFileName);
  4644. SFTPConfirmOverwrite(OpenParams->FileName, RemoteFileNameOnly,
  4645. OpenParams->CopyParam, OpenParams->Params, OperationProgress, OpenParams->OverwriteMode, OpenParams->FileParams);
  4646. if (RemoteFileNameOnly != UnixExtractFileName(OpenParams->RemoteFileName))
  4647. {
  4648. OpenParams->RemoteFileName =
  4649. UnixExtractFilePath(OpenParams->RemoteFileName) + RemoteFileNameOnly;
  4650. }
  4651. OpenParams->Confirmed = true;
  4652. }
  4653. else
  4654. {
  4655. DebugAssert(FTerminal->SessionData->OverwrittenToRecycleBin);
  4656. }
  4657. if ((OpenParams->OverwriteMode == omOverwrite) &&
  4658. FTerminal->SessionData->OverwrittenToRecycleBin &&
  4659. !FTerminal->SessionData->RecycleBinPath.IsEmpty())
  4660. {
  4661. OperationProgress->Progress();
  4662. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  4663. }
  4664. }
  4665. else if (FTerminal->Active)
  4666. {
  4667. // if file overwriting was confirmed, it means that the file already exists,
  4668. // if not, check now
  4669. if (!OpenParams->Confirmed)
  4670. {
  4671. bool ThrowOriginal = false;
  4672. // When file does not exist, failure was probably caused by 'permission denied'
  4673. // or similar error. In this case throw original exception.
  4674. try
  4675. {
  4676. TRemoteFile * File;
  4677. UnicodeString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4678. ReadFile(RealFileName, File);
  4679. SAFE_DESTROY(File);
  4680. }
  4681. catch(...)
  4682. {
  4683. if (!FTerminal->Active)
  4684. {
  4685. throw;
  4686. }
  4687. else
  4688. {
  4689. ThrowOriginal = true;
  4690. }
  4691. }
  4692. if (ThrowOriginal)
  4693. {
  4694. throw;
  4695. }
  4696. }
  4697. // now we know that the file exists
  4698. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  4699. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR2, (OpenParams->RemoteFileName)),
  4700. folAllowSkip, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  4701. {
  4702. OperationProgress->Progress();
  4703. int Params = dfNoRecursive;
  4704. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Params);
  4705. }
  4706. }
  4707. else
  4708. {
  4709. throw;
  4710. }
  4711. }
  4712. }
  4713. while (!Success);
  4714. return 0;
  4715. }
  4716. //---------------------------------------------------------------------------
  4717. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const RawByteString Handle,
  4718. const UnicodeString FileName, TFileOperationProgressType * OperationProgress,
  4719. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  4720. {
  4721. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  4722. FILE_OPERATION_LOOP_BEGIN
  4723. {
  4724. try
  4725. {
  4726. TSFTPPacket CloseRequest;
  4727. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  4728. if (Request)
  4729. {
  4730. P->ChangeType(SSH_FXP_CLOSE);
  4731. P->AddString(Handle);
  4732. SendPacket(P);
  4733. ReserveResponse(P, Packet);
  4734. }
  4735. else
  4736. {
  4737. DebugAssert(Packet != NULL);
  4738. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  4739. }
  4740. }
  4741. catch(...)
  4742. {
  4743. if (!FTerminal->Active || TransferFinished)
  4744. {
  4745. throw;
  4746. }
  4747. }
  4748. }
  4749. FILE_OPERATION_LOOP_END(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)));
  4750. }
  4751. //---------------------------------------------------------------------------
  4752. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  4753. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  4754. int Params, TFileOperationProgressType * OperationProgress,
  4755. TOnceDoneOperation & OnceDoneOperation)
  4756. {
  4757. TAutoFlag AvoidBusyFlag(FAvoidBusy);
  4758. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  4759. }
  4760. //---------------------------------------------------------------------------
  4761. void __fastcall TSFTPFileSystem::DirectorySunk(
  4762. const UnicodeString & DestFullName, const TRemoteFile * File, const TCopyParamType * CopyParam)
  4763. {
  4764. if (CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  4765. {
  4766. // FILE_FLAG_BACKUP_SEMANTICS is needed to "open" directory
  4767. HANDLE LocalHandle =
  4768. CreateFile(
  4769. ApiPath(DestFullName).c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
  4770. FILE_FLAG_BACKUP_SEMANTICS, 0);
  4771. if (LocalHandle == INVALID_HANDLE_VALUE)
  4772. {
  4773. int SetFileTimeError = GetLastError();
  4774. FTerminal->LogEvent(
  4775. FORMAT(L"Preserving directory timestamp failed, ignoring: %s", (SysErrorMessageForError(SetFileTimeError))));
  4776. }
  4777. else
  4778. {
  4779. FTerminal->UpdateTargetTime(LocalHandle, File->Modification, FTerminal->SessionData->DSTMode);
  4780. CloseHandle(LocalHandle);
  4781. }
  4782. }
  4783. }
  4784. //---------------------------------------------------------------------------
  4785. void __fastcall TSFTPFileSystem::WriteLocalFile(
  4786. TStream * FileStream, TFileBuffer & BlockBuf, const UnicodeString & LocalFileName,
  4787. TFileOperationProgressType * OperationProgress)
  4788. {
  4789. FILE_OPERATION_LOOP_BEGIN
  4790. {
  4791. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  4792. }
  4793. FILE_OPERATION_LOOP_END(FMTLOAD(WRITE_ERROR, (LocalFileName)));
  4794. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  4795. }
  4796. //---------------------------------------------------------------------------
  4797. void __fastcall TSFTPFileSystem::Sink(
  4798. const UnicodeString & FileName, const TRemoteFile * File,
  4799. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  4800. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  4801. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  4802. {
  4803. // resume has no sense for temporary downloads
  4804. bool ResumeAllowed =
  4805. FLAGCLEAR(Params, cpTemporary) &&
  4806. !OperationProgress->AsciiTransfer &&
  4807. CopyParam->AllowResume(OperationProgress->TransferSize) &&
  4808. !FTerminal->IsEncryptingFiles();
  4809. HANDLE LocalHandle = NULL;
  4810. TStream * FileStream = NULL;
  4811. bool DeleteLocalFile = false;
  4812. RawByteString RemoteHandle;
  4813. UnicodeString DestFullName = TargetDir + DestFileName;
  4814. UnicodeString LocalFileName = DestFullName;
  4815. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  4816. try
  4817. {
  4818. bool ResumeTransfer = false;
  4819. UnicodeString DestPartialFullName;
  4820. if (ResumeAllowed)
  4821. {
  4822. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4823. LocalFileName = DestPartialFullName;
  4824. FTerminal->LogEvent(L"Checking existence of partially transferred file.");
  4825. if (FileExists(ApiPath(DestPartialFullName)))
  4826. {
  4827. FTerminal->LogEvent(L"Partially transferred file exists.");
  4828. __int64 ResumeOffset;
  4829. FTerminal->OpenLocalFile(DestPartialFullName, GENERIC_WRITE,
  4830. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  4831. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  4832. if (FLAGCLEAR(Params, cpNoConfirmation))
  4833. {
  4834. ResumeTransfer = SFTPConfirmResume(DestFileName, PartialBiggerThanSource, OperationProgress);
  4835. }
  4836. else
  4837. {
  4838. ResumeTransfer = !PartialBiggerThanSource;
  4839. if (!ResumeTransfer)
  4840. {
  4841. FTerminal->LogEvent(L"Partially transferred file is bigger that original file.");
  4842. }
  4843. }
  4844. if (!ResumeTransfer)
  4845. {
  4846. CloseHandle(LocalHandle);
  4847. LocalHandle = NULL;
  4848. FILE_OPERATION_LOOP_BEGIN
  4849. {
  4850. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestPartialFullName)));
  4851. }
  4852. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartialFullName)));
  4853. }
  4854. else
  4855. {
  4856. FTerminal->LogEvent(L"Resuming file transfer.");
  4857. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  4858. OperationProgress->AddResumed(ResumeOffset);
  4859. }
  4860. }
  4861. OperationProgress->Progress();
  4862. }
  4863. // first open source file, not to loose the destination file,
  4864. // if we cannot open the source one in the first place
  4865. FTerminal->LogEvent(L"Opening remote file.");
  4866. FILE_OPERATION_LOOP_BEGIN
  4867. {
  4868. int OpenType = SSH_FXF_READ;
  4869. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  4870. {
  4871. OpenType |= SSH_FXF_TEXT;
  4872. }
  4873. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  4874. OperationProgress->Progress();
  4875. }
  4876. FILE_OPERATION_LOOP_END(FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)));
  4877. TSFTPPacket RemoteFilePacket(SSH_FXP_FSTAT);
  4878. RemoteFilePacket.AddString(RemoteHandle);
  4879. SendCustomReadFile(&RemoteFilePacket, &RemoteFilePacket, SSH_FILEXFER_ATTR_MODIFYTIME);
  4880. ReceiveResponse(&RemoteFilePacket, &RemoteFilePacket);
  4881. OperationProgress->Progress();
  4882. TDateTime Modification = File->Modification; // fallback
  4883. // ignore errors
  4884. if (RemoteFilePacket.Type == SSH_FXP_ATTRS)
  4885. {
  4886. // load file, avoid completion (resolving symlinks) as we do not need that
  4887. std::unique_ptr<TRemoteFile> AFile(
  4888. LoadFile(&RemoteFilePacket, NULL, UnixExtractFileName(FileName), NULL, false));
  4889. if (AFile->Modification != TDateTime())
  4890. {
  4891. Modification = File->Modification;
  4892. }
  4893. }
  4894. if ((Attrs >= 0) && !ResumeTransfer)
  4895. {
  4896. __int64 DestFileSize;
  4897. __int64 MTime;
  4898. FTerminal->OpenLocalFile(
  4899. DestFullName, GENERIC_WRITE, NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  4900. FTerminal->LogEvent(L"Confirming overwriting of file.");
  4901. TOverwriteFileParams FileParams;
  4902. FileParams.SourceSize = OperationProgress->TransferSize;
  4903. FileParams.SourceTimestamp = Modification;
  4904. FileParams.DestTimestamp = UnixToDateTime(MTime,
  4905. FTerminal->SessionData->DSTMode);
  4906. FileParams.DestSize = DestFileSize;
  4907. UnicodeString PrevDestFileName = DestFileName;
  4908. SFTPConfirmOverwrite(FileName, DestFileName, CopyParam, Params, OperationProgress, OverwriteMode, &FileParams);
  4909. if (PrevDestFileName != DestFileName)
  4910. {
  4911. DestFullName = TargetDir + DestFileName;
  4912. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4913. if (ResumeAllowed)
  4914. {
  4915. if (FileExists(ApiPath(DestPartialFullName)))
  4916. {
  4917. FILE_OPERATION_LOOP_BEGIN
  4918. {
  4919. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestPartialFullName)));
  4920. }
  4921. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartialFullName)));
  4922. }
  4923. LocalFileName = DestPartialFullName;
  4924. }
  4925. else
  4926. {
  4927. LocalFileName = DestFullName;
  4928. }
  4929. }
  4930. if (OverwriteMode == omOverwrite)
  4931. {
  4932. // is NULL when overwriting read-only file
  4933. if (LocalHandle)
  4934. {
  4935. CloseHandle(LocalHandle);
  4936. LocalHandle = NULL;
  4937. }
  4938. }
  4939. else
  4940. {
  4941. // is NULL when overwriting read-only file, so following will
  4942. // probably fail anyway
  4943. if (LocalHandle == NULL)
  4944. {
  4945. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE, NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  4946. }
  4947. ResumeAllowed = false;
  4948. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  4949. if (OverwriteMode == omAppend)
  4950. {
  4951. FTerminal->LogEvent(L"Appending to file.");
  4952. }
  4953. else
  4954. {
  4955. FTerminal->LogEvent(L"Resuming file transfer (append style).");
  4956. DebugAssert(OverwriteMode == omResume);
  4957. OperationProgress->AddResumed(DestFileSize);
  4958. }
  4959. }
  4960. }
  4961. Action.Destination(ExpandUNCFileName(DestFullName));
  4962. // if not already opened (resume, append...), create new empty file
  4963. if (!LocalHandle)
  4964. {
  4965. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  4966. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  4967. {
  4968. throw ESkipFile();
  4969. }
  4970. }
  4971. DebugAssert(LocalHandle);
  4972. DeleteLocalFile = true;
  4973. FileStream = new TSafeHandleStream((THandle)LocalHandle);
  4974. // at end of this block queue is discarded
  4975. {
  4976. TSFTPDownloadQueue Queue(this);
  4977. try
  4978. {
  4979. TSFTPPacket DataPacket;
  4980. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  4981. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  4982. (QueueLen < 0))
  4983. {
  4984. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  4985. }
  4986. if (QueueLen < 1)
  4987. {
  4988. QueueLen = 1;
  4989. }
  4990. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferredSize, OperationProgress);
  4991. bool Eof = false;
  4992. bool PrevIncomplete = false;
  4993. int GapFillCount = 0;
  4994. int GapCount = 0;
  4995. unsigned long Missing = 0;
  4996. unsigned long DataLen = 0;
  4997. unsigned long BlockSize;
  4998. bool ConvertToken = false;
  4999. TEncryption Encryption(FTerminal->GetEncryptKey());
  5000. bool Decrypt = FTerminal->IsFileEncrypted(FileName);
  5001. while (!Eof)
  5002. {
  5003. if (Missing > 0)
  5004. {
  5005. Queue.InitFillGapRequest(OperationProgress->TransferredSize, Missing, &DataPacket);
  5006. GapFillCount++;
  5007. SendPacketAndReceiveResponse(&DataPacket, &DataPacket, SSH_FXP_DATA, asEOF);
  5008. }
  5009. else
  5010. {
  5011. Queue.ReceivePacket(&DataPacket, BlockSize);
  5012. }
  5013. if (DataPacket.Type == SSH_FXP_STATUS)
  5014. {
  5015. // must be SSH_FX_EOF, any other status packet would raise exception
  5016. Eof = true;
  5017. // close file right away, before waiting for pending responses
  5018. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress, true, true, NULL);
  5019. RemoteHandle = L""; // do not close file again in __finally block
  5020. }
  5021. if (!Eof)
  5022. {
  5023. if ((Missing == 0) && PrevIncomplete)
  5024. {
  5025. // This can happen only if last request returned less bytes
  5026. // than expected, but exactly number of bytes missing to last
  5027. // known file size, but actually EOF was not reached.
  5028. // Can happen only when filesize has changed since directory
  5029. // listing and server returns less bytes than requested and
  5030. // file has some special file size.
  5031. FTerminal->LogEvent(FORMAT(
  5032. L"Received incomplete data packet before end of file, offset: %s, size: %d, requested: %d",
  5033. (IntToStr(OperationProgress->TransferredSize), int(DataLen), int(BlockSize))));
  5034. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  5035. }
  5036. // Buffer for one block of data
  5037. TFileBuffer BlockBuf;
  5038. DataLen = DataPacket.GetCardinal();
  5039. PrevIncomplete = false;
  5040. if (Missing > 0)
  5041. {
  5042. DebugAssert(DataLen <= Missing);
  5043. Missing -= DataLen;
  5044. }
  5045. else if (DataLen < BlockSize)
  5046. {
  5047. if (OperationProgress->TransferredSize + DataLen !=
  5048. OperationProgress->TransferSize)
  5049. {
  5050. // with native text transfer mode (SFTP>=4), do not bother about
  5051. // getting less than requested, read offset is ignored anyway
  5052. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  5053. {
  5054. GapCount++;
  5055. Missing = BlockSize - DataLen;
  5056. }
  5057. }
  5058. else
  5059. {
  5060. PrevIncomplete = true;
  5061. }
  5062. }
  5063. DebugAssert(DataLen <= BlockSize);
  5064. BlockBuf.Insert(0, reinterpret_cast<const char *>(DataPacket.GetNextData(DataLen)), DataLen);
  5065. DataPacket.DataConsumed(DataLen);
  5066. OperationProgress->AddTransferred(DataLen);
  5067. if ((FVersion >= 6) && DataPacket.CanGetBool() && (Missing == 0))
  5068. {
  5069. Eof = DataPacket.GetBool();
  5070. }
  5071. if (OperationProgress->AsciiTransfer)
  5072. {
  5073. DebugAssert(!ResumeTransfer && !ResumeAllowed);
  5074. unsigned int PrevBlockSize = BlockBuf.Size;
  5075. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
  5076. OperationProgress->SetLocalSize(OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  5077. }
  5078. if (Decrypt)
  5079. {
  5080. Encryption.Decrypt(BlockBuf);
  5081. }
  5082. WriteLocalFile(FileStream, BlockBuf, LocalFileName, OperationProgress);
  5083. }
  5084. if (OperationProgress->Cancel != csContinue)
  5085. {
  5086. if (OperationProgress->ClearCancelFile())
  5087. {
  5088. throw ESkipFile();
  5089. }
  5090. else
  5091. {
  5092. Abort();
  5093. }
  5094. }
  5095. };
  5096. if (GapCount > 0)
  5097. {
  5098. FTerminal->LogEvent(FORMAT(L"%d requests to fill %d data gaps were issued.", (GapFillCount, GapCount)));
  5099. }
  5100. if (Decrypt)
  5101. {
  5102. TFileBuffer BlockBuf;
  5103. if (Encryption.DecryptEnd(BlockBuf))
  5104. {
  5105. WriteLocalFile(FileStream, BlockBuf, LocalFileName, OperationProgress);
  5106. }
  5107. }
  5108. }
  5109. __finally
  5110. {
  5111. Queue.DisposeSafe();
  5112. }
  5113. // queue is discarded here
  5114. }
  5115. if (CopyParam->PreserveTime)
  5116. {
  5117. FTerminal->UpdateTargetTime(LocalHandle, Modification, FTerminal->SessionData->DSTMode);
  5118. }
  5119. CloseHandle(LocalHandle);
  5120. LocalHandle = NULL;
  5121. if (ResumeAllowed)
  5122. {
  5123. FILE_OPERATION_LOOP_BEGIN
  5124. {
  5125. if (FileExists(ApiPath(DestFullName)))
  5126. {
  5127. DeleteFileChecked(DestFullName);
  5128. }
  5129. THROWOSIFFALSE(Sysutils::RenameFile(ApiPath(DestPartialFullName), ApiPath(DestFullName)));
  5130. }
  5131. FILE_OPERATION_LOOP_END(FMTLOAD(RENAME_AFTER_RESUME_ERROR, (ExtractFileName(DestPartialFullName), DestFileName)));
  5132. }
  5133. DeleteLocalFile = false;
  5134. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  5135. }
  5136. __finally
  5137. {
  5138. if (LocalHandle)
  5139. {
  5140. CloseHandle(LocalHandle);
  5141. }
  5142. if (FileStream != NULL)
  5143. {
  5144. delete FileStream;
  5145. }
  5146. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocallyUsed == 0) &&
  5147. (OverwriteMode == omOverwrite))
  5148. {
  5149. FILE_OPERATION_LOOP_BEGIN
  5150. {
  5151. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(LocalFileName)));
  5152. }
  5153. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (LocalFileName)));
  5154. }
  5155. // if the transfer was finished, the file is closed already
  5156. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  5157. {
  5158. // do not wait for response
  5159. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress, true, true, NULL);
  5160. }
  5161. }
  5162. }
  5163. //---------------------------------------------------------------------------
  5164. void __fastcall TSFTPFileSystem::RegisterChecksumAlg(const UnicodeString & Alg, const UnicodeString & SftpAlg)
  5165. {
  5166. FChecksumAlgs->Add(Alg);
  5167. FChecksumSftpAlgs->Add(SftpAlg);
  5168. }
  5169. //---------------------------------------------------------------------------
  5170. void __fastcall TSFTPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  5171. {
  5172. Algs->AddStrings(FChecksumAlgs.get());
  5173. }
  5174. //---------------------------------------------------------------------------
  5175. void __fastcall TSFTPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  5176. {
  5177. DebugFail();
  5178. }
  5179. //---------------------------------------------------------------------------
  5180. void __fastcall TSFTPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  5181. {
  5182. DebugFail();
  5183. }
  5184. //---------------------------------------------------------------------------
  5185. void __fastcall TSFTPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  5186. {
  5187. // noop
  5188. }
  5189. //---------------------------------------------------------------------------
  5190. void __fastcall TSFTPFileSystem::ClearCaches()
  5191. {
  5192. // noop
  5193. }
  5194. //---------------------------------------------------------------------------
  5195. void TSFTPFileSystem::AddPathString(TSFTPPacket & Packet, const UnicodeString & Value, bool EncryptNewFiles)
  5196. {
  5197. UnicodeString EncryptedPath = FTerminal->EncryptFileName(Value, EncryptNewFiles);
  5198. Packet.AddPathString(EncryptedPath, FUtfStrings);
  5199. }