SftpFileSystem.cpp 182 KB

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