SftpFileSystem.cpp 191 KB

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