SftpFileSystem.cpp 158 KB

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