SftpFileSystem.cpp 183 KB

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