SftpFileSystem.cpp 167 KB

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