SftpFileSystem.cpp 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070
  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. FStream = NULL;
  1157. OperationProgress = NULL;
  1158. FLastBlockSize = 0;
  1159. FEnd = false;
  1160. }
  1161. virtual __fastcall ~TSFTPUploadQueue()
  1162. {
  1163. delete FStream;
  1164. }
  1165. bool __fastcall Init(const AnsiString AFileName,
  1166. HANDLE AFile, TFileOperationProgressType * AOperationProgress,
  1167. const AnsiString AHandle, __int64 ATransfered)
  1168. {
  1169. FFileName = AFileName;
  1170. FStream = new TSafeHandleStream((THandle)AFile);
  1171. OperationProgress = AOperationProgress;
  1172. FHandle = AHandle;
  1173. FTransfered = ATransfered;
  1174. return TSFTPAsynchronousQueue::Init();
  1175. }
  1176. protected:
  1177. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1178. {
  1179. TTerminal * FTerminal = FFileSystem->FTerminal;
  1180. // Buffer for one block of data
  1181. TFileBuffer BlockBuf;
  1182. unsigned long BlockSize = GetBlockSize();
  1183. bool Result = (BlockSize > 0);
  1184. if (Result)
  1185. {
  1186. FILE_OPERATION_LOOP(FMTLOAD(READ_ERROR, (FFileName)),
  1187. BlockBuf.LoadStream(FStream, BlockSize, false);
  1188. );
  1189. FEnd = (BlockBuf.Size == 0);
  1190. Result = !FEnd;
  1191. if (Result)
  1192. {
  1193. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1194. // We do ASCII transfer: convert EOL of current block
  1195. if (OperationProgress->AsciiTransfer)
  1196. {
  1197. __int64 PrevBufSize = BlockBuf.Size;
  1198. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1199. FFileSystem->GetEOL(), cpRemoveCtrlZ);
  1200. // update transfer size with difference arised from EOL conversion
  1201. OperationProgress->ChangeTransferSize(OperationProgress->TransferSize -
  1202. PrevBufSize + BlockBuf.Size);
  1203. }
  1204. Request->ChangeType(SSH_FXP_WRITE);
  1205. Request->AddString(FHandle);
  1206. Request->AddInt64(FTransfered);
  1207. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  1208. FLastBlockSize = BlockBuf.Size;
  1209. FTransfered += BlockBuf.Size;
  1210. }
  1211. }
  1212. return Result;
  1213. }
  1214. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1215. {
  1216. TSFTPAsynchronousQueue::SendPacket(Packet);
  1217. OperationProgress->AddTransfered(FLastBlockSize);
  1218. }
  1219. virtual bool __fastcall ReceivePacketAsynchronously()
  1220. {
  1221. // do not read response to close request
  1222. bool Result = (FRequests->Count > 0);
  1223. if (Result)
  1224. {
  1225. ReceivePacket(NULL, SSH_FXP_STATUS);
  1226. }
  1227. return Result;
  1228. }
  1229. inline int __fastcall GetBlockSize()
  1230. {
  1231. return FFileSystem->UploadBlockSize(FHandle, OperationProgress);
  1232. }
  1233. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1234. {
  1235. return FEnd;
  1236. }
  1237. private:
  1238. TStream * FStream;
  1239. TFileOperationProgressType * OperationProgress;
  1240. AnsiString FFileName;
  1241. unsigned long FLastBlockSize;
  1242. bool FEnd;
  1243. __int64 FTransfered;
  1244. AnsiString FHandle;
  1245. };
  1246. //---------------------------------------------------------------------------
  1247. class TSFTPLoadFilesPropertiesQueue : public TSFTPFixedLenQueue
  1248. {
  1249. public:
  1250. TSFTPLoadFilesPropertiesQueue(TSFTPFileSystem * AFileSystem) :
  1251. TSFTPFixedLenQueue(AFileSystem)
  1252. {
  1253. FIndex = 0;
  1254. }
  1255. bool __fastcall Init(int QueueLen, TStrings * FileList)
  1256. {
  1257. FFileList = FileList;
  1258. return TSFTPFixedLenQueue::Init(QueueLen);
  1259. }
  1260. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1261. {
  1262. void * Token;
  1263. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_ATTRS, asAll, &Token);
  1264. File = static_cast<TRemoteFile *>(Token);
  1265. return Result;
  1266. }
  1267. protected:
  1268. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1269. {
  1270. bool Result = false;
  1271. while (!Result && (FIndex < FFileList->Count))
  1272. {
  1273. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1274. FIndex++;
  1275. bool MissingRights =
  1276. (FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS) &&
  1277. File->Rights->Unknown);
  1278. bool MissingOwnerGroup =
  1279. (FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP) &&
  1280. File->Owner.IsEmpty() || File->Group.IsEmpty());
  1281. Result = (MissingRights || MissingOwnerGroup);
  1282. if (Result)
  1283. {
  1284. Request->ChangeType(SSH_FXP_LSTAT);
  1285. Request->AddPathString(FFileSystem->LocalCanonify(File->FileName),
  1286. FFileSystem->FUtfStrings);
  1287. if (FFileSystem->FVersion >= 4)
  1288. {
  1289. Request->AddCardinal(
  1290. FLAGMASK(MissingRights, SSH_FILEXFER_ATTR_PERMISSIONS) |
  1291. FLAGMASK(MissingOwnerGroup, SSH_FILEXFER_ATTR_OWNERGROUP));
  1292. }
  1293. Request->Token = File;
  1294. }
  1295. }
  1296. return Result;
  1297. }
  1298. virtual bool __fastcall SendRequest()
  1299. {
  1300. bool Result =
  1301. (FIndex < FFileList->Count) &&
  1302. TSFTPFixedLenQueue::SendRequest();
  1303. return Result;
  1304. }
  1305. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1306. {
  1307. return (FRequests->Count == 0);
  1308. }
  1309. private:
  1310. TStrings * FFileList;
  1311. int FIndex;
  1312. };
  1313. //---------------------------------------------------------------------------
  1314. class TSFTPCalculateFilesChecksumQueue : public TSFTPFixedLenQueue
  1315. {
  1316. public:
  1317. TSFTPCalculateFilesChecksumQueue(TSFTPFileSystem * AFileSystem) :
  1318. TSFTPFixedLenQueue(AFileSystem)
  1319. {
  1320. FIndex = 0;
  1321. }
  1322. bool __fastcall Init(int QueueLen, const AnsiString & Alg, TStrings * FileList)
  1323. {
  1324. FAlg = Alg;
  1325. FFileList = FileList;
  1326. return TSFTPFixedLenQueue::Init(QueueLen);
  1327. }
  1328. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1329. {
  1330. void * Token;
  1331. bool Result;
  1332. try
  1333. {
  1334. Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_EXTENDED_REPLY, asNo, &Token);
  1335. }
  1336. __finally
  1337. {
  1338. File = static_cast<TRemoteFile *>(Token);
  1339. }
  1340. return Result;
  1341. }
  1342. protected:
  1343. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1344. {
  1345. bool Result = false;
  1346. while (!Result && (FIndex < FFileList->Count))
  1347. {
  1348. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1349. assert(File != NULL);
  1350. FIndex++;
  1351. Result = !File->IsDirectory;
  1352. if (Result)
  1353. {
  1354. assert(!File->IsParentDirectory && !File->IsThisDirectory);
  1355. Request->ChangeType(SSH_FXP_EXTENDED);
  1356. Request->AddString(SFTP_EXT_CHECK_FILE_NAME);
  1357. Request->AddPathString(FFileSystem->LocalCanonify(File->FullFileName),
  1358. FFileSystem->FUtfStrings);
  1359. Request->AddString(FAlg);
  1360. Request->AddInt64(0); // offset
  1361. Request->AddInt64(0); // length (0 = till end)
  1362. Request->AddCardinal(0); // block size (0 = no blocks or "one block")
  1363. Request->Token = File;
  1364. }
  1365. }
  1366. return Result;
  1367. }
  1368. virtual bool __fastcall SendRequest()
  1369. {
  1370. bool Result =
  1371. (FIndex < FFileList->Count) &&
  1372. TSFTPFixedLenQueue::SendRequest();
  1373. return Result;
  1374. }
  1375. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1376. {
  1377. return (FRequests->Count == 0);
  1378. }
  1379. private:
  1380. AnsiString FAlg;
  1381. TStrings * FFileList;
  1382. int FIndex;
  1383. };
  1384. //---------------------------------------------------------------------------
  1385. #pragma warn .inl
  1386. //---------------------------------------------------------------------------
  1387. class TSFTPBusy
  1388. {
  1389. public:
  1390. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  1391. {
  1392. FFileSystem = FileSystem;
  1393. assert(FFileSystem != NULL);
  1394. FFileSystem->BusyStart();
  1395. }
  1396. __fastcall ~TSFTPBusy()
  1397. {
  1398. FFileSystem->BusyEnd();
  1399. }
  1400. private:
  1401. TSFTPFileSystem * FFileSystem;
  1402. };
  1403. //===========================================================================
  1404. struct TOpenRemoteFileParams
  1405. {
  1406. int LocalFileAttrs;
  1407. AnsiString RemoteFileName;
  1408. TFileOperationProgressType * OperationProgress;
  1409. const TCopyParamType * CopyParam;
  1410. int Params;
  1411. bool Resume;
  1412. TSFTPOverwriteMode OverwriteMode;
  1413. __int64 DestFileSize; // output
  1414. AnsiString RemoteFileHandle; // output
  1415. TOverwriteFileParams * FileParams;
  1416. bool Confirmed;
  1417. };
  1418. //---------------------------------------------------------------------------
  1419. struct TSinkFileParams
  1420. {
  1421. AnsiString TargetDir;
  1422. const TCopyParamType * CopyParam;
  1423. int Params;
  1424. TFileOperationProgressType * OperationProgress;
  1425. bool Skipped;
  1426. unsigned int Flags;
  1427. };
  1428. //===========================================================================
  1429. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal,
  1430. TSecureShell * SecureShell):
  1431. TCustomFileSystem(ATerminal)
  1432. {
  1433. FSecureShell = SecureShell;
  1434. FPacketReservations = new TList();
  1435. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varInteger);
  1436. FPreviousLoggedPacket = 0;
  1437. FNotLoggedPackets = 0;
  1438. FBusy = 0;
  1439. FAvoidBusy = false;
  1440. FUtfStrings = false;
  1441. FUtfNever = false;
  1442. FSignedTS = false;
  1443. FSupport = new TSFTPSupport();
  1444. FExtensions = new TStringList();
  1445. FFixedPaths = NULL;
  1446. FFileSystemInfoValid = false;
  1447. }
  1448. //---------------------------------------------------------------------------
  1449. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  1450. {
  1451. delete FSupport;
  1452. ResetConnection();
  1453. delete FPacketReservations;
  1454. delete FExtensions;
  1455. delete FFixedPaths;
  1456. delete FSecureShell;
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. void __fastcall TSFTPFileSystem::Open()
  1460. {
  1461. FSecureShell->Open();
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. void __fastcall TSFTPFileSystem::Close()
  1465. {
  1466. FSecureShell->Close();
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. bool __fastcall TSFTPFileSystem::GetActive()
  1470. {
  1471. return FSecureShell->Active;
  1472. }
  1473. //---------------------------------------------------------------------------
  1474. const TSessionInfo & __fastcall TSFTPFileSystem::GetSessionInfo()
  1475. {
  1476. return FSecureShell->GetSessionInfo();
  1477. }
  1478. //---------------------------------------------------------------------------
  1479. const TFileSystemInfo & __fastcall TSFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1480. {
  1481. if (!FFileSystemInfoValid)
  1482. {
  1483. FFileSystemInfo.AdditionalInfo = "";
  1484. if (!IsCapable(fcRename))
  1485. {
  1486. FFileSystemInfo.AdditionalInfo += LoadStr(FS_RENAME_NOT_SUPPORTED) + "\r\n\r\n";
  1487. }
  1488. if (FExtensions->Count > 0)
  1489. {
  1490. AnsiString Name;
  1491. AnsiString Value;
  1492. AnsiString Line;
  1493. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_EXTENSION_INFO) + "\r\n";
  1494. for (int Index = 0; Index < FExtensions->Count; Index++)
  1495. {
  1496. AnsiString Name = FExtensions->Names[Index];
  1497. AnsiString Value = FExtensions->Values[Name];
  1498. AnsiString Line;
  1499. if (Value.IsEmpty())
  1500. {
  1501. Line = Name;
  1502. }
  1503. else
  1504. {
  1505. if (!IsDisplayableStr(Value))
  1506. {
  1507. Value = "0x" + StrToHex(Value);
  1508. }
  1509. Line = FORMAT("%s=%s", (Name, Value));
  1510. }
  1511. FFileSystemInfo.AdditionalInfo += FORMAT(" %s\r\n", (Line));
  1512. }
  1513. }
  1514. else
  1515. {
  1516. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_NO_EXTENSION_INFO) + "\r\n";
  1517. }
  1518. FFileSystemInfo.ProtocolBaseName = "SFTP";
  1519. FFileSystemInfo.ProtocolName = FMTLOAD(SFTP_PROTOCOL_NAME2, (FVersion));
  1520. for (int Index = 0; Index < fcCount; Index++)
  1521. {
  1522. FFileSystemInfo.IsCapable[Index] = IsCapable((TFSCapability)Index);
  1523. }
  1524. FFileSystemInfoValid = true;
  1525. }
  1526. return FFileSystemInfo;
  1527. }
  1528. //---------------------------------------------------------------------------
  1529. bool __fastcall TSFTPFileSystem::TemporaryTransferFile(const AnsiString & FileName)
  1530. {
  1531. return AnsiSameText(UnixExtractFileExt(FileName), PARTIAL_EXT);
  1532. }
  1533. //---------------------------------------------------------------------------
  1534. bool __fastcall TSFTPFileSystem::GetStoredCredentialsTried()
  1535. {
  1536. return FSecureShell->GetStoredCredentialsTried();
  1537. }
  1538. //---------------------------------------------------------------------------
  1539. AnsiString __fastcall TSFTPFileSystem::GetUserName()
  1540. {
  1541. return FSecureShell->UserName;
  1542. }
  1543. //---------------------------------------------------------------------------
  1544. void __fastcall TSFTPFileSystem::Idle()
  1545. {
  1546. // Keep session alive
  1547. if ((FTerminal->SessionData->PingType != ptOff) &&
  1548. (Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
  1549. {
  1550. if (FTerminal->SessionData->PingType == ptDummyCommand)
  1551. {
  1552. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1553. Packet.AddPathString("/", FUtfStrings);
  1554. SendPacketAndReceiveResponse(&Packet, &Packet);
  1555. }
  1556. else
  1557. {
  1558. FSecureShell->KeepAlive();
  1559. }
  1560. }
  1561. FSecureShell->Idle();
  1562. }
  1563. //---------------------------------------------------------------------------
  1564. void __fastcall TSFTPFileSystem::ResetConnection()
  1565. {
  1566. // there must be no valid packet reservation at the end
  1567. for (int i = 0; i < FPacketReservations->Count; i++)
  1568. {
  1569. assert(FPacketReservations->Items[i] == NULL);
  1570. delete (TSFTPPacket *)FPacketReservations->Items[i];
  1571. }
  1572. FPacketReservations->Clear();
  1573. FPacketNumbers.Clear();
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  1577. {
  1578. assert(FTerminal);
  1579. switch (Capability) {
  1580. case fcAnyCommand:
  1581. case fcShellAnyCommand:
  1582. case fcHardLink:
  1583. case fcRemoteCopy:
  1584. return false;
  1585. case fcNewerOnlyUpload:
  1586. case fcTimestampChanging:
  1587. case fcIgnorePermErrors:
  1588. case fcPreservingTimestampUpload:
  1589. case fcSecondaryShell:
  1590. return true;
  1591. case fcRename:
  1592. case fcRemoteMove:
  1593. return (FVersion >= 2);
  1594. case fcSymbolicLink:
  1595. case fcResolveSymlink:
  1596. return (FVersion >= 3);
  1597. case fcModeChanging:
  1598. case fcModeChangingUpload:
  1599. return !FSupport->Loaded ||
  1600. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS);
  1601. case fcOwnerChanging:
  1602. case fcGroupChanging:
  1603. return (FVersion >= 4) &&
  1604. (!FSupport->Loaded ||
  1605. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP));
  1606. case fcNativeTextMode:
  1607. return (FVersion >= 4);
  1608. case fcTextMode:
  1609. return (FVersion >= 4) ||
  1610. strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
  1611. case fcUserGroupListing:
  1612. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1613. case fcLoadingAdditionalProperties:
  1614. // we allow loading properties only, if "suported" extension is supported and
  1615. // the server support "permissions" and/or "owner/group" attributes
  1616. // (no other attributes are loaded)
  1617. return FSupport->Loaded &&
  1618. ((FSupport->AttributeMask &
  1619. (SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_OWNERGROUP)) != 0);
  1620. case fcCheckingSpaceAvailable:
  1621. return SupportsExtension(SFTP_EXT_SPACE_AVAILABLE);
  1622. case fcCalculatingChecksum:
  1623. return SupportsExtension(SFTP_EXT_CHECK_FILE);
  1624. default:
  1625. assert(false);
  1626. return false;
  1627. }
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. bool __fastcall TSFTPFileSystem::SupportsExtension(const AnsiString & Extension) const
  1631. {
  1632. return FSupport->Loaded && (FSupport->Extensions->IndexOf(Extension) >= 0);
  1633. }
  1634. //---------------------------------------------------------------------------
  1635. inline void __fastcall TSFTPFileSystem::BusyStart()
  1636. {
  1637. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1638. {
  1639. Busy(true);
  1640. }
  1641. FBusy++;
  1642. assert(FBusy < 10);
  1643. }
  1644. //---------------------------------------------------------------------------
  1645. inline void __fastcall TSFTPFileSystem::BusyEnd()
  1646. {
  1647. assert(FBusy > 0);
  1648. FBusy--;
  1649. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1650. {
  1651. Busy(false);
  1652. }
  1653. }
  1654. //---------------------------------------------------------------------------
  1655. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  1656. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  1657. {
  1658. const unsigned long MinPacketSize = 4096;
  1659. // size + message number + type
  1660. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  1661. unsigned long AMaxPacketSize = FSecureShell->MaxPacketSize();
  1662. bool MaxPacketSizeValid = (AMaxPacketSize > 0);
  1663. unsigned long Result = OperationProgress->CPS();
  1664. if ((MaxPacketSize > 0) &&
  1665. ((MaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1666. {
  1667. AMaxPacketSize = MaxPacketSize;
  1668. MaxPacketSizeValid = true;
  1669. }
  1670. if ((FMaxPacketSize > 0) &&
  1671. ((FMaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1672. {
  1673. AMaxPacketSize = FMaxPacketSize;
  1674. MaxPacketSizeValid = true;
  1675. }
  1676. if (Result == 0)
  1677. {
  1678. Result = OperationProgress->StaticBlockSize();
  1679. }
  1680. if (Result < MinPacketSize)
  1681. {
  1682. Result = MinPacketSize;
  1683. }
  1684. if (MaxPacketSizeValid)
  1685. {
  1686. Overhead += SFTPPacketOverhead;
  1687. if (AMaxPacketSize < Overhead)
  1688. {
  1689. // do not send another request
  1690. // (generally should happen only if upload buffer if full)
  1691. Result = 0;
  1692. }
  1693. else
  1694. {
  1695. AMaxPacketSize -= Overhead;
  1696. if (Result > AMaxPacketSize)
  1697. {
  1698. Result = AMaxPacketSize;
  1699. }
  1700. }
  1701. }
  1702. return Result;
  1703. }
  1704. //---------------------------------------------------------------------------
  1705. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const AnsiString & Handle,
  1706. TFileOperationProgressType * OperationProgress)
  1707. {
  1708. // handle length + offset + data size
  1709. const unsigned long UploadPacketOverhead =
  1710. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  1711. return TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress);
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  1715. TFileOperationProgressType * OperationProgress)
  1716. {
  1717. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  1718. if (FSupport->Loaded && (FSupport->MaxReadSize > 0) &&
  1719. (Result > FSupport->MaxReadSize))
  1720. {
  1721. Result = FSupport->MaxReadSize;
  1722. }
  1723. return Result;
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  1727. {
  1728. BusyStart();
  1729. try
  1730. {
  1731. if (FTerminal->Log->Logging)
  1732. {
  1733. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1734. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1735. (Packet->Type != FPreviousLoggedPacket) ||
  1736. (FTerminal->Configuration->LogProtocol >= 1))
  1737. {
  1738. if (FNotLoggedPackets)
  1739. {
  1740. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1741. (FNotLoggedPackets)));
  1742. FNotLoggedPackets = 0;
  1743. }
  1744. FTerminal->Log->Add(llInput, FORMAT("Type: %s, Size: %d, Number: %d",
  1745. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1746. if (FTerminal->Configuration->LogProtocol >= 2)
  1747. {
  1748. FTerminal->Log->Add(llInput, Packet->Dump());
  1749. }
  1750. FPreviousLoggedPacket = Packet->Type;
  1751. }
  1752. else
  1753. {
  1754. FNotLoggedPackets++;
  1755. }
  1756. }
  1757. FSecureShell->Send(Packet->SendData, Packet->SendLength);
  1758. }
  1759. __finally
  1760. {
  1761. BusyEnd();
  1762. }
  1763. }
  1764. //---------------------------------------------------------------------------
  1765. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  1766. int AllowStatus)
  1767. {
  1768. unsigned long Code = Packet->GetCardinal();
  1769. static int Messages[] = {
  1770. SFTP_STATUS_OK,
  1771. SFTP_STATUS_EOF,
  1772. SFTP_STATUS_NO_SUCH_FILE,
  1773. SFTP_STATUS_PERMISSION_DENIED,
  1774. SFTP_STATUS_FAILURE,
  1775. SFTP_STATUS_BAD_MESSAGE,
  1776. SFTP_STATUS_NO_CONNECTION,
  1777. SFTP_STATUS_CONNECTION_LOST,
  1778. SFTP_STATUS_OP_UNSUPPORTED,
  1779. SFTP_STATUS_INVALID_HANDLE,
  1780. SFTP_STATUS_NO_SUCH_PATH,
  1781. SFTP_STATUS_FILE_ALREADY_EXISTS,
  1782. SFTP_STATUS_WRITE_PROTECT,
  1783. SFTP_STATUS_NO_MEDIA,
  1784. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  1785. SFTP_STATUS_QUOTA_EXCEEDED,
  1786. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  1787. SFTP_STATUS_LOCK_CONFLICT,
  1788. SFTP_STATUS_DIR_NOT_EMPTY,
  1789. SFTP_STATUS_NOT_A_DIRECTORY,
  1790. SFTP_STATUS_INVALID_FILENAME,
  1791. SFTP_STATUS_LINK_LOOP,
  1792. SFTP_STATUS_CANNOT_DELETE,
  1793. SFTP_STATUS_INVALID_PARAMETER,
  1794. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  1795. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  1796. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  1797. SFTP_STATUS_DELETE_PENDING,
  1798. SFTP_STATUS_FILE_CORRUPT
  1799. };
  1800. int Message;
  1801. if ((AllowStatus & (0x01 << Code)) == 0)
  1802. {
  1803. if (Code >= LENOF(Messages))
  1804. {
  1805. Message = SFTP_STATUS_UNKNOWN;
  1806. }
  1807. else
  1808. {
  1809. Message = Messages[Code];
  1810. }
  1811. AnsiString MessageStr = LoadStr(Message);
  1812. AnsiString ServerMessage;
  1813. AnsiString LanguageTag;
  1814. if (FVersion >= 3)
  1815. {
  1816. // message is in UTF only since SFTP specification 01 (specification 00
  1817. // is also version 3)
  1818. // (in other words, always use UTF unless server is know to be buggy)
  1819. ServerMessage = Packet->GetString(!FUtfNever);
  1820. LanguageTag = Packet->GetString();
  1821. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  1822. {
  1823. AnsiString Principals;
  1824. while (Packet->GetNextData() != NULL)
  1825. {
  1826. if (!Principals.IsEmpty())
  1827. {
  1828. Principals += ", ";
  1829. }
  1830. Principals += Packet->GetString();
  1831. }
  1832. MessageStr = FORMAT(MessageStr, (Principals));
  1833. }
  1834. }
  1835. else
  1836. {
  1837. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  1838. }
  1839. if (FTerminal->Log->Logging)
  1840. {
  1841. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d, Message: %d, Server: %s, Language: %s ",
  1842. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  1843. }
  1844. if (!LanguageTag.IsEmpty())
  1845. {
  1846. LanguageTag = FORMAT(" (%s)", (LanguageTag));
  1847. }
  1848. AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT2, (MessageStr,
  1849. int(Code), LanguageTag, ServerMessage, int(Packet->RequestType)));
  1850. FTerminal->TerminalError(NULL, Error);
  1851. return 0;
  1852. }
  1853. else
  1854. {
  1855. if (!FNotLoggedPackets || Code)
  1856. {
  1857. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d", ((int)Code)));
  1858. }
  1859. return Code;
  1860. }
  1861. }
  1862. //---------------------------------------------------------------------------
  1863. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  1864. {
  1865. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  1866. {
  1867. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  1868. }
  1869. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  1870. if (Packet)
  1871. {
  1872. assert(Packet->ReservedBy == this);
  1873. Packet->ReservedBy = NULL;
  1874. }
  1875. FPacketReservations->Delete(Reservation);
  1876. }
  1877. //---------------------------------------------------------------------------
  1878. inline int __fastcall TSFTPFileSystem::PacketLength(char * LenBuf, int ExpectedType)
  1879. {
  1880. int Length = GET_32BIT(LenBuf);
  1881. if (Length > SFTP_MAX_PACKET_LEN)
  1882. {
  1883. AnsiString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  1884. int(Length), SFTP_MAX_PACKET_LEN));
  1885. if (ExpectedType == SSH_FXP_VERSION)
  1886. {
  1887. AnsiString LenString(LenBuf, 4);
  1888. if (!IsDisplayableStr(LenString))
  1889. {
  1890. LenString = "0x" + StrToHex(LenString);
  1891. }
  1892. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  1893. (Message, LenString));
  1894. }
  1895. FTerminal->FatalError(NULL, Message);
  1896. }
  1897. return Length;
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. bool __fastcall TSFTPFileSystem::PeekPacket()
  1901. {
  1902. bool Result;
  1903. char * Buf;
  1904. Result = FSecureShell->Peek(Buf, 4);
  1905. if (Result)
  1906. {
  1907. int Length = PacketLength(Buf, -1);
  1908. Result = FSecureShell->Peek(Buf, 4 + Length);
  1909. }
  1910. return Result;
  1911. }
  1912. //---------------------------------------------------------------------------
  1913. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  1914. int ExpectedType, int AllowStatus)
  1915. {
  1916. TSFTPBusy Busy(this);
  1917. int Result = SSH_FX_OK;
  1918. int Reservation = FPacketReservations->IndexOf(Packet);
  1919. if (Reservation < 0 || Packet->Capacity == 0)
  1920. {
  1921. bool IsReserved;
  1922. do
  1923. {
  1924. IsReserved = false;
  1925. assert(Packet);
  1926. char LenBuf[4];
  1927. FSecureShell->Receive(LenBuf, sizeof(LenBuf));
  1928. int Length = PacketLength(LenBuf, ExpectedType);
  1929. Packet->Capacity = Length;
  1930. FSecureShell->Receive(Packet->Data, Length);
  1931. Packet->DataUpdated(Length);
  1932. if (FTerminal->Log->Logging)
  1933. {
  1934. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1935. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1936. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  1937. (FTerminal->Configuration->LogProtocol >= 1))
  1938. {
  1939. if (FNotLoggedPackets)
  1940. {
  1941. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1942. (FNotLoggedPackets)));
  1943. FNotLoggedPackets = 0;
  1944. }
  1945. FTerminal->Log->Add(llOutput, FORMAT("Type: %s, Size: %d, Number: %d",
  1946. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1947. if (FTerminal->Configuration->LogProtocol >= 2)
  1948. {
  1949. FTerminal->Log->Add(llOutput, Packet->Dump());
  1950. }
  1951. }
  1952. else
  1953. {
  1954. FNotLoggedPackets++;
  1955. }
  1956. }
  1957. if (Reservation < 0 ||
  1958. Packet->MessageNumber != (unsigned long)FPacketNumbers.GetElement(Reservation))
  1959. {
  1960. TSFTPPacket * ReservedPacket;
  1961. unsigned long MessageNumber;
  1962. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  1963. {
  1964. MessageNumber = FPacketNumbers.GetElement(Index);
  1965. if (MessageNumber == Packet->MessageNumber)
  1966. {
  1967. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  1968. IsReserved = true;
  1969. if (ReservedPacket)
  1970. {
  1971. FTerminal->LogEvent("Storing reserved response");
  1972. *ReservedPacket = *Packet;
  1973. }
  1974. else
  1975. {
  1976. FTerminal->LogEvent("Discarding reserved response");
  1977. RemoveReservation(Index);
  1978. if ((Reservation >= 0) && (Reservation > Index))
  1979. {
  1980. Reservation--;
  1981. assert(Reservation == FPacketReservations->IndexOf(Packet));
  1982. }
  1983. }
  1984. break;
  1985. }
  1986. }
  1987. }
  1988. }
  1989. while (IsReserved);
  1990. }
  1991. // before we removed the reservation after check for packet type,
  1992. // but if it raises exception, removal is unnecessarily
  1993. // postponed until the packet is removed
  1994. // (and it have not worked anyway until recent fix to UnreserveResponse)
  1995. if (Reservation >= 0)
  1996. {
  1997. assert(Packet->MessageNumber == (unsigned long)FPacketNumbers.GetElement(Reservation));
  1998. RemoveReservation(Reservation);
  1999. }
  2000. if (ExpectedType >= 0)
  2001. {
  2002. if (Packet->Type == SSH_FXP_STATUS)
  2003. {
  2004. if (AllowStatus < 0)
  2005. {
  2006. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  2007. }
  2008. Result = GotStatusPacket(Packet, AllowStatus);
  2009. }
  2010. else if (ExpectedType != Packet->Type)
  2011. {
  2012. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  2013. }
  2014. }
  2015. return Result;
  2016. }
  2017. //---------------------------------------------------------------------------
  2018. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  2019. TSFTPPacket * Response)
  2020. {
  2021. if (Response != NULL)
  2022. {
  2023. assert(FPacketReservations->IndexOf(Response) < 0);
  2024. // mark response as not received yet
  2025. Response->Capacity = 0;
  2026. Response->ReservedBy = this;
  2027. }
  2028. FPacketReservations->Add(Response);
  2029. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  2030. {
  2031. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  2032. }
  2033. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  2034. }
  2035. //---------------------------------------------------------------------------
  2036. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  2037. {
  2038. int Reservation = FPacketReservations->IndexOf(Response);
  2039. if (Response->Capacity != 0)
  2040. {
  2041. // added check for already received packet
  2042. // (it happens when the reserved response is received out of order,
  2043. // unexpectedly soon, and then receivepacket() on the packet
  2044. // is not actually called, due to exception)
  2045. RemoveReservation(Reservation);
  2046. }
  2047. else
  2048. {
  2049. if (Reservation >= 0)
  2050. {
  2051. // we probably do not remove the item at all, because
  2052. // we must remember that the respose was expected, so we skip it
  2053. // in receivepacket()
  2054. FPacketReservations->Items[Reservation] = NULL;
  2055. }
  2056. }
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. int __fastcall TSFTPFileSystem::ReceiveResponse(
  2060. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2061. int AllowStatus)
  2062. {
  2063. int Result;
  2064. unsigned int MessageNumber = Packet->MessageNumber;
  2065. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  2066. try
  2067. {
  2068. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus);
  2069. if (MessageNumber != AResponse->MessageNumber)
  2070. {
  2071. FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER,
  2072. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  2073. }
  2074. }
  2075. __finally
  2076. {
  2077. if (!Response) delete AResponse;
  2078. }
  2079. return Result;
  2080. }
  2081. //---------------------------------------------------------------------------
  2082. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2083. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2084. int AllowStatus)
  2085. {
  2086. int Result;
  2087. TSFTPBusy Busy(this);
  2088. SendPacket(Packet);
  2089. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2090. return Result;
  2091. }
  2092. //---------------------------------------------------------------------------
  2093. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
  2094. {
  2095. try
  2096. {
  2097. FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
  2098. (Path)));
  2099. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2100. Packet.AddPathString(Path, FUtfStrings);
  2101. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2102. if (Packet.GetCardinal() != 1)
  2103. {
  2104. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2105. }
  2106. AnsiString RealDir = Packet.GetPathString(FUtfStrings);
  2107. // ignore rest of SSH_FXP_NAME packet
  2108. FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
  2109. return RealDir;
  2110. }
  2111. catch(Exception & E)
  2112. {
  2113. if (FTerminal->Active)
  2114. {
  2115. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2116. }
  2117. else
  2118. {
  2119. throw;
  2120. }
  2121. }
  2122. }
  2123. //---------------------------------------------------------------------------
  2124. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
  2125. const AnsiString BaseDir)
  2126. {
  2127. AnsiString APath;
  2128. if (TTerminal::IsAbsolutePath(Path))
  2129. {
  2130. APath = Path;
  2131. }
  2132. else
  2133. {
  2134. if (!Path.IsEmpty())
  2135. {
  2136. // this condition/block was outside (before) current block
  2137. // but it dod not work when Path was empty
  2138. if (!BaseDir.IsEmpty())
  2139. {
  2140. APath = UnixIncludeTrailingBackslash(BaseDir);
  2141. }
  2142. APath = APath + Path;
  2143. }
  2144. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
  2145. }
  2146. return RealPath(APath);
  2147. }
  2148. //---------------------------------------------------------------------------
  2149. AnsiString __fastcall TSFTPFileSystem::LocalCanonify(const AnsiString & Path)
  2150. {
  2151. // TODO: improve (handle .. etc.)
  2152. if (TTerminal::IsAbsolutePath(Path) ||
  2153. (!FCurrentDirectory.IsEmpty() && UnixComparePaths(FCurrentDirectory, Path)))
  2154. {
  2155. return Path;
  2156. }
  2157. else
  2158. {
  2159. return ::AbsolutePath(FCurrentDirectory, Path);
  2160. }
  2161. }
  2162. //---------------------------------------------------------------------------
  2163. AnsiString __fastcall TSFTPFileSystem::Canonify(AnsiString Path)
  2164. {
  2165. // inspired by canonify() from PSFTP.C
  2166. AnsiString Result;
  2167. FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
  2168. Path = LocalCanonify(Path);
  2169. bool TryParent = false;
  2170. try
  2171. {
  2172. Result = RealPath(Path);
  2173. }
  2174. catch(...)
  2175. {
  2176. if (FTerminal->Active)
  2177. {
  2178. TryParent = true;
  2179. }
  2180. else
  2181. {
  2182. throw;
  2183. }
  2184. }
  2185. if (TryParent)
  2186. {
  2187. AnsiString APath = UnixExcludeTrailingBackslash(Path);
  2188. AnsiString Name = UnixExtractFileName(APath);
  2189. if (Name == "." || Name == "..")
  2190. {
  2191. Result = Path;
  2192. }
  2193. else
  2194. {
  2195. AnsiString FPath = UnixExtractFilePath(APath);
  2196. try
  2197. {
  2198. Result = RealPath(FPath);
  2199. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2200. }
  2201. catch(...)
  2202. {
  2203. if (FTerminal->Active)
  2204. {
  2205. Result = Path;
  2206. }
  2207. else
  2208. {
  2209. throw;
  2210. }
  2211. }
  2212. }
  2213. }
  2214. FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
  2215. return Result;
  2216. }
  2217. //---------------------------------------------------------------------------
  2218. AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path)
  2219. {
  2220. return RealPath(Path, CurrentDirectory);
  2221. }
  2222. //---------------------------------------------------------------------------
  2223. AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2224. {
  2225. if (FHomeDirectory.IsEmpty())
  2226. {
  2227. FHomeDirectory = RealPath(".");
  2228. }
  2229. return FHomeDirectory;
  2230. }
  2231. //---------------------------------------------------------------------------
  2232. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2233. bool Complete)
  2234. {
  2235. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode,
  2236. FUtfStrings, FSignedTS, Complete);
  2237. }
  2238. //---------------------------------------------------------------------------
  2239. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2240. TRemoteFile * ALinkedByFile, const AnsiString FileName,
  2241. TRemoteFileList * TempFileList, bool Complete)
  2242. {
  2243. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2244. try
  2245. {
  2246. File->Terminal = FTerminal;
  2247. if (!FileName.IsEmpty())
  2248. {
  2249. File->FileName = FileName;
  2250. }
  2251. // to get full path for symlink completion
  2252. File->Directory = TempFileList;
  2253. LoadFile(File, Packet, Complete);
  2254. File->Directory = NULL;
  2255. }
  2256. catch(...)
  2257. {
  2258. delete File;
  2259. throw;
  2260. }
  2261. return File;
  2262. }
  2263. //---------------------------------------------------------------------------
  2264. AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2265. {
  2266. return FCurrentDirectory;
  2267. }
  2268. //---------------------------------------------------------------------------
  2269. void __fastcall TSFTPFileSystem::DoStartup()
  2270. {
  2271. FFileSystemInfoValid = false;
  2272. TSFTPPacket Packet(SSH_FXP_INIT);
  2273. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2274. if (MaxVersion > SFTPMaxVersion)
  2275. {
  2276. MaxVersion = SFTPMaxVersion;
  2277. }
  2278. Packet.AddCardinal(MaxVersion);
  2279. try
  2280. {
  2281. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2282. }
  2283. catch(Exception &E)
  2284. {
  2285. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
  2286. }
  2287. FVersion = Packet.GetCardinal();
  2288. FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
  2289. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2290. {
  2291. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2292. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2293. }
  2294. FExtensions->Clear();
  2295. FEOL = "\r\n";
  2296. FSupport->Loaded = false;
  2297. SAFE_DESTROY(FFixedPaths);
  2298. if (FVersion >= 3)
  2299. {
  2300. AnsiString ExtensionName;
  2301. AnsiString ExtensionData;
  2302. AnsiString ExtensionDisplayData;
  2303. while (Packet.GetNextData() != NULL)
  2304. {
  2305. ExtensionName = Packet.GetString();
  2306. ExtensionData = Packet.GetString();
  2307. if (IsDisplayableStr(ExtensionData))
  2308. {
  2309. ExtensionDisplayData = ExtensionData;
  2310. }
  2311. else
  2312. {
  2313. ExtensionDisplayData = "0x" + StrToHex(ExtensionData);
  2314. }
  2315. if (ExtensionName == SFTP_EXT_NEWLINE)
  2316. {
  2317. FEOL = ExtensionData;
  2318. FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
  2319. (ExtensionDisplayData)));
  2320. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2321. {
  2322. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2323. }
  2324. }
  2325. // do not allow "supported" to override "supported2" if both are received
  2326. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2327. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2328. {
  2329. FSupport->Reset();
  2330. TSFTPPacket SupportedStruct(ExtensionData);
  2331. FSupport->Loaded = true;
  2332. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2333. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2334. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2335. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2336. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2337. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2338. {
  2339. while (SupportedStruct.GetNextData() != NULL)
  2340. {
  2341. FSupport->Extensions->Add(SupportedStruct.GetString());
  2342. }
  2343. }
  2344. else
  2345. {
  2346. FSupport->OpenBlockMasks = SupportedStruct.GetSmallCardinal();
  2347. FSupport->BlockMasks = SupportedStruct.GetSmallCardinal();
  2348. unsigned int ExtensionCount;
  2349. ExtensionCount = SupportedStruct.GetCardinal();
  2350. for (unsigned int i = 0; i < ExtensionCount; i++)
  2351. {
  2352. FSupport->AttribExtensions->Add(SupportedStruct.GetString());
  2353. }
  2354. ExtensionCount = SupportedStruct.GetCardinal();
  2355. for (unsigned int i = 0; i < ExtensionCount; i++)
  2356. {
  2357. FSupport->Extensions->Add(SupportedStruct.GetString());
  2358. }
  2359. }
  2360. if (FTerminal->Log->Logging)
  2361. {
  2362. FTerminal->LogEvent(FORMAT(
  2363. "Server support information:\n"
  2364. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2365. " Access mask: %x, Open block masks: %x, Block masks: %x, Max read size: %d\n",
  2366. (int(FSupport->AttributeMask),
  2367. int(FSupport->AttributeBits),
  2368. int(FSupport->OpenFlags),
  2369. int(FSupport->AccessMask),
  2370. int(FSupport->OpenBlockMasks),
  2371. int(FSupport->BlockMasks),
  2372. int(FSupport->MaxReadSize))));
  2373. FTerminal->LogEvent(FORMAT( " Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2374. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2375. {
  2376. FTerminal->LogEvent(
  2377. FORMAT(" %s", (FSupport->AttribExtensions->Strings[Index])));
  2378. }
  2379. FTerminal->LogEvent(FORMAT( " Extensions (%d)\n", (FSupport->Extensions->Count)));
  2380. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2381. {
  2382. FTerminal->LogEvent(
  2383. FORMAT(" %s", (FSupport->Extensions->Strings[Index])));
  2384. }
  2385. }
  2386. }
  2387. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2388. {
  2389. TSFTPPacket VendorIdStruct(ExtensionData);
  2390. AnsiString VendorName(VendorIdStruct.GetString());
  2391. AnsiString ProductName(VendorIdStruct.GetString());
  2392. AnsiString ProductVersion(VendorIdStruct.GetString());
  2393. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2394. FTerminal->LogEvent(FORMAT("Server software: %s %s (%d) by %s",
  2395. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2396. }
  2397. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2398. {
  2399. FTerminal->LogEvent("File system roots:\n");
  2400. assert(FFixedPaths == NULL);
  2401. FFixedPaths = new TStringList();
  2402. try
  2403. {
  2404. TSFTPPacket RootsPacket(ExtensionData);
  2405. while (RootsPacket.GetNextData() != NULL)
  2406. {
  2407. unsigned long Dummy = RootsPacket.GetCardinal();
  2408. if (Dummy != 1)
  2409. {
  2410. break;
  2411. }
  2412. else
  2413. {
  2414. char Drive = RootsPacket.GetByte();
  2415. char MaybeType = RootsPacket.GetByte();
  2416. FTerminal->LogEvent(FORMAT(" %s: (type %d)", (Drive, (int)MaybeType)));
  2417. FFixedPaths->Add(FORMAT("%s:", (Drive)));
  2418. }
  2419. }
  2420. }
  2421. catch(Exception & E)
  2422. {
  2423. FFixedPaths->Clear();
  2424. FTerminal->LogEvent(FORMAT("Failed to decode %s extension",
  2425. (SFTP_EXT_FSROOTS)));
  2426. FTerminal->HandleException(&E);
  2427. }
  2428. }
  2429. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2430. {
  2431. try
  2432. {
  2433. // first try legacy decoding according to incorrect encoding
  2434. // (structure-like) as of VShell.
  2435. TSFTPPacket VersionsPacket(ExtensionData);
  2436. AnsiString Versions = VersionsPacket.GetString();
  2437. if (VersionsPacket.GetNextData() != NULL)
  2438. {
  2439. Abort();
  2440. }
  2441. FTerminal->LogEvent(FORMAT("SFTP versions supported by the server (VShell format): %s",
  2442. (Versions)));
  2443. }
  2444. catch(...)
  2445. {
  2446. // if that fails, fallback to proper decoding
  2447. FTerminal->LogEvent(FORMAT("SFTP versions supported by the server: %s",
  2448. (ExtensionData)));
  2449. }
  2450. }
  2451. else
  2452. {
  2453. FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
  2454. (ExtensionName, ExtensionDisplayData)));
  2455. }
  2456. FExtensions->Values[ExtensionName] = ExtensionData;
  2457. }
  2458. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2459. {
  2460. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2461. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2462. Packet.AddString(FTerminal->Configuration->CompanyName);
  2463. Packet.AddString(FTerminal->Configuration->ProductName);
  2464. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2465. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2466. SendPacket(&Packet);
  2467. // we are not interested in the response, do not wait for it
  2468. ReserveResponse(&Packet, NULL);
  2469. }
  2470. }
  2471. if (FVersion < 4)
  2472. {
  2473. // currently enable the bug for all servers (really known on OpenSSH)
  2474. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2475. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2476. if (FSignedTS)
  2477. {
  2478. FTerminal->LogEvent("We believe the server has signed timestamps bug");
  2479. }
  2480. }
  2481. else
  2482. {
  2483. FSignedTS = false;
  2484. }
  2485. // use UTF when forced or ...
  2486. // when "auto" and version is at least 4 and the server is not know not to use UTF
  2487. FUtfNever = (GetSessionInfo().SshImplementation.Pos("Foxit-WAC-Server") == 1) ||
  2488. (FTerminal->SessionData->SFTPBug[sbUtf] == asOn);
  2489. FUtfStrings =
  2490. (FTerminal->SessionData->SFTPBug[sbUtf] == asOff) ||
  2491. ((FTerminal->SessionData->SFTPBug[sbUtf] == asAuto) &&
  2492. (FVersion >= 4) && !FUtfNever);
  2493. if (FUtfStrings)
  2494. {
  2495. FTerminal->LogEvent("We will use UTF-8 strings when appropriate");
  2496. }
  2497. else if (FUtfNever)
  2498. {
  2499. FTerminal->LogEvent("We will never use UTF-8 strings");
  2500. }
  2501. else
  2502. {
  2503. FTerminal->LogEvent("We will use UTF-8 strings for status messages only");
  2504. }
  2505. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2506. if (FMaxPacketSize == 0)
  2507. {
  2508. if ((GetSessionInfo().SshImplementation.Pos("OpenSSH") == 1) &&
  2509. (FVersion == 3) && !FSupport->Loaded)
  2510. {
  2511. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2512. FTerminal->LogEvent(FORMAT("Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  2513. (int(FMaxPacketSize))));
  2514. }
  2515. }
  2516. }
  2517. //---------------------------------------------------------------------------
  2518. char * __fastcall TSFTPFileSystem::GetEOL() const
  2519. {
  2520. if (FVersion >= 4)
  2521. {
  2522. assert(!FEOL.IsEmpty());
  2523. return FEOL.c_str();
  2524. }
  2525. else
  2526. {
  2527. return EOLToStr(FTerminal->SessionData->EOLType);
  2528. }
  2529. }
  2530. //---------------------------------------------------------------------------
  2531. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2532. {
  2533. assert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2534. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2535. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2536. TSFTPPacket * Packet;
  2537. TUsersGroupsList * List;
  2538. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2539. TUsersGroupsList * Lists[] = { FTerminal->FUsers, FTerminal->FGroups };
  2540. char ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2541. for (int Index = 0; Index < LENOF(Packets); Index++)
  2542. {
  2543. Packet = Packets[Index];
  2544. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  2545. Packet->AddByte(ListTypes[Index]);
  2546. SendPacket(Packet);
  2547. ReserveResponse(Packet, Packet);
  2548. }
  2549. for (int Index = 0; Index < LENOF(Packets); Index++)
  2550. {
  2551. Packet = Packets[Index];
  2552. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  2553. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  2554. (Packet->GetString() != SFTP_EXT_OWNER_GROUP_REPLY))
  2555. {
  2556. FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  2557. }
  2558. else
  2559. {
  2560. List = Lists[Index];
  2561. unsigned long Count = Packet->GetCardinal();
  2562. List->BeginUpdate();
  2563. try
  2564. {
  2565. List->Clear();
  2566. for (unsigned long Item = 0; Item < Count; Item++)
  2567. {
  2568. List->Add(Packet->GetString(!FUtfNever));
  2569. }
  2570. }
  2571. __finally
  2572. {
  2573. List->EndUpdate();
  2574. }
  2575. }
  2576. }
  2577. }
  2578. //---------------------------------------------------------------------------
  2579. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  2580. {
  2581. if (!FDirectoryToChangeTo.IsEmpty())
  2582. {
  2583. FCurrentDirectory = FDirectoryToChangeTo;
  2584. FDirectoryToChangeTo = "";
  2585. }
  2586. else if (FCurrentDirectory.IsEmpty())
  2587. {
  2588. // this happens only after startup when default remote directory is not specified
  2589. FCurrentDirectory = GetHomeDirectory();
  2590. }
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. void __fastcall TSFTPFileSystem::HomeDirectory()
  2594. {
  2595. ChangeDirectory(GetHomeDirectory());
  2596. }
  2597. //---------------------------------------------------------------------------
  2598. void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
  2599. {
  2600. FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
  2601. TRemoteFile * File;
  2602. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  2603. if (File == NULL)
  2604. {
  2605. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  2606. // Fallback to legacy solution, which in turn does not allow entering
  2607. // traverse-only (chmod 110) directories.
  2608. // This is workaround for http://www.ftpshell.com/
  2609. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2610. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  2611. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2612. AnsiString Handle = Packet.GetString();
  2613. Packet.ChangeType(SSH_FXP_CLOSE);
  2614. Packet.AddString(Handle);
  2615. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  2616. }
  2617. else
  2618. {
  2619. delete File;
  2620. }
  2621. }
  2622. //---------------------------------------------------------------------------
  2623. void __fastcall TSFTPFileSystem::AnnounceFileListOperation()
  2624. {
  2625. }
  2626. //---------------------------------------------------------------------------
  2627. void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
  2628. {
  2629. AnsiString Path, Current;
  2630. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  2631. Path = RealPath(Directory, Current);
  2632. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  2633. // for invalid paths on some systems, like CygWin)
  2634. TryOpenDirectory(Path);
  2635. // if open dir did not fail, directory exists -> success.
  2636. FDirectoryToChangeTo = Path;
  2637. }
  2638. //---------------------------------------------------------------------------
  2639. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  2640. {
  2641. FDirectoryToChangeTo = Directory;
  2642. }
  2643. //---------------------------------------------------------------------------
  2644. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  2645. {
  2646. assert(FileList && !FileList->Directory.IsEmpty());
  2647. AnsiString Directory;
  2648. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  2649. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
  2650. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  2651. // old data (e.g. parent directory) when reading fails
  2652. FileList->Clear();
  2653. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2654. AnsiString Handle;
  2655. try
  2656. {
  2657. Packet.AddPathString(Directory, FUtfStrings);
  2658. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2659. Handle = Packet.GetString();
  2660. }
  2661. catch(...)
  2662. {
  2663. if (FTerminal->Active)
  2664. {
  2665. FileList->AddFile(new TRemoteParentDirectory());
  2666. }
  2667. throw;
  2668. }
  2669. TSFTPPacket Response;
  2670. try
  2671. {
  2672. bool isEOF = false;
  2673. int Total = 0;
  2674. TRemoteFile * File;
  2675. Packet.ChangeType(SSH_FXP_READDIR);
  2676. Packet.AddString(Handle);
  2677. SendPacket(&Packet);
  2678. do
  2679. {
  2680. ReceiveResponse(&Packet, &Response);
  2681. if (Response.Type == SSH_FXP_NAME)
  2682. {
  2683. TSFTPPacket ListingPacket = Response;
  2684. Packet.ChangeType(SSH_FXP_READDIR);
  2685. Packet.AddString(Handle);
  2686. SendPacket(&Packet);
  2687. ReserveResponse(&Packet, &Response);
  2688. unsigned int Count = ListingPacket.GetCardinal();
  2689. for (unsigned long Index = 0; !isEOF && (Index < Count); Index++)
  2690. {
  2691. File = LoadFile(&ListingPacket, NULL, "", FileList);
  2692. // security fix
  2693. // (LastDelimiter works for MBCS)
  2694. if (((File->FileName.Length() > 2) && IsDots(File->FileName)) ||
  2695. (File->FileName.LastDelimiter("/\\") > 0))
  2696. {
  2697. FTerminal->LogEvent(FORMAT("Ignored suspicious file '%s'", (File->FileName)));
  2698. delete File;
  2699. }
  2700. else
  2701. {
  2702. FileList->AddFile(File);
  2703. Total++;
  2704. }
  2705. if (Total % 10 == 0)
  2706. {
  2707. FTerminal->DoReadDirectoryProgress(Total, isEOF);
  2708. if (isEOF)
  2709. {
  2710. FTerminal->DoReadDirectoryProgress(-2, isEOF);
  2711. }
  2712. }
  2713. }
  2714. if (Count == 0)
  2715. {
  2716. FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
  2717. isEOF = true;
  2718. }
  2719. }
  2720. else if (Response.Type == SSH_FXP_STATUS)
  2721. {
  2722. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  2723. }
  2724. else
  2725. {
  2726. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  2727. }
  2728. }
  2729. while (!isEOF);
  2730. if (Total == 0)
  2731. {
  2732. // Empty file list -> probably "permision denied", we
  2733. // at least get link to parent directory ("..")
  2734. try
  2735. {
  2736. FTerminal->ExceptionOnFail = true;
  2737. try
  2738. {
  2739. File = NULL;
  2740. FTerminal->ReadFile(
  2741. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  2742. }
  2743. __finally
  2744. {
  2745. FTerminal->ExceptionOnFail = false;
  2746. }
  2747. }
  2748. catch(Exception &E)
  2749. {
  2750. if (E.InheritsFrom(__classid(EFatal))) throw;
  2751. else File = NULL;
  2752. }
  2753. // on some systems even getting ".." fails, we create dummy ".." instead
  2754. bool Failure = (File == NULL);
  2755. if (Failure)
  2756. {
  2757. File = new TRemoteParentDirectory();
  2758. }
  2759. assert(File && File->IsParentDirectory);
  2760. FileList->AddFile(File);
  2761. if (Failure)
  2762. {
  2763. throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
  2764. }
  2765. }
  2766. }
  2767. __finally
  2768. {
  2769. if (FTerminal->Active)
  2770. {
  2771. Packet.ChangeType(SSH_FXP_CLOSE);
  2772. Packet.AddString(Handle);
  2773. SendPacket(&Packet);
  2774. // we are not interested in the response, do not wait for it
  2775. ReserveResponse(&Packet, NULL);
  2776. }
  2777. }
  2778. }
  2779. //---------------------------------------------------------------------------
  2780. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2781. TRemoteFile *& File)
  2782. {
  2783. assert(SymlinkFile && SymlinkFile->IsSymLink);
  2784. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2785. // need to use full filename when resolving links within subdirectory
  2786. // (i.e. for download)
  2787. AnsiString FileName = LocalCanonify(
  2788. SymlinkFile->Directory != NULL ? SymlinkFile->FullFileName : SymlinkFile->FileName);
  2789. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  2790. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  2791. SendPacket(&ReadLinkPacket);
  2792. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  2793. // send second request before reading response to first one
  2794. // (performance benefit)
  2795. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  2796. AttrsPacket.AddPathString(FileName, FUtfStrings);
  2797. if (FVersion >= 4)
  2798. {
  2799. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  2800. }
  2801. SendPacket(&AttrsPacket);
  2802. ReserveResponse(&AttrsPacket, &AttrsPacket);
  2803. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  2804. if (ReadLinkPacket.GetCardinal() != 1)
  2805. {
  2806. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2807. }
  2808. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  2809. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  2810. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  2811. File = LoadFile(&AttrsPacket, SymlinkFile,
  2812. UnixExtractFileName(SymlinkFile->LinkTo));
  2813. }
  2814. //---------------------------------------------------------------------------
  2815. void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
  2816. TRemoteFile *& File)
  2817. {
  2818. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  2819. }
  2820. //---------------------------------------------------------------------------
  2821. bool __fastcall TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
  2822. TRemoteFile ** File)
  2823. {
  2824. bool Result;
  2825. try
  2826. {
  2827. TRemoteFile * AFile;
  2828. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  2829. Result = (AFile != NULL);
  2830. if (Result)
  2831. {
  2832. if (File)
  2833. {
  2834. *File = AFile;
  2835. }
  2836. else
  2837. {
  2838. delete AFile;
  2839. }
  2840. }
  2841. }
  2842. catch(...)
  2843. {
  2844. if (!FTerminal->Active)
  2845. {
  2846. throw;
  2847. }
  2848. Result = false;
  2849. }
  2850. return Result;
  2851. }
  2852. //---------------------------------------------------------------------------
  2853. void __fastcall TSFTPFileSystem::SendCustomReadFile(TSFTPPacket * Packet,
  2854. TSFTPPacket * Response, const AnsiString FileName, unsigned long Flags)
  2855. {
  2856. if ((Packet->Type == SSH_FXP_STAT) || (Packet->Type == SSH_FXP_LSTAT))
  2857. {
  2858. Packet->AddPathString(LocalCanonify(FileName), FUtfStrings);
  2859. }
  2860. else
  2861. {
  2862. assert(Packet->Type == SSH_FXP_FSTAT);
  2863. // actualy handle, not filename
  2864. Packet->AddString(FileName);
  2865. }
  2866. if (FVersion >= 4)
  2867. {
  2868. Packet->AddCardinal(Flags);
  2869. }
  2870. SendPacket(Packet);
  2871. ReserveResponse(Packet, Response);
  2872. }
  2873. //---------------------------------------------------------------------------
  2874. void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
  2875. TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
  2876. int AllowStatus)
  2877. {
  2878. unsigned long Flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  2879. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  2880. SSH_FILEXFER_ATTR_OWNERGROUP;
  2881. TSFTPPacket Packet(Type);
  2882. SendCustomReadFile(&Packet, &Packet, FileName, Flags);
  2883. ReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS, AllowStatus);
  2884. if (Packet.Type == SSH_FXP_ATTRS)
  2885. {
  2886. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  2887. }
  2888. else
  2889. {
  2890. assert(AllowStatus > 0);
  2891. File = NULL;
  2892. }
  2893. }
  2894. //---------------------------------------------------------------------------
  2895. void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
  2896. const TRemoteFile * File, bool Recursive)
  2897. {
  2898. char Type;
  2899. AnsiString RealFileName = LocalCanonify(FileName);
  2900. if (File && File->IsDirectory && !File->IsSymLink)
  2901. {
  2902. if (Recursive)
  2903. {
  2904. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Recursive);
  2905. }
  2906. Type = SSH_FXP_RMDIR;
  2907. }
  2908. else
  2909. {
  2910. Type = SSH_FXP_REMOVE;
  2911. }
  2912. TSFTPPacket Packet(Type);
  2913. Packet.AddPathString(RealFileName, FUtfStrings);
  2914. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2915. }
  2916. //---------------------------------------------------------------------------
  2917. void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
  2918. const AnsiString NewName)
  2919. {
  2920. TSFTPPacket Packet(SSH_FXP_RENAME);
  2921. AnsiString RealName = LocalCanonify(FileName);
  2922. Packet.AddPathString(RealName, FUtfStrings);
  2923. AnsiString TargetName;
  2924. if (UnixExtractFilePath(NewName).IsEmpty())
  2925. {
  2926. // rename case (TTerminal::RenameFile)
  2927. TargetName = UnixExtractFilePath(RealName) + NewName;
  2928. }
  2929. else
  2930. {
  2931. TargetName = LocalCanonify(NewName);
  2932. }
  2933. Packet.AddPathString(TargetName, FUtfStrings);
  2934. if (FVersion >= 5)
  2935. {
  2936. Packet.AddCardinal(0);
  2937. }
  2938. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2939. }
  2940. //---------------------------------------------------------------------------
  2941. void __fastcall TSFTPFileSystem::CopyFile(const AnsiString /*FileName*/,
  2942. const AnsiString /*NewName*/)
  2943. {
  2944. assert(false);
  2945. }
  2946. //---------------------------------------------------------------------------
  2947. void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName,
  2948. const TRemoteProperties * Properties)
  2949. {
  2950. TSFTPPacket Packet(SSH_FXP_MKDIR);
  2951. AnsiString CanonifiedName = Canonify(DirName);
  2952. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2953. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings);
  2954. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2955. // explicitly set permissions after directory creation,
  2956. // permissions specified in SSH_FXP_MKDIR are ignored at least by OpenSSH
  2957. try
  2958. {
  2959. Packet.ChangeType(SSH_FXP_SETSTAT);
  2960. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2961. Packet.AddProperties(Properties, 0, true, FVersion, FUtfStrings);
  2962. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2963. }
  2964. catch(Exception & E)
  2965. {
  2966. if (FTerminal->Active)
  2967. {
  2968. throw ECommand(&E, FMTLOAD(CHANGE_PROPERTIES_ERROR, (DirName)));
  2969. }
  2970. else
  2971. {
  2972. throw;
  2973. }
  2974. }
  2975. }
  2976. //---------------------------------------------------------------------------
  2977. void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
  2978. const AnsiString PointTo, bool Symbolic)
  2979. {
  2980. USEDPARAM(Symbolic);
  2981. assert(Symbolic); // only symlinks are supported by SFTP
  2982. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2983. TSFTPPacket Packet(SSH_FXP_SYMLINK);
  2984. bool Buggy = (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn) ||
  2985. ((FTerminal->SessionData->SFTPBug[sbSymlink] == asAuto) &&
  2986. (GetSessionInfo().SshImplementation.Pos("OpenSSH") == 1));
  2987. if (!Buggy)
  2988. {
  2989. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  2990. Packet.AddPathString(PointTo, FUtfStrings);
  2991. }
  2992. else
  2993. {
  2994. FTerminal->LogEvent("We believe the server has SFTP symlink bug");
  2995. Packet.AddPathString(PointTo, FUtfStrings);
  2996. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  2997. }
  2998. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2999. }
  3000. //---------------------------------------------------------------------------
  3001. void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
  3002. const TRemoteFile * /*File*/, const TRemoteProperties * Properties)
  3003. {
  3004. assert(Properties);
  3005. TRemoteFile * File;
  3006. AnsiString RealFileName = LocalCanonify(FileName);
  3007. ReadFile(RealFileName, File);
  3008. try
  3009. {
  3010. assert(File);
  3011. if (File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  3012. {
  3013. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  3014. (void*)Properties);
  3015. }
  3016. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  3017. Packet.AddPathString(RealFileName, FUtfStrings);
  3018. Packet.AddProperties(Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings);
  3019. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3020. }
  3021. __finally
  3022. {
  3023. delete File;
  3024. }
  3025. }
  3026. //---------------------------------------------------------------------------
  3027. bool __fastcall TSFTPFileSystem::LoadFilesProperties(TStrings * FileList)
  3028. {
  3029. bool Result = false;
  3030. // without knowledge of server's capabilities, this all make no sense
  3031. if (FSupport->Loaded)
  3032. {
  3033. TFileOperationProgressType Progress(FTerminal->FOnProgress, FTerminal->FOnFinished);
  3034. Progress.Start(foGetProperties, osRemote, FileList->Count);
  3035. FTerminal->FOperationProgress = &Progress;
  3036. try
  3037. {
  3038. static int LoadFilesPropertiesQueueLen = 5;
  3039. // at end of this block queue is disposed
  3040. TSFTPLoadFilesPropertiesQueue Queue(this);
  3041. if (Queue.Init(LoadFilesPropertiesQueueLen, FileList))
  3042. {
  3043. TRemoteFile * File;
  3044. TSFTPPacket Packet;
  3045. bool Next;
  3046. do
  3047. {
  3048. Next = Queue.ReceivePacket(&Packet, File);
  3049. assert((Packet.Type == SSH_FXP_ATTRS) || (Packet.Type == SSH_FXP_STATUS));
  3050. if (Packet.Type == SSH_FXP_ATTRS)
  3051. {
  3052. Progress.SetFile(File->FileName);
  3053. assert(File != NULL);
  3054. LoadFile(File, &Packet);
  3055. Result = true;
  3056. bool DisconnectWhenComplete;
  3057. Progress.Finish(File->FileName, true, DisconnectWhenComplete);
  3058. }
  3059. if (Progress.Cancel != csContinue)
  3060. {
  3061. Next = false;
  3062. }
  3063. }
  3064. while (Next);
  3065. }
  3066. }
  3067. __finally
  3068. {
  3069. FTerminal->FOperationProgress = NULL;
  3070. Progress.Stop();
  3071. }
  3072. }
  3073. return Result;
  3074. }
  3075. //---------------------------------------------------------------------------
  3076. void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(const AnsiString & Alg,
  3077. TStrings * FileList, TStrings * Checksums,
  3078. TCalculatedChecksumEvent OnCalculatedChecksum,
  3079. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  3080. {
  3081. bool DisconnectWhenComplete; // not used
  3082. // recurse into subdirectories only if we have callback function
  3083. if (OnCalculatedChecksum != NULL)
  3084. {
  3085. for (int Index = 0; Index < FileList->Count; Index++)
  3086. {
  3087. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  3088. assert(File != NULL);
  3089. if (File->IsDirectory && !File->IsSymLink &&
  3090. !File->IsParentDirectory && !File->IsThisDirectory)
  3091. {
  3092. OperationProgress->SetFile(File->FileName);
  3093. TRemoteFileList * SubFiles =
  3094. FTerminal->ReadDirectoryListing(File->FullFileName, false);
  3095. if (SubFiles != NULL)
  3096. {
  3097. TStrings * SubFileList = new TStringList();
  3098. bool Success = false;
  3099. try
  3100. {
  3101. OperationProgress->SetFile(File->FileName);
  3102. for (int Index = 0; Index < SubFiles->Count; Index++)
  3103. {
  3104. TRemoteFile * SubFile = SubFiles->Files[Index];
  3105. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  3106. }
  3107. // do not collect checksums for files in subdirectories,
  3108. // only send back checksums via callback
  3109. DoCalculateFilesChecksum(Alg, SubFileList, NULL,
  3110. OnCalculatedChecksum, OperationProgress, false);
  3111. Success = true;
  3112. }
  3113. __finally
  3114. {
  3115. delete SubFiles;
  3116. delete SubFileList;
  3117. if (FirstLevel)
  3118. {
  3119. OperationProgress->Finish(File->FileName, Success, DisconnectWhenComplete);
  3120. }
  3121. }
  3122. }
  3123. }
  3124. }
  3125. }
  3126. static int CalculateFilesChecksumQueueLen = 5;
  3127. // at end of this block queue is disposed
  3128. TSFTPCalculateFilesChecksumQueue Queue(this);
  3129. if (Queue.Init(CalculateFilesChecksumQueueLen, Alg, FileList))
  3130. {
  3131. TSFTPPacket Packet;
  3132. bool Next;
  3133. do
  3134. {
  3135. bool Success = false;
  3136. AnsiString Alg;
  3137. AnsiString Checksum;
  3138. TRemoteFile * File = NULL;
  3139. try
  3140. {
  3141. try
  3142. {
  3143. Next = Queue.ReceivePacket(&Packet, File);
  3144. assert(Packet.Type == SSH_FXP_EXTENDED_REPLY);
  3145. OperationProgress->SetFile(File->FileName);
  3146. Alg = Packet.GetString();
  3147. Checksum = StrToHex(AnsiString(Packet.GetNextData(Packet.RemainingLength), Packet.RemainingLength));
  3148. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  3149. Success = true;
  3150. }
  3151. catch (Exception & E)
  3152. {
  3153. FTerminal->CommandError(&E, FMTLOAD(CHECKSUM_ERROR,
  3154. (File != NULL ? File->FullFileName : AnsiString(""))));
  3155. // TODO: retries? resume?
  3156. Next = false;
  3157. }
  3158. if (Checksums != NULL)
  3159. {
  3160. Checksums->Add("");
  3161. }
  3162. }
  3163. __finally
  3164. {
  3165. if (FirstLevel)
  3166. {
  3167. OperationProgress->Finish(File->FileName, Success, DisconnectWhenComplete);
  3168. }
  3169. }
  3170. if (OperationProgress->Cancel != csContinue)
  3171. {
  3172. Next = false;
  3173. }
  3174. }
  3175. while (Next);
  3176. }
  3177. }
  3178. //---------------------------------------------------------------------------
  3179. void __fastcall TSFTPFileSystem::CalculateFilesChecksum(const AnsiString & Alg,
  3180. TStrings * FileList, TStrings * Checksums,
  3181. TCalculatedChecksumEvent OnCalculatedChecksum)
  3182. {
  3183. TFileOperationProgressType Progress(FTerminal->FOnProgress, FTerminal->FOnFinished);
  3184. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  3185. FTerminal->FOperationProgress = &Progress;
  3186. try
  3187. {
  3188. DoCalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum,
  3189. &Progress, true);
  3190. }
  3191. __finally
  3192. {
  3193. FTerminal->FOperationProgress = NULL;
  3194. Progress.Stop();
  3195. }
  3196. }
  3197. //---------------------------------------------------------------------------
  3198. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  3199. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  3200. TCaptureOutputEvent /*OutputEvent*/)
  3201. {
  3202. assert(false);
  3203. }
  3204. //---------------------------------------------------------------------------
  3205. void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/,
  3206. TCaptureOutputEvent /*OutputEvent*/)
  3207. {
  3208. assert(false);
  3209. }
  3210. //---------------------------------------------------------------------------
  3211. AnsiString __fastcall TSFTPFileSystem::FileUrl(const AnsiString FileName)
  3212. {
  3213. return FTerminal->FileUrl("sftp", FileName);
  3214. }
  3215. //---------------------------------------------------------------------------
  3216. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  3217. {
  3218. return FFixedPaths;
  3219. }
  3220. //---------------------------------------------------------------------------
  3221. void __fastcall TSFTPFileSystem::SpaceAvailable(const AnsiString Path,
  3222. TSpaceAvailable & ASpaceAvailable)
  3223. {
  3224. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3225. Packet.AddString(SFTP_EXT_SPACE_AVAILABLE);
  3226. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3227. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3228. ASpaceAvailable.BytesOnDevice = Packet.GetInt64();
  3229. ASpaceAvailable.UnusedBytesOnDevice = Packet.GetInt64();
  3230. ASpaceAvailable.BytesAvailableToUser = Packet.GetInt64();
  3231. ASpaceAvailable.UnusedBytesAvailableToUser = Packet.GetInt64();
  3232. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetCardinal();
  3233. }
  3234. //---------------------------------------------------------------------------
  3235. // transfer protocol
  3236. //---------------------------------------------------------------------------
  3237. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  3238. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  3239. int Params, TFileOperationProgressType * OperationProgress,
  3240. bool & DisconnectWhenComplete)
  3241. {
  3242. assert(FilesToCopy && OperationProgress);
  3243. AnsiString FileName, FileNameOnly;
  3244. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  3245. int Index = 0;
  3246. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3247. {
  3248. bool Success = false;
  3249. FileName = FilesToCopy->Strings[Index];
  3250. FileNameOnly = ExtractFileName(FileName);
  3251. assert(!FAvoidBusy);
  3252. FAvoidBusy = true;
  3253. try
  3254. {
  3255. try
  3256. {
  3257. if (FTerminal->SessionData->CacheDirectories)
  3258. {
  3259. FTerminal->DirectoryModified(TargetDir, false);
  3260. if (DirectoryExists(FileName))
  3261. {
  3262. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  3263. FileNameOnly, true);
  3264. }
  3265. }
  3266. SFTPSourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  3267. tfFirstLevel);
  3268. Success = true;
  3269. }
  3270. catch(EScpSkipFile & E)
  3271. {
  3272. SUSPEND_OPERATION (
  3273. if (!FTerminal->HandleException(&E))
  3274. {
  3275. throw;
  3276. };
  3277. );
  3278. }
  3279. }
  3280. __finally
  3281. {
  3282. FAvoidBusy = false;
  3283. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  3284. }
  3285. Index++;
  3286. }
  3287. }
  3288. //---------------------------------------------------------------------------
  3289. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(AnsiString & FileName,
  3290. TFileOperationProgressType * OperationProgress,
  3291. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  3292. {
  3293. bool TargetBiggerThanSource = (FileParams->DestSize > FileParams->SourceSize);
  3294. bool CanAlternateResume = !TargetBiggerThanSource && !OperationProgress->AsciiTransfer;
  3295. if (OperationProgress->NoToAll)
  3296. {
  3297. THROW_SKIP_FILE_NULL;
  3298. }
  3299. else if (CanAlternateResume && OperationProgress->AlternateResumeAlways)
  3300. {
  3301. OverwriteMode = omResume;
  3302. }
  3303. else
  3304. {
  3305. int Answer;
  3306. SUSPEND_OPERATION
  3307. (
  3308. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  3309. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  3310. {
  3311. Answers |= qaRetry;
  3312. }
  3313. TQueryButtonAlias Aliases[3];
  3314. Aliases[0].Button = qaRetry;
  3315. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  3316. Aliases[1].Button = qaAll;
  3317. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  3318. Aliases[2].Button = qaIgnore;
  3319. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  3320. TQueryParams Params(qpNeverAskAgainCheck);
  3321. Params.Aliases = Aliases;
  3322. Params.AliasesCount = LENOF(Aliases);
  3323. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  3324. Answers, &Params,
  3325. OperationProgress->Side == osLocal ? osRemote : osLocal,
  3326. OperationProgress);
  3327. );
  3328. if (Answer == qaRetry)
  3329. {
  3330. if (!CanAlternateResume)
  3331. {
  3332. OverwriteMode = omAppend;
  3333. }
  3334. else
  3335. {
  3336. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  3337. SUSPEND_OPERATION
  3338. (
  3339. Answer = FTerminal->QueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
  3340. NULL, qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  3341. );
  3342. switch (Answer)
  3343. {
  3344. case qaYes:
  3345. OverwriteMode = omAppend;
  3346. break;
  3347. case qaNo:
  3348. OverwriteMode = omResume;
  3349. break;
  3350. case qaNoToAll:
  3351. OverwriteMode = omResume;
  3352. OperationProgress->AlternateResumeAlways = true;
  3353. break;
  3354. default: assert(false); //fallthru
  3355. case qaCancel:
  3356. if (!OperationProgress->Cancel)
  3357. {
  3358. OperationProgress->Cancel = csCancel;
  3359. }
  3360. Abort();
  3361. break;
  3362. }
  3363. }
  3364. }
  3365. else if (Answer == qaIgnore)
  3366. {
  3367. if (FTerminal->PromptUser(FTerminal->SessionData, LoadStr(RENAME_PROMPT),
  3368. pkPrompt, FileName))
  3369. {
  3370. OverwriteMode = omOverwrite;
  3371. }
  3372. else
  3373. {
  3374. if (!OperationProgress->Cancel)
  3375. {
  3376. OperationProgress->Cancel = csCancel;
  3377. }
  3378. Abort();
  3379. }
  3380. }
  3381. else
  3382. {
  3383. OverwriteMode = omOverwrite;
  3384. switch (Answer)
  3385. {
  3386. case qaCancel:
  3387. if (!OperationProgress->Cancel)
  3388. {
  3389. OperationProgress->Cancel = csCancel;
  3390. }
  3391. Abort();
  3392. break;
  3393. case qaNo:
  3394. THROW_SKIP_FILE_NULL;
  3395. }
  3396. }
  3397. }
  3398. }
  3399. //---------------------------------------------------------------------------
  3400. bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
  3401. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  3402. {
  3403. bool ResumeTransfer;
  3404. assert(OperationProgress);
  3405. if (PartialBiggerThanSource)
  3406. {
  3407. int Answer;
  3408. SUSPEND_OPERATION
  3409. (
  3410. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  3411. Answer = FTerminal->QueryUser(
  3412. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  3413. qaOK | qaAbort, &Params, qtWarning);
  3414. )
  3415. if (Answer == qaAbort)
  3416. {
  3417. if (!OperationProgress->Cancel)
  3418. {
  3419. OperationProgress->Cancel = csCancel;
  3420. }
  3421. Abort();
  3422. }
  3423. ResumeTransfer = false;
  3424. }
  3425. else if (FTerminal->Configuration->ConfirmResume)
  3426. {
  3427. int Answer;
  3428. SUSPEND_OPERATION
  3429. (
  3430. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  3431. HELP_RESUME_TRANSFER);
  3432. // "abort" replaced with "cancel" to unify with "append/resume" query
  3433. Answer = FTerminal->QueryUser(
  3434. FMTLOAD(RESUME_TRANSFER, (DestFileName)), NULL, qaYes | qaNo | qaCancel,
  3435. &Params);
  3436. );
  3437. switch (Answer) {
  3438. case qaNeverAskAgain:
  3439. FTerminal->Configuration->ConfirmResume = false;
  3440. case qaYes:
  3441. ResumeTransfer = true;
  3442. break;
  3443. case qaNo:
  3444. ResumeTransfer = false;
  3445. break;
  3446. case qaCancel:
  3447. if (!OperationProgress->Cancel)
  3448. {
  3449. OperationProgress->Cancel = csCancel;
  3450. }
  3451. Abort();
  3452. break;
  3453. }
  3454. }
  3455. else
  3456. {
  3457. ResumeTransfer = true;
  3458. }
  3459. return ResumeTransfer;
  3460. }
  3461. //---------------------------------------------------------------------------
  3462. void __fastcall TSFTPFileSystem::SFTPSourceRobust(const AnsiString FileName,
  3463. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  3464. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3465. {
  3466. // the same in TFTPFileSystem
  3467. bool Retry;
  3468. do
  3469. {
  3470. Retry = false;
  3471. try
  3472. {
  3473. SFTPSource(FileName, TargetDir, CopyParam, Params, OperationProgress, Flags);
  3474. }
  3475. catch(Exception & E)
  3476. {
  3477. Retry = true;
  3478. if (FTerminal->Active ||
  3479. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  3480. {
  3481. throw;
  3482. }
  3483. }
  3484. if (Retry)
  3485. {
  3486. OperationProgress->RollbackTransfer();
  3487. // prevent overwrite and resume confirmations
  3488. // (should not be set for directories!)
  3489. Params |= cpNoConfirmation;
  3490. // enable resume even if we are uploading into new directory
  3491. Flags &= ~tfNewDirectory;
  3492. }
  3493. }
  3494. while (Retry);
  3495. }
  3496. //---------------------------------------------------------------------------
  3497. void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
  3498. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  3499. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3500. {
  3501. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  3502. OperationProgress->SetFile(FileName);
  3503. TOpenRemoteFileParams OpenParams;
  3504. OpenParams.OverwriteMode = omOverwrite;
  3505. HANDLE File;
  3506. __int64 MTime, ATime;
  3507. __int64 Size;
  3508. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  3509. &File, NULL, &MTime, &ATime, &Size);
  3510. try
  3511. {
  3512. bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
  3513. TFileMasks::TParams MaskParams;
  3514. MaskParams.Size = Size;
  3515. if (FLAGCLEAR(Params, cpDelete) &&
  3516. !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
  3517. {
  3518. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  3519. THROW_SKIP_FILE_NULL;
  3520. }
  3521. if (Dir)
  3522. {
  3523. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  3524. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  3525. }
  3526. else
  3527. {
  3528. // File is regular file (not directory)
  3529. assert(File);
  3530. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  3531. osLocal, FLAGSET(Flags, tfFirstLevel));
  3532. AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
  3533. AnsiString DestPartinalFullName;
  3534. bool ResumeAllowed;
  3535. bool ResumeTransfer = false;
  3536. bool DestFileExists = false;
  3537. TRights DestRights;
  3538. __int64 ResumeOffset;
  3539. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  3540. OperationProgress->SetLocalSize(Size);
  3541. // Suppose same data size to transfer as to read
  3542. // (not true with ASCII transfer)
  3543. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  3544. OperationProgress->TransferingFile = false;
  3545. // Will we use ASCII of BINARY file tranfer?
  3546. OperationProgress->SetAsciiTransfer(
  3547. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  3548. FTerminal->LogEvent(
  3549. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  3550. " transfer mode selected.");
  3551. // should we check for interrupted transfer?
  3552. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  3553. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  3554. IsCapable(fcRename);
  3555. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  3556. TOverwriteFileParams FileParams;
  3557. FileParams.SourceSize = OperationProgress->LocalSize;
  3558. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  3559. FTerminal->SessionData->DSTMode);
  3560. if (ResumeAllowed)
  3561. {
  3562. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3563. if (FLAGCLEAR(Flags, tfNewDirectory))
  3564. {
  3565. FTerminal->LogEvent("Checking existence of file.");
  3566. TRemoteFile * File = NULL;
  3567. DestFileExists = RemoteFileExists(DestFullName, &File);
  3568. if (DestFileExists)
  3569. {
  3570. OpenParams.DestFileSize = File->Size;
  3571. FileParams.DestSize = OpenParams.DestFileSize;
  3572. FileParams.DestTimestamp = File->Modification;
  3573. DestRights = *File->Rights;
  3574. // if destination file is symlink, never do resumable transfer,
  3575. // as it would delete the symlink.
  3576. // also bit of heuristics to detect symlink on SFTP-3 and older
  3577. // (which does not indicate symlink in SSH_FXP_ATTRS).
  3578. // if file has all permissions and is small, then it is likely symlink.
  3579. // also it is not likely that such a small file (if it is not symlink)
  3580. // gets overwritten by large file (that would trigger resumable transfer).
  3581. if (File->IsSymLink ||
  3582. ((FVersion < 4) &&
  3583. ((*File->Rights & TRights::rfAll) == TRights::rfAll) &&
  3584. (File->Size < 100)))
  3585. {
  3586. ResumeAllowed = false;
  3587. OperationProgress->SetResumeStatus(rsDisabled);
  3588. }
  3589. delete File;
  3590. File = NULL;
  3591. }
  3592. if (ResumeAllowed)
  3593. {
  3594. FTerminal->LogEvent("Checking existence of partially transfered file.");
  3595. if (RemoteFileExists(DestPartinalFullName, &File))
  3596. {
  3597. ResumeOffset = File->Size;
  3598. delete File;
  3599. File = NULL;
  3600. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  3601. if (FLAGCLEAR(Params, cpNoConfirmation))
  3602. {
  3603. ResumeTransfer = SFTPConfirmResume(DestFileName,
  3604. PartialBiggerThanSource, OperationProgress);
  3605. }
  3606. else
  3607. {
  3608. ResumeTransfer = !PartialBiggerThanSource;
  3609. }
  3610. if (!ResumeTransfer)
  3611. {
  3612. DeleteFile(DestPartinalFullName);
  3613. }
  3614. else
  3615. {
  3616. FTerminal->LogEvent("Resuming file transfer.");
  3617. }
  3618. }
  3619. else
  3620. {
  3621. // partial upload file does not exists, check for full file
  3622. if (DestFileExists &&
  3623. (FLAGSET(Params, cpNewerOnly) ||
  3624. (FTerminal->Configuration->ConfirmOverwriting &&
  3625. !OperationProgress->YesToAll && FLAGCLEAR(Params, cpNoConfirmation))))
  3626. {
  3627. AnsiString PrevDestFileName = DestFileName;
  3628. SFTPConfirmOverwrite(DestFileName,
  3629. OperationProgress, OpenParams.OverwriteMode, &FileParams);
  3630. if (PrevDestFileName != DestFileName)
  3631. {
  3632. // update paths in case user changes the file name
  3633. DestFullName = LocalCanonify(TargetDir + DestFileName);
  3634. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3635. FTerminal->LogEvent("Checking existence of new file.");
  3636. DestFileExists = RemoteFileExists(DestFullName, NULL);
  3637. }
  3638. }
  3639. }
  3640. }
  3641. }
  3642. }
  3643. // will the transfer be resumable?
  3644. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  3645. if (DoResume && DestFileExists)
  3646. {
  3647. FILE_OPERATION_LOOP(FMTLOAD(DELETE_BEFORE_RESUME_ERROR,
  3648. (UnixExtractFileName(DestFullName), DestFullName)),
  3649. DeleteFile(DestFullName);
  3650. );
  3651. }
  3652. OpenParams.RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
  3653. OpenParams.Resume = DoResume;
  3654. OpenParams.OperationProgress = OperationProgress;
  3655. OpenParams.CopyParam = CopyParam;
  3656. OpenParams.Params = Params;
  3657. OpenParams.FileParams = &FileParams;
  3658. OpenParams.Confirmed = false;
  3659. FTerminal->LogEvent("Opening remote file.");
  3660. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  3661. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  3662. &OpenParams);
  3663. bool TransferFinished = false;
  3664. __int64 DestWriteOffset = 0;
  3665. TSFTPPacket CloseRequest;
  3666. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  3667. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  3668. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  3669. TSFTPPacket PropertiesResponse;
  3670. if (SetProperties)
  3671. {
  3672. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  3673. unsigned short Rights = 0;
  3674. if (CopyParam->PreserveRights)
  3675. {
  3676. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  3677. }
  3678. else if (DoResume && DestFileExists)
  3679. {
  3680. Rights = DestRights.NumberSet;
  3681. }
  3682. PropertiesRequest.AddProperties(
  3683. SetRights ? &Rights : NULL, NULL, NULL,
  3684. CopyParam->PreserveTime ? &MTime : NULL,
  3685. CopyParam->PreserveTime ? &ATime : NULL,
  3686. NULL, false, FVersion, FUtfStrings);
  3687. }
  3688. try
  3689. {
  3690. if (OpenParams.OverwriteMode == omAppend)
  3691. {
  3692. FTerminal->LogEvent("Appending file.");
  3693. DestWriteOffset = OpenParams.DestFileSize;
  3694. }
  3695. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  3696. {
  3697. if (OpenParams.OverwriteMode == omResume)
  3698. {
  3699. FTerminal->LogEvent("Resuming file transfer (append style).");
  3700. ResumeOffset = OpenParams.DestFileSize;
  3701. }
  3702. FileSeek((THandle)File, ResumeOffset, 0);
  3703. OperationProgress->AddResumed(ResumeOffset);
  3704. }
  3705. // at end of this block queue is disposed
  3706. {
  3707. TSFTPUploadQueue Queue(this);
  3708. Queue.Init(FileName, File, OperationProgress,
  3709. OpenParams.RemoteFileHandle,
  3710. DestWriteOffset + OperationProgress->TransferedSize);
  3711. while (Queue.Continue())
  3712. {
  3713. if (OperationProgress->Cancel)
  3714. {
  3715. Abort();
  3716. }
  3717. }
  3718. // send close request before waiting for pending read responses
  3719. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3720. OperationProgress, false, true, &CloseRequest);
  3721. OpenParams.RemoteFileHandle = "";
  3722. // when resuming is disabled, we can send "set properties"
  3723. // request before waiting for pending read/close responses
  3724. if (SetProperties && !DoResume)
  3725. {
  3726. SendPacket(&PropertiesRequest);
  3727. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  3728. }
  3729. }
  3730. TransferFinished = true;
  3731. }
  3732. __finally
  3733. {
  3734. if (FTerminal->Active)
  3735. {
  3736. // if file transfer was finished, the close request was already sent
  3737. if (!OpenParams.RemoteFileHandle.IsEmpty())
  3738. {
  3739. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3740. OperationProgress, TransferFinished, true, &CloseRequest);
  3741. }
  3742. // wait for the response
  3743. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3744. OperationProgress, TransferFinished, false, &CloseRequest);
  3745. // delete file if transfer was not completed, resuming was not allowed and
  3746. // we were not appending (incl. alternate resume),
  3747. // shortly after plain transfer completes (eq. !ResumeAllowed)
  3748. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  3749. {
  3750. DeleteFile(OpenParams.RemoteFileName);
  3751. }
  3752. }
  3753. }
  3754. // originally this was before CLOSE (last __finally statement),
  3755. // on VShell it failed
  3756. if (DoResume)
  3757. {
  3758. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3759. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  3760. RenameFile(OpenParams.RemoteFileName, DestFileName);
  3761. );
  3762. }
  3763. if (SetProperties)
  3764. {
  3765. // when resuming is enabled, the set properties request was not sent yet
  3766. if (DoResume)
  3767. {
  3768. SendPacket(&PropertiesRequest);
  3769. }
  3770. bool Resend = false;
  3771. FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_PERM_ERROR, (DestFileName)),
  3772. TSFTPPacket DummyResponse;
  3773. TSFTPPacket * Response = &PropertiesResponse;
  3774. if (Resend)
  3775. {
  3776. PropertiesRequest.Reuse();
  3777. SendPacket(&PropertiesRequest);
  3778. // ReceiveResponse currently cannot receive twice into same packet,
  3779. // so DummyResponse is temporary workaround
  3780. Response = &DummyResponse;
  3781. }
  3782. Resend = true;
  3783. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS,
  3784. asOK | FLAGMASK(CopyParam->IgnorePermErrors, asPermDenied));
  3785. );
  3786. }
  3787. }
  3788. }
  3789. __finally
  3790. {
  3791. if (File != NULL)
  3792. {
  3793. CloseHandle(File);
  3794. }
  3795. }
  3796. /* TODO : Delete also read-only files. */
  3797. /* TODO : Show error message on failure. */
  3798. if (FLAGSET(Params, cpDelete))
  3799. {
  3800. Sysutils::DeleteFile(FileName);
  3801. }
  3802. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  3803. {
  3804. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  3805. THROWIFFALSE(FileSetAttr(FileName, OpenParams.LocalFileAttrs & ~faArchive) == 0);
  3806. )
  3807. }
  3808. }
  3809. //---------------------------------------------------------------------------
  3810. AnsiString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  3811. const AnsiString & FileName, unsigned int OpenType, __int64 Size)
  3812. {
  3813. TSFTPPacket Packet(SSH_FXP_OPEN);
  3814. Packet.AddPathString(FileName, FUtfStrings);
  3815. if (FVersion < 5)
  3816. {
  3817. Packet.AddCardinal(OpenType);
  3818. }
  3819. else
  3820. {
  3821. unsigned long Access =
  3822. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  3823. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  3824. unsigned long Flags;
  3825. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  3826. {
  3827. Flags = SSH_FXF_CREATE_NEW;
  3828. }
  3829. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  3830. {
  3831. Flags = SSH_FXF_CREATE_TRUNCATE;
  3832. }
  3833. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  3834. {
  3835. Flags = SSH_FXF_OPEN_OR_CREATE;
  3836. }
  3837. else
  3838. {
  3839. Flags = SSH_FXF_OPEN_EXISTING;
  3840. }
  3841. Flags |=
  3842. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  3843. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  3844. Packet.AddCardinal(Access);
  3845. Packet.AddCardinal(Flags);
  3846. }
  3847. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  3848. Size >= 0 ? &Size : NULL, false, FVersion, FUtfStrings);
  3849. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3850. return Packet.GetString();
  3851. }
  3852. //---------------------------------------------------------------------------
  3853. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  3854. {
  3855. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  3856. assert(OpenParams);
  3857. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  3858. int OpenType;
  3859. bool Success = false;
  3860. do
  3861. {
  3862. try
  3863. {
  3864. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  3865. if (FTerminal->Configuration->ConfirmOverwriting &&
  3866. !OpenParams->Confirmed && !OperationProgress->YesToAll && !OpenParams->Resume &&
  3867. !(OpenParams->Params & cpNoConfirmation) &&
  3868. (OpenParams->OverwriteMode == omOverwrite))
  3869. {
  3870. OpenType |= SSH_FXF_EXCL;
  3871. }
  3872. if (!OpenParams->Resume && (OpenParams->OverwriteMode == omOverwrite))
  3873. {
  3874. OpenType |= SSH_FXF_TRUNC;
  3875. }
  3876. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  3877. {
  3878. OpenType |= SSH_FXF_TEXT;
  3879. }
  3880. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  3881. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  3882. Success = true;
  3883. }
  3884. catch(Exception & E)
  3885. {
  3886. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  3887. {
  3888. bool ThrowOriginal = false;
  3889. // When exclusive opening of file fails, try to detect if file exists.
  3890. // When file does not exist, failure was probably caused by 'permission denied'
  3891. // or similar error. In this case throw original exception.
  3892. try
  3893. {
  3894. TRemoteFile * File;
  3895. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3896. ReadFile(RealFileName, File);
  3897. OpenParams->DestFileSize = File->Size;
  3898. if (OpenParams->FileParams != NULL)
  3899. {
  3900. OpenParams->FileParams->DestTimestamp = File->Modification;
  3901. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  3902. }
  3903. // file exists (otherwise exception was thrown)
  3904. assert(File);
  3905. SAFE_DESTROY(File);
  3906. }
  3907. catch(...)
  3908. {
  3909. if (!FTerminal->Active)
  3910. {
  3911. throw;
  3912. }
  3913. else
  3914. {
  3915. ThrowOriginal = true;
  3916. }
  3917. }
  3918. if (ThrowOriginal)
  3919. {
  3920. throw;
  3921. }
  3922. // confirmation duplicated in SFTPSource for resumable file transfers.
  3923. AnsiString RemoteFileNameOnly = UnixExtractFileName(OpenParams->RemoteFileName);
  3924. SFTPConfirmOverwrite(RemoteFileNameOnly,
  3925. OperationProgress, OpenParams->OverwriteMode, OpenParams->FileParams);
  3926. if (RemoteFileNameOnly != UnixExtractFileName(OpenParams->RemoteFileName))
  3927. {
  3928. OpenParams->RemoteFileName =
  3929. UnixExtractFilePath(OpenParams->RemoteFileName) + RemoteFileNameOnly;
  3930. }
  3931. OpenParams->Confirmed = true;
  3932. if (FTerminal->SessionData->OverwrittenToRecycleBin)
  3933. {
  3934. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  3935. }
  3936. }
  3937. else if (FTerminal->Active)
  3938. {
  3939. // if file overwritting was confirmed, it means that the file already exists,
  3940. // if not, check now
  3941. if (!OpenParams->Confirmed)
  3942. {
  3943. bool ThrowOriginal = false;
  3944. // When file does not exist, failure was probably caused by 'permission denied'
  3945. // or similar error. In this case throw original exception.
  3946. try
  3947. {
  3948. TRemoteFile * File;
  3949. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3950. ReadFile(RealFileName, File);
  3951. SAFE_DESTROY(File);
  3952. }
  3953. catch(...)
  3954. {
  3955. if (!FTerminal->Active)
  3956. {
  3957. throw;
  3958. }
  3959. else
  3960. {
  3961. ThrowOriginal = true;
  3962. }
  3963. }
  3964. if (ThrowOriginal)
  3965. {
  3966. throw;
  3967. }
  3968. }
  3969. // now we know that the file exists
  3970. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  3971. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR, (OpenParams->RemoteFileName)),
  3972. true, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  3973. {
  3974. bool Recursive = false;
  3975. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Recursive);
  3976. }
  3977. }
  3978. else
  3979. {
  3980. throw;
  3981. }
  3982. }
  3983. }
  3984. while (!Success);
  3985. return 0;
  3986. }
  3987. //---------------------------------------------------------------------------
  3988. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
  3989. const AnsiString FileName, TFileOperationProgressType * OperationProgress,
  3990. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  3991. {
  3992. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  3993. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
  3994. try
  3995. {
  3996. TSFTPPacket CloseRequest;
  3997. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  3998. if (Request)
  3999. {
  4000. P->ChangeType(SSH_FXP_CLOSE);
  4001. P->AddString(Handle);
  4002. SendPacket(P);
  4003. ReserveResponse(P, Packet);
  4004. }
  4005. else
  4006. {
  4007. assert(Packet != NULL);
  4008. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  4009. }
  4010. }
  4011. catch(...)
  4012. {
  4013. if (!FTerminal->Active || TransferFinished)
  4014. {
  4015. throw;
  4016. }
  4017. }
  4018. );
  4019. }
  4020. //---------------------------------------------------------------------------
  4021. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
  4022. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  4023. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4024. {
  4025. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  4026. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  4027. FLAGSET(Flags, tfFirstLevel));
  4028. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  4029. OperationProgress->SetFile(DirectoryName);
  4030. bool CreateDir = false;
  4031. try
  4032. {
  4033. TryOpenDirectory(DestFullName);
  4034. }
  4035. catch(...)
  4036. {
  4037. if (FTerminal->Active)
  4038. {
  4039. // opening directory failed, it probably does not exists, try to
  4040. // create it
  4041. CreateDir = true;
  4042. }
  4043. else
  4044. {
  4045. throw;
  4046. }
  4047. }
  4048. if (CreateDir)
  4049. {
  4050. TRemoteProperties Properties;
  4051. if (CopyParam->PreserveRights)
  4052. {
  4053. Properties.Valid = TValidProperties() << vpRights;
  4054. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  4055. }
  4056. FTerminal->CreateDirectory(DestFullName, &Properties);
  4057. Flags |= tfNewDirectory;
  4058. }
  4059. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4060. TSearchRec SearchRec;
  4061. bool FindOK;
  4062. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  4063. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  4064. FindAttrs, SearchRec) == 0);
  4065. );
  4066. while (FindOK && !OperationProgress->Cancel)
  4067. {
  4068. AnsiString FileName = DirectoryName + SearchRec.Name;
  4069. try
  4070. {
  4071. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  4072. {
  4073. SFTPSourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  4074. Flags & ~tfFirstLevel);
  4075. }
  4076. }
  4077. catch (EScpSkipFile &E)
  4078. {
  4079. // If ESkipFile occurs, just log it and continue with next file
  4080. SUSPEND_OPERATION (
  4081. // here a message to user was displayed, which was not appropriate
  4082. // when user refused to overwrite the file in subdirectory.
  4083. // hopefuly it won't be missing in other situations.
  4084. if (!FTerminal->HandleException(&E)) throw;
  4085. );
  4086. }
  4087. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  4088. FindOK = (FindNext(SearchRec) == 0);
  4089. );
  4090. };
  4091. FindClose(SearchRec);
  4092. /* TODO : Delete also read-only directories. */
  4093. /* TODO : Show error message on failure. */
  4094. if (!OperationProgress->Cancel)
  4095. {
  4096. if (FLAGSET(Params, cpDelete))
  4097. {
  4098. RemoveDir(DirectoryName);
  4099. }
  4100. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  4101. {
  4102. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  4103. THROWIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  4104. )
  4105. }
  4106. }
  4107. }
  4108. //---------------------------------------------------------------------------
  4109. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  4110. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  4111. int Params, TFileOperationProgressType * OperationProgress,
  4112. bool & DisconnectWhenComplete)
  4113. {
  4114. assert(FilesToCopy && OperationProgress);
  4115. AnsiString FileName;
  4116. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  4117. const TRemoteFile * File;
  4118. bool Success;
  4119. int Index = 0;
  4120. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  4121. {
  4122. Success = false;
  4123. FileName = FilesToCopy->Strings[Index];
  4124. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  4125. assert(!FAvoidBusy);
  4126. FAvoidBusy = true;
  4127. try
  4128. {
  4129. try
  4130. {
  4131. SFTPSinkRobust(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  4132. Params, OperationProgress, tfFirstLevel);
  4133. Success = true;
  4134. }
  4135. catch(EScpSkipFile & E)
  4136. {
  4137. SUSPEND_OPERATION (
  4138. if (!FTerminal->HandleException(&E)) throw;
  4139. );
  4140. }
  4141. catch(...)
  4142. {
  4143. // TODO: remove the block?
  4144. throw;
  4145. }
  4146. }
  4147. __finally
  4148. {
  4149. FAvoidBusy = false;
  4150. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  4151. }
  4152. Index++;
  4153. }
  4154. }
  4155. //---------------------------------------------------------------------------
  4156. void __fastcall TSFTPFileSystem::SFTPSinkRobust(const AnsiString FileName,
  4157. const TRemoteFile * File, const AnsiString TargetDir,
  4158. const TCopyParamType * CopyParam, int Params,
  4159. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4160. {
  4161. // the same in TFTPFileSystem
  4162. bool Retry;
  4163. do
  4164. {
  4165. Retry = false;
  4166. try
  4167. {
  4168. SFTPSink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags);
  4169. }
  4170. catch(Exception & E)
  4171. {
  4172. Retry = true;
  4173. if (FTerminal->Active ||
  4174. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  4175. {
  4176. throw;
  4177. }
  4178. }
  4179. if (Retry)
  4180. {
  4181. OperationProgress->RollbackTransfer();
  4182. assert(File != NULL);
  4183. if (!File->IsDirectory)
  4184. {
  4185. // prevent overwrite and resume confirmations
  4186. Params |= cpNoConfirmation;
  4187. }
  4188. }
  4189. }
  4190. while (Retry);
  4191. }
  4192. //---------------------------------------------------------------------------
  4193. void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
  4194. const TRemoteFile * File, const AnsiString TargetDir,
  4195. const TCopyParamType * CopyParam, int Params,
  4196. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4197. {
  4198. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  4199. TFileMasks::TParams MaskParams;
  4200. MaskParams.Size = File->Size;
  4201. if (FLAGCLEAR(Params, cpDelete) &&
  4202. !CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  4203. {
  4204. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  4205. THROW_SKIP_FILE_NULL;
  4206. }
  4207. assert(File);
  4208. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  4209. OperationProgress->SetFile(OnlyFileName);
  4210. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  4211. osRemote, FLAGSET(Flags, tfFirstLevel));
  4212. AnsiString DestFullName = TargetDir + DestFileName;
  4213. if (File->IsDirectory)
  4214. {
  4215. if (!File->IsSymLink)
  4216. {
  4217. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  4218. int Attrs = FileGetAttr(DestFullName);
  4219. if ((Attrs & faDirectory) == 0) EXCEPTION;
  4220. );
  4221. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  4222. if (!ForceDirectories(DestFullName)) EXCEPTION;
  4223. );
  4224. TSinkFileParams SinkFileParams;
  4225. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  4226. SinkFileParams.CopyParam = CopyParam;
  4227. SinkFileParams.Params = Params;
  4228. SinkFileParams.OperationProgress = OperationProgress;
  4229. SinkFileParams.Skipped = false;
  4230. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  4231. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  4232. // Do not delete directory if some of its files were skip.
  4233. // Throw "skip file" for the directory to avoid attempt to deletion
  4234. // of any parent directory
  4235. if ((Params & cpDelete) && SinkFileParams.Skipped)
  4236. {
  4237. THROW_SKIP_FILE_NULL;
  4238. }
  4239. }
  4240. else
  4241. {
  4242. // file is symlink to directory, currently do nothing, but it should be
  4243. // reported to user
  4244. }
  4245. }
  4246. else
  4247. {
  4248. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  4249. AnsiString DestPartinalFullName;
  4250. bool ResumeAllowed;
  4251. bool ResumeTransfer = false;
  4252. __int64 ResumeOffset;
  4253. // Will we use ASCII of BINARY file tranfer?
  4254. OperationProgress->SetAsciiTransfer(
  4255. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  4256. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  4257. " transfer mode selected.");
  4258. // Suppose same data size to transfer as to write
  4259. // (not true with ASCII transfer)
  4260. OperationProgress->SetTransferSize(File->Size);
  4261. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  4262. // resume has no sense for temporary downloads
  4263. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  4264. !OperationProgress->AsciiTransfer &&
  4265. CopyParam->AllowResume(OperationProgress->TransferSize);
  4266. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  4267. int Attrs;
  4268. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  4269. Attrs = FileGetAttr(DestFullName);
  4270. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  4271. );
  4272. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  4273. HANDLE LocalHandle = NULL;
  4274. TStream * FileStream = NULL;
  4275. bool DeleteLocalFile = false;
  4276. AnsiString RemoteHandle;
  4277. AnsiString LocalFileName = DestFullName;
  4278. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  4279. try
  4280. {
  4281. if (ResumeAllowed)
  4282. {
  4283. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4284. LocalFileName = DestPartinalFullName;
  4285. FTerminal->LogEvent("Checking existence of partially transfered file.");
  4286. if (FileExists(DestPartinalFullName))
  4287. {
  4288. FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
  4289. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  4290. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  4291. if (FLAGCLEAR(Params, cpNoConfirmation))
  4292. {
  4293. ResumeTransfer = SFTPConfirmResume(DestFileName,
  4294. PartialBiggerThanSource, OperationProgress);
  4295. }
  4296. else
  4297. {
  4298. ResumeTransfer = !PartialBiggerThanSource;
  4299. }
  4300. if (!ResumeTransfer)
  4301. {
  4302. CloseHandle(LocalHandle);
  4303. LocalHandle = NULL;
  4304. Sysutils::DeleteFile(DestPartinalFullName);
  4305. }
  4306. else
  4307. {
  4308. FTerminal->LogEvent("Resuming file transfer.");
  4309. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  4310. OperationProgress->AddResumed(ResumeOffset);
  4311. }
  4312. }
  4313. }
  4314. if ((Attrs >= 0) && !ResumeTransfer &&
  4315. (FLAGSET(Params, cpNewerOnly) ||
  4316. (FTerminal->Configuration->ConfirmOverwriting &&
  4317. !OperationProgress->YesToAll &&
  4318. FLAGCLEAR(Params, cpNoConfirmation))))
  4319. {
  4320. __int64 DestFileSize;
  4321. __int64 MTime;
  4322. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  4323. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  4324. FTerminal->LogEvent("Checking existence of file.");
  4325. TOverwriteFileParams FileParams;
  4326. FileParams.SourceSize = OperationProgress->TransferSize;
  4327. FileParams.SourceTimestamp = File->Modification;
  4328. FileParams.DestTimestamp = UnixToDateTime(MTime,
  4329. FTerminal->SessionData->DSTMode);
  4330. FileParams.DestSize = DestFileSize;
  4331. AnsiString PrevDestFileName = DestFileName;
  4332. SFTPConfirmOverwrite(DestFileName, OperationProgress, OverwriteMode, &FileParams);
  4333. if (PrevDestFileName != DestFileName)
  4334. {
  4335. DestFullName = TargetDir + DestFileName;
  4336. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4337. if (ResumeAllowed)
  4338. {
  4339. if (FileExists(DestPartinalFullName))
  4340. {
  4341. Sysutils::DeleteFile(DestPartinalFullName);
  4342. }
  4343. LocalFileName = DestPartinalFullName;
  4344. }
  4345. else
  4346. {
  4347. LocalFileName = DestFullName;
  4348. }
  4349. }
  4350. if (OverwriteMode == omOverwrite)
  4351. {
  4352. // is NULL when overwritting read-only file
  4353. if (LocalHandle)
  4354. {
  4355. CloseHandle(LocalHandle);
  4356. LocalHandle = NULL;
  4357. }
  4358. }
  4359. else
  4360. {
  4361. // is NULL when overwritting read-only file, so following will
  4362. // probably fail anyway
  4363. if (LocalHandle == NULL)
  4364. {
  4365. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  4366. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  4367. }
  4368. ResumeAllowed = false;
  4369. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  4370. if (OverwriteMode == omAppend)
  4371. {
  4372. FTerminal->LogEvent("Appending to file.");
  4373. }
  4374. else
  4375. {
  4376. FTerminal->LogEvent("Resuming file transfer (append style).");
  4377. assert(OverwriteMode == omResume);
  4378. OperationProgress->AddResumed(DestFileSize);
  4379. }
  4380. }
  4381. }
  4382. // if not already opened (resume, append...), create new empty file
  4383. if (!LocalHandle)
  4384. {
  4385. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  4386. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  4387. {
  4388. THROW_SKIP_FILE_NULL;
  4389. }
  4390. }
  4391. assert(LocalHandle);
  4392. DeleteLocalFile = true;
  4393. FTerminal->LogEvent("Opening remote file.");
  4394. FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
  4395. int OpenType = SSH_FXF_READ;
  4396. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  4397. {
  4398. OpenType |= SSH_FXF_TEXT;
  4399. }
  4400. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  4401. );
  4402. TSFTPPacket RemoteFilePacket(SSH_FXP_FSTAT);
  4403. if (CopyParam->PreserveTime)
  4404. {
  4405. SendCustomReadFile(&RemoteFilePacket, &RemoteFilePacket, RemoteHandle,
  4406. SSH_FILEXFER_ATTR_MODIFYTIME);
  4407. }
  4408. FileStream = new TSafeHandleStream((THandle)LocalHandle);
  4409. // at end of this block queue is disposed
  4410. {
  4411. TSFTPDownloadQueue Queue(this);
  4412. TSFTPPacket DataPacket;
  4413. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  4414. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  4415. (QueueLen < 0))
  4416. {
  4417. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  4418. }
  4419. if (QueueLen < 1)
  4420. {
  4421. QueueLen = 1;
  4422. }
  4423. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferedSize,
  4424. OperationProgress);
  4425. bool Eof = false;
  4426. bool PrevIncomplete = false;
  4427. int GapFillCount = 0;
  4428. int GapCount = 0;
  4429. unsigned long Missing = 0;
  4430. unsigned long DataLen = 0;
  4431. unsigned long BlockSize;
  4432. while (!Eof)
  4433. {
  4434. if (Missing > 0)
  4435. {
  4436. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  4437. &DataPacket);
  4438. GapFillCount++;
  4439. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  4440. SSH_FXP_DATA, asEOF);
  4441. }
  4442. else
  4443. {
  4444. Queue.ReceivePacket(&DataPacket, BlockSize);
  4445. }
  4446. if (DataPacket.Type == SSH_FXP_STATUS)
  4447. {
  4448. // must be SSH_FX_EOF, any other status packet would raise exception
  4449. Eof = true;
  4450. // close file right away, before waiting for pending responses
  4451. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  4452. true, true, NULL);
  4453. RemoteHandle = ""; // do not close file again in __finally block
  4454. }
  4455. if (!Eof)
  4456. {
  4457. if ((Missing == 0) && PrevIncomplete)
  4458. {
  4459. // This can happen only if last request returned less bytes
  4460. // than expected, but exacly number of bytes missing to last
  4461. // known file size, but actually EOF was not reached.
  4462. // Can happen only when filesize has changed since directory
  4463. // listing and server returns less bytes than requested and
  4464. // file has some special file size.
  4465. FTerminal->LogEvent(FORMAT(
  4466. "Received incomplete data packet before end of file, "
  4467. "offset: %s, size: %d, requested: %d",
  4468. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  4469. int(BlockSize))));
  4470. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  4471. }
  4472. // Buffer for one block of data
  4473. TFileBuffer BlockBuf;
  4474. DataLen = DataPacket.GetCardinal();
  4475. PrevIncomplete = false;
  4476. if (Missing > 0)
  4477. {
  4478. assert(DataLen <= Missing);
  4479. Missing -= DataLen;
  4480. }
  4481. else if (DataLen < BlockSize)
  4482. {
  4483. if (OperationProgress->TransferedSize + DataLen !=
  4484. OperationProgress->TransferSize)
  4485. {
  4486. // with native text transfer mode (SFTP>=4), do not bother about
  4487. // getting less than requested, read offset is ignored anyway
  4488. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  4489. {
  4490. GapCount++;
  4491. Missing = BlockSize - DataLen;
  4492. }
  4493. }
  4494. else
  4495. {
  4496. PrevIncomplete = true;
  4497. }
  4498. }
  4499. assert(DataLen <= BlockSize);
  4500. BlockBuf.Insert(0, DataPacket.GetNextData(DataLen), DataLen);
  4501. OperationProgress->AddTransfered(DataLen);
  4502. if (OperationProgress->AsciiTransfer)
  4503. {
  4504. assert(!ResumeTransfer && !ResumeAllowed);
  4505. unsigned int PrevBlockSize = BlockBuf.Size;
  4506. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
  4507. OperationProgress->SetLocalSize(
  4508. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  4509. }
  4510. FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
  4511. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  4512. );
  4513. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  4514. }
  4515. if (OperationProgress->Cancel == csCancel)
  4516. {
  4517. Abort();
  4518. }
  4519. };
  4520. if (GapCount > 0)
  4521. {
  4522. FTerminal->LogEvent(FORMAT(
  4523. "%d requests to fill %d data gaps were issued.",
  4524. (GapFillCount, GapCount)));
  4525. }
  4526. }
  4527. if (CopyParam->PreserveTime)
  4528. {
  4529. ReceiveResponse(&RemoteFilePacket, &RemoteFilePacket);
  4530. const TRemoteFile * AFile = File;
  4531. try
  4532. {
  4533. // ignore errors
  4534. if (RemoteFilePacket.Type == SSH_FXP_ATTRS)
  4535. {
  4536. // load file, avoid completion (resolving symlinks) as we do not need that
  4537. AFile = LoadFile(&RemoteFilePacket, NULL, UnixExtractFileName(FileName),
  4538. NULL, false);
  4539. }
  4540. FILETIME AcTime = DateTimeToFileTime(AFile->LastAccess,
  4541. FTerminal->SessionData->DSTMode);
  4542. FILETIME WrTime = DateTimeToFileTime(AFile->Modification,
  4543. FTerminal->SessionData->DSTMode);
  4544. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  4545. }
  4546. __finally
  4547. {
  4548. if (AFile != File)
  4549. {
  4550. delete AFile;
  4551. }
  4552. }
  4553. }
  4554. CloseHandle(LocalHandle);
  4555. LocalHandle = NULL;
  4556. if (ResumeAllowed)
  4557. {
  4558. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  4559. (ExtractFileName(DestPartinalFullName), DestFileName)),
  4560. if (FileExists(DestFullName))
  4561. {
  4562. if (!Sysutils::DeleteFile(DestFullName)) EXCEPTION;
  4563. }
  4564. if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
  4565. {
  4566. EXCEPTION;
  4567. }
  4568. );
  4569. }
  4570. DeleteLocalFile = false;
  4571. if (Attrs == -1)
  4572. {
  4573. Attrs = faArchive;
  4574. }
  4575. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  4576. if ((NewAttrs & Attrs) != NewAttrs)
  4577. {
  4578. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  4579. THROWIFFALSE(FileSetAttr(DestFullName, Attrs | NewAttrs) == 0);
  4580. );
  4581. }
  4582. }
  4583. __finally
  4584. {
  4585. if (LocalHandle) CloseHandle(LocalHandle);
  4586. if (FileStream) delete FileStream;
  4587. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0) &&
  4588. (OverwriteMode == omOverwrite))
  4589. {
  4590. Sysutils::DeleteFile(LocalFileName);
  4591. }
  4592. // if the transfer was finished, the file is closed already
  4593. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  4594. {
  4595. // do not wait for response
  4596. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  4597. true, true, NULL);
  4598. }
  4599. }
  4600. }
  4601. if (Params & cpDelete)
  4602. {
  4603. // If file is directory, do not delete it recursively, because it should be
  4604. // empty already. If not, it should not be deleted (some files were
  4605. // skipped or some new files were copied to it, while we were downloading)
  4606. bool Recursive = false;
  4607. FTerminal->DeleteFile(FileName, File, &Recursive);
  4608. }
  4609. }
  4610. //---------------------------------------------------------------------------
  4611. void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
  4612. const TRemoteFile * File, void * Param)
  4613. {
  4614. TSinkFileParams * Params = (TSinkFileParams *)Param;
  4615. assert(Params->OperationProgress);
  4616. try
  4617. {
  4618. SFTPSinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  4619. Params->Params, Params->OperationProgress, Params->Flags);
  4620. }
  4621. catch(EScpSkipFile & E)
  4622. {
  4623. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  4624. Params->Skipped = true;
  4625. SUSPEND_OPERATION (
  4626. if (!FTerminal->HandleException(&E)) throw;
  4627. );
  4628. if (OperationProgress->Cancel)
  4629. {
  4630. Abort();
  4631. }
  4632. }
  4633. }