SftpFileSystem.cpp 181 KB

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