SftpFileSystem.cpp 185 KB

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