SftpFileSystem.cpp 178 KB

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