SftpFileSystem.cpp 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805
  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. Extensions(new TStringList())
  180. {
  181. Reset();
  182. }
  183. ~TSFTPSupport()
  184. {
  185. delete AttribExtensions;
  186. delete Extensions;
  187. }
  188. void Reset()
  189. {
  190. AttributeMask = 0;
  191. AttributeBits = 0;
  192. OpenFlags = 0;
  193. AccessMask = 0;
  194. MaxReadSize = 0;
  195. OpenBlockVector = 0;
  196. BlockVector = 0;
  197. AttribExtensions->Clear();
  198. Extensions->Clear();
  199. Loaded = false;
  200. }
  201. unsigned int AttributeMask;
  202. unsigned int AttributeBits;
  203. unsigned int OpenFlags;
  204. unsigned int AccessMask;
  205. unsigned int MaxReadSize;
  206. unsigned int OpenBlockVector;
  207. unsigned int BlockVector;
  208. TStrings * AttribExtensions;
  209. TStrings * Extensions;
  210. bool Loaded;
  211. };
  212. //---------------------------------------------------------------------------
  213. class TSFTPPacket
  214. {
  215. public:
  216. TSFTPPacket()
  217. {
  218. Init();
  219. }
  220. TSFTPPacket(const TSFTPPacket & Source)
  221. {
  222. Init();
  223. *this = Source;
  224. }
  225. TSFTPPacket(unsigned char AType)
  226. {
  227. Init();
  228. ChangeType(AType);
  229. }
  230. TSFTPPacket(const unsigned char * Source, unsigned int Len)
  231. {
  232. Init();
  233. FLength = Len;
  234. Capacity = FLength;
  235. memcpy(Data, Source, Len);
  236. }
  237. TSFTPPacket(const RawByteString & Source)
  238. {
  239. Init();
  240. FLength = Source.Length();
  241. Capacity = FLength;
  242. memcpy(Data, Source.c_str(), Source.Length());
  243. }
  244. ~TSFTPPacket()
  245. {
  246. if (FData != NULL)
  247. {
  248. delete[] (FData - FSendPrefixLen);
  249. }
  250. if (FReservedBy) FReservedBy->UnreserveResponse(this);
  251. }
  252. void ChangeType(unsigned char AType)
  253. {
  254. FPosition = 0;
  255. FLength = 0;
  256. Capacity = 0;
  257. FType = AType;
  258. AddByte(FType);
  259. if ((FType != 1) && (FType != SSH_FXP_INIT))
  260. {
  261. AssignNumber();
  262. AddCardinal(FMessageNumber);
  263. }
  264. }
  265. void Reuse()
  266. {
  267. AssignNumber();
  268. DebugAssert(Length >= 5);
  269. // duplicated in AddCardinal()
  270. unsigned char Buf[4];
  271. PUT_32BIT(Buf, FMessageNumber);
  272. memcpy(FData + 1, Buf, sizeof(Buf));
  273. }
  274. void AddByte(unsigned char Value)
  275. {
  276. Add(&Value, sizeof(Value));
  277. }
  278. void AddBool(bool Value)
  279. {
  280. AddByte(Value ? 1 : 0);
  281. }
  282. void AddCardinal(unsigned long Value)
  283. {
  284. // duplicated in Reuse()
  285. unsigned char Buf[4];
  286. PUT_32BIT(Buf, Value);
  287. Add(&Buf, sizeof(Buf));
  288. }
  289. void AddInt64(__int64 Value)
  290. {
  291. AddCardinal((unsigned long)(Value >> 32));
  292. AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
  293. }
  294. void AddData(const void * Data, int ALength)
  295. {
  296. AddCardinal(ALength);
  297. Add(Data, ALength);
  298. }
  299. void AddString(const RawByteString & Value)
  300. {
  301. AddCardinal(Value.Length());
  302. Add(Value.c_str(), Value.Length());
  303. }
  304. inline void AddUtfString(const UTF8String & Value)
  305. {
  306. AddString(Value);
  307. }
  308. inline void AddUtfString(const UnicodeString & Value)
  309. {
  310. AddUtfString(UTF8String(Value));
  311. }
  312. inline void AddString(const UnicodeString Value, TAutoSwitch Utf)
  313. {
  314. // asAuto: Using UTF until we receive non-UTF string from the server
  315. if ((Utf == asOn) || (Utf == asAuto))
  316. {
  317. AddUtfString(Value);
  318. }
  319. else
  320. {
  321. AddString(RawByteString(AnsiString(Value)));
  322. }
  323. }
  324. // now purposeless alias to AddString
  325. inline void AddPathString(const UnicodeString & Value, TAutoSwitch Utf)
  326. {
  327. AddString(Value, Utf);
  328. }
  329. unsigned int AllocationSizeAttribute(int Version)
  330. {
  331. return (Version >= 6) ? SSH_FILEXFER_ATTR_ALLOCATION_SIZE : SSH_FILEXFER_ATTR_SIZE;
  332. }
  333. void AddProperties(unsigned short * Rights, TRemoteToken * Owner,
  334. TRemoteToken * Group, __int64 * MTime, __int64 * ATime,
  335. __int64 * Size, bool IsDirectory, int Version, TAutoSwitch Utf)
  336. {
  337. int Flags = 0;
  338. if (Size != NULL)
  339. {
  340. Flags |= AllocationSizeAttribute(Version);
  341. }
  342. // both or neither
  343. DebugAssert((Owner != NULL) == (Group != NULL));
  344. if ((Owner != NULL) && (Group != NULL))
  345. {
  346. if (Version < 4)
  347. {
  348. DebugAssert(Owner->IDValid && Group->IDValid);
  349. Flags |= SSH_FILEXFER_ATTR_UIDGID;
  350. }
  351. else
  352. {
  353. DebugAssert(Owner->NameValid && Group->NameValid);
  354. Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
  355. }
  356. }
  357. if (Rights != NULL)
  358. {
  359. Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
  360. }
  361. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  362. {
  363. Flags |= SSH_FILEXFER_ATTR_ACMODTIME;
  364. }
  365. if ((Version >= 4) && (ATime != NULL))
  366. {
  367. Flags |= SSH_FILEXFER_ATTR_ACCESSTIME;
  368. }
  369. if ((Version >= 4) && (MTime != NULL))
  370. {
  371. Flags |= SSH_FILEXFER_ATTR_MODIFYTIME;
  372. }
  373. AddCardinal(Flags);
  374. if (Version >= 4)
  375. {
  376. AddByte(static_cast<unsigned char>(IsDirectory ?
  377. SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
  378. }
  379. if (Size != NULL)
  380. {
  381. // this is SSH_FILEXFER_ATTR_SIZE for version <= 5, but
  382. // SSH_FILEXFER_ATTR_ALLOCATION_SIZE for version >= 6
  383. AddInt64(*Size);
  384. }
  385. if ((Owner != NULL) && (Group != NULL))
  386. {
  387. if (Version < 4)
  388. {
  389. DebugAssert(Owner->IDValid && Group->IDValid);
  390. AddCardinal(Owner->ID);
  391. AddCardinal(Group->ID);
  392. }
  393. else
  394. {
  395. DebugAssert(Owner->NameValid && Group->NameValid);
  396. AddString(Owner->Name, Utf);
  397. AddString(Group->Name, Utf);
  398. }
  399. }
  400. if (Rights != NULL)
  401. {
  402. AddCardinal(*Rights);
  403. }
  404. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  405. {
  406. // any way to reflect sbSignedTS here?
  407. // (note that casting __int64 > 2^31 < 2^32 to unsigned long is wrapped,
  408. // thus we never can set time after 2038, even if the server supports it)
  409. AddCardinal(static_cast<unsigned long>(ATime != NULL ? *ATime : *MTime));
  410. AddCardinal(static_cast<unsigned long>(MTime != NULL ? *MTime : *ATime));
  411. }
  412. if ((Version >= 4) && (ATime != NULL))
  413. {
  414. AddInt64(*ATime);
  415. }
  416. if ((Version >= 4) && (MTime != NULL))
  417. {
  418. AddInt64(*MTime);
  419. }
  420. }
  421. void AddProperties(const TRemoteProperties * Properties,
  422. unsigned short BaseRights, bool IsDirectory, int Version, TAutoSwitch Utf,
  423. TChmodSessionAction * Action)
  424. {
  425. enum TValid { valNone = 0, valRights = 0x01, valOwner = 0x02, valGroup = 0x04,
  426. valMTime = 0x08, valATime = 0x10 } Valid = valNone;
  427. unsigned short RightsNum = 0;
  428. TRemoteToken Owner;
  429. TRemoteToken Group;
  430. __int64 MTime;
  431. __int64 ATime;
  432. if (Properties != NULL)
  433. {
  434. if (Properties->Valid.Contains(vpGroup))
  435. {
  436. Valid = (TValid)(Valid | valGroup);
  437. Group = Properties->Group;
  438. }
  439. if (Properties->Valid.Contains(vpOwner))
  440. {
  441. Valid = (TValid)(Valid | valOwner);
  442. Owner = Properties->Owner;
  443. }
  444. if (Properties->Valid.Contains(vpRights))
  445. {
  446. Valid = (TValid)(Valid | valRights);
  447. TRights Rights = TRights(BaseRights).Combine(Properties->Rights);
  448. if (IsDirectory && Properties->AddXToDirectories)
  449. {
  450. Rights.AddExecute();
  451. }
  452. RightsNum = Rights;
  453. if (Action != NULL)
  454. {
  455. Action->Rights(Rights);
  456. }
  457. }
  458. if (Properties->Valid.Contains(vpLastAccess))
  459. {
  460. Valid = (TValid)(Valid | valATime);
  461. ATime = Properties->LastAccess;
  462. }
  463. if (Properties->Valid.Contains(vpModification))
  464. {
  465. Valid = (TValid)(Valid | valMTime);
  466. MTime = Properties->Modification;
  467. }
  468. }
  469. AddProperties(
  470. Valid & valRights ? &RightsNum : NULL,
  471. Valid & valOwner ? &Owner : NULL,
  472. Valid & valGroup ? &Group : NULL,
  473. Valid & valMTime ? &MTime : NULL,
  474. Valid & valATime ? &ATime : NULL,
  475. NULL, IsDirectory, Version, Utf);
  476. }
  477. unsigned char GetByte()
  478. {
  479. Need(sizeof(unsigned char));
  480. unsigned char Result = FData[FPosition];
  481. DataConsumed(sizeof(unsigned char));
  482. return Result;
  483. }
  484. bool GetBool()
  485. {
  486. return (GetByte() != 0);
  487. }
  488. bool CanGetBool()
  489. {
  490. return (RemainingLength >= sizeof(unsigned char));
  491. }
  492. unsigned long GetCardinal()
  493. {
  494. unsigned long Result = PeekCardinal();
  495. DataConsumed(sizeof(Result));
  496. return Result;
  497. }
  498. bool CanGetCardinal()
  499. {
  500. return (RemainingLength >= sizeof(unsigned long));
  501. }
  502. unsigned long GetSmallCardinal()
  503. {
  504. unsigned long Result;
  505. Need(2);
  506. Result = (FData[FPosition] << 8) + FData[FPosition + 1];
  507. DataConsumed(2);
  508. return Result;
  509. }
  510. bool CanGetSmallCardinal()
  511. {
  512. return (RemainingLength >= 2);
  513. }
  514. __int64 GetInt64()
  515. {
  516. __int64 Hi = GetCardinal();
  517. __int64 Lo = GetCardinal();
  518. return (Hi << 32) + Lo;
  519. }
  520. RawByteString GetRawByteString()
  521. {
  522. RawByteString Result;
  523. unsigned long Len = GetCardinal();
  524. Need(Len);
  525. // cannot happen anyway as Need() would raise exception
  526. DebugAssert(Len < SFTP_MAX_PACKET_LEN);
  527. Result.SetLength(Len);
  528. memcpy(Result.c_str(), FData + FPosition, Len);
  529. DataConsumed(Len);
  530. return Result;
  531. }
  532. bool CanGetString(unsigned int & Size)
  533. {
  534. bool Result = CanGetCardinal();
  535. if (Result)
  536. {
  537. unsigned long Len = PeekCardinal();
  538. Size = (sizeof(Len) + Len);
  539. Result = (Size <= RemainingLength);
  540. }
  541. return Result;
  542. }
  543. // For reading strings that are character strings (not byte strings as
  544. // as file handles), and SFTP spec does not say explicitly that they
  545. // are in UTF. For most of them it actually does not matter as
  546. // the content should be pure ASCII (e.g. extension names, etc.)
  547. inline UnicodeString GetAnsiString()
  548. {
  549. return AnsiToString(GetRawByteString());
  550. }
  551. inline RawByteString GetFileHandle()
  552. {
  553. return GetRawByteString();
  554. }
  555. inline UnicodeString GetString(TAutoSwitch & Utf)
  556. {
  557. if (Utf != asOff)
  558. {
  559. return GetUtfString(Utf);
  560. }
  561. else
  562. {
  563. return GetAnsiString();
  564. }
  565. }
  566. // now purposeless alias to GetString(bool)
  567. inline UnicodeString GetPathString(TAutoSwitch & Utf)
  568. {
  569. return GetString(Utf);
  570. }
  571. void GetFile(TRemoteFile * File, int Version, TDSTMode DSTMode, TAutoSwitch & Utf, bool SignedTS, bool Complete)
  572. {
  573. DebugAssert(File);
  574. unsigned int Flags;
  575. UnicodeString ListingStr;
  576. unsigned long Permissions = 0;
  577. bool ParsingFailed = false;
  578. if (Type != SSH_FXP_ATTRS)
  579. {
  580. File->FileName = GetPathString(Utf);
  581. if (Version < 4)
  582. {
  583. ListingStr = GetString(Utf);
  584. }
  585. }
  586. Flags = GetCardinal();
  587. if (Version >= 4)
  588. {
  589. unsigned char FXType = GetByte();
  590. // -:regular, D:directory, L:symlink, S:special, U:unknown
  591. // O:socket, C:char device, B:block device, F:fifo
  592. // SSH-2.0-cryptlib returns file type 0 in response to SSH_FXP_LSTAT,
  593. // handle this undefined value as "unknown"
  594. static wchar_t * Types = L"U-DLSUOCBF";
  595. if (FXType > (unsigned char)wcslen(Types))
  596. {
  597. throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
  598. }
  599. File->Type = Types[FXType];
  600. }
  601. if (Flags & SSH_FILEXFER_ATTR_SIZE)
  602. {
  603. File->Size = GetInt64();
  604. }
  605. // SFTP-6 only
  606. if (Flags & SSH_FILEXFER_ATTR_ALLOCATION_SIZE)
  607. {
  608. GetInt64(); // skip
  609. }
  610. // SSH-2.0-3.2.0 F-SECURE SSH - Process Software MultiNet
  611. // sets SSH_FILEXFER_ATTR_UIDGID for v4, but does not include the UID/GUID
  612. if ((Flags & SSH_FILEXFER_ATTR_UIDGID) && (Version < 4))
  613. {
  614. File->Owner.ID = GetCardinal();
  615. File->Group.ID = GetCardinal();
  616. }
  617. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  618. {
  619. DebugAssert(Version >= 4);
  620. File->Owner.Name = GetString(Utf);
  621. File->Group.Name = GetString(Utf);
  622. }
  623. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  624. {
  625. Permissions = GetCardinal();
  626. }
  627. if (Version < 4)
  628. {
  629. if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
  630. {
  631. File->LastAccess = UnixToDateTime(
  632. SignedTS ?
  633. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  634. static_cast<__int64>(GetCardinal()),
  635. DSTMode);
  636. File->Modification = UnixToDateTime(
  637. SignedTS ?
  638. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  639. static_cast<__int64>(GetCardinal()),
  640. DSTMode);
  641. }
  642. }
  643. else
  644. {
  645. if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
  646. {
  647. File->LastAccess = UnixToDateTime(GetInt64(), DSTMode);
  648. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  649. {
  650. GetCardinal(); // skip access time subseconds
  651. }
  652. }
  653. if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
  654. {
  655. GetInt64(); // skip create time
  656. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  657. {
  658. GetCardinal(); // skip create time subseconds
  659. }
  660. }
  661. if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
  662. {
  663. File->Modification = UnixToDateTime(GetInt64(), DSTMode);
  664. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  665. {
  666. GetCardinal(); // skip modification time subseconds
  667. }
  668. }
  669. // SFTP-6
  670. if (Flags & SSH_FILEXFER_ATTR_CTIME)
  671. {
  672. GetInt64(); // skip attribute modification time
  673. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  674. {
  675. GetCardinal(); // skip attribute modification time subseconds
  676. }
  677. }
  678. }
  679. if (Flags & SSH_FILEXFER_ATTR_ACL)
  680. {
  681. GetRawByteString();
  682. }
  683. if (Flags & SSH_FILEXFER_ATTR_BITS)
  684. {
  685. // while SSH_FILEXFER_ATTR_BITS is defined for SFTP5 only, vandyke 2.3.3 sets it
  686. // for SFTP4 as well
  687. unsigned long Bits = GetCardinal();
  688. if (Version >= 6)
  689. {
  690. unsigned long BitsValid = GetCardinal();
  691. Bits = Bits & BitsValid;
  692. }
  693. if (FLAGSET(Bits, SSH_FILEXFER_ATTR_FLAGS_HIDDEN))
  694. {
  695. File->IsHidden = true;
  696. }
  697. }
  698. // skip some SFTP-6 only fields
  699. if (Flags & SSH_FILEXFER_ATTR_TEXT_HINT)
  700. {
  701. GetByte();
  702. }
  703. if (Flags & SSH_FILEXFER_ATTR_MIME_TYPE)
  704. {
  705. GetAnsiString();
  706. }
  707. if (Flags & SSH_FILEXFER_ATTR_LINK_COUNT)
  708. {
  709. GetCardinal();
  710. }
  711. if (Flags & SSH_FILEXFER_ATTR_UNTRANSLATED_NAME)
  712. {
  713. GetPathString(Utf);
  714. }
  715. if ((Version < 4) && (Type != SSH_FXP_ATTRS))
  716. {
  717. try
  718. {
  719. // update permissions and user/group name
  720. // modification time and filename is ignored
  721. File->ListingStr = ListingStr;
  722. }
  723. catch(...)
  724. {
  725. // ignore any error while parsing listing line,
  726. // SFTP specification do not recommend to parse it
  727. ParsingFailed = true;
  728. }
  729. }
  730. if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
  731. {
  732. wchar_t Type = FILETYPE_DEFAULT;
  733. if (FLAGSET(Flags, SSH_FILEXFER_ATTR_PERMISSIONS))
  734. {
  735. File->Rights->Number = (unsigned short)(Permissions & TRights::rfAllSpecials);
  736. if (FLAGSET(Permissions, TRights::rfDirectory))
  737. {
  738. Type = FILETYPE_DIRECTORY;
  739. }
  740. }
  741. if (Version < 4)
  742. {
  743. File->Type = Type;
  744. }
  745. }
  746. if (Flags & SSH_FILEXFER_ATTR_EXTENDED)
  747. {
  748. unsigned int ExtendedCount = GetCardinal();
  749. for (unsigned int Index = 0; Index < ExtendedCount; Index++)
  750. {
  751. GetRawByteString(); // skip extended_type
  752. GetRawByteString(); // skip extended_data
  753. }
  754. }
  755. if (Complete)
  756. {
  757. File->Complete();
  758. }
  759. }
  760. unsigned char * GetNextData(unsigned int Size = 0)
  761. {
  762. if (Size > 0)
  763. {
  764. Need(Size);
  765. }
  766. return FPosition < FLength ? FData + FPosition : NULL;
  767. }
  768. void DataConsumed(unsigned int Size)
  769. {
  770. FPosition += Size;
  771. }
  772. void DataUpdated(int ALength)
  773. {
  774. FPosition = 0;
  775. FLength = ALength;
  776. FType = GetByte();
  777. if (FType != SSH_FXP_VERSION)
  778. {
  779. FMessageNumber = GetCardinal();
  780. }
  781. else
  782. {
  783. FMessageNumber = SFTPNoMessageNumber;
  784. }
  785. }
  786. void LoadFromFile(const UnicodeString FileName)
  787. {
  788. TStringList * DumpLines = new TStringList();
  789. RawByteString Dump;
  790. try
  791. {
  792. DumpLines->LoadFromFile(FileName);
  793. Dump = RawByteString(AnsiString(DumpLines->Text));
  794. }
  795. __finally
  796. {
  797. delete DumpLines;
  798. }
  799. Capacity = 20480;
  800. unsigned char Byte[3];
  801. memset(Byte, '\0', sizeof(Byte));
  802. int Index = 1;
  803. unsigned int Length = 0;
  804. while (Index < Dump.Length())
  805. {
  806. char C = Dump[Index];
  807. if (IsHex(C))
  808. {
  809. if (Byte[0] == '\0')
  810. {
  811. Byte[0] = C;
  812. }
  813. else
  814. {
  815. Byte[1] = C;
  816. DebugAssert(Length < Capacity);
  817. Data[Length] = HexToByte(UnicodeString(reinterpret_cast<char *>(Byte)));
  818. Length++;
  819. memset(Byte, '\0', sizeof(Byte));
  820. }
  821. }
  822. Index++;
  823. }
  824. DataUpdated(Length);
  825. }
  826. UnicodeString __fastcall Dump() const
  827. {
  828. UnicodeString Result;
  829. for (unsigned int Index = 0; Index < Length; Index++)
  830. {
  831. Result += ByteToHex(Data[Index]) + L",";
  832. if (((Index + 1) % 25) == 0)
  833. {
  834. Result += L"\n";
  835. }
  836. }
  837. return Result;
  838. }
  839. TSFTPPacket & operator = (const TSFTPPacket & Source)
  840. {
  841. Capacity = 0;
  842. Add(Source.Data, Source.Length);
  843. DataUpdated(Source.Length);
  844. FPosition = Source.FPosition;
  845. return *this;
  846. }
  847. __property unsigned int Length = { read = FLength };
  848. __property unsigned int RemainingLength = { read = GetRemainingLength };
  849. __property unsigned char * Data = { read = FData };
  850. __property unsigned char * SendData = { read = GetSendData };
  851. __property unsigned int SendLength = { read = GetSendLength };
  852. __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
  853. __property unsigned char Type = { read = FType };
  854. __property unsigned char RequestType = { read = GetRequestType };
  855. __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
  856. __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
  857. __property UnicodeString TypeName = { read = GetTypeName };
  858. private:
  859. unsigned char * FData;
  860. unsigned int FLength;
  861. unsigned int FCapacity;
  862. unsigned int FPosition;
  863. unsigned char FType;
  864. unsigned int FMessageNumber;
  865. TSFTPFileSystem * FReservedBy;
  866. static int FMessageCounter;
  867. static const FSendPrefixLen = 4;
  868. void Init()
  869. {
  870. FData = NULL;
  871. FCapacity = 0;
  872. FLength = 0;
  873. FPosition = 0;
  874. FMessageNumber = SFTPNoMessageNumber;
  875. FType = -1;
  876. FReservedBy = NULL;
  877. }
  878. void AssignNumber()
  879. {
  880. // this is not strictly thread-safe, but as it is accessed from multiple
  881. // threads only for multiple connection, it is not problem if two threads get
  882. // the same number
  883. FMessageNumber = (FMessageCounter << 8) + FType;
  884. FMessageCounter++;
  885. }
  886. unsigned char GetRequestType()
  887. {
  888. if (FMessageNumber != SFTPNoMessageNumber)
  889. {
  890. return (unsigned char)(FMessageNumber & 0xFF);
  891. }
  892. else
  893. {
  894. DebugAssert(Type == SSH_FXP_VERSION);
  895. return SSH_FXP_INIT;
  896. }
  897. }
  898. inline void Add(const void * AData, int ALength)
  899. {
  900. if (Length + ALength > Capacity)
  901. {
  902. Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
  903. }
  904. memcpy(FData + Length, AData, ALength);
  905. FLength += ALength;
  906. }
  907. void SetCapacity(unsigned int ACapacity)
  908. {
  909. if (ACapacity != Capacity)
  910. {
  911. FCapacity = ACapacity;
  912. if (FCapacity > 0)
  913. {
  914. unsigned char * NData = (new unsigned char[FCapacity + FSendPrefixLen]) + FSendPrefixLen;
  915. if (FData)
  916. {
  917. memcpy(NData - FSendPrefixLen, FData - FSendPrefixLen,
  918. (FLength < FCapacity ? FLength : FCapacity) + FSendPrefixLen);
  919. delete[] (FData - FSendPrefixLen);
  920. }
  921. FData = NData;
  922. }
  923. else
  924. {
  925. if (FData) delete[] (FData - FSendPrefixLen);
  926. FData = NULL;
  927. }
  928. if (FLength > FCapacity) FLength = FCapacity;
  929. }
  930. }
  931. UnicodeString GetTypeName() const
  932. {
  933. #define TYPE_CASE(TYPE) case TYPE: return TEXT(#TYPE)
  934. switch (Type) {
  935. TYPE_CASE(SSH_FXP_INIT);
  936. TYPE_CASE(SSH_FXP_VERSION);
  937. TYPE_CASE(SSH_FXP_OPEN);
  938. TYPE_CASE(SSH_FXP_CLOSE);
  939. TYPE_CASE(SSH_FXP_READ);
  940. TYPE_CASE(SSH_FXP_WRITE);
  941. TYPE_CASE(SSH_FXP_LSTAT);
  942. TYPE_CASE(SSH_FXP_FSTAT);
  943. TYPE_CASE(SSH_FXP_SETSTAT);
  944. TYPE_CASE(SSH_FXP_FSETSTAT);
  945. TYPE_CASE(SSH_FXP_OPENDIR);
  946. TYPE_CASE(SSH_FXP_READDIR);
  947. TYPE_CASE(SSH_FXP_REMOVE);
  948. TYPE_CASE(SSH_FXP_MKDIR);
  949. TYPE_CASE(SSH_FXP_RMDIR);
  950. TYPE_CASE(SSH_FXP_REALPATH);
  951. TYPE_CASE(SSH_FXP_STAT);
  952. TYPE_CASE(SSH_FXP_RENAME);
  953. TYPE_CASE(SSH_FXP_READLINK);
  954. TYPE_CASE(SSH_FXP_SYMLINK);
  955. TYPE_CASE(SSH_FXP_LINK);
  956. TYPE_CASE(SSH_FXP_STATUS);
  957. TYPE_CASE(SSH_FXP_HANDLE);
  958. TYPE_CASE(SSH_FXP_DATA);
  959. TYPE_CASE(SSH_FXP_NAME);
  960. TYPE_CASE(SSH_FXP_ATTRS);
  961. TYPE_CASE(SSH_FXP_EXTENDED);
  962. TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
  963. default:
  964. return FORMAT(L"Unknown message (%d)", (int(Type)));
  965. }
  966. }
  967. unsigned char * GetSendData() const
  968. {
  969. unsigned char * Result = FData - FSendPrefixLen;
  970. // this is not strictly const-object operation
  971. PUT_32BIT(Result, Length);
  972. return Result;
  973. }
  974. unsigned int GetSendLength() const
  975. {
  976. return FSendPrefixLen + Length;
  977. }
  978. unsigned int GetRemainingLength() const
  979. {
  980. return Length - FPosition;
  981. }
  982. inline void Need(unsigned int Size)
  983. {
  984. if (Size > RemainingLength)
  985. {
  986. throw Exception(FMTLOAD(SFTP_PACKET_ERROR, (int(FPosition), int(Size), int(FLength))));
  987. }
  988. }
  989. unsigned long PeekCardinal()
  990. {
  991. unsigned long Result;
  992. Need(sizeof(Result));
  993. Result = GET_32BIT(FData + FPosition);
  994. return Result;
  995. }
  996. inline UnicodeString GetUtfString(TAutoSwitch & Utf)
  997. {
  998. DebugAssert(Utf != asOff);
  999. UnicodeString Result;
  1000. RawByteString S = GetRawByteString();
  1001. if (Utf == asAuto)
  1002. {
  1003. TEncodeType EncodeType = DetectUTF8Encoding(S);
  1004. if (EncodeType == etANSI)
  1005. {
  1006. Utf = asOff;
  1007. Result = AnsiToString(S);
  1008. }
  1009. }
  1010. if (Utf != asOff)
  1011. {
  1012. Result = UTF8ToString(S);
  1013. }
  1014. return Result;
  1015. }
  1016. };
  1017. //---------------------------------------------------------------------------
  1018. int TSFTPPacket::FMessageCounter = 0;
  1019. //---------------------------------------------------------------------------
  1020. class TSFTPQueue
  1021. {
  1022. public:
  1023. __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
  1024. {
  1025. FFileSystem = AFileSystem;
  1026. DebugAssert(FFileSystem);
  1027. FRequests = new TList();
  1028. FResponses = new TList();
  1029. }
  1030. virtual __fastcall ~TSFTPQueue()
  1031. {
  1032. TSFTPQueuePacket * Request;
  1033. TSFTPPacket * Response;
  1034. DebugAssert(FResponses->Count == FRequests->Count);
  1035. for (int Index = 0; Index < FRequests->Count; Index++)
  1036. {
  1037. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[Index]);
  1038. DebugAssert(Request);
  1039. delete Request;
  1040. Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
  1041. DebugAssert(Response);
  1042. delete Response;
  1043. }
  1044. delete FRequests;
  1045. delete FResponses;
  1046. }
  1047. bool __fastcall Init()
  1048. {
  1049. return SendRequests();
  1050. }
  1051. virtual void __fastcall Dispose(int ExpectedType, int AllowStatus)
  1052. {
  1053. DebugAssert(FFileSystem->FTerminal->Active);
  1054. while (FRequests->Count)
  1055. {
  1056. DebugAssert(FResponses->Count);
  1057. std::unique_ptr<TSFTPQueuePacket> Request(DebugNotNull(static_cast<TSFTPQueuePacket*>(FRequests->Items[0])));
  1058. std::unique_ptr<TSFTPPacket> Response(DebugNotNull(static_cast<TSFTPPacket*>(FResponses->Items[0])));
  1059. // Particularly when ExpectedType >= 0, the ReceiveResponse may throw, and we have to remove the packets from queue
  1060. FRequests->Delete(0);
  1061. FResponses->Delete(0);
  1062. try
  1063. {
  1064. ReceiveResponse(Request.get(), Response.get(), ExpectedType, AllowStatus);
  1065. }
  1066. catch(Exception & E)
  1067. {
  1068. if (ExpectedType < 0)
  1069. {
  1070. if (FFileSystem->FTerminal->Active)
  1071. {
  1072. FFileSystem->FTerminal->LogEvent(L"Error while disposing the SFTP queue.");
  1073. FFileSystem->FTerminal->Log->AddException(&E);
  1074. }
  1075. else
  1076. {
  1077. FFileSystem->FTerminal->LogEvent(L"Fatal error while disposing the SFTP queue.");
  1078. throw;
  1079. }
  1080. }
  1081. else
  1082. {
  1083. throw;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. void __fastcall DisposeSafe(int ExpectedType = -1, int AllowStatus = -1)
  1089. {
  1090. if (FFileSystem->FTerminal->Active)
  1091. {
  1092. Dispose(ExpectedType, AllowStatus);
  1093. }
  1094. }
  1095. bool __fastcall ReceivePacket(TSFTPPacket * Packet,
  1096. int ExpectedType = -1, int AllowStatus = -1, void ** Token = NULL, bool TryOnly = false)
  1097. {
  1098. DebugAssert(FRequests->Count);
  1099. bool Result;
  1100. TSFTPQueuePacket * Request = NULL;
  1101. TSFTPPacket * Response = NULL;
  1102. try
  1103. {
  1104. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  1105. FRequests->Delete(0);
  1106. DebugAssert(Request);
  1107. if (Token != NULL)
  1108. {
  1109. *Token = Request->Token;
  1110. }
  1111. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  1112. FResponses->Delete(0);
  1113. DebugAssert(Response);
  1114. ReceiveResponse(Request, Response, ExpectedType, AllowStatus, TryOnly);
  1115. if ((Response->Capacity == 0) && DebugAlwaysTrue(TryOnly))
  1116. {
  1117. FRequests->Insert(0, Request);
  1118. Request = NULL;
  1119. FResponses->Insert(0, Response);
  1120. Response = NULL;
  1121. Result = true;
  1122. }
  1123. else
  1124. {
  1125. if (Packet)
  1126. {
  1127. *Packet = *Response;
  1128. }
  1129. Result = !End(Response);
  1130. if (Result)
  1131. {
  1132. SendRequests();
  1133. }
  1134. }
  1135. }
  1136. __finally
  1137. {
  1138. delete Request;
  1139. delete Response;
  1140. }
  1141. return Result;
  1142. }
  1143. bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
  1144. {
  1145. return ReceivePacket(NULL, ExpectedType, AllowStatus);
  1146. }
  1147. protected:
  1148. TList * FRequests;
  1149. TList * FResponses;
  1150. TSFTPFileSystem * FFileSystem;
  1151. class TSFTPQueuePacket : public TSFTPPacket
  1152. {
  1153. public:
  1154. TSFTPQueuePacket() :
  1155. TSFTPPacket()
  1156. {
  1157. Token = NULL;
  1158. }
  1159. void * Token;
  1160. };
  1161. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request) = 0;
  1162. virtual bool __fastcall End(TSFTPPacket * Response) = 0;
  1163. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1164. {
  1165. FFileSystem->SendPacket(Packet);
  1166. }
  1167. virtual void __fastcall ReceiveResponse(
  1168. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1169. int AllowStatus, bool TryOnly = false)
  1170. {
  1171. FFileSystem->ReceiveResponse(Packet, Response, ExpectedType, AllowStatus, TryOnly);
  1172. }
  1173. // sends as many requests as allowed by implementation
  1174. virtual bool SendRequests() = 0;
  1175. virtual bool __fastcall SendRequest()
  1176. {
  1177. TSFTPQueuePacket * Request = NULL;
  1178. try
  1179. {
  1180. Request = new TSFTPQueuePacket();
  1181. if (!InitRequest(Request))
  1182. {
  1183. delete Request;
  1184. Request = NULL;
  1185. }
  1186. }
  1187. catch(...)
  1188. {
  1189. delete Request;
  1190. throw;
  1191. }
  1192. if (Request != NULL)
  1193. {
  1194. TSFTPPacket * Response = new TSFTPPacket();
  1195. FRequests->Add(Request);
  1196. FResponses->Add(Response);
  1197. // make sure the response is reserved before actually ending the message
  1198. // as we may receive response asynchronously before SendPacket finishes
  1199. FFileSystem->ReserveResponse(Request, Response);
  1200. SendPacket(Request);
  1201. }
  1202. return (Request != NULL);
  1203. }
  1204. };
  1205. //---------------------------------------------------------------------------
  1206. class TSFTPFixedLenQueue : public TSFTPQueue
  1207. {
  1208. public:
  1209. __fastcall TSFTPFixedLenQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1210. {
  1211. FMissedRequests = 0;
  1212. }
  1213. virtual __fastcall ~TSFTPFixedLenQueue(){}
  1214. bool Init(int QueueLen)
  1215. {
  1216. FMissedRequests = QueueLen - 1;
  1217. return TSFTPQueue::Init();
  1218. }
  1219. protected:
  1220. int FMissedRequests;
  1221. // sends as many requests as allowed by implementation
  1222. virtual bool SendRequests()
  1223. {
  1224. bool Result = false;
  1225. FMissedRequests++;
  1226. while ((FMissedRequests > 0) && SendRequest())
  1227. {
  1228. Result = true;
  1229. FMissedRequests--;
  1230. }
  1231. return Result;
  1232. }
  1233. };
  1234. //---------------------------------------------------------------------------
  1235. class TSFTPAsynchronousQueue : public TSFTPQueue
  1236. {
  1237. public:
  1238. __fastcall TSFTPAsynchronousQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1239. {
  1240. FFileSystem->FSecureShell->RegisterReceiveHandler(ReceiveHandler);
  1241. FReceiveHandlerRegistered = true;
  1242. }
  1243. virtual __fastcall ~TSFTPAsynchronousQueue()
  1244. {
  1245. UnregisterReceiveHandler();
  1246. }
  1247. virtual void __fastcall Dispose(int ExpectedType, int AllowStatus)
  1248. {
  1249. // we do not want to receive asynchronous notifications anymore,
  1250. // while waiting synchronously for pending responses
  1251. UnregisterReceiveHandler();
  1252. TSFTPQueue::Dispose(ExpectedType, AllowStatus);
  1253. }
  1254. bool __fastcall Continue()
  1255. {
  1256. return SendRequest();
  1257. }
  1258. protected:
  1259. // event handler for incoming data
  1260. void __fastcall ReceiveHandler(TObject * /*Sender*/)
  1261. {
  1262. while (// optimization only as we call ReceivePacket with TryOnly anyway
  1263. FFileSystem->PeekPacket() &&
  1264. ReceivePacketAsynchronously())
  1265. {
  1266. // loop
  1267. }
  1268. }
  1269. virtual bool __fastcall ReceivePacketAsynchronously() = 0;
  1270. // sends as many requests as allowed by implementation
  1271. virtual bool SendRequests()
  1272. {
  1273. // noop
  1274. return true;
  1275. }
  1276. void __fastcall UnregisterReceiveHandler()
  1277. {
  1278. if (FReceiveHandlerRegistered)
  1279. {
  1280. FReceiveHandlerRegistered = false;
  1281. FFileSystem->FSecureShell->UnregisterReceiveHandler(ReceiveHandler);
  1282. }
  1283. }
  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 ATransferred, __int64 PartSize, TFileOperationProgressType * AOperationProgress)
  1298. {
  1299. FHandle = AHandle;
  1300. FTransferred = ATransferred;
  1301. FPartSize = PartSize;
  1302. OperationProgress = AOperationProgress;
  1303. return TSFTPFixedLenQueue::Init(QueueLen);
  1304. }
  1305. void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
  1306. TSFTPPacket * Packet)
  1307. {
  1308. InitRequest(Packet, Offset, Missing);
  1309. }
  1310. bool __fastcall ReceivePacket(TSFTPPacket * Packet, unsigned long & BlockSize)
  1311. {
  1312. void * Token;
  1313. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_DATA, asEOF, &Token);
  1314. BlockSize = reinterpret_cast<unsigned long>(Token);
  1315. return Result;
  1316. }
  1317. protected:
  1318. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1319. {
  1320. unsigned int BlockSize = FFileSystem->DownloadBlockSize(OperationProgress);
  1321. if (FPartSize >= 0)
  1322. {
  1323. __int64 Remaining = FPartSize - FTransferred;
  1324. if (Remaining < BlockSize)
  1325. {
  1326. // It's lower, so the cast is safe
  1327. BlockSize = static_cast<unsigned int>(Remaining);
  1328. }
  1329. }
  1330. bool Result = (BlockSize > 0);
  1331. if (Result)
  1332. {
  1333. InitRequest(Request, FTransferred, BlockSize);
  1334. Request->Token = reinterpret_cast<void*>(BlockSize);
  1335. FTransferred += BlockSize;
  1336. }
  1337. return Result;
  1338. }
  1339. void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
  1340. unsigned long Size)
  1341. {
  1342. Request->ChangeType(SSH_FXP_READ);
  1343. Request->AddString(FHandle);
  1344. Request->AddInt64(Offset);
  1345. Request->AddCardinal(Size);
  1346. }
  1347. virtual bool __fastcall End(TSFTPPacket * Response)
  1348. {
  1349. return (Response->Type != SSH_FXP_DATA);
  1350. }
  1351. private:
  1352. TFileOperationProgressType * OperationProgress;
  1353. __int64 FTransferred;
  1354. __int64 FPartSize;
  1355. RawByteString FHandle;
  1356. };
  1357. //---------------------------------------------------------------------------
  1358. class TSFTPUploadQueue : public TSFTPAsynchronousQueue
  1359. {
  1360. public:
  1361. TSFTPUploadQueue(TSFTPFileSystem * AFileSystem, TEncryption * Encryption) :
  1362. TSFTPAsynchronousQueue(AFileSystem),
  1363. FEncryption(Encryption)
  1364. {
  1365. FStream = NULL;
  1366. FOnTransferIn = NULL;
  1367. OperationProgress = NULL;
  1368. FLastBlockSize = 0;
  1369. FEnd = false;
  1370. FConvertToken = false;
  1371. }
  1372. virtual __fastcall ~TSFTPUploadQueue()
  1373. {
  1374. delete FStream;
  1375. }
  1376. bool __fastcall Init(const UnicodeString & AFileName,
  1377. HANDLE AFile, TTransferInEvent OnTransferIn, TFileOperationProgressType * AOperationProgress,
  1378. const RawByteString AHandle, __int64 ATransferred,
  1379. int ConvertParams)
  1380. {
  1381. FFileName = AFileName;
  1382. if (OnTransferIn == NULL)
  1383. {
  1384. FStream = new TSafeHandleStream((THandle)AFile);
  1385. }
  1386. OperationProgress = AOperationProgress;
  1387. FHandle = AHandle;
  1388. FOnTransferIn = OnTransferIn;
  1389. FTransferred = ATransferred;
  1390. FConvertParams = ConvertParams;
  1391. return TSFTPAsynchronousQueue::Init();
  1392. }
  1393. void __fastcall DisposeSafeWithErrorHandling()
  1394. {
  1395. DisposeSafe(SSH_FXP_STATUS);
  1396. }
  1397. protected:
  1398. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1399. {
  1400. TTerminal * FTerminal = FFileSystem->FTerminal;
  1401. // Buffer for one block of data
  1402. TFileBuffer BlockBuf;
  1403. unsigned long BlockSize = GetBlockSize();
  1404. bool Result = (BlockSize > 0);
  1405. if (Result)
  1406. {
  1407. bool Last;
  1408. if (FOnTransferIn != NULL)
  1409. {
  1410. size_t Read = BlockBuf.LoadFromIn(FOnTransferIn, FTerminal, BlockSize);
  1411. Last = (Read < BlockSize);
  1412. }
  1413. else
  1414. {
  1415. FILE_OPERATION_LOOP_BEGIN
  1416. {
  1417. BlockBuf.LoadStream(FStream, BlockSize, false);
  1418. }
  1419. FILE_OPERATION_LOOP_END(FMTLOAD(READ_ERROR, (FFileName)));
  1420. Last = (FStream->Position >= FStream->Size);
  1421. }
  1422. FEnd = (BlockBuf.Size == 0);
  1423. Result = !FEnd;
  1424. if (Result)
  1425. {
  1426. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  1427. // We do ASCII transfer: convert EOL of current block
  1428. if (OperationProgress->AsciiTransfer)
  1429. {
  1430. __int64 PrevBufSize = BlockBuf.Size;
  1431. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1432. FFileSystem->GetEOL(), FConvertParams, FConvertToken);
  1433. // update transfer size with difference arised from EOL conversion
  1434. OperationProgress->ChangeTransferSize(OperationProgress->TransferSize -
  1435. PrevBufSize + BlockBuf.Size);
  1436. }
  1437. if (FFileSystem->FTerminal->Configuration->ActualLogProtocol >= 1)
  1438. {
  1439. FFileSystem->FTerminal->LogEvent(FORMAT(L"Write request offset: %d, len: %d",
  1440. (int(FTransferred), int(BlockBuf.Size))));
  1441. }
  1442. if (FEncryption != NULL)
  1443. {
  1444. FEncryption->Encrypt(BlockBuf, Last);
  1445. }
  1446. Request->ChangeType(SSH_FXP_WRITE);
  1447. Request->AddString(FHandle);
  1448. Request->AddInt64(FTransferred);
  1449. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  1450. FLastBlockSize = BlockBuf.Size;
  1451. FTransferred += BlockBuf.Size;
  1452. }
  1453. }
  1454. return Result;
  1455. }
  1456. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1457. {
  1458. TSFTPAsynchronousQueue::SendPacket(Packet);
  1459. OperationProgress->AddTransferred(FLastBlockSize);
  1460. }
  1461. virtual void __fastcall ReceiveResponse(
  1462. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1463. int AllowStatus, bool TryOnly)
  1464. {
  1465. TSFTPAsynchronousQueue::ReceiveResponse(Packet, Response, ExpectedType, AllowStatus, TryOnly);
  1466. if (Response->Capacity > 0)
  1467. {
  1468. // particularly when uploading a file that completely fits into send buffer
  1469. // over slow line, we may end up seemingly completing the transfer immediatelly
  1470. // but hanging the application for a long time waiting for responses
  1471. // (common is that the progress window would not even manage to draw itself,
  1472. // showing that upload finished, before the application "hangs")
  1473. FFileSystem->Progress(OperationProgress);
  1474. }
  1475. else
  1476. {
  1477. DebugAssert(TryOnly);
  1478. }
  1479. }
  1480. virtual bool __fastcall ReceivePacketAsynchronously()
  1481. {
  1482. // do not read response to close request
  1483. bool Result = (FRequests->Count > 0);
  1484. if (Result)
  1485. {
  1486. // Try only: We cannot read from the socket here as we are already called
  1487. // from TSecureShell::HandleNetworkEvents as it would cause a recursion
  1488. // that would potentially make PuTTY code process the SSH packets in wrong order.
  1489. ReceivePacket(NULL, SSH_FXP_STATUS, -1, NULL, true);
  1490. }
  1491. return Result;
  1492. }
  1493. inline int __fastcall GetBlockSize()
  1494. {
  1495. return FFileSystem->UploadBlockSize(FHandle, OperationProgress);
  1496. }
  1497. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1498. {
  1499. return FEnd;
  1500. }
  1501. private:
  1502. TStream * FStream;
  1503. TTransferInEvent FOnTransferIn;
  1504. TFileOperationProgressType * OperationProgress;
  1505. UnicodeString FFileName;
  1506. unsigned long FLastBlockSize;
  1507. bool FEnd;
  1508. __int64 FTransferred;
  1509. RawByteString FHandle;
  1510. bool FConvertToken;
  1511. int FConvertParams;
  1512. TEncryption * FEncryption;
  1513. };
  1514. //---------------------------------------------------------------------------
  1515. class TSFTPLoadFilesPropertiesQueue : public TSFTPFixedLenQueue
  1516. {
  1517. public:
  1518. TSFTPLoadFilesPropertiesQueue(TSFTPFileSystem * AFileSystem) :
  1519. TSFTPFixedLenQueue(AFileSystem)
  1520. {
  1521. FIndex = 0;
  1522. }
  1523. virtual __fastcall ~TSFTPLoadFilesPropertiesQueue(){}
  1524. bool __fastcall Init(int QueueLen, TStrings * FileList)
  1525. {
  1526. FFileList = FileList;
  1527. return TSFTPFixedLenQueue::Init(QueueLen);
  1528. }
  1529. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1530. {
  1531. void * Token;
  1532. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_ATTRS, asAll, &Token);
  1533. File = static_cast<TRemoteFile *>(Token);
  1534. return Result;
  1535. }
  1536. protected:
  1537. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1538. {
  1539. bool Result = false;
  1540. while (!Result && (FIndex < FFileList->Count))
  1541. {
  1542. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1543. FIndex++;
  1544. bool MissingRights =
  1545. (FFileSystem->FSupport->Loaded &&
  1546. FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS) &&
  1547. File->Rights->Unknown);
  1548. bool MissingOwnerGroup =
  1549. (FFileSystem->FSecureShell->SshImplementation == sshiBitvise) ||
  1550. (FFileSystem->FSupport->Loaded &&
  1551. FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP) &&
  1552. !File->Owner.IsSet || !File->Group.IsSet);
  1553. Result = (MissingRights || MissingOwnerGroup);
  1554. if (Result)
  1555. {
  1556. Request->ChangeType(SSH_FXP_LSTAT);
  1557. FFileSystem->AddPathString(*Request, FFileSystem->LocalCanonify(File->FileName));
  1558. if (FFileSystem->FVersion >= 4)
  1559. {
  1560. Request->AddCardinal(
  1561. FLAGMASK(MissingRights, SSH_FILEXFER_ATTR_PERMISSIONS) |
  1562. FLAGMASK(MissingOwnerGroup, SSH_FILEXFER_ATTR_OWNERGROUP));
  1563. }
  1564. Request->Token = File;
  1565. }
  1566. }
  1567. return Result;
  1568. }
  1569. virtual bool __fastcall SendRequest()
  1570. {
  1571. bool Result =
  1572. (FIndex < FFileList->Count) &&
  1573. TSFTPFixedLenQueue::SendRequest();
  1574. return Result;
  1575. }
  1576. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1577. {
  1578. return (FRequests->Count == 0);
  1579. }
  1580. private:
  1581. TStrings * FFileList;
  1582. int FIndex;
  1583. };
  1584. //---------------------------------------------------------------------------
  1585. class TSFTPCalculateFilesChecksumQueue : public TSFTPFixedLenQueue
  1586. {
  1587. public:
  1588. TSFTPCalculateFilesChecksumQueue(TSFTPFileSystem * AFileSystem) :
  1589. TSFTPFixedLenQueue(AFileSystem)
  1590. {
  1591. FIndex = 0;
  1592. }
  1593. virtual __fastcall ~TSFTPCalculateFilesChecksumQueue(){}
  1594. bool __fastcall Init(int QueueLen, const UnicodeString & Alg, TStrings * FileList)
  1595. {
  1596. FAlg = Alg;
  1597. FFileList = FileList;
  1598. return TSFTPFixedLenQueue::Init(QueueLen);
  1599. }
  1600. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1601. {
  1602. void * Token;
  1603. bool Result;
  1604. try
  1605. {
  1606. Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_EXTENDED_REPLY, asNo, &Token);
  1607. }
  1608. __finally
  1609. {
  1610. File = static_cast<TRemoteFile *>(Token);
  1611. }
  1612. return Result;
  1613. }
  1614. protected:
  1615. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1616. {
  1617. bool Result = false;
  1618. while (!Result && (FIndex < FFileList->Count))
  1619. {
  1620. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1621. DebugAssert(File != NULL);
  1622. FIndex++;
  1623. Result = !File->IsDirectory;
  1624. if (Result)
  1625. {
  1626. DebugAssert(IsRealFile(File->FileName));
  1627. Request->ChangeType(SSH_FXP_EXTENDED);
  1628. Request->AddString(SFTP_EXT_CHECK_FILE_NAME);
  1629. FFileSystem->AddPathString(*Request, FFileSystem->LocalCanonify(File->FullFileName));
  1630. Request->AddString(FAlg);
  1631. Request->AddInt64(0); // offset
  1632. Request->AddInt64(0); // length (0 = till end)
  1633. Request->AddCardinal(0); // block size (0 = no blocks or "one block")
  1634. Request->Token = File;
  1635. }
  1636. }
  1637. return Result;
  1638. }
  1639. virtual bool __fastcall SendRequest()
  1640. {
  1641. bool Result =
  1642. (FIndex < FFileList->Count) &&
  1643. TSFTPFixedLenQueue::SendRequest();
  1644. return Result;
  1645. }
  1646. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1647. {
  1648. return (FRequests->Count == 0);
  1649. }
  1650. private:
  1651. UnicodeString FAlg;
  1652. TStrings * FFileList;
  1653. int FIndex;
  1654. };
  1655. //---------------------------------------------------------------------------
  1656. #pragma warn .inl
  1657. //---------------------------------------------------------------------------
  1658. class TSFTPBusy
  1659. {
  1660. public:
  1661. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  1662. {
  1663. FFileSystem = FileSystem;
  1664. DebugAssert(FFileSystem != NULL);
  1665. FFileSystem->BusyStart();
  1666. }
  1667. __fastcall ~TSFTPBusy()
  1668. {
  1669. FFileSystem->BusyEnd();
  1670. }
  1671. private:
  1672. TSFTPFileSystem * FFileSystem;
  1673. };
  1674. //===========================================================================
  1675. struct TOpenRemoteFileParams
  1676. {
  1677. UnicodeString FileName;
  1678. UnicodeString RemoteFileName;
  1679. TFileOperationProgressType * OperationProgress;
  1680. const TCopyParamType * CopyParam;
  1681. int Params;
  1682. bool Resume;
  1683. bool Resuming;
  1684. TSFTPOverwriteMode OverwriteMode;
  1685. __int64 DestFileSize; // output
  1686. RawByteString RemoteFileHandle; // output
  1687. TOverwriteFileParams * FileParams;
  1688. bool Confirmed;
  1689. bool DontRecycle;
  1690. bool Recycled;
  1691. TRights RecycledRights;
  1692. };
  1693. //===========================================================================
  1694. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal,
  1695. TSecureShell * SecureShell):
  1696. TCustomFileSystem(ATerminal)
  1697. {
  1698. FSecureShell = SecureShell;
  1699. FPacketReservations = new TList();
  1700. ResetConnection();
  1701. FBusy = 0;
  1702. FAvoidBusy = false;
  1703. FUtfStrings = asOff;
  1704. FUtfDisablingAnnounced = true;
  1705. FSignedTS = false;
  1706. FSupport = new TSFTPSupport();
  1707. FExtensions = new TStringList();
  1708. FFixedPaths = NULL;
  1709. FFileSystemInfoValid = false;
  1710. FChecksumAlgs.reset(new TStringList());
  1711. FChecksumSftpAlgs.reset(new TStringList());
  1712. // List as defined by draft-ietf-secsh-filexfer-extensions-00
  1713. // MD5 moved to the back
  1714. RegisterChecksumAlg(Sha1ChecksumAlg, L"sha1");
  1715. RegisterChecksumAlg(Sha224ChecksumAlg, L"sha224");
  1716. RegisterChecksumAlg(Sha256ChecksumAlg, L"sha256");
  1717. RegisterChecksumAlg(Sha384ChecksumAlg, L"sha384");
  1718. RegisterChecksumAlg(Sha512ChecksumAlg, L"sha512");
  1719. RegisterChecksumAlg(Md5ChecksumAlg, L"md5");
  1720. RegisterChecksumAlg(Crc32ChecksumAlg, L"crc32");
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  1724. {
  1725. delete FSupport;
  1726. ResetConnection();
  1727. delete FPacketReservations;
  1728. delete FExtensions;
  1729. delete FFixedPaths;
  1730. delete FSecureShell;
  1731. }
  1732. //---------------------------------------------------------------------------
  1733. void __fastcall TSFTPFileSystem::Open()
  1734. {
  1735. // this is used for reconnects only
  1736. FSecureShell->Open();
  1737. }
  1738. //---------------------------------------------------------------------------
  1739. void __fastcall TSFTPFileSystem::Close()
  1740. {
  1741. FSecureShell->Close();
  1742. ResetConnection();
  1743. }
  1744. //---------------------------------------------------------------------------
  1745. bool __fastcall TSFTPFileSystem::GetActive()
  1746. {
  1747. return FSecureShell->Active;
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. void __fastcall TSFTPFileSystem::CollectUsage()
  1751. {
  1752. FSecureShell->CollectUsage();
  1753. UnicodeString VersionCounter;
  1754. switch (FVersion)
  1755. {
  1756. case 0:
  1757. VersionCounter = L"OpenedSessionsSFTP0";
  1758. break;
  1759. case 1:
  1760. VersionCounter = L"OpenedSessionsSFTP1";
  1761. break;
  1762. case 2:
  1763. VersionCounter = L"OpenedSessionsSFTP2";
  1764. break;
  1765. case 3:
  1766. VersionCounter = L"OpenedSessionsSFTP3";
  1767. break;
  1768. case 4:
  1769. VersionCounter = L"OpenedSessionsSFTP4";
  1770. break;
  1771. case 5:
  1772. VersionCounter = L"OpenedSessionsSFTP5";
  1773. break;
  1774. case 6:
  1775. VersionCounter = L"OpenedSessionsSFTP6";
  1776. break;
  1777. default:
  1778. DebugFail();
  1779. }
  1780. FTerminal->Configuration->Usage->Inc(VersionCounter);
  1781. }
  1782. //---------------------------------------------------------------------------
  1783. const TSessionInfo & __fastcall TSFTPFileSystem::GetSessionInfo()
  1784. {
  1785. return FSecureShell->GetSessionInfo();
  1786. }
  1787. //---------------------------------------------------------------------------
  1788. const TFileSystemInfo & __fastcall TSFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1789. {
  1790. if (!FFileSystemInfoValid)
  1791. {
  1792. FFileSystemInfo.AdditionalInfo = L"";
  1793. if (!IsCapable(fcRename))
  1794. {
  1795. FFileSystemInfo.AdditionalInfo += LoadStr(FS_RENAME_NOT_SUPPORTED) + L"\r\n\r\n";
  1796. }
  1797. if (FExtensions->Count > 0)
  1798. {
  1799. UnicodeString Name;
  1800. UnicodeString Value;
  1801. UnicodeString Line;
  1802. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_EXTENSION_INFO) + L"\r\n";
  1803. for (int Index = 0; Index < FExtensions->Count; Index++)
  1804. {
  1805. UnicodeString Name = FExtensions->Names[Index];
  1806. UnicodeString Value = FExtensions->Values[Name];
  1807. UnicodeString Line;
  1808. if (Value.IsEmpty())
  1809. {
  1810. Line = Name;
  1811. }
  1812. else
  1813. {
  1814. Line = FORMAT(L"%s=%s", (Name, Value));
  1815. }
  1816. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (Line));
  1817. }
  1818. }
  1819. else
  1820. {
  1821. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_NO_EXTENSION_INFO) + L"\r\n";
  1822. }
  1823. FFileSystemInfo.ProtocolBaseName = L"SFTP";
  1824. FFileSystemInfo.ProtocolName = FMTLOAD(SFTP_PROTOCOL_NAME2, (FVersion));
  1825. FTerminal->SaveCapabilities(FFileSystemInfo);
  1826. FFileSystemInfoValid = true;
  1827. }
  1828. return FFileSystemInfo;
  1829. }
  1830. //---------------------------------------------------------------------------
  1831. bool __fastcall TSFTPFileSystem::TemporaryTransferFile(const UnicodeString & FileName)
  1832. {
  1833. return (GetPartialFileExtLen(FileName) > 0);
  1834. }
  1835. //---------------------------------------------------------------------------
  1836. bool __fastcall TSFTPFileSystem::GetStoredCredentialsTried()
  1837. {
  1838. return FSecureShell->GetStoredCredentialsTried();
  1839. }
  1840. //---------------------------------------------------------------------------
  1841. UnicodeString __fastcall TSFTPFileSystem::GetUserName()
  1842. {
  1843. return FSecureShell->UserName;
  1844. }
  1845. //---------------------------------------------------------------------------
  1846. void __fastcall TSFTPFileSystem::Idle()
  1847. {
  1848. // Keep session alive
  1849. if ((FTerminal->SessionData->PingType != ptOff) &&
  1850. (Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
  1851. {
  1852. if ((FTerminal->SessionData->PingType == ptDummyCommand) &&
  1853. FSecureShell->Ready)
  1854. {
  1855. FTerminal->LogEvent(L"Sending dummy command to keep session alive.");
  1856. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1857. AddPathString(Packet, L"/");
  1858. SendPacketAndReceiveResponse(&Packet, &Packet);
  1859. }
  1860. else
  1861. {
  1862. FSecureShell->KeepAlive();
  1863. }
  1864. }
  1865. FSecureShell->Idle();
  1866. }
  1867. //---------------------------------------------------------------------------
  1868. void __fastcall TSFTPFileSystem::ResetConnection()
  1869. {
  1870. // there must be no valid packet reservation at the end
  1871. for (int i = 0; i < FPacketReservations->Count; i++)
  1872. {
  1873. DebugAssert(FPacketReservations->Items[i] == NULL);
  1874. delete (TSFTPPacket *)FPacketReservations->Items[i];
  1875. }
  1876. FPacketReservations->Clear();
  1877. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varLongWord);
  1878. FNotLoggedRequests.clear();
  1879. FPreviousLoggedPacket = 0;
  1880. FNotLoggedWritePackets = FNotLoggedReadPackets = FNotLoggedStatusPackets = FNotLoggedDataPackets = 0;
  1881. }
  1882. //---------------------------------------------------------------------------
  1883. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  1884. {
  1885. DebugAssert(FTerminal);
  1886. switch (Capability) {
  1887. case fcAnyCommand:
  1888. case fcShellAnyCommand:
  1889. case fcLocking:
  1890. case fcAclChangingFiles: // pending implementation
  1891. case fcMoveOverExistingFile:
  1892. return false;
  1893. case fcNewerOnlyUpload:
  1894. case fcTimestampChanging:
  1895. case fcIgnorePermErrors:
  1896. case fcPreservingTimestampUpload:
  1897. case fcSecondaryShell:
  1898. case fcRemoveCtrlZUpload:
  1899. case fcRemoveBOMUpload:
  1900. case fcPreservingTimestampDirs:
  1901. case fcTransferOut:
  1902. case fcTransferIn:
  1903. return true;
  1904. case fcMoveToQueue:
  1905. case fcResumeSupport:
  1906. case fcSkipTransfer:
  1907. case fcParallelTransfers:
  1908. case fcParallelFileTransfers:
  1909. return !FTerminal->IsEncryptingFiles();
  1910. case fcRename:
  1911. case fcRemoteMove:
  1912. return (FVersion >= 2);
  1913. case fcSymbolicLink:
  1914. case fcResolveSymlink:
  1915. return (FVersion >= 3) && !FTerminal->IsEncryptingFiles();
  1916. case fcModeChanging:
  1917. case fcModeChangingUpload:
  1918. return !FSupport->Loaded ||
  1919. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS);
  1920. case fcGroupOwnerChangingByID:
  1921. return (FVersion <= 3);
  1922. case fcOwnerChanging:
  1923. case fcGroupChanging:
  1924. return
  1925. (FVersion <= 3) ||
  1926. ((FVersion >= 4) &&
  1927. (!FSupport->Loaded ||
  1928. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP)));
  1929. case fcNativeTextMode:
  1930. return !FTerminal->IsEncryptingFiles() && (FVersion >= 4);
  1931. case fcTextMode:
  1932. return
  1933. !FTerminal->IsEncryptingFiles() &&
  1934. ((FVersion >= 4) ||
  1935. (strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0));
  1936. case fcUserGroupListing:
  1937. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1938. case fcLoadingAdditionalProperties:
  1939. // We allow loading properties only, if "supported" extension is supported and
  1940. // the server supports "permissions" and/or "owner/group" attributes
  1941. // (no other attributes are loaded).
  1942. // This is here only because of VShell
  1943. // (it supports owner/group, but does not include them into response to
  1944. // SSH_FXP_READDIR)
  1945. // and Bitvise (the same as VShell, but it does not even bother to provide "supported" extension until 6.21)
  1946. // No other use is known.
  1947. return
  1948. (FSupport->Loaded &&
  1949. ((FSupport->AttributeMask &
  1950. (SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_OWNERGROUP)) != 0)) ||
  1951. (FSecureShell->SshImplementation == sshiBitvise);
  1952. case fcCheckingSpaceAvailable:
  1953. return
  1954. // extension announced in extension list of by
  1955. // SFTP_EXT_SUPPORTED/SFTP_EXT_SUPPORTED2 extension
  1956. // (SFTP version 5 and newer only)
  1957. SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  1958. // extension announced by proprietary SFTP_EXT_STATVFS extension
  1959. FSupportsStatVfsV2 ||
  1960. // Bitvise (until 6.21) fails to report it's supported extensions.
  1961. (FSecureShell->SshImplementation == sshiBitvise);
  1962. case fcCalculatingChecksum:
  1963. return
  1964. !FTerminal->IsEncryptingFiles() &&
  1965. (// Specification says that "check-file" should be announced,
  1966. // yet Vandyke VShell (as of 4.0.3) announce "check-file-name"
  1967. // https://forums.vandyke.com/showthread.php?t=11597
  1968. SupportsExtension(SFTP_EXT_CHECK_FILE) ||
  1969. SupportsExtension(SFTP_EXT_CHECK_FILE_NAME) ||
  1970. // see above
  1971. (FSecureShell->SshImplementation == sshiBitvise));
  1972. case fcRemoteCopy:
  1973. return
  1974. // Implemented by ProFTPD/mod_sftp, OpenSSH (since 9.0) and Bitvise WinSSHD (without announcing it)
  1975. SupportsExtension(SFTP_EXT_COPY_FILE) ||
  1976. SupportsExtension(SFTP_EXT_COPY_DATA) ||
  1977. // see above
  1978. (FSecureShell->SshImplementation == sshiBitvise);
  1979. case fcHardLink:
  1980. return
  1981. (FVersion >= 6) ||
  1982. FSupportsHardlink;
  1983. case fcChangePassword:
  1984. return FSecureShell->CanChangePassword();
  1985. default:
  1986. DebugFail();
  1987. return false;
  1988. }
  1989. }
  1990. //---------------------------------------------------------------------------
  1991. bool __fastcall TSFTPFileSystem::SupportsExtension(const UnicodeString & Extension) const
  1992. {
  1993. return
  1994. // OpenSSH announce extensions directly in the SSH_FXP_VERSION packet only.
  1995. // Bitvise uses "supported2" extension for some (mostly the standard ones) and SSH_FXP_VERSION for other.
  1996. // ProFTPD uses "supported2" extension for the standard extensions. And repeats them along with non-standard in the SSH_FXP_VERSION.
  1997. (FExtensions->IndexOfName(Extension) >= 0) ||
  1998. (FSupport->Loaded && (FSupport->Extensions->IndexOf(Extension) >= 0));
  1999. }
  2000. //---------------------------------------------------------------------------
  2001. inline void __fastcall TSFTPFileSystem::BusyStart()
  2002. {
  2003. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  2004. {
  2005. FBusyToken = ::BusyStart();
  2006. }
  2007. FBusy++;
  2008. DebugAssert(FBusy < 10);
  2009. }
  2010. //---------------------------------------------------------------------------
  2011. inline void __fastcall TSFTPFileSystem::BusyEnd()
  2012. {
  2013. DebugAssert(FBusy > 0);
  2014. FBusy--;
  2015. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  2016. {
  2017. ::BusyEnd(FBusyToken);
  2018. FBusyToken = NULL;
  2019. }
  2020. }
  2021. //---------------------------------------------------------------------------
  2022. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  2023. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  2024. {
  2025. const unsigned long MinPacketSize = 32768;
  2026. // size + message number + type
  2027. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  2028. unsigned long AMaxPacketSize = FSecureShell->MaxPacketSize();
  2029. bool MaxPacketSizeValid = (AMaxPacketSize > 0);
  2030. unsigned long CPSRounded = TEncryption::RoundToBlock(OperationProgress->CPS());
  2031. unsigned long Result = CPSRounded;
  2032. if ((MaxPacketSize > 0) &&
  2033. ((MaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  2034. {
  2035. AMaxPacketSize = MaxPacketSize;
  2036. MaxPacketSizeValid = true;
  2037. }
  2038. if ((FMaxPacketSize > 0) &&
  2039. ((FMaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  2040. {
  2041. AMaxPacketSize = FMaxPacketSize;
  2042. MaxPacketSizeValid = true;
  2043. }
  2044. if (Result == 0)
  2045. {
  2046. Result = OperationProgress->StaticBlockSize();
  2047. }
  2048. if (Result < MinPacketSize)
  2049. {
  2050. Result = MinPacketSize;
  2051. }
  2052. if (MaxPacketSizeValid)
  2053. {
  2054. Overhead += SFTPPacketOverhead;
  2055. if (AMaxPacketSize < Overhead)
  2056. {
  2057. // do not send another request
  2058. // (generally should happen only if upload buffer is full)
  2059. Result = 0;
  2060. }
  2061. else
  2062. {
  2063. AMaxPacketSize -= Overhead;
  2064. if (Result > AMaxPacketSize)
  2065. {
  2066. unsigned int MaxPacketSizeRounded = TEncryption::RoundToBlockDown(AMaxPacketSize);
  2067. if (MaxPacketSizeRounded > 0)
  2068. {
  2069. AMaxPacketSize = MaxPacketSizeRounded;
  2070. }
  2071. Result = AMaxPacketSize;
  2072. }
  2073. }
  2074. }
  2075. Result = OperationProgress->AdjustToCPSLimit(Result);
  2076. return Result;
  2077. }
  2078. //---------------------------------------------------------------------------
  2079. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const RawByteString & Handle,
  2080. TFileOperationProgressType * OperationProgress)
  2081. {
  2082. // handle length + offset + data size
  2083. const unsigned long UploadPacketOverhead =
  2084. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  2085. return TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress);
  2086. }
  2087. //---------------------------------------------------------------------------
  2088. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  2089. TFileOperationProgressType * OperationProgress)
  2090. {
  2091. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  2092. if (FSupport->Loaded && (FSupport->MaxReadSize > 0) &&
  2093. (Result > FSupport->MaxReadSize))
  2094. {
  2095. Result = FSupport->MaxReadSize;
  2096. }
  2097. return Result;
  2098. }
  2099. //---------------------------------------------------------------------------
  2100. void __fastcall TSFTPFileSystem::Progress(TFileOperationProgressType * OperationProgress)
  2101. {
  2102. FTerminal->Progress(OperationProgress);
  2103. }
  2104. //---------------------------------------------------------------------------
  2105. void TSFTPFileSystem::LogPacket(const TSFTPPacket * Packet, TLogLineType Type)
  2106. {
  2107. std::vector<UnicodeString> NotLogged;
  2108. #define ADD_NOT_LOGGED(V, N) \
  2109. if (FNotLogged##V##Packets > 0) \
  2110. { \
  2111. NotLogged.push_back(FORMAT(L"%d SSH_FXP_"#N, (FNotLogged##V##Packets))); \
  2112. FNotLogged##V##Packets = 0; \
  2113. }
  2114. ADD_NOT_LOGGED(Write, WRITE);
  2115. ADD_NOT_LOGGED(Read, READ);
  2116. ADD_NOT_LOGGED(Data, DATA);
  2117. ADD_NOT_LOGGED(Status, STATUS);
  2118. if (!NotLogged.empty())
  2119. {
  2120. UnicodeString S;
  2121. for (size_t Index = 0; Index < NotLogged.size(); Index++)
  2122. {
  2123. AddToList(S, NotLogged[Index], (Index < NotLogged.size() - 1 ? L", " : L" and "));
  2124. }
  2125. FTerminal->LogEvent(FORMAT(L"Skipped %s packets", (S)));
  2126. }
  2127. FTerminal->Log->Add(
  2128. Type, FORMAT(L"Type: %s, Size: %d, Number: %d", (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2129. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2130. {
  2131. FTerminal->Log->Add(Type, Packet->Dump());
  2132. }
  2133. }
  2134. //---------------------------------------------------------------------------
  2135. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  2136. {
  2137. // putting here for a lack of better place
  2138. if (!FUtfDisablingAnnounced && (FUtfStrings == asOff))
  2139. {
  2140. FTerminal->LogEvent(L"Strings received in non-UTF-8 encoding in a previous packet, will not use UTF-8 anymore");
  2141. FUtfDisablingAnnounced = true;
  2142. }
  2143. BusyStart();
  2144. try
  2145. {
  2146. if (FTerminal->Log->Logging && (FTerminal->Configuration->ActualLogProtocol >= 0))
  2147. {
  2148. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2149. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2150. (Packet->Type != FPreviousLoggedPacket) ||
  2151. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2152. {
  2153. LogPacket(Packet, llInput);
  2154. FPreviousLoggedPacket = Packet->Type;
  2155. }
  2156. else
  2157. {
  2158. if (Packet->Type == SSH_FXP_WRITE)
  2159. {
  2160. FNotLoggedWritePackets++;
  2161. }
  2162. else if (DebugAlwaysTrue(Packet->Type == SSH_FXP_READ))
  2163. {
  2164. FNotLoggedReadPackets++;
  2165. }
  2166. FNotLoggedRequests.insert(Packet->MessageNumber);
  2167. }
  2168. }
  2169. FSecureShell->Send(Packet->SendData, Packet->SendLength);
  2170. }
  2171. __finally
  2172. {
  2173. BusyEnd();
  2174. }
  2175. }
  2176. //---------------------------------------------------------------------------
  2177. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(
  2178. TSFTPPacket * Packet, int AllowStatus, bool DoNotForceLog)
  2179. {
  2180. unsigned long Code = Packet->GetCardinal();
  2181. static int Messages[] = {
  2182. SFTP_STATUS_OK,
  2183. SFTP_STATUS_EOF,
  2184. SFTP_STATUS_NO_SUCH_FILE,
  2185. SFTP_STATUS_PERMISSION_DENIED,
  2186. SFTP_STATUS_FAILURE,
  2187. SFTP_STATUS_BAD_MESSAGE,
  2188. SFTP_STATUS_NO_CONNECTION,
  2189. SFTP_STATUS_CONNECTION_LOST,
  2190. SFTP_STATUS_OP_UNSUPPORTED,
  2191. SFTP_STATUS_INVALID_HANDLE,
  2192. SFTP_STATUS_NO_SUCH_PATH,
  2193. SFTP_STATUS_FILE_ALREADY_EXISTS,
  2194. SFTP_STATUS_WRITE_PROTECT,
  2195. SFTP_STATUS_NO_MEDIA,
  2196. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  2197. SFTP_STATUS_QUOTA_EXCEEDED,
  2198. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  2199. SFTP_STATUS_LOCK_CONFLICT,
  2200. SFTP_STATUS_DIR_NOT_EMPTY,
  2201. SFTP_STATUS_NOT_A_DIRECTORY,
  2202. SFTP_STATUS_INVALID_FILENAME,
  2203. SFTP_STATUS_LINK_LOOP,
  2204. SFTP_STATUS_CANNOT_DELETE,
  2205. SFTP_STATUS_INVALID_PARAMETER,
  2206. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  2207. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  2208. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  2209. SFTP_STATUS_DELETE_PENDING,
  2210. SFTP_STATUS_FILE_CORRUPT,
  2211. SFTP_STATUS_OWNER_INVALID,
  2212. SFTP_STATUS_GROUP_INVALID,
  2213. SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK
  2214. };
  2215. int Message;
  2216. if ((AllowStatus & (0x01 << Code)) == 0)
  2217. {
  2218. if (Code >= LENOF(Messages))
  2219. {
  2220. Message = SFTP_STATUS_UNKNOWN;
  2221. }
  2222. else
  2223. {
  2224. Message = Messages[Code];
  2225. }
  2226. UnicodeString MessageStr = LoadStr(Message);
  2227. UnicodeString ServerMessage;
  2228. UnicodeString LanguageTag;
  2229. if ((FVersion >= 3) ||
  2230. // if version is not decided yet (i.e. this is status response
  2231. // to the init request), go on, only if there are any more data
  2232. ((FVersion < 0) && (Packet->RemainingLength > 0)))
  2233. {
  2234. // message is in UTF only since SFTP specification 01 (specification 00
  2235. // is also version 3)
  2236. // (in other words, always use UTF unless server is known to be buggy)
  2237. ServerMessage = Packet->GetString(FUtfStrings);
  2238. // SSH-2.0-Maverick_SSHD and SSH-2.0-CIGNA SFTP Server Ready! omit the language tag
  2239. // and I believe I've seen one more server doing the same.
  2240. if (Packet->RemainingLength > 0)
  2241. {
  2242. LanguageTag = Packet->GetAnsiString();
  2243. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  2244. {
  2245. UnicodeString Principals;
  2246. while (Packet->GetNextData() != NULL)
  2247. {
  2248. if (!Principals.IsEmpty())
  2249. {
  2250. Principals += L", ";
  2251. }
  2252. Principals += Packet->GetAnsiString();
  2253. }
  2254. MessageStr = FORMAT(MessageStr, (Principals));
  2255. }
  2256. }
  2257. }
  2258. else
  2259. {
  2260. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  2261. }
  2262. if (FTerminal->Log->Logging &&
  2263. (FTerminal->Configuration->ActualLogProtocol >= 0))
  2264. {
  2265. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d, Message: %d, Server: %s, Language: %s ",
  2266. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  2267. }
  2268. if (!LanguageTag.IsEmpty())
  2269. {
  2270. LanguageTag = FORMAT(L" (%s)", (LanguageTag));
  2271. }
  2272. UnicodeString HelpKeyword;
  2273. switch (Code)
  2274. {
  2275. case SSH_FX_FAILURE:
  2276. HelpKeyword = HELP_SFTP_STATUS_FAILURE;
  2277. break;
  2278. case SSH_FX_PERMISSION_DENIED:
  2279. HelpKeyword = HELP_SFTP_STATUS_PERMISSION_DENIED;
  2280. break;
  2281. }
  2282. UnicodeString Error = FMTLOAD(SFTP_ERROR_FORMAT3, (MessageStr,
  2283. int(Code), LanguageTag, ServerMessage));
  2284. if (Code == SSH_FX_FAILURE)
  2285. {
  2286. FTerminal->Configuration->Usage->Inc(L"SftpFailureErrors");
  2287. Error += L"\n\n" + LoadStr(SFTP_STATUS_4);
  2288. }
  2289. FTerminal->TerminalError(NULL, Error, HelpKeyword);
  2290. return 0;
  2291. }
  2292. else
  2293. {
  2294. if (!DoNotForceLog || (Code != 0))
  2295. {
  2296. if (FTerminal->Configuration->ActualLogProtocol >= 0)
  2297. {
  2298. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d", ((int)Code)));
  2299. }
  2300. }
  2301. return Code;
  2302. }
  2303. }
  2304. //---------------------------------------------------------------------------
  2305. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  2306. {
  2307. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  2308. {
  2309. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  2310. }
  2311. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  2312. if (Packet)
  2313. {
  2314. DebugAssert(Packet->ReservedBy == this);
  2315. Packet->ReservedBy = NULL;
  2316. }
  2317. FPacketReservations->Delete(Reservation);
  2318. }
  2319. //---------------------------------------------------------------------------
  2320. inline int __fastcall TSFTPFileSystem::PacketLength(unsigned char * LenBuf, int ExpectedType)
  2321. {
  2322. int Length = GET_32BIT(LenBuf);
  2323. if (Length > SFTP_MAX_PACKET_LEN)
  2324. {
  2325. UnicodeString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  2326. int(Length), SFTP_MAX_PACKET_LEN));
  2327. if (ExpectedType == SSH_FXP_VERSION)
  2328. {
  2329. RawByteString LenString(reinterpret_cast<char *>(LenBuf), 4);
  2330. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  2331. (Message, DisplayableStr(LenString)));
  2332. }
  2333. FTerminal->FatalError(NULL, Message, HELP_SFTP_PACKET_TOO_BIG);
  2334. }
  2335. return Length;
  2336. }
  2337. //---------------------------------------------------------------------------
  2338. bool __fastcall TSFTPFileSystem::PeekPacket()
  2339. {
  2340. bool Result;
  2341. unsigned char * Buf;
  2342. Result = FSecureShell->Peek(Buf, 4);
  2343. if (Result)
  2344. {
  2345. int Length = PacketLength(Buf, -1);
  2346. Result = FSecureShell->Peek(Buf, 4 + Length);
  2347. }
  2348. return Result;
  2349. }
  2350. //---------------------------------------------------------------------------
  2351. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  2352. int ExpectedType, int AllowStatus, bool TryOnly)
  2353. {
  2354. TSFTPBusy Busy(this);
  2355. int Result = SSH_FX_OK;
  2356. int Reservation = FPacketReservations->IndexOf(Packet);
  2357. bool NotLogged;
  2358. if (Reservation < 0 || Packet->Capacity == 0)
  2359. {
  2360. bool IsReserved;
  2361. do
  2362. {
  2363. IsReserved = false;
  2364. NotLogged = false;
  2365. DebugAssert(Packet);
  2366. if (TryOnly && !PeekPacket())
  2367. {
  2368. // Reset packet in case it was filled by previous out-of-order
  2369. // reserved packet
  2370. *Packet = TSFTPPacket();
  2371. }
  2372. else
  2373. {
  2374. unsigned char LenBuf[4];
  2375. FSecureShell->Receive(LenBuf, sizeof(LenBuf));
  2376. int Length = PacketLength(LenBuf, ExpectedType);
  2377. Packet->Capacity = Length;
  2378. FSecureShell->Receive(Packet->Data, Length);
  2379. Packet->DataUpdated(Length);
  2380. bool ResponseToNotLoggedRequest = (FNotLoggedRequests.erase(Packet->MessageNumber) != 0);
  2381. if (FTerminal->Log->Logging && (FTerminal->Configuration->ActualLogProtocol >= 0))
  2382. {
  2383. if (!ResponseToNotLoggedRequest ||
  2384. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  2385. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2386. {
  2387. LogPacket(Packet, llOutput);
  2388. }
  2389. else
  2390. {
  2391. if (Packet->Type == SSH_FXP_STATUS)
  2392. {
  2393. FNotLoggedStatusPackets++;
  2394. }
  2395. else if (DebugAlwaysTrue(Packet->Type == SSH_FXP_DATA))
  2396. {
  2397. FNotLoggedDataPackets++;
  2398. }
  2399. NotLogged = true; // used only for the response we wait for
  2400. }
  2401. }
  2402. if (Reservation < 0 ||
  2403. Packet->MessageNumber != (unsigned int)FPacketNumbers.GetElement(Reservation))
  2404. {
  2405. TSFTPPacket * ReservedPacket;
  2406. unsigned int MessageNumber;
  2407. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  2408. {
  2409. MessageNumber = (unsigned int)FPacketNumbers.GetElement(Index);
  2410. if (MessageNumber == Packet->MessageNumber)
  2411. {
  2412. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  2413. IsReserved = true;
  2414. if (ReservedPacket)
  2415. {
  2416. FTerminal->LogEvent(0, L"Storing reserved response");
  2417. *ReservedPacket = *Packet;
  2418. }
  2419. else
  2420. {
  2421. FTerminal->LogEvent(0, L"Discarding reserved response");
  2422. RemoveReservation(Index);
  2423. if ((Reservation >= 0) && (Reservation > Index))
  2424. {
  2425. Reservation--;
  2426. DebugAssert(Reservation == FPacketReservations->IndexOf(Packet));
  2427. }
  2428. }
  2429. break;
  2430. }
  2431. }
  2432. }
  2433. }
  2434. }
  2435. while (IsReserved);
  2436. }
  2437. if ((Packet->Capacity == 0) && DebugAlwaysTrue(TryOnly))
  2438. {
  2439. // noop
  2440. }
  2441. else
  2442. {
  2443. // before we removed the reservation after check for packet type,
  2444. // but if it raises exception, removal is unnecessarily
  2445. // postponed until the packet is removed
  2446. // (and it have not worked anyway until recent fix to UnreserveResponse)
  2447. if (Reservation >= 0)
  2448. {
  2449. DebugAssert(Packet->MessageNumber == (unsigned int)FPacketNumbers.GetElement(Reservation));
  2450. RemoveReservation(Reservation);
  2451. }
  2452. if (ExpectedType >= 0)
  2453. {
  2454. if (Packet->Type == SSH_FXP_STATUS)
  2455. {
  2456. if (AllowStatus < 0)
  2457. {
  2458. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  2459. }
  2460. Result = GotStatusPacket(Packet, AllowStatus, NotLogged);
  2461. }
  2462. else if (ExpectedType != Packet->Type)
  2463. {
  2464. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  2465. }
  2466. }
  2467. }
  2468. return Result;
  2469. }
  2470. //---------------------------------------------------------------------------
  2471. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  2472. TSFTPPacket * Response)
  2473. {
  2474. if (Response != NULL)
  2475. {
  2476. DebugAssert(FPacketReservations->IndexOf(Response) < 0);
  2477. // mark response as not received yet
  2478. Response->Capacity = 0;
  2479. Response->ReservedBy = this;
  2480. }
  2481. FPacketReservations->Add(Response);
  2482. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  2483. {
  2484. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  2485. }
  2486. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  2487. }
  2488. //---------------------------------------------------------------------------
  2489. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  2490. {
  2491. int Reservation = FPacketReservations->IndexOf(Response);
  2492. if (Response->Capacity != 0)
  2493. {
  2494. // added check for already received packet
  2495. // (it happens when the reserved response is received out of order,
  2496. // unexpectedly soon, and then receivepacket() on the packet
  2497. // is not actually called, due to exception)
  2498. RemoveReservation(Reservation);
  2499. }
  2500. else
  2501. {
  2502. if (Reservation >= 0)
  2503. {
  2504. // we probably do not remove the item at all, because
  2505. // we must remember that the response was expected, so we skip it
  2506. // in receivepacket()
  2507. FPacketReservations->Items[Reservation] = NULL;
  2508. }
  2509. }
  2510. }
  2511. //---------------------------------------------------------------------------
  2512. int __fastcall TSFTPFileSystem::ReceiveResponse(
  2513. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2514. int AllowStatus, bool TryOnly)
  2515. {
  2516. int Result;
  2517. unsigned int MessageNumber = Packet->MessageNumber;
  2518. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  2519. try
  2520. {
  2521. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus, TryOnly);
  2522. if (MessageNumber != AResponse->MessageNumber)
  2523. {
  2524. FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER,
  2525. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  2526. }
  2527. }
  2528. __finally
  2529. {
  2530. if (!Response)
  2531. {
  2532. delete AResponse;
  2533. }
  2534. }
  2535. return Result;
  2536. }
  2537. //---------------------------------------------------------------------------
  2538. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2539. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2540. int AllowStatus)
  2541. {
  2542. int Result;
  2543. TSFTPBusy Busy(this);
  2544. SendPacket(Packet);
  2545. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2546. return Result;
  2547. }
  2548. //---------------------------------------------------------------------------
  2549. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString & Path)
  2550. {
  2551. if (FTerminal->SessionData->SFTPRealPath == asOff)
  2552. {
  2553. return LocalCanonify(Path);
  2554. }
  2555. else
  2556. {
  2557. try
  2558. {
  2559. FTerminal->LogEvent(0, FORMAT(L"Getting real path for '%s'", (Path)));
  2560. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2561. AddPathString(Packet, Path);
  2562. // In SFTP-6 new optional field control-byte is added that defaults to
  2563. // SSH_FXP_REALPATH_NO_CHECK=0x01, meaning it won't fail, if the path does not exist.
  2564. // That differs from SFTP-5 recommendation that
  2565. // "The server SHOULD fail the request if the path is not present on the server."
  2566. // Earlier versions had no recommendation, though canonical SFTP-3 implementation
  2567. // in OpenSSH fails.
  2568. // While we really do not care much, we anyway set the flag to ~ & 0x01 to make the request fail.
  2569. // First for consistency.
  2570. // Second to workaround a bug in ProFTPD/mod_sftp version 1.3.5rc1 through 1.3.5-stable
  2571. // that sends a completely malformed response for non-existing paths,
  2572. // when SSH_FXP_REALPATH_NO_CHECK (even implicitly) is used.
  2573. // See http://bugs.proftpd.org/show_bug.cgi?id=4160
  2574. // Note that earlier drafts of SFTP-6 (filexfer-07 and -08) had optional compose-path field
  2575. // before control-byte field. If we ever use this against a server conforming to those drafts,
  2576. // it may cause trouble.
  2577. if (FVersion >= 6)
  2578. {
  2579. if (FSecureShell->SshImplementation != sshiProFTPD)
  2580. {
  2581. Packet.AddByte(SSH_FXP_REALPATH_STAT_ALWAYS);
  2582. }
  2583. else
  2584. {
  2585. // Cannot use SSH_FXP_REALPATH_STAT_ALWAYS as ProFTPD does wrong bitwise test
  2586. // so it incorrectly evaluates SSH_FXP_REALPATH_STAT_ALWAYS (0x03) as
  2587. // SSH_FXP_REALPATH_NO_CHECK (0x01). The only value conforming to the
  2588. // specification, yet working with ProFTPD is SSH_FXP_REALPATH_STAT_IF (0x02).
  2589. Packet.AddByte(SSH_FXP_REALPATH_STAT_IF);
  2590. }
  2591. }
  2592. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2593. if (Packet.GetCardinal() != 1)
  2594. {
  2595. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2596. }
  2597. UnicodeString RealDir = UnixExcludeTrailingBackslash(Packet.GetPathString(FUtfStrings));
  2598. // do not cache, as particularly when called from CreateDirectory > Canonify,
  2599. // we would cache an unencrypted path to a directory we want to create encrypted,
  2600. // what would prevent the encryption later.
  2601. RealDir = FTerminal->DecryptFileName(RealDir, true, true);
  2602. // ignore rest of SSH_FXP_NAME packet
  2603. FTerminal->LogEvent(0, FORMAT(L"Real path is '%s'", (RealDir)));
  2604. return RealDir;
  2605. }
  2606. catch(Exception & E)
  2607. {
  2608. if (FTerminal->Active)
  2609. {
  2610. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2611. }
  2612. else
  2613. {
  2614. throw;
  2615. }
  2616. }
  2617. }
  2618. }
  2619. //---------------------------------------------------------------------------
  2620. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString & Path, const UnicodeString & BaseDir)
  2621. {
  2622. UnicodeString APath;
  2623. if (UnixIsAbsolutePath(Path))
  2624. {
  2625. APath = Path;
  2626. }
  2627. else
  2628. {
  2629. if (!Path.IsEmpty())
  2630. {
  2631. // this condition/block was outside (before) current block
  2632. // but it did not work when Path was empty
  2633. if (!BaseDir.IsEmpty())
  2634. {
  2635. APath = UnixIncludeTrailingBackslash(BaseDir);
  2636. }
  2637. APath = APath + Path;
  2638. }
  2639. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(L".");
  2640. }
  2641. return RealPath(APath);
  2642. }
  2643. //---------------------------------------------------------------------------
  2644. UnicodeString __fastcall TSFTPFileSystem::LocalCanonify(const UnicodeString & Path)
  2645. {
  2646. // TODO: improve (handle .. etc.)
  2647. if (UnixIsAbsolutePath(Path) ||
  2648. (!FCurrentDirectory.IsEmpty() && UnixSamePath(FCurrentDirectory, Path)))
  2649. {
  2650. return Path;
  2651. }
  2652. else
  2653. {
  2654. return ::AbsolutePath(FCurrentDirectory, Path);
  2655. }
  2656. }
  2657. //---------------------------------------------------------------------------
  2658. UnicodeString __fastcall TSFTPFileSystem::Canonify(const UnicodeString & AAPath)
  2659. {
  2660. // inspired by canonify() from PSFTP.C
  2661. UnicodeString Result;
  2662. FTerminal->LogEvent(FORMAT(L"Canonifying: \"%s\"", (AAPath)));
  2663. UnicodeString Path = LocalCanonify(AAPath);
  2664. bool TryParent = false;
  2665. try
  2666. {
  2667. Result = RealPath(Path);
  2668. }
  2669. catch(...)
  2670. {
  2671. if (FTerminal->Active)
  2672. {
  2673. TryParent = true;
  2674. }
  2675. else
  2676. {
  2677. throw;
  2678. }
  2679. }
  2680. if (TryParent)
  2681. {
  2682. UnicodeString APath = UnixExcludeTrailingBackslash(Path);
  2683. UnicodeString Name = UnixExtractFileName(APath);
  2684. if (!IsRealFile(Name))
  2685. {
  2686. Result = Path;
  2687. }
  2688. else
  2689. {
  2690. UnicodeString FPath = UnixExtractFilePath(APath);
  2691. try
  2692. {
  2693. Result = RealPath(FPath);
  2694. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2695. }
  2696. catch(...)
  2697. {
  2698. if (FTerminal->Active)
  2699. {
  2700. Result = Path;
  2701. }
  2702. else
  2703. {
  2704. throw;
  2705. }
  2706. }
  2707. }
  2708. }
  2709. FTerminal->LogEvent(FORMAT(L"Canonified: \"%s\"", (Result)));
  2710. return Result;
  2711. }
  2712. //---------------------------------------------------------------------------
  2713. UnicodeString __fastcall TSFTPFileSystem::AbsolutePath(UnicodeString Path, bool Local)
  2714. {
  2715. if (Local)
  2716. {
  2717. return LocalCanonify(Path);
  2718. }
  2719. else
  2720. {
  2721. return RealPath(Path, CurrentDirectory);
  2722. }
  2723. }
  2724. //---------------------------------------------------------------------------
  2725. UnicodeString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2726. {
  2727. if (FHomeDirectory.IsEmpty())
  2728. {
  2729. FHomeDirectory = RealPath(L".");
  2730. // Prevent infinite recursion when the server is broken
  2731. if (FHomeDirectory.IsEmpty())
  2732. {
  2733. FHomeDirectory = ROOTDIRECTORY;
  2734. }
  2735. }
  2736. return FHomeDirectory;
  2737. }
  2738. //---------------------------------------------------------------------------
  2739. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2740. bool Complete)
  2741. {
  2742. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode, FUtfStrings, FSignedTS, Complete);
  2743. }
  2744. //---------------------------------------------------------------------------
  2745. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2746. TRemoteFile * ALinkedByFile, const UnicodeString FileName,
  2747. TRemoteFileList * TempFileList, bool Complete)
  2748. {
  2749. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2750. try
  2751. {
  2752. File->Terminal = FTerminal;
  2753. if (!FileName.IsEmpty())
  2754. {
  2755. File->FileName = FileName;
  2756. }
  2757. // to get full path for symlink completion
  2758. File->Directory = TempFileList;
  2759. LoadFile(File, Packet, Complete);
  2760. File->Directory = NULL;
  2761. }
  2762. catch(...)
  2763. {
  2764. delete File;
  2765. throw;
  2766. }
  2767. return File;
  2768. }
  2769. //---------------------------------------------------------------------------
  2770. UnicodeString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2771. {
  2772. return FCurrentDirectory;
  2773. }
  2774. //---------------------------------------------------------------------------
  2775. void __fastcall TSFTPFileSystem::DoStartup()
  2776. {
  2777. // do not know yet
  2778. FVersion = -1;
  2779. FFileSystemInfoValid = false;
  2780. TSFTPPacket Packet(SSH_FXP_INIT);
  2781. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2782. if (MaxVersion > SFTPMaxVersion)
  2783. {
  2784. MaxVersion = SFTPMaxVersion;
  2785. }
  2786. Packet.AddCardinal(MaxVersion);
  2787. try
  2788. {
  2789. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2790. }
  2791. catch(Exception &E)
  2792. {
  2793. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR), HELP_SFTP_INITIALIZE_ERROR);
  2794. }
  2795. FVersion = Packet.GetCardinal();
  2796. FTerminal->LogEvent(FORMAT(L"SFTP version %d negotiated.", (FVersion)));
  2797. if (FVersion > MaxVersion)
  2798. {
  2799. // This happens with ProFTPD:
  2800. // https://github.com/proftpd/proftpd/issues/1200
  2801. FTerminal->LogEvent(L"Got higher version than asked for.");
  2802. }
  2803. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2804. {
  2805. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2806. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2807. }
  2808. FExtensions->Clear();
  2809. FEOL = "\r\n";
  2810. FSupport->Loaded = false;
  2811. FSupportsStatVfsV2 = false;
  2812. FSupportsHardlink = false;
  2813. bool SupportsLimits = false;
  2814. SAFE_DESTROY(FFixedPaths);
  2815. if (FVersion >= 3)
  2816. {
  2817. while (Packet.GetNextData() != NULL)
  2818. {
  2819. UnicodeString ExtensionName = Packet.GetAnsiString();
  2820. RawByteString ExtensionData = Packet.GetRawByteString();
  2821. UnicodeString ExtensionDisplayData = DisplayableStr(ExtensionData);
  2822. if (ExtensionName == SFTP_EXT_NEWLINE)
  2823. {
  2824. FEOL = AnsiString(ExtensionData);
  2825. FTerminal->LogEvent(FORMAT(L"Server requests EOL sequence %s.",
  2826. (ExtensionDisplayData)));
  2827. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2828. {
  2829. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2830. }
  2831. }
  2832. // do not allow "supported" to override "supported2" if both are received
  2833. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2834. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2835. {
  2836. FSupport->Reset();
  2837. TSFTPPacket SupportedStruct(ExtensionData);
  2838. FSupport->Loaded = true;
  2839. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2840. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2841. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2842. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2843. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2844. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2845. {
  2846. while (SupportedStruct.GetNextData() != NULL)
  2847. {
  2848. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2849. }
  2850. }
  2851. else
  2852. {
  2853. // note that supported-open-block-vector, supported-block-vector,
  2854. // attrib-extension-count and attrib-extension-names fields
  2855. // were added only in rev 08, while "supported2" was defined in rev 07
  2856. FSupport->OpenBlockVector = SupportedStruct.GetSmallCardinal();
  2857. FSupport->BlockVector = SupportedStruct.GetSmallCardinal();
  2858. unsigned int ExtensionCount;
  2859. ExtensionCount = SupportedStruct.GetCardinal();
  2860. for (unsigned int i = 0; i < ExtensionCount; i++)
  2861. {
  2862. FSupport->AttribExtensions->Add(SupportedStruct.GetAnsiString());
  2863. }
  2864. ExtensionCount = SupportedStruct.GetCardinal();
  2865. for (unsigned int i = 0; i < ExtensionCount; i++)
  2866. {
  2867. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2868. }
  2869. }
  2870. if (FTerminal->Log->Logging)
  2871. {
  2872. FTerminal->LogEvent(FORMAT(
  2873. L"Server support information (%s):\n"
  2874. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2875. " Access mask: %x, Open block vector: %x, Block vector: %x, Max read size: %d\n",
  2876. (ExtensionName,
  2877. int(FSupport->AttributeMask),
  2878. int(FSupport->AttributeBits),
  2879. int(FSupport->OpenFlags),
  2880. int(FSupport->AccessMask),
  2881. int(FSupport->OpenBlockVector),
  2882. int(FSupport->BlockVector),
  2883. int(FSupport->MaxReadSize))));
  2884. FTerminal->LogEvent(FORMAT(L" Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2885. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2886. {
  2887. FTerminal->LogEvent(
  2888. FORMAT(L" %s", (FSupport->AttribExtensions->Strings[Index])));
  2889. }
  2890. FTerminal->LogEvent(FORMAT(L" Extensions (%d)\n", (FSupport->Extensions->Count)));
  2891. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2892. {
  2893. FTerminal->LogEvent(
  2894. FORMAT(L" %s", (FSupport->Extensions->Strings[Index])));
  2895. }
  2896. }
  2897. }
  2898. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2899. {
  2900. TSFTPPacket VendorIdStruct(ExtensionData);
  2901. UnicodeString VendorName(VendorIdStruct.GetAnsiString());
  2902. UnicodeString ProductName(VendorIdStruct.GetAnsiString());
  2903. UnicodeString ProductVersion(VendorIdStruct.GetAnsiString());
  2904. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2905. FTerminal->LogEvent(FORMAT(L"Server software: %s %s (%d) by %s",
  2906. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2907. }
  2908. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2909. {
  2910. FTerminal->LogEvent(L"File system roots:\n");
  2911. DebugAssert(FFixedPaths == NULL);
  2912. FFixedPaths = new TStringList();
  2913. try
  2914. {
  2915. TSFTPPacket RootsPacket(ExtensionData);
  2916. while (RootsPacket.GetNextData() != NULL)
  2917. {
  2918. unsigned long Dummy = RootsPacket.GetCardinal();
  2919. if (Dummy != 1)
  2920. {
  2921. break;
  2922. }
  2923. else
  2924. {
  2925. unsigned char Drive = RootsPacket.GetByte();
  2926. unsigned char MaybeType = RootsPacket.GetByte();
  2927. FTerminal->LogEvent(FORMAT(L" %s: (type %d)", (static_cast<char>(Drive), (int)MaybeType)));
  2928. FFixedPaths->Add(FORMAT(L"%s:", (static_cast<char>(Drive))));
  2929. }
  2930. }
  2931. }
  2932. catch(Exception & E)
  2933. {
  2934. FFixedPaths->Clear();
  2935. FTerminal->LogEvent(FORMAT(L"Failed to decode %s extension",
  2936. (ExtensionName)));
  2937. FTerminal->HandleException(&E);
  2938. }
  2939. }
  2940. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2941. {
  2942. // first try legacy decoding according to incorrect encoding
  2943. // (structure-like) as of VShell (bug no longer present as of 4.0.3).
  2944. TSFTPPacket VersionsPacket(ExtensionData);
  2945. unsigned int StringSize;
  2946. if (VersionsPacket.CanGetString(StringSize) &&
  2947. (StringSize == VersionsPacket.RemainingLength))
  2948. {
  2949. UnicodeString Versions = VersionsPacket.GetAnsiString();
  2950. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server (VShell format): %s",
  2951. (Versions)));
  2952. }
  2953. else
  2954. {
  2955. // if that fails, fallback to proper decoding
  2956. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server: %s",
  2957. (AnsiToString(ExtensionData))));
  2958. }
  2959. }
  2960. else if (ExtensionName == SFTP_EXT_STATVFS)
  2961. {
  2962. UnicodeString StatVfsVersion = AnsiToString(ExtensionData);
  2963. if (StatVfsVersion == SFTP_EXT_STATVFS_VALUE_V2)
  2964. {
  2965. FSupportsStatVfsV2 = true;
  2966. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, StatVfsVersion)));
  2967. }
  2968. else
  2969. {
  2970. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, StatVfsVersion)));
  2971. }
  2972. }
  2973. else if (ExtensionName == SFTP_EXT_HARDLINK)
  2974. {
  2975. UnicodeString HardlinkVersion = AnsiToString(ExtensionData);
  2976. if (HardlinkVersion == SFTP_EXT_HARDLINK_VALUE_V1)
  2977. {
  2978. FSupportsHardlink = true;
  2979. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, HardlinkVersion)));
  2980. }
  2981. else
  2982. {
  2983. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, HardlinkVersion)));
  2984. }
  2985. }
  2986. else if (ExtensionName == SFTP_EXT_LIMITS)
  2987. {
  2988. UnicodeString LimitsVersion = AnsiToString(ExtensionData);
  2989. if (LimitsVersion == SFTP_EXT_LIMITS_VALUE_V1)
  2990. {
  2991. SupportsLimits = true;
  2992. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, LimitsVersion)));
  2993. }
  2994. else
  2995. {
  2996. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, LimitsVersion)));
  2997. }
  2998. }
  2999. // See the comment in SupportsExtension
  3000. else if ((ExtensionName == SFTP_EXT_COPY_FILE) ||
  3001. (ExtensionName == SFTP_EXT_COPY_DATA) ||
  3002. (ExtensionName == SFTP_EXT_SPACE_AVAILABLE) ||
  3003. (ExtensionName == SFTP_EXT_CHECK_FILE))
  3004. {
  3005. FTerminal->LogEvent(FORMAT(L"Supports extension %s=%s", (ExtensionName, ExtensionDisplayData)));
  3006. }
  3007. else
  3008. {
  3009. FTerminal->LogEvent(0, FORMAT(L"Unknown server extension %s=%s", (ExtensionName, ExtensionDisplayData)));
  3010. }
  3011. FExtensions->Values[ExtensionName] = ExtensionDisplayData;
  3012. }
  3013. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  3014. {
  3015. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3016. Packet.AddString(SFTP_EXT_VENDOR_ID);
  3017. Packet.AddString(FTerminal->Configuration->CompanyName);
  3018. Packet.AddString(FTerminal->Configuration->ProductName);
  3019. Packet.AddString(FTerminal->Configuration->ProductVersion);
  3020. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  3021. SendPacket(&Packet);
  3022. // we are not interested in the response, do not wait for it
  3023. ReserveResponse(&Packet, NULL);
  3024. }
  3025. }
  3026. if (FVersion < 4)
  3027. {
  3028. // currently enable the bug for all servers (really known on OpenSSH)
  3029. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  3030. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  3031. if (FSignedTS)
  3032. {
  3033. FTerminal->LogEvent(L"We believe the server has signed timestamps bug");
  3034. }
  3035. }
  3036. else
  3037. {
  3038. FSignedTS = false;
  3039. }
  3040. switch (FTerminal->SessionData->NotUtf)
  3041. {
  3042. case asOff:
  3043. FUtfStrings = asOn;
  3044. FTerminal->LogEvent(L"We will use UTF-8 strings as configured");
  3045. break;
  3046. default:
  3047. DebugFail();
  3048. case asAuto:
  3049. // Nb, Foxit server does not exist anymore
  3050. if (GetSessionInfo().SshImplementation.Pos(L"Foxit-WAC-Server") == 1)
  3051. {
  3052. FUtfStrings = asOff;
  3053. FTerminal->LogEvent(L"We will not use UTF-8 strings as the server is known not to use them");
  3054. }
  3055. else
  3056. {
  3057. if (FVersion >= 4)
  3058. {
  3059. FTerminal->LogEvent(L"We will use UTF-8 strings as it is mandatory with SFTP version 4 and newer");
  3060. FUtfStrings = asOn;
  3061. }
  3062. else
  3063. {
  3064. 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");
  3065. FUtfStrings = asAuto;
  3066. FUtfDisablingAnnounced = false;
  3067. }
  3068. }
  3069. break;
  3070. case asOn:
  3071. FTerminal->LogEvent(L"We will not use UTF-8 strings as configured");
  3072. FUtfStrings = asOff;
  3073. break;
  3074. }
  3075. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  3076. if (FMaxPacketSize == 0)
  3077. {
  3078. unsigned int PacketPayload = 4;
  3079. if (SupportsLimits)
  3080. {
  3081. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3082. Packet.AddString(SFTP_EXT_LIMITS);
  3083. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3084. unsigned int MaxPacketSize = std::min(static_cast<__int64>(std::numeric_limits<unsigned long>::max()), Packet.GetInt64());
  3085. FTerminal->LogEvent(FORMAT(L"Limiting packet size to server's limit of %d + %d bytes",
  3086. (static_cast<int>(MaxPacketSize), static_cast<int>(PacketPayload))));
  3087. FMaxPacketSize = MaxPacketSize + PacketPayload;
  3088. }
  3089. else if ((FSecureShell->SshImplementation == sshiOpenSSH) && (FVersion == 3) && !FSupport->Loaded)
  3090. {
  3091. FMaxPacketSize = PacketPayload + (256 * 1024); // len + 256kB payload
  3092. FTerminal->LogEvent(FORMAT(L"Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  3093. (int(FMaxPacketSize))));
  3094. }
  3095. // full string is "1.77 sshlib: Momentum SSH Server",
  3096. // possibly it is sshlib-related
  3097. else if (GetSessionInfo().SshImplementation.Pos(L"Momentum SSH Server") != 0)
  3098. {
  3099. FMaxPacketSize = PacketPayload + (32 * 1024);
  3100. FTerminal->LogEvent(FORMAT(L"Limiting packet size to Momentum sftp-server limit of %d bytes",
  3101. (int(FMaxPacketSize))));
  3102. }
  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(const UnicodeString FileName, const TRemoteFile * /*File*/,
  3552. const UnicodeString NewName)
  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)
  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);
  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);
  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. }