SftpFileSystem.cpp 183 KB

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