1
0

SftpFileSystem.cpp 179 KB

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