1
0

SftpFileSystem.cpp 192 KB

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