SftpFileSystem.cpp 182 KB

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