SftpFileSystem.cpp 182 KB

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