SftpFileSystem.cpp 177 KB

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