SftpFileSystem.cpp 180 KB

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