SftpFileSystem.cpp 185 KB

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