SftpFileSystem.cpp 150 KB

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