SftpFileSystem.cpp 157 KB

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