Terminal.cpp 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "PuttyTools.h"
  9. #include "FileBuffer.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "SecureShell.h"
  13. #include "ScpFileSystem.h"
  14. #include "SftpFileSystem.h"
  15. #ifndef NO_FILEZILLA
  16. #include "FtpFileSystem.h"
  17. #endif
  18. #include "WebDAVFileSystem.h"
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "CoreMain.h"
  22. #include "Queue.h"
  23. #ifndef AUTO_WINSOCK
  24. #include <winsock2.h>
  25. #endif
  26. //---------------------------------------------------------------------------
  27. #pragma package(smart_init)
  28. //---------------------------------------------------------------------------
  29. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  30. { \
  31. unsigned int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  32. switch (Result) { \
  33. case qaRetry: { REPEAT; } break; \
  34. case qaAbort: Abort(); \
  35. } \
  36. }
  37. //---------------------------------------------------------------------------
  38. // Note that the action may already be canceled when RollbackAction is called
  39. #define COMMAND_ERROR_ARI_ACTION(MESSAGE, REPEAT, ACTION) \
  40. { \
  41. unsigned int Result; \
  42. try \
  43. { \
  44. Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  45. } \
  46. catch(Exception & E2) \
  47. { \
  48. RollbackAction(ACTION, NULL, &E2); \
  49. throw; \
  50. } \
  51. switch (Result) { \
  52. case qaRetry: ACTION.Cancel(); { REPEAT; } break; \
  53. case qaAbort: RollbackAction(ACTION, NULL, &E); Abort(); \
  54. case qaSkip: ACTION.Cancel(); break; \
  55. default: assert(false); \
  56. } \
  57. }
  58. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  59. FILE_OPERATION_LOOP_CUSTOM(this, ALLOW_SKIP, MESSAGE, OPERATION)
  60. //---------------------------------------------------------------------------
  61. struct TMoveFileParams
  62. {
  63. UnicodeString Target;
  64. UnicodeString FileMask;
  65. };
  66. //---------------------------------------------------------------------------
  67. struct TFilesFindParams
  68. {
  69. TFileMasks FileMask;
  70. TFileFoundEvent OnFileFound;
  71. TFindingFileEvent OnFindingFile;
  72. bool Cancel;
  73. };
  74. //---------------------------------------------------------------------------
  75. TCalculateSizeStats::TCalculateSizeStats()
  76. {
  77. memset(this, 0, sizeof(*this));
  78. }
  79. //---------------------------------------------------------------------------
  80. TSynchronizeOptions::TSynchronizeOptions()
  81. {
  82. memset(this, 0, sizeof(*this));
  83. }
  84. //---------------------------------------------------------------------------
  85. TSynchronizeOptions::~TSynchronizeOptions()
  86. {
  87. delete Filter;
  88. }
  89. //---------------------------------------------------------------------------
  90. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  91. {
  92. int FoundIndex;
  93. bool Result;
  94. if (Filter == NULL)
  95. {
  96. Result = true;
  97. }
  98. else
  99. {
  100. Result = Filter->Find(FileName, FoundIndex);
  101. }
  102. return Result;
  103. }
  104. //---------------------------------------------------------------------------
  105. TSpaceAvailable::TSpaceAvailable()
  106. {
  107. memset(this, 0, sizeof(*this));
  108. }
  109. //---------------------------------------------------------------------------
  110. TOverwriteFileParams::TOverwriteFileParams()
  111. {
  112. SourceSize = 0;
  113. DestSize = 0;
  114. SourcePrecision = mfFull;
  115. DestPrecision = mfFull;
  116. }
  117. //---------------------------------------------------------------------------
  118. //---------------------------------------------------------------------------
  119. TSynchronizeChecklist::TItem::TItem() :
  120. Action(saNone), IsDirectory(false), RemoteFile(NULL), Checked(true), ImageIndex(-1)
  121. {
  122. Local.ModificationFmt = mfFull;
  123. Local.Modification = 0;
  124. Local.Size = 0;
  125. Remote.ModificationFmt = mfFull;
  126. Remote.Modification = 0;
  127. Remote.Size = 0;
  128. }
  129. //---------------------------------------------------------------------------
  130. TSynchronizeChecklist::TItem::~TItem()
  131. {
  132. delete RemoteFile;
  133. }
  134. //---------------------------------------------------------------------------
  135. const UnicodeString& TSynchronizeChecklist::TItem::GetFileName() const
  136. {
  137. if (!Remote.FileName.IsEmpty())
  138. {
  139. return Remote.FileName;
  140. }
  141. else
  142. {
  143. assert(!Local.FileName.IsEmpty());
  144. return Local.FileName;
  145. }
  146. }
  147. //---------------------------------------------------------------------------
  148. //---------------------------------------------------------------------------
  149. TSynchronizeChecklist::TSynchronizeChecklist() :
  150. FList(new TList())
  151. {
  152. }
  153. //---------------------------------------------------------------------------
  154. TSynchronizeChecklist::~TSynchronizeChecklist()
  155. {
  156. for (int Index = 0; Index < FList->Count; Index++)
  157. {
  158. delete static_cast<TItem *>(FList->Items[Index]);
  159. }
  160. delete FList;
  161. }
  162. //---------------------------------------------------------------------------
  163. void TSynchronizeChecklist::Add(TItem * Item)
  164. {
  165. FList->Add(Item);
  166. }
  167. //---------------------------------------------------------------------------
  168. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  169. {
  170. TItem * Item1 = static_cast<TItem *>(AItem1);
  171. TItem * Item2 = static_cast<TItem *>(AItem2);
  172. int Result;
  173. if (!Item1->Local.Directory.IsEmpty())
  174. {
  175. Result = AnsiCompareText(Item1->Local.Directory, Item2->Local.Directory);
  176. }
  177. else
  178. {
  179. assert(!Item1->Remote.Directory.IsEmpty());
  180. Result = AnsiCompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  181. }
  182. if (Result == 0)
  183. {
  184. Result = AnsiCompareText(Item1->GetFileName(), Item2->GetFileName());
  185. }
  186. return Result;
  187. }
  188. //---------------------------------------------------------------------------
  189. void TSynchronizeChecklist::Sort()
  190. {
  191. FList->Sort(Compare);
  192. }
  193. //---------------------------------------------------------------------------
  194. int TSynchronizeChecklist::GetCount() const
  195. {
  196. return FList->Count;
  197. }
  198. //---------------------------------------------------------------------------
  199. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  200. {
  201. return static_cast<TItem *>(FList->Items[Index]);
  202. }
  203. //---------------------------------------------------------------------------
  204. //---------------------------------------------------------------------------
  205. class TTunnelThread : public TSimpleThread
  206. {
  207. public:
  208. __fastcall TTunnelThread(TSecureShell * SecureShell);
  209. virtual __fastcall ~TTunnelThread();
  210. virtual void __fastcall Terminate();
  211. protected:
  212. virtual void __fastcall Execute();
  213. private:
  214. TSecureShell * FSecureShell;
  215. bool FTerminated;
  216. };
  217. //---------------------------------------------------------------------------
  218. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  219. FSecureShell(SecureShell),
  220. FTerminated(false)
  221. {
  222. Start();
  223. }
  224. //---------------------------------------------------------------------------
  225. __fastcall TTunnelThread::~TTunnelThread()
  226. {
  227. // close before the class's virtual functions (Terminate particularly) are lost
  228. Close();
  229. }
  230. //---------------------------------------------------------------------------
  231. void __fastcall TTunnelThread::Terminate()
  232. {
  233. FTerminated = true;
  234. }
  235. //---------------------------------------------------------------------------
  236. void __fastcall TTunnelThread::Execute()
  237. {
  238. try
  239. {
  240. while (!FTerminated)
  241. {
  242. FSecureShell->Idle(250);
  243. }
  244. }
  245. catch(...)
  246. {
  247. if (FSecureShell->Active)
  248. {
  249. FSecureShell->Close();
  250. }
  251. // do not pass exception out of thread's proc
  252. }
  253. }
  254. //---------------------------------------------------------------------------
  255. //---------------------------------------------------------------------------
  256. class TTunnelUI : public TSessionUI
  257. {
  258. public:
  259. __fastcall TTunnelUI(TTerminal * Terminal);
  260. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  261. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  262. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  263. TQueryType QueryType);
  264. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  265. Exception * E, unsigned int Answers, const TQueryParams * Params,
  266. TQueryType QueryType);
  267. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  268. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  269. TStrings * Results);
  270. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  271. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg);
  272. virtual void __fastcall HandleExtendedException(Exception * E);
  273. virtual void __fastcall Closed();
  274. private:
  275. TTerminal * FTerminal;
  276. unsigned int FTerminalThread;
  277. };
  278. //---------------------------------------------------------------------------
  279. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  280. {
  281. FTerminal = Terminal;
  282. FTerminalThread = GetCurrentThreadId();
  283. }
  284. //---------------------------------------------------------------------------
  285. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  286. {
  287. if (GetCurrentThreadId() == FTerminalThread)
  288. {
  289. FTerminal->Information(Str, Status);
  290. }
  291. }
  292. //---------------------------------------------------------------------------
  293. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  294. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  295. TQueryType QueryType)
  296. {
  297. unsigned int Result;
  298. if (GetCurrentThreadId() == FTerminalThread)
  299. {
  300. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  301. }
  302. else
  303. {
  304. Result = AbortAnswer(Answers);
  305. }
  306. return Result;
  307. }
  308. //---------------------------------------------------------------------------
  309. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  310. Exception * E, unsigned int Answers, const TQueryParams * Params,
  311. TQueryType QueryType)
  312. {
  313. unsigned int Result;
  314. if (GetCurrentThreadId() == FTerminalThread)
  315. {
  316. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  317. }
  318. else
  319. {
  320. Result = AbortAnswer(Answers);
  321. }
  322. return Result;
  323. }
  324. //---------------------------------------------------------------------------
  325. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  326. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  327. {
  328. bool Result;
  329. if (GetCurrentThreadId() == FTerminalThread)
  330. {
  331. if (IsAuthenticationPrompt(Kind))
  332. {
  333. Instructions = LoadStr(TUNNEL_INSTRUCTION) +
  334. (Instructions.IsEmpty() ? L"" : L"\n") +
  335. Instructions;
  336. }
  337. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  338. }
  339. else
  340. {
  341. Result = false;
  342. }
  343. return Result;
  344. }
  345. //---------------------------------------------------------------------------
  346. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  347. {
  348. if (GetCurrentThreadId() == FTerminalThread)
  349. {
  350. FTerminal->DisplayBanner(Banner);
  351. }
  352. }
  353. //---------------------------------------------------------------------------
  354. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg)
  355. {
  356. throw ESshFatal(E, Msg);
  357. }
  358. //---------------------------------------------------------------------------
  359. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  360. {
  361. if (GetCurrentThreadId() == FTerminalThread)
  362. {
  363. FTerminal->HandleExtendedException(E);
  364. }
  365. }
  366. //---------------------------------------------------------------------------
  367. void __fastcall TTunnelUI::Closed()
  368. {
  369. // noop
  370. }
  371. //---------------------------------------------------------------------------
  372. //---------------------------------------------------------------------------
  373. class TCallbackGuard
  374. {
  375. public:
  376. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  377. inline __fastcall ~TCallbackGuard();
  378. void __fastcall FatalError(Exception * E, const UnicodeString & Msg);
  379. inline void __fastcall Verify();
  380. void __fastcall Dismiss();
  381. private:
  382. ExtException * FFatalError;
  383. TTerminal * FTerminal;
  384. bool FGuarding;
  385. };
  386. //---------------------------------------------------------------------------
  387. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  388. FTerminal(Terminal),
  389. FFatalError(NULL),
  390. FGuarding(FTerminal->FCallbackGuard == NULL)
  391. {
  392. if (FGuarding)
  393. {
  394. FTerminal->FCallbackGuard = this;
  395. }
  396. }
  397. //---------------------------------------------------------------------------
  398. __fastcall TCallbackGuard::~TCallbackGuard()
  399. {
  400. if (FGuarding)
  401. {
  402. assert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  403. FTerminal->FCallbackGuard = NULL;
  404. }
  405. delete FFatalError;
  406. }
  407. //---------------------------------------------------------------------------
  408. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg)
  409. {
  410. assert(FGuarding);
  411. // make sure we do not bother about getting back the silent abort exception
  412. // we issued ourselves. this may happen when there is an exception handler
  413. // that converts any exception to fatal one (such as in TTerminal::Open).
  414. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  415. {
  416. delete FFatalError;
  417. FFatalError = new ExtException(E, Msg);
  418. }
  419. // silently abort what we are doing.
  420. // non-silent exception would be caught probably by default application
  421. // exception handler, which may not do an appropriate action
  422. // (particularly it will not resume broken transfer).
  423. throw ECallbackGuardAbort();
  424. }
  425. //---------------------------------------------------------------------------
  426. void __fastcall TCallbackGuard::Dismiss()
  427. {
  428. assert(FFatalError == NULL);
  429. FGuarding = false;
  430. }
  431. //---------------------------------------------------------------------------
  432. void __fastcall TCallbackGuard::Verify()
  433. {
  434. if (FGuarding)
  435. {
  436. FGuarding = false;
  437. assert(FTerminal->FCallbackGuard == this);
  438. FTerminal->FCallbackGuard = NULL;
  439. if (FFatalError != NULL)
  440. {
  441. throw ESshFatal(FFatalError, L"");
  442. }
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. //---------------------------------------------------------------------------
  447. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  448. TConfiguration * Configuration)
  449. {
  450. FConfiguration = Configuration;
  451. FSessionData = new TSessionData(L"");
  452. FSessionData->Assign(SessionData);
  453. FLog = new TSessionLog(this, FSessionData, Configuration);
  454. FActionLog = new TActionLog(this, FSessionData, Configuration);
  455. FFiles = new TRemoteDirectory(this);
  456. FExceptionOnFail = 0;
  457. FInTransaction = 0;
  458. FReadCurrentDirectoryPending = false;
  459. FReadDirectoryPending = false;
  460. FUsersGroupsLookedup = False;
  461. FTunnelLocalPortNumber = 0;
  462. FFileSystem = NULL;
  463. FSecureShell = NULL;
  464. FOnProgress = NULL;
  465. FOnFinished = NULL;
  466. FOnDeleteLocalFile = NULL;
  467. FOnReadDirectoryProgress = NULL;
  468. FOnQueryUser = NULL;
  469. FOnPromptUser = NULL;
  470. FOnDisplayBanner = NULL;
  471. FOnShowExtendedException = NULL;
  472. FOnInformation = NULL;
  473. FOnClose = NULL;
  474. FOnFindingFile = NULL;
  475. FUseBusyCursor = True;
  476. FLockDirectory = L"";
  477. FDirectoryCache = new TRemoteDirectoryCache();
  478. FDirectoryChangesCache = NULL;
  479. FFSProtocol = cfsUnknown;
  480. FCommandSession = NULL;
  481. FAutoReadDirectory = true;
  482. FReadingCurrentDirectory = false;
  483. FStatus = ssClosed;
  484. FTunnelThread = NULL;
  485. FTunnel = NULL;
  486. FTunnelData = NULL;
  487. FTunnelLog = NULL;
  488. FTunnelUI = NULL;
  489. FTunnelOpening = false;
  490. FCallbackGuard = NULL;
  491. FEnableSecureShellUsage = false;
  492. }
  493. //---------------------------------------------------------------------------
  494. __fastcall TTerminal::~TTerminal()
  495. {
  496. if (Active)
  497. {
  498. Close();
  499. }
  500. if (FCallbackGuard != NULL)
  501. {
  502. // see TTerminal::HandleExtendedException
  503. FCallbackGuard->Dismiss();
  504. }
  505. assert(FTunnel == NULL);
  506. SAFE_DESTROY(FCommandSession);
  507. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  508. (FDirectoryChangesCache != NULL))
  509. {
  510. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  511. FDirectoryChangesCache);
  512. }
  513. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  514. SAFE_DESTROY_EX(TSessionLog, FLog);
  515. SAFE_DESTROY_EX(TActionLog, FActionLog);
  516. delete FFiles;
  517. delete FDirectoryCache;
  518. delete FDirectoryChangesCache;
  519. SAFE_DESTROY(FSessionData);
  520. }
  521. //---------------------------------------------------------------------------
  522. void __fastcall TTerminal::Idle()
  523. {
  524. // once we disconnect, do nothing, until reconnect handler
  525. // "receives the information"
  526. if (Active)
  527. {
  528. if (Configuration->ActualLogProtocol >= 1)
  529. {
  530. LogEvent(L"Session upkeep");
  531. }
  532. assert(FFileSystem != NULL);
  533. FFileSystem->Idle();
  534. if (CommandSessionOpened)
  535. {
  536. try
  537. {
  538. FCommandSession->Idle();
  539. }
  540. catch(Exception & E)
  541. {
  542. // If the secondary session is dropped, ignore the error and let
  543. // it be reconnected when needed.
  544. // BTW, non-fatal error can hardly happen here, that's why
  545. // it is displayed, because it can be useful to know.
  546. if (FCommandSession->Active)
  547. {
  548. FCommandSession->HandleExtendedException(&E);
  549. }
  550. }
  551. }
  552. }
  553. }
  554. //---------------------------------------------------------------------
  555. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  556. {
  557. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  558. }
  559. //---------------------------------------------------------------------
  560. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  561. {
  562. UnicodeString Result;
  563. try
  564. {
  565. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  566. }
  567. catch(EAbort &)
  568. {
  569. // silently ignore aborted prompts for master password and return empty password
  570. }
  571. return Result;
  572. }
  573. //---------------------------------------------------------------------------
  574. void __fastcall TTerminal::RecryptPasswords()
  575. {
  576. FSessionData->RecryptPasswords();
  577. FPassword = EncryptPassword(DecryptPassword(FPassword));
  578. FTunnelPassword = EncryptPassword(DecryptPassword(FTunnelPassword));
  579. }
  580. //---------------------------------------------------------------------------
  581. bool __fastcall TTerminal::IsAbsolutePath(const UnicodeString Path)
  582. {
  583. return !Path.IsEmpty() && Path[1] == L'/';
  584. }
  585. //---------------------------------------------------------------------------
  586. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  587. const UnicodeString BasePath)
  588. {
  589. Path = UnixExcludeTrailingBackslash(Path);
  590. if (!IsAbsolutePath(Path) && !BasePath.IsEmpty())
  591. {
  592. // TODO: Handle more complicated cases like "../../xxx"
  593. if (Path == L"..")
  594. {
  595. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  596. UnixExcludeTrailingBackslash(BasePath)));
  597. }
  598. else
  599. {
  600. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  601. }
  602. }
  603. return Path;
  604. }
  605. //---------------------------------------------------------------------------
  606. bool __fastcall TTerminal::GetActive()
  607. {
  608. return (FFileSystem != NULL) && FFileSystem->GetActive();
  609. }
  610. //---------------------------------------------------------------------------
  611. void __fastcall TTerminal::Close()
  612. {
  613. FFileSystem->Close();
  614. if (CommandSessionOpened)
  615. {
  616. FCommandSession->Close();
  617. }
  618. }
  619. //---------------------------------------------------------------------------
  620. void __fastcall TTerminal::ResetConnection()
  621. {
  622. // used to be called from Reopen(), why?
  623. FTunnelError = L"";
  624. if (FDirectoryChangesCache != NULL)
  625. {
  626. delete FDirectoryChangesCache;
  627. FDirectoryChangesCache = NULL;
  628. }
  629. FFiles->Directory = L"";
  630. // note that we cannot clear contained files
  631. // as they can still be referenced in the GUI atm
  632. }
  633. //---------------------------------------------------------------------------
  634. void __fastcall TTerminal::Open()
  635. {
  636. ReflectSettings();
  637. try
  638. {
  639. DoInformation(L"", true, 1);
  640. try
  641. {
  642. try
  643. {
  644. ResetConnection();
  645. FStatus = ssOpening;
  646. try
  647. {
  648. if (FFileSystem == NULL)
  649. {
  650. Log->AddSystemInfo();
  651. DoInitializeLog();
  652. Log->AddStartupInfo();
  653. }
  654. assert(FTunnel == NULL);
  655. if (FSessionData->Tunnel)
  656. {
  657. DoInformation(LoadStr(OPEN_TUNNEL), true);
  658. LogEvent(L"Opening tunnel.");
  659. OpenTunnel();
  660. Log->AddSeparator();
  661. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  662. DoInformation(LoadStr(USING_TUNNEL), false);
  663. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  664. (FSessionData->HostName, FSessionData->PortNumber)));
  665. }
  666. else
  667. {
  668. assert(FTunnelLocalPortNumber == 0);
  669. }
  670. if (FFileSystem == NULL)
  671. {
  672. if (SessionData->FSProtocol == fsFTP)
  673. {
  674. #ifdef NO_FILEZILLA
  675. LogEvent(L"FTP protocol is not supported by this build.");
  676. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  677. #else
  678. FFSProtocol = cfsFTP;
  679. FFileSystem = new TFTPFileSystem(this);
  680. FFileSystem->Open();
  681. Log->AddSeparator();
  682. LogEvent(L"Using FTP protocol.");
  683. #endif
  684. }
  685. else if (SessionData->FSProtocol == fsWebDAV)
  686. {
  687. FFSProtocol = cfsWebDAV;
  688. FFileSystem = new TWebDAVFileSystem(this);
  689. FFileSystem->Open();
  690. Log->AddSeparator();
  691. LogEvent(L"Using WebDAV protocol.");
  692. }
  693. else
  694. {
  695. assert(FSecureShell == NULL);
  696. try
  697. {
  698. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  699. try
  700. {
  701. if (FEnableSecureShellUsage)
  702. {
  703. // only on the first connect,
  704. // this is not ideal as it may prevent usage from being collected,
  705. // e.g. when connection fails on the first try
  706. FSecureShell->EnableUsage();
  707. FEnableSecureShellUsage = false;
  708. }
  709. // there will be only one channel in this session
  710. FSecureShell->Simple = true;
  711. FSecureShell->Open();
  712. }
  713. catch(Exception & E)
  714. {
  715. assert(!FSecureShell->Active);
  716. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  717. {
  718. // the only case where we expect this to happen
  719. assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  720. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  721. }
  722. else
  723. {
  724. throw;
  725. }
  726. }
  727. Log->AddSeparator();
  728. if ((SessionData->FSProtocol == fsSCPonly) ||
  729. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  730. {
  731. FFSProtocol = cfsSCP;
  732. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  733. FSecureShell = NULL; // ownership passed
  734. LogEvent(L"Using SCP protocol.");
  735. }
  736. else
  737. {
  738. FFSProtocol = cfsSFTP;
  739. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  740. FSecureShell = NULL; // ownership passed
  741. LogEvent(L"Using SFTP protocol.");
  742. }
  743. }
  744. __finally
  745. {
  746. delete FSecureShell;
  747. FSecureShell = NULL;
  748. }
  749. }
  750. }
  751. else
  752. {
  753. FFileSystem->Open();
  754. }
  755. }
  756. __finally
  757. {
  758. if (FSessionData->Tunnel)
  759. {
  760. FSessionData->RollbackTunnel();
  761. }
  762. }
  763. if (SessionData->CacheDirectoryChanges)
  764. {
  765. assert(FDirectoryChangesCache == NULL);
  766. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  767. Configuration->CacheDirectoryChangesMaxSize);
  768. if (SessionData->PreserveDirectoryChanges)
  769. {
  770. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  771. FDirectoryChangesCache);
  772. }
  773. }
  774. DoStartup();
  775. DoInformation(LoadStr(STATUS_READY), true);
  776. FStatus = ssOpened;
  777. }
  778. catch(...)
  779. {
  780. // rollback
  781. if (FDirectoryChangesCache != NULL)
  782. {
  783. delete FDirectoryChangesCache;
  784. FDirectoryChangesCache = NULL;
  785. }
  786. throw;
  787. }
  788. }
  789. __finally
  790. {
  791. DoInformation(L"", true, 0);
  792. }
  793. }
  794. catch(EFatal &)
  795. {
  796. throw;
  797. }
  798. catch(Exception & E)
  799. {
  800. // any exception while opening session is fatal
  801. FatalError(&E, L"");
  802. }
  803. }
  804. //---------------------------------------------------------------------------
  805. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  806. {
  807. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  808. bool Result = (Socket != INVALID_SOCKET);
  809. if (Result)
  810. {
  811. SOCKADDR_IN Address;
  812. memset(&Address, 0, sizeof(Address));
  813. Address.sin_family = AF_INET;
  814. Address.sin_port = htons(static_cast<short>(PortNumber));
  815. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  816. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  817. closesocket(Socket);
  818. }
  819. return Result;
  820. }
  821. //---------------------------------------------------------------------------
  822. void __fastcall TTerminal::OpenTunnel()
  823. {
  824. assert(FTunnelData == NULL);
  825. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  826. if (FTunnelLocalPortNumber == 0)
  827. {
  828. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  829. while (!IsListenerFree(FTunnelLocalPortNumber))
  830. {
  831. FTunnelLocalPortNumber++;
  832. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  833. {
  834. FTunnelLocalPortNumber = 0;
  835. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  836. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  837. }
  838. }
  839. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  840. }
  841. try
  842. {
  843. FTunnelData = new TSessionData(L"");
  844. FTunnelData->Assign(StoredSessions->DefaultSettings);
  845. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  846. FTunnelData->Tunnel = false;
  847. FTunnelData->HostName = FSessionData->TunnelHostName;
  848. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  849. FTunnelData->UserName = FSessionData->TunnelUserName;
  850. FTunnelData->Password = FSessionData->TunnelPassword;
  851. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  852. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  853. (FTunnelLocalPortNumber, FSessionData->HostName, FSessionData->PortNumber));
  854. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  855. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  856. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  857. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  858. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  859. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  860. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  861. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  862. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  863. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  864. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  865. FTunnelLog->Parent = FLog;
  866. FTunnelLog->Name = L"Tunnel";
  867. FTunnelLog->ReflectSettings();
  868. FTunnelUI = new TTunnelUI(this);
  869. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  870. FTunnelOpening = true;
  871. try
  872. {
  873. FTunnel->Open();
  874. }
  875. __finally
  876. {
  877. FTunnelOpening = false;
  878. }
  879. FTunnelThread = new TTunnelThread(FTunnel);
  880. }
  881. catch(...)
  882. {
  883. CloseTunnel();
  884. throw;
  885. }
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall TTerminal::CloseTunnel()
  889. {
  890. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  891. FTunnelError = FTunnel->LastTunnelError;
  892. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  893. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  894. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  895. SAFE_DESTROY(FTunnelData);
  896. FTunnelLocalPortNumber = 0;
  897. }
  898. //---------------------------------------------------------------------------
  899. void __fastcall TTerminal::Closed()
  900. {
  901. if (FTunnel != NULL)
  902. {
  903. CloseTunnel();
  904. }
  905. if (OnClose)
  906. {
  907. TCallbackGuard Guard(this);
  908. OnClose(this);
  909. Guard.Verify();
  910. }
  911. FStatus = ssClosed;
  912. }
  913. //---------------------------------------------------------------------------
  914. void __fastcall TTerminal::Reopen(int Params)
  915. {
  916. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  917. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  918. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  919. bool PrevReadDirectoryPending = FReadDirectoryPending;
  920. assert(!FSuspendTransaction);
  921. bool PrevAutoReadDirectory = FAutoReadDirectory;
  922. // here used to be a check for FExceptionOnFail being 0
  923. // but it can happen, e.g. when we are downloading file to execute it.
  924. // however I'm not sure why we mind having excaption-on-fail enabled here
  925. int PrevExceptionOnFail = FExceptionOnFail;
  926. try
  927. {
  928. FReadCurrentDirectoryPending = false;
  929. FReadDirectoryPending = false;
  930. FSuspendTransaction = true;
  931. FExceptionOnFail = 0;
  932. // typically, we avoid reading directory, when there is operation ongoing,
  933. // for file list which may reference files from current directory
  934. if (FLAGSET(Params, ropNoReadDirectory))
  935. {
  936. AutoReadDirectory = false;
  937. }
  938. // only peek, we may not be connected at all atm,
  939. // so make sure we do not try retrieving current directory from the server
  940. // (particularly with FTP)
  941. AnsiString ACurrentDirectory = PeekCurrentDirectory();
  942. if (!ACurrentDirectory.IsEmpty())
  943. {
  944. SessionData->RemoteDirectory = ACurrentDirectory;
  945. }
  946. if (SessionData->FSProtocol == fsSFTP)
  947. {
  948. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  949. }
  950. if (Active)
  951. {
  952. Close();
  953. }
  954. Open();
  955. }
  956. __finally
  957. {
  958. SessionData->RemoteDirectory = PrevRemoteDirectory;
  959. SessionData->FSProtocol = OrigFSProtocol;
  960. FAutoReadDirectory = PrevAutoReadDirectory;
  961. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  962. FReadDirectoryPending = PrevReadDirectoryPending;
  963. FSuspendTransaction = false;
  964. FExceptionOnFail = PrevExceptionOnFail;
  965. }
  966. }
  967. //---------------------------------------------------------------------------
  968. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  969. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  970. {
  971. bool AResult;
  972. TStrings * Prompts = new TStringList;
  973. TStrings * Results = new TStringList;
  974. try
  975. {
  976. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  977. Results->AddObject(Result, (TObject *)MaxLen);
  978. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  979. Result = Results->Strings[0];
  980. }
  981. __finally
  982. {
  983. delete Prompts;
  984. delete Results;
  985. }
  986. return AResult;
  987. }
  988. //---------------------------------------------------------------------------
  989. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  990. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  991. {
  992. // If PromptUser is overridden in descendant class, the overridden version
  993. // is not called when accessed via TSessionIU interface.
  994. // So this is workaround.
  995. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  996. }
  997. //---------------------------------------------------------------------------
  998. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  999. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1000. {
  1001. bool AResult = false;
  1002. bool PasswordPrompt =
  1003. (Prompts->Count == 1) && FLAGCLEAR(int(Prompts->Objects[0]), pupEcho) &&
  1004. ((Kind == pkPassword) || (Kind == pkPassphrase) || (Kind == pkKeybInteractive) ||
  1005. (Kind == pkTIS) || (Kind == pkCryptoCard));
  1006. if (PasswordPrompt && !Configuration->RememberPassword)
  1007. {
  1008. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1009. }
  1010. if (OnPromptUser != NULL)
  1011. {
  1012. TCallbackGuard Guard(this);
  1013. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1014. Guard.Verify();
  1015. }
  1016. if (AResult && PasswordPrompt &&
  1017. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1018. {
  1019. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1020. if (FTunnelOpening)
  1021. {
  1022. FTunnelPassword = EncryptedPassword;
  1023. }
  1024. else
  1025. {
  1026. FPassword = EncryptedPassword;
  1027. }
  1028. }
  1029. return AResult;
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1033. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1034. TQueryType QueryType)
  1035. {
  1036. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1037. unsigned int Answer = AbortAnswer(Answers);
  1038. if (FOnQueryUser)
  1039. {
  1040. TCallbackGuard Guard(this);
  1041. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1042. Guard.Verify();
  1043. }
  1044. return Answer;
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1048. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1049. TQueryType QueryType)
  1050. {
  1051. unsigned int Result;
  1052. TStrings * MoreMessages = new TStringList();
  1053. try
  1054. {
  1055. if (!E->Message.IsEmpty() && !Query.IsEmpty())
  1056. {
  1057. MoreMessages->Add(E->Message);
  1058. }
  1059. ExtException * EE = dynamic_cast<ExtException*>(E);
  1060. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1061. {
  1062. MoreMessages->AddStrings(EE->MoreMessages);
  1063. }
  1064. Result = QueryUser(!Query.IsEmpty() ? Query : UnicodeString(E->Message),
  1065. MoreMessages->Count ? MoreMessages : NULL,
  1066. Answers, Params, QueryType);
  1067. }
  1068. __finally
  1069. {
  1070. delete MoreMessages;
  1071. }
  1072. return Result;
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1076. {
  1077. if (OnDisplayBanner != NULL)
  1078. {
  1079. if (Configuration->ForceBanners ||
  1080. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1081. {
  1082. bool NeverShowAgain = false;
  1083. int Options =
  1084. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1085. TCallbackGuard Guard(this);
  1086. OnDisplayBanner(this, SessionData->SessionName, Banner,
  1087. NeverShowAgain, Options);
  1088. Guard.Verify();
  1089. if (!Configuration->ForceBanners && NeverShowAgain)
  1090. {
  1091. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1092. }
  1093. }
  1094. }
  1095. }
  1096. //---------------------------------------------------------------------------
  1097. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1098. {
  1099. Log->AddException(E);
  1100. if (OnShowExtendedException != NULL)
  1101. {
  1102. TCallbackGuard Guard(this);
  1103. // the event handler may destroy 'this' ...
  1104. OnShowExtendedException(this, E, NULL);
  1105. // .. hence guard is dismissed from destructor, to make following call no-op
  1106. Guard.Verify();
  1107. }
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1111. {
  1112. Log->AddException(E);
  1113. if (OnShowExtendedException != NULL)
  1114. {
  1115. OnShowExtendedException(this, E, NULL);
  1116. }
  1117. }
  1118. //---------------------------------------------------------------------------
  1119. void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
  1120. int Phase)
  1121. {
  1122. if (OnInformation)
  1123. {
  1124. TCallbackGuard Guard(this);
  1125. OnInformation(this, Str, Status, Phase);
  1126. Guard.Verify();
  1127. }
  1128. }
  1129. //---------------------------------------------------------------------------
  1130. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1131. {
  1132. DoInformation(Str, Status);
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData,
  1136. TCancelStatus & Cancel)
  1137. {
  1138. if (OnProgress != NULL)
  1139. {
  1140. TCallbackGuard Guard(this);
  1141. OnProgress(ProgressData, Cancel);
  1142. Guard.Verify();
  1143. }
  1144. }
  1145. //---------------------------------------------------------------------------
  1146. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1147. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1148. {
  1149. if (OnFinished != NULL)
  1150. {
  1151. TCallbackGuard Guard(this);
  1152. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1153. Guard.Verify();
  1154. }
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1158. {
  1159. assert(FFileSystem);
  1160. return FFileSystem->IsCapable(Capability);
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1164. {
  1165. return FFileSystem->AbsolutePath(Path, Local);
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1169. {
  1170. bool ChangesDirectory = false;
  1171. bool ModifiesFiles = false;
  1172. switch ((TFSCommand)Cmd) {
  1173. case fsChangeDirectory:
  1174. case fsHomeDirectory:
  1175. ChangesDirectory = true;
  1176. break;
  1177. case fsCopyToRemote:
  1178. case fsDeleteFile:
  1179. case fsRenameFile:
  1180. case fsMoveFile:
  1181. case fsCopyFile:
  1182. case fsCreateDirectory:
  1183. case fsChangeMode:
  1184. case fsChangeGroup:
  1185. case fsChangeOwner:
  1186. case fsChangeProperties:
  1187. ModifiesFiles = true;
  1188. break;
  1189. case fsAnyCommand:
  1190. ChangesDirectory = true;
  1191. ModifiesFiles = true;
  1192. break;
  1193. }
  1194. if (ChangesDirectory)
  1195. {
  1196. if (!InTransaction())
  1197. {
  1198. ReadCurrentDirectory();
  1199. if (AutoReadDirectory)
  1200. {
  1201. ReadDirectory(false);
  1202. }
  1203. }
  1204. else
  1205. {
  1206. FReadCurrentDirectoryPending = true;
  1207. if (AutoReadDirectory)
  1208. {
  1209. FReadDirectoryPending = true;
  1210. }
  1211. }
  1212. }
  1213. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  1214. {
  1215. if (!InTransaction())
  1216. {
  1217. ReadDirectory(true);
  1218. }
  1219. else
  1220. {
  1221. FReadDirectoryPending = true;
  1222. }
  1223. }
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  1227. {
  1228. TerminalError(NULL, Msg);
  1229. }
  1230. //---------------------------------------------------------------------------
  1231. void __fastcall TTerminal::TerminalError(Exception * E, UnicodeString Msg)
  1232. {
  1233. throw ETerminal(E, Msg);
  1234. }
  1235. //---------------------------------------------------------------------------
  1236. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  1237. {
  1238. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  1239. assert(Fatal != NULL);
  1240. bool Result;
  1241. if ((Fatal != NULL) && Fatal->ReopenQueried)
  1242. {
  1243. Result = false;
  1244. }
  1245. else
  1246. {
  1247. LogEvent(L"Connection was lost, asking what to do.");
  1248. TQueryParams Params(qpAllowContinueOnError);
  1249. Params.Timeout = Configuration->SessionReopenAuto;
  1250. Params.TimeoutAnswer = qaRetry;
  1251. TQueryButtonAlias Aliases[1];
  1252. Aliases[0].Button = qaRetry;
  1253. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  1254. Params.Aliases = Aliases;
  1255. Params.AliasesCount = LENOF(Aliases);
  1256. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  1257. if (Fatal != NULL)
  1258. {
  1259. Fatal->ReopenQueried = true;
  1260. }
  1261. }
  1262. return Result;
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  1266. TFileOperationProgressType * OperationProgress)
  1267. {
  1268. TSuspendFileOperationProgress Suspend(OperationProgress);
  1269. bool Result = DoQueryReopen(E);
  1270. if (Result)
  1271. {
  1272. TDateTime Start = Now();
  1273. do
  1274. {
  1275. try
  1276. {
  1277. Reopen(Params);
  1278. }
  1279. catch(Exception & E)
  1280. {
  1281. if (!Active)
  1282. {
  1283. Result =
  1284. ((Configuration->SessionReopenTimeout == 0) ||
  1285. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout)) &&
  1286. DoQueryReopen(&E);
  1287. }
  1288. else
  1289. {
  1290. throw;
  1291. }
  1292. }
  1293. }
  1294. while (!Active && Result);
  1295. }
  1296. return Result;
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  1300. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  1301. bool AllowSkip, UnicodeString SpecialRetry)
  1302. {
  1303. bool Result = false;
  1304. Log->AddException(&E);
  1305. unsigned int Answer;
  1306. bool SkipPossible = AllowSkip && (OperationProgress != NULL);
  1307. if (SkipPossible && OperationProgress->SkipToAll)
  1308. {
  1309. Answer = qaSkip;
  1310. }
  1311. else
  1312. {
  1313. int Answers = qaRetry | qaAbort |
  1314. FLAGMASK(SkipPossible, (qaSkip | qaAll)) |
  1315. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  1316. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  1317. TQueryButtonAlias Aliases[2];
  1318. int AliasCount = 0;
  1319. if (FLAGSET(Answers, qaAll))
  1320. {
  1321. Aliases[AliasCount].Button = qaAll;
  1322. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  1323. AliasCount++;
  1324. }
  1325. if (FLAGSET(Answers, qaYes))
  1326. {
  1327. Aliases[AliasCount].Button = qaYes;
  1328. Aliases[AliasCount].Alias = SpecialRetry;
  1329. AliasCount++;
  1330. }
  1331. if (AliasCount > 0)
  1332. {
  1333. Params.Aliases = Aliases;
  1334. Params.AliasesCount = AliasCount;
  1335. }
  1336. SUSPEND_OPERATION (
  1337. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1338. );
  1339. if (Answer == qaAll)
  1340. {
  1341. assert(OperationProgress != NULL);
  1342. OperationProgress->SkipToAll = true;
  1343. Answer = qaSkip;
  1344. }
  1345. if (Answer == qaYes)
  1346. {
  1347. Result = true;
  1348. Answer = qaRetry;
  1349. }
  1350. }
  1351. if (Answer != qaRetry)
  1352. {
  1353. if ((Answer == qaAbort) && (OperationProgress != NULL))
  1354. {
  1355. OperationProgress->Cancel = csCancel;
  1356. }
  1357. if (AllowSkip)
  1358. {
  1359. THROW_SKIP_FILE(&E, Message);
  1360. }
  1361. else
  1362. {
  1363. // this can happen only during file transfer with SCP
  1364. throw ExtException(&E, Message);
  1365. }
  1366. }
  1367. return Result;
  1368. }
  1369. //---------------------------------------------------------------------------
  1370. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1371. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1372. const UnicodeString Message, void * Param1, void * Param2)
  1373. {
  1374. assert(CallBackFunc);
  1375. int Result;
  1376. FILE_OPERATION_LOOP_EX
  1377. (
  1378. AllowSkip, Message,
  1379. Result = CallBackFunc(Param1, Param2);
  1380. );
  1381. return Result;
  1382. }
  1383. //---------------------------------------------------------------------------
  1384. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  1385. {
  1386. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  1387. {
  1388. if (Lock)
  1389. {
  1390. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1391. {
  1392. Path.Delete(1, FLockDirectory.Length());
  1393. if (Path.IsEmpty()) Path = L"/";
  1394. }
  1395. }
  1396. else
  1397. {
  1398. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1399. }
  1400. }
  1401. return Path;
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall TTerminal::ClearCaches()
  1405. {
  1406. FDirectoryCache->Clear();
  1407. if (FDirectoryChangesCache != NULL)
  1408. {
  1409. FDirectoryChangesCache->Clear();
  1410. }
  1411. if (FCommandSession != NULL)
  1412. {
  1413. FCommandSession->ClearCaches();
  1414. }
  1415. }
  1416. //---------------------------------------------------------------------------
  1417. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  1418. bool SubDirs)
  1419. {
  1420. FDirectoryCache->ClearFileList(Path, SubDirs);
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1424. {
  1425. FDirectoryCache->AddFileList(FileList);
  1426. }
  1427. //---------------------------------------------------------------------------
  1428. bool __fastcall TTerminal::DirectoryFileList(const UnicodeString Path,
  1429. TRemoteFileList *& FileList, bool CanLoad)
  1430. {
  1431. bool Result = false;
  1432. if (UnixComparePaths(FFiles->Directory, Path))
  1433. {
  1434. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1435. if (Result)
  1436. {
  1437. if (FileList == NULL)
  1438. {
  1439. FileList = new TRemoteFileList();
  1440. }
  1441. FFiles->DuplicateTo(FileList);
  1442. }
  1443. }
  1444. else
  1445. {
  1446. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1447. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1448. {
  1449. bool Created = (FileList == NULL);
  1450. if (Created)
  1451. {
  1452. FileList = new TRemoteFileList();
  1453. }
  1454. Result = FDirectoryCache->GetFileList(Path, FileList);
  1455. if (!Result && Created)
  1456. {
  1457. SAFE_DESTROY(FileList);
  1458. }
  1459. }
  1460. // do not attempt to load file list if there is cached version,
  1461. // only absence of cached version indicates that we consider
  1462. // the directory content obsolete
  1463. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1464. {
  1465. bool Created = (FileList == NULL);
  1466. if (Created)
  1467. {
  1468. FileList = new TRemoteFileList();
  1469. }
  1470. FileList->Directory = Path;
  1471. try
  1472. {
  1473. ReadDirectory(FileList);
  1474. Result = true;
  1475. }
  1476. catch(...)
  1477. {
  1478. if (Created)
  1479. {
  1480. SAFE_DESTROY(FileList);
  1481. }
  1482. throw;
  1483. }
  1484. }
  1485. }
  1486. return Result;
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  1490. {
  1491. assert(FFileSystem);
  1492. value = TranslateLockedPath(value, false);
  1493. if (value != FFileSystem->CurrentDirectory)
  1494. {
  1495. ChangeDirectory(value);
  1496. }
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  1500. {
  1501. if (FFileSystem != NULL)
  1502. {
  1503. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  1504. // to FCurrentDirectory, splitting the assignment to two statemets
  1505. // to locate the crash more closely
  1506. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  1507. FCurrentDirectory = CurrentDirectory;
  1508. if (FCurrentDirectory.IsEmpty())
  1509. {
  1510. ReadCurrentDirectory();
  1511. }
  1512. }
  1513. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1514. return Result;
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  1518. {
  1519. if (FFileSystem)
  1520. {
  1521. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1522. }
  1523. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1524. return Result;
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  1528. {
  1529. assert(FFileSystem);
  1530. LookupUsersGroups();
  1531. return &FGroups;
  1532. }
  1533. //---------------------------------------------------------------------------
  1534. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  1535. {
  1536. assert(FFileSystem);
  1537. LookupUsersGroups();
  1538. return &FUsers;
  1539. }
  1540. //---------------------------------------------------------------------------
  1541. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  1542. {
  1543. assert(FFileSystem);
  1544. LookupUsersGroups();
  1545. return &FMembership;
  1546. }
  1547. //---------------------------------------------------------------------------
  1548. UnicodeString __fastcall TTerminal::GetUserName() const
  1549. {
  1550. // in future might also be implemented to detect username similar to GetUserGroups
  1551. assert(FFileSystem != NULL);
  1552. UnicodeString Result = FFileSystem->GetUserName();
  1553. // Is empty also when stored username was used
  1554. if (Result.IsEmpty())
  1555. {
  1556. Result = SessionData->UserNameExpanded;
  1557. }
  1558. return Result;
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1562. {
  1563. return FDirectoryCache->IsEmpty &&
  1564. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1565. }
  1566. //---------------------------------------------------------------------------
  1567. void __fastcall TTerminal::DoInitializeLog()
  1568. {
  1569. if (FOnInitializeLog)
  1570. {
  1571. TCallbackGuard Guard(this);
  1572. FOnInitializeLog(this);
  1573. Guard.Verify();
  1574. }
  1575. }
  1576. //---------------------------------------------------------------------------
  1577. void __fastcall TTerminal::DoChangeDirectory()
  1578. {
  1579. if (FOnChangeDirectory)
  1580. {
  1581. TCallbackGuard Guard(this);
  1582. FOnChangeDirectory(this);
  1583. Guard.Verify();
  1584. }
  1585. }
  1586. //---------------------------------------------------------------------------
  1587. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1588. {
  1589. if (FOnReadDirectory)
  1590. {
  1591. TCallbackGuard Guard(this);
  1592. FOnReadDirectory(this, ReloadOnly);
  1593. Guard.Verify();
  1594. }
  1595. }
  1596. //---------------------------------------------------------------------------
  1597. void __fastcall TTerminal::DoStartReadDirectory()
  1598. {
  1599. if (FOnStartReadDirectory)
  1600. {
  1601. TCallbackGuard Guard(this);
  1602. FOnStartReadDirectory(this);
  1603. Guard.Verify();
  1604. }
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, bool & Cancel)
  1608. {
  1609. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1610. {
  1611. TCallbackGuard Guard(this);
  1612. FOnReadDirectoryProgress(this, Progress, Cancel);
  1613. Guard.Verify();
  1614. }
  1615. if (FOnFindingFile != NULL)
  1616. {
  1617. TCallbackGuard Guard(this);
  1618. FOnFindingFile(this, L"", Cancel);
  1619. Guard.Verify();
  1620. }
  1621. }
  1622. //---------------------------------------------------------------------------
  1623. bool __fastcall TTerminal::InTransaction()
  1624. {
  1625. return (FInTransaction > 0) && !FSuspendTransaction;
  1626. }
  1627. //---------------------------------------------------------------------------
  1628. void __fastcall TTerminal::BeginTransaction()
  1629. {
  1630. if (FInTransaction == 0)
  1631. {
  1632. FReadCurrentDirectoryPending = false;
  1633. FReadDirectoryPending = false;
  1634. }
  1635. FInTransaction++;
  1636. if (FCommandSession != NULL)
  1637. {
  1638. FCommandSession->BeginTransaction();
  1639. }
  1640. }
  1641. //---------------------------------------------------------------------------
  1642. void __fastcall TTerminal::EndTransaction()
  1643. {
  1644. if (FInTransaction == 0)
  1645. TerminalError(L"Can't end transaction, not in transaction");
  1646. assert(FInTransaction > 0);
  1647. FInTransaction--;
  1648. // it connection was closed due to fatal error during transaction, do nothing
  1649. if (Active)
  1650. {
  1651. if (FInTransaction == 0)
  1652. {
  1653. try
  1654. {
  1655. if (FReadCurrentDirectoryPending) ReadCurrentDirectory();
  1656. if (FReadDirectoryPending) ReadDirectory(!FReadCurrentDirectoryPending);
  1657. }
  1658. __finally
  1659. {
  1660. FReadCurrentDirectoryPending = false;
  1661. FReadDirectoryPending = false;
  1662. }
  1663. }
  1664. }
  1665. if (FCommandSession != NULL)
  1666. {
  1667. FCommandSession->EndTransaction();
  1668. }
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1672. {
  1673. if (value)
  1674. {
  1675. FExceptionOnFail++;
  1676. }
  1677. else
  1678. {
  1679. if (FExceptionOnFail == 0)
  1680. throw Exception(L"ExceptionOnFail is already zero.");
  1681. FExceptionOnFail--;
  1682. }
  1683. if (FCommandSession != NULL)
  1684. {
  1685. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  1686. }
  1687. }
  1688. //---------------------------------------------------------------------------
  1689. bool __fastcall TTerminal::GetExceptionOnFail() const
  1690. {
  1691. return (bool)(FExceptionOnFail > 0);
  1692. }
  1693. //---------------------------------------------------------------------------
  1694. void __fastcall TTerminal::FatalAbort()
  1695. {
  1696. FatalError(NULL, "");
  1697. }
  1698. //---------------------------------------------------------------------------
  1699. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg)
  1700. {
  1701. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  1702. if (Active || SecureShellActive)
  1703. {
  1704. // We log this instead of exception handler, because Close() would
  1705. // probably cause exception handler to loose pointer to TShellLog()
  1706. LogEvent(L"Attempt to close connection due to fatal exception:");
  1707. Log->Add(llException, Msg);
  1708. Log->AddException(E);
  1709. if (Active)
  1710. {
  1711. Close();
  1712. }
  1713. // this may happen if failure of authentication of SSH, owned by terminal yet
  1714. // (because the protocol was not decided yet), is detected by us (not by putty).
  1715. // e.g. not verified host key
  1716. if (SecureShellActive)
  1717. {
  1718. FSecureShell->Close();
  1719. }
  1720. }
  1721. if (FCallbackGuard != NULL)
  1722. {
  1723. FCallbackGuard->FatalError(E, Msg);
  1724. }
  1725. else
  1726. {
  1727. throw ESshFatal(E, Msg);
  1728. }
  1729. }
  1730. //---------------------------------------------------------------------------
  1731. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  1732. {
  1733. CommandError(E, Msg, 0);
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  1737. unsigned int Answers)
  1738. {
  1739. // may not be, particularly when TTerminal::Reopen is being called
  1740. // from within OnShowExtendedException handler
  1741. assert(FCallbackGuard == NULL);
  1742. unsigned int Result = 0;
  1743. if (E && E->InheritsFrom(__classid(EFatal)))
  1744. {
  1745. FatalError(E, Msg);
  1746. }
  1747. else if (E && E->InheritsFrom(__classid(EAbort)))
  1748. {
  1749. // resent EAbort exception
  1750. Abort();
  1751. }
  1752. else if (ExceptionOnFail)
  1753. {
  1754. throw ECommand(E, Msg);
  1755. }
  1756. else if (!Answers)
  1757. {
  1758. ECommand * ECmd = new ECommand(E, Msg);
  1759. try
  1760. {
  1761. HandleExtendedException(ECmd);
  1762. }
  1763. __finally
  1764. {
  1765. delete ECmd;
  1766. }
  1767. }
  1768. else
  1769. {
  1770. // small hack to enable "skip to all" for COMMAND_ERROR_ARI
  1771. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  1772. if (CanSkip && OperationProgress->SkipToAll)
  1773. {
  1774. Result = qaSkip;
  1775. }
  1776. else
  1777. {
  1778. TQueryParams Params(qpAllowContinueOnError);
  1779. TQueryButtonAlias Aliases[1];
  1780. if (CanSkip)
  1781. {
  1782. Aliases[0].Button = qaAll;
  1783. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  1784. Params.Aliases = Aliases;
  1785. Params.AliasesCount = LENOF(Aliases);
  1786. Answers |= qaAll;
  1787. }
  1788. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  1789. if (Result == qaAll)
  1790. {
  1791. assert(OperationProgress != NULL);
  1792. OperationProgress->SkipToAll = true;
  1793. Result = qaSkip;
  1794. }
  1795. }
  1796. }
  1797. return Result;
  1798. }
  1799. //---------------------------------------------------------------------------
  1800. bool __fastcall TTerminal::HandleException(Exception * E)
  1801. {
  1802. if (ExceptionOnFail)
  1803. {
  1804. return false;
  1805. }
  1806. else
  1807. {
  1808. Log->AddException(E);
  1809. return true;
  1810. }
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. void __fastcall TTerminal::CloseOnCompletion(TOnceDoneOperation Operation, const UnicodeString Message)
  1814. {
  1815. LogEvent(L"Closing session after completed operation (as requested by user)");
  1816. Close();
  1817. throw ESshTerminate(NULL,
  1818. Message.IsEmpty() ? UnicodeString(LoadStr(CLOSED_ON_COMPLETION)) : Message,
  1819. Operation);
  1820. }
  1821. //---------------------------------------------------------------------------
  1822. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  1823. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  1824. {
  1825. TBatchOverwrite Result;
  1826. if (Special && FLAGSET(Params, cpResume))
  1827. {
  1828. Result = boResume;
  1829. }
  1830. else if (FLAGSET(Params, cpAppend))
  1831. {
  1832. Result = boAppend;
  1833. }
  1834. else if (CopyParam->NewerOnly &&
  1835. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  1836. (OperationProgress->Side != osLocal)))
  1837. {
  1838. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  1839. Result = boOlder;
  1840. }
  1841. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  1842. {
  1843. // no way to change batch overwrite mode when overwrite confirmations are off
  1844. assert(OperationProgress->BatchOverwrite == boNo);
  1845. Result = boAll;
  1846. }
  1847. else
  1848. {
  1849. Result = OperationProgress->BatchOverwrite;
  1850. if (!Special &&
  1851. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  1852. {
  1853. Result = boNo;
  1854. }
  1855. }
  1856. return Result;
  1857. }
  1858. //---------------------------------------------------------------------------
  1859. bool __fastcall TTerminal::CheckRemoteFile(
  1860. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  1861. {
  1862. return (EffectiveBatchOverwrite(CopyParam, Params, OperationProgress, true) != boAll);
  1863. }
  1864. //---------------------------------------------------------------------------
  1865. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(const UnicodeString FileName,
  1866. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  1867. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1868. UnicodeString Message)
  1869. {
  1870. unsigned int Result;
  1871. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  1872. bool CanAlternateResume =
  1873. (FileParams != NULL) &&
  1874. (FileParams->DestSize < FileParams->SourceSize) &&
  1875. !OperationProgress->AsciiTransfer;
  1876. TBatchOverwrite BatchOverwrite = EffectiveBatchOverwrite(CopyParam, Params, OperationProgress, true);
  1877. bool Applicable = true;
  1878. switch (BatchOverwrite)
  1879. {
  1880. case boOlder:
  1881. Applicable = (FileParams != NULL);
  1882. break;
  1883. case boAlternateResume:
  1884. Applicable = CanAlternateResume;
  1885. break;
  1886. case boResume:
  1887. Applicable = CanAlternateResume;
  1888. break;
  1889. }
  1890. if (!Applicable)
  1891. {
  1892. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(CopyParam, Params, OperationProgress, false);
  1893. assert(BatchOverwrite != ABatchOverwrite);
  1894. BatchOverwrite = ABatchOverwrite;
  1895. }
  1896. if (BatchOverwrite == boNo)
  1897. {
  1898. if (Message.IsEmpty())
  1899. {
  1900. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  1901. REMOTE_FILE_OVERWRITE2), (FileName, FileName));
  1902. }
  1903. if (FileParams != NULL)
  1904. {
  1905. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  1906. FormatSize(FileParams->SourceSize),
  1907. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  1908. FormatSize(FileParams->DestSize),
  1909. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  1910. }
  1911. if (ALWAYS_TRUE(QueryParams->HelpKeyword.IsEmpty()))
  1912. {
  1913. QueryParams->HelpKeyword = L"ui_overwrite";
  1914. }
  1915. Result = QueryUser(Message, NULL, Answers, QueryParams);
  1916. switch (Result)
  1917. {
  1918. case qaNeverAskAgain:
  1919. Configuration->ConfirmOverwriting = false;
  1920. Result = qaYes;
  1921. break;
  1922. case qaYesToAll:
  1923. BatchOverwrite = boAll;
  1924. break;
  1925. case qaAll:
  1926. BatchOverwrite = boOlder;
  1927. break;
  1928. case qaNoToAll:
  1929. BatchOverwrite = boNone;
  1930. break;
  1931. }
  1932. // we user has not selected another batch overwrite mode,
  1933. // keep the current one. note that we may get here even
  1934. // when batch overwrite was selected already, but it could not be applied
  1935. // to current transfer (see condition above)
  1936. if (BatchOverwrite != boNo)
  1937. {
  1938. OperationProgress->BatchOverwrite = BatchOverwrite;
  1939. }
  1940. }
  1941. if (BatchOverwrite != boNo)
  1942. {
  1943. switch (BatchOverwrite)
  1944. {
  1945. case boAll:
  1946. Result = qaYes;
  1947. break;
  1948. case boNone:
  1949. Result = qaNo;
  1950. break;
  1951. case boOlder:
  1952. if (FileParams == NULL)
  1953. {
  1954. Result = qaNo;
  1955. }
  1956. else
  1957. {
  1958. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  1959. TDateTime ReducedSourceTimestamp =
  1960. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  1961. TDateTime ReducedDestTimestamp =
  1962. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  1963. Result =
  1964. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  1965. qaYes : qaNo;
  1966. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  1967. (StandardTimestamp(ReducedSourceTimestamp),
  1968. StandardTimestamp(ReducedDestTimestamp),
  1969. ((Result == qaYes) ? L"" : L" not"))));
  1970. }
  1971. break;
  1972. case boAlternateResume:
  1973. assert(CanAlternateResume);
  1974. Result = qaSkip; // ugh
  1975. break;
  1976. case boAppend:
  1977. Result = qaRetry;
  1978. break;
  1979. case boResume:
  1980. Result = qaRetry;
  1981. break;
  1982. }
  1983. }
  1984. return Result;
  1985. }
  1986. //---------------------------------------------------------------------------
  1987. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  1988. const UnicodeString FileName, bool ClearDirectoryChange)
  1989. {
  1990. UnicodeString ParentDirectory;
  1991. UnicodeString Directory;
  1992. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  1993. {
  1994. if ((File != NULL) && (File->Directory != NULL))
  1995. {
  1996. if (File->IsDirectory)
  1997. {
  1998. Directory = File->Directory->FullDirectory + File->FileName;
  1999. }
  2000. ParentDirectory = File->Directory->Directory;
  2001. }
  2002. else if (!FileName.IsEmpty())
  2003. {
  2004. ParentDirectory = UnixExtractFilePath(FileName);
  2005. if (ParentDirectory.IsEmpty())
  2006. {
  2007. ParentDirectory = CurrentDirectory;
  2008. }
  2009. // this case for scripting
  2010. if ((File != NULL) && File->IsDirectory)
  2011. {
  2012. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2013. UnixExtractFileName(File->FileName);
  2014. }
  2015. }
  2016. }
  2017. if (SessionData->CacheDirectories)
  2018. {
  2019. if (!Directory.IsEmpty())
  2020. {
  2021. DirectoryModified(Directory, true);
  2022. }
  2023. if (!ParentDirectory.IsEmpty())
  2024. {
  2025. DirectoryModified(ParentDirectory, false);
  2026. }
  2027. }
  2028. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2029. {
  2030. if (!Directory.IsEmpty())
  2031. {
  2032. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2033. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2034. }
  2035. }
  2036. }
  2037. //---------------------------------------------------------------------------
  2038. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2039. {
  2040. if (Path.IsEmpty())
  2041. {
  2042. ClearCachedFileList(CurrentDirectory, SubDirs);
  2043. }
  2044. else
  2045. {
  2046. ClearCachedFileList(Path, SubDirs);
  2047. }
  2048. }
  2049. //---------------------------------------------------------------------------
  2050. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  2051. {
  2052. AddCachedFileList(FileList);
  2053. }
  2054. //---------------------------------------------------------------------------
  2055. void __fastcall TTerminal::ReloadDirectory()
  2056. {
  2057. if (SessionData->CacheDirectories)
  2058. {
  2059. DirectoryModified(CurrentDirectory, false);
  2060. }
  2061. if (SessionData->CacheDirectoryChanges)
  2062. {
  2063. assert(FDirectoryChangesCache != NULL);
  2064. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  2065. }
  2066. ReadCurrentDirectory();
  2067. FReadCurrentDirectoryPending = false;
  2068. ReadDirectory(true);
  2069. FReadDirectoryPending = false;
  2070. }
  2071. //---------------------------------------------------------------------------
  2072. void __fastcall TTerminal::RefreshDirectory()
  2073. {
  2074. if (SessionData->CacheDirectories &&
  2075. FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  2076. {
  2077. // Second parameter was added to allow (rather force) using the cache.
  2078. // Before, the directory was reloaded always, it seems useless,
  2079. // has it any reason?
  2080. ReadDirectory(true, true);
  2081. FReadDirectoryPending = false;
  2082. }
  2083. }
  2084. //---------------------------------------------------------------------------
  2085. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  2086. {
  2087. // if filename doesn't contain path, we check for existence of file
  2088. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  2089. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  2090. {
  2091. TRemoteFile *File = FFiles->FindFile(FileName);
  2092. if (File)
  2093. {
  2094. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  2095. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  2096. }
  2097. }
  2098. }
  2099. //---------------------------------------------------------------------------
  2100. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  2101. {
  2102. if (Log->Logging)
  2103. {
  2104. Log->Add(llMessage, Str);
  2105. }
  2106. }
  2107. //---------------------------------------------------------------------------
  2108. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  2109. TFileOperationProgressType * OperationProgress, Exception * E)
  2110. {
  2111. // EScpSkipFile without "cancel" is file skip,
  2112. // and we do not want to record skipped actions.
  2113. // But EScpSkipFile with "cancel" is abort and we want to record that.
  2114. // Note that TSCPFileSystem modifies the logic of RollbackAction little bit.
  2115. if ((dynamic_cast<EScpSkipFile *>(E) != NULL) &&
  2116. ((OperationProgress == NULL) ||
  2117. (OperationProgress->Cancel == csContinue)))
  2118. {
  2119. Action.Cancel();
  2120. }
  2121. else
  2122. {
  2123. Action.Rollback(E);
  2124. }
  2125. }
  2126. //---------------------------------------------------------------------------
  2127. void __fastcall TTerminal::DoStartup()
  2128. {
  2129. LogEvent(L"Doing startup conversation with host.");
  2130. BeginTransaction();
  2131. try
  2132. {
  2133. DoInformation(LoadStr(STATUS_STARTUP), true);
  2134. // Make sure that directory would be loaded at last
  2135. FReadCurrentDirectoryPending = true;
  2136. FReadDirectoryPending = AutoReadDirectory;
  2137. FFileSystem->DoStartup();
  2138. LookupUsersGroups();
  2139. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  2140. if (!SessionData->RemoteDirectory.IsEmpty())
  2141. {
  2142. ChangeDirectory(SessionData->RemoteDirectory);
  2143. }
  2144. }
  2145. __finally
  2146. {
  2147. EndTransaction();
  2148. }
  2149. LogEvent(L"Startup conversation with host finished.");
  2150. }
  2151. //---------------------------------------------------------------------------
  2152. void __fastcall TTerminal::ReadCurrentDirectory()
  2153. {
  2154. assert(FFileSystem);
  2155. try
  2156. {
  2157. // reset flag is case we are called externally (like from console dialog)
  2158. FReadCurrentDirectoryPending = false;
  2159. LogEvent(L"Getting current directory name.");
  2160. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  2161. FFileSystem->ReadCurrentDirectory();
  2162. ReactOnCommand(fsCurrentDirectory);
  2163. if (SessionData->CacheDirectoryChanges)
  2164. {
  2165. assert(FDirectoryChangesCache != NULL);
  2166. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  2167. {
  2168. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  2169. FLastDirectoryChange, CurrentDirectory);
  2170. }
  2171. // not to broke the cache, if the next directory change would not
  2172. // be initialized by ChangeDirectory(), which sets it
  2173. // (HomeDirectory() particularly)
  2174. FLastDirectoryChange = L"";
  2175. }
  2176. if (OldDirectory.IsEmpty())
  2177. {
  2178. FLockDirectory = (SessionData->LockInHome ?
  2179. FFileSystem->CurrentDirectory : UnicodeString(L""));
  2180. }
  2181. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  2182. }
  2183. catch (Exception &E)
  2184. {
  2185. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  2186. }
  2187. }
  2188. //---------------------------------------------------------------------------
  2189. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  2190. {
  2191. bool LoadedFromCache = false;
  2192. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  2193. {
  2194. if (ReloadOnly && !ForceCache)
  2195. {
  2196. LogEvent(L"Cached directory not reloaded.");
  2197. }
  2198. else
  2199. {
  2200. DoStartReadDirectory();
  2201. try
  2202. {
  2203. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  2204. }
  2205. __finally
  2206. {
  2207. DoReadDirectory(ReloadOnly);
  2208. }
  2209. if (LoadedFromCache)
  2210. {
  2211. LogEvent(L"Directory content loaded from cache.");
  2212. }
  2213. else
  2214. {
  2215. LogEvent(L"Cached Directory content has been removed.");
  2216. }
  2217. }
  2218. }
  2219. if (!LoadedFromCache)
  2220. {
  2221. DoStartReadDirectory();
  2222. FReadingCurrentDirectory = true;
  2223. bool Cancel = false; // dummy
  2224. DoReadDirectoryProgress(0, Cancel);
  2225. try
  2226. {
  2227. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  2228. try
  2229. {
  2230. Files->Directory = CurrentDirectory;
  2231. CustomReadDirectory(Files);
  2232. }
  2233. __finally
  2234. {
  2235. DoReadDirectoryProgress(-1, Cancel);
  2236. FReadingCurrentDirectory = false;
  2237. TRemoteDirectory * OldFiles = FFiles;
  2238. FFiles = Files;
  2239. try
  2240. {
  2241. DoReadDirectory(ReloadOnly);
  2242. }
  2243. __finally
  2244. {
  2245. // delete only after loading new files to dir view,
  2246. // not to destroy the file objects that the view holds
  2247. // (can be issue in multi threaded environment, such as when the
  2248. // terminal is reconnecting in the terminal thread)
  2249. delete OldFiles;
  2250. }
  2251. if (Active)
  2252. {
  2253. if (SessionData->CacheDirectories)
  2254. {
  2255. DirectoryLoaded(FFiles);
  2256. }
  2257. }
  2258. }
  2259. }
  2260. catch (Exception &E)
  2261. {
  2262. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  2263. }
  2264. }
  2265. }
  2266. //---------------------------------------------------------------------------
  2267. void __fastcall TTerminal::LogFile(TRemoteFile * File)
  2268. {
  2269. LogEvent(FORMAT(L"%s;%s;%d;%s;%s;%s;%s;%d",
  2270. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification),
  2271. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  2272. File->Attr)));
  2273. }
  2274. //---------------------------------------------------------------------------
  2275. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2276. {
  2277. assert(FileList);
  2278. assert(FFileSystem);
  2279. FFileSystem->ReadDirectory(FileList);
  2280. if (Log->Logging)
  2281. {
  2282. for (int Index = 0; Index < FileList->Count; Index++)
  2283. {
  2284. LogFile(FileList->Files[Index]);
  2285. }
  2286. }
  2287. ReactOnCommand(fsListDirectory);
  2288. }
  2289. //---------------------------------------------------------------------------
  2290. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2291. {
  2292. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2293. TRemoteFileList * FileList = NULL;
  2294. try
  2295. {
  2296. FileList = DoReadDirectoryListing(Directory, false);
  2297. if (FileList != NULL)
  2298. {
  2299. int Index = 0;
  2300. while (Index < FileList->Count)
  2301. {
  2302. TRemoteFile * File = FileList->Files[Index];
  2303. if (!Mask.Matches(File->FileName))
  2304. {
  2305. FileList->Delete(Index);
  2306. }
  2307. else
  2308. {
  2309. Index++;
  2310. }
  2311. }
  2312. Action.FileList(FileList);
  2313. }
  2314. }
  2315. catch(Exception & E)
  2316. {
  2317. COMMAND_ERROR_ARI_ACTION
  2318. (
  2319. L"",
  2320. FileList = ReadDirectoryListing(Directory, Mask),
  2321. Action
  2322. );
  2323. }
  2324. return FileList;
  2325. }
  2326. //---------------------------------------------------------------------------
  2327. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2328. {
  2329. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2330. TRemoteFile * File = NULL;
  2331. try
  2332. {
  2333. // reset caches
  2334. AnnounceFileListOperation();
  2335. ReadFile(Path, File);
  2336. Action.File(File);
  2337. }
  2338. catch(Exception & E)
  2339. {
  2340. COMMAND_ERROR_ARI_ACTION
  2341. (
  2342. L"",
  2343. File = ReadFileListing(Path),
  2344. Action
  2345. );
  2346. }
  2347. return File;
  2348. }
  2349. //---------------------------------------------------------------------------
  2350. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2351. {
  2352. TRemoteFileList * FileList = NULL;
  2353. try
  2354. {
  2355. FileList = DoReadDirectoryListing(Directory, UseCache);
  2356. }
  2357. catch(Exception & E)
  2358. {
  2359. COMMAND_ERROR_ARI
  2360. (
  2361. L"",
  2362. FileList = CustomReadDirectoryListing(Directory, UseCache);
  2363. );
  2364. }
  2365. return FileList;
  2366. }
  2367. //---------------------------------------------------------------------------
  2368. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2369. {
  2370. TRemoteFileList * FileList = new TRemoteFileList();
  2371. try
  2372. {
  2373. bool Cache = UseCache && SessionData->CacheDirectories;
  2374. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2375. if (LoadedFromCache)
  2376. {
  2377. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2378. }
  2379. if (!LoadedFromCache)
  2380. {
  2381. FileList->Directory = Directory;
  2382. ExceptionOnFail = true;
  2383. try
  2384. {
  2385. ReadDirectory(FileList);
  2386. }
  2387. __finally
  2388. {
  2389. ExceptionOnFail = false;
  2390. }
  2391. if (Cache)
  2392. {
  2393. AddCachedFileList(FileList);
  2394. }
  2395. }
  2396. }
  2397. catch(...)
  2398. {
  2399. delete FileList;
  2400. throw;
  2401. }
  2402. return FileList;
  2403. }
  2404. //---------------------------------------------------------------------------
  2405. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2406. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2407. {
  2408. TRemoteFileList * FileList = NULL;
  2409. if (IgnoreErrors)
  2410. {
  2411. ExceptionOnFail = true;
  2412. try
  2413. {
  2414. try
  2415. {
  2416. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2417. }
  2418. catch(...)
  2419. {
  2420. if (!Active)
  2421. {
  2422. throw;
  2423. }
  2424. }
  2425. }
  2426. __finally
  2427. {
  2428. ExceptionOnFail = false;
  2429. }
  2430. }
  2431. else
  2432. {
  2433. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2434. }
  2435. // skip if directory listing fails and user selects "skip"
  2436. if (FileList)
  2437. {
  2438. try
  2439. {
  2440. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2441. TRemoteFile * File;
  2442. for (int Index = 0; Index < FileList->Count; Index++)
  2443. {
  2444. File = FileList->Files[Index];
  2445. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2446. {
  2447. CallBackFunc(Directory + File->FileName, File, Param);
  2448. }
  2449. }
  2450. }
  2451. __finally
  2452. {
  2453. delete FileList;
  2454. }
  2455. }
  2456. }
  2457. //---------------------------------------------------------------------------
  2458. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2459. {
  2460. try
  2461. {
  2462. CustomReadDirectory(FileList);
  2463. }
  2464. catch (Exception &E)
  2465. {
  2466. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2467. }
  2468. }
  2469. //---------------------------------------------------------------------------
  2470. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2471. TRemoteFile *& File)
  2472. {
  2473. assert(FFileSystem);
  2474. try
  2475. {
  2476. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2477. FFileSystem->ReadSymlink(SymlinkFile, File);
  2478. ReactOnCommand(fsReadSymlink);
  2479. }
  2480. catch (Exception &E)
  2481. {
  2482. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2483. }
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2487. TRemoteFile *& File)
  2488. {
  2489. assert(FFileSystem);
  2490. File = NULL;
  2491. try
  2492. {
  2493. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2494. FFileSystem->ReadFile(FileName, File);
  2495. ReactOnCommand(fsListFile);
  2496. LogFile(File);
  2497. }
  2498. catch (Exception &E)
  2499. {
  2500. if (File) delete File;
  2501. File = NULL;
  2502. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2503. }
  2504. }
  2505. //---------------------------------------------------------------------------
  2506. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2507. {
  2508. bool Result;
  2509. TRemoteFile * File = NULL;
  2510. try
  2511. {
  2512. ExceptionOnFail = true;
  2513. try
  2514. {
  2515. ReadFile(FileName, File);
  2516. }
  2517. __finally
  2518. {
  2519. ExceptionOnFail = false;
  2520. }
  2521. if (AFile != NULL)
  2522. {
  2523. *AFile = File;
  2524. }
  2525. else
  2526. {
  2527. delete File;
  2528. }
  2529. Result = true;
  2530. }
  2531. catch(...)
  2532. {
  2533. if (Active)
  2534. {
  2535. Result = false;
  2536. }
  2537. else
  2538. {
  2539. throw;
  2540. }
  2541. }
  2542. return Result;
  2543. }
  2544. //---------------------------------------------------------------------------
  2545. void __fastcall TTerminal::AnnounceFileListOperation()
  2546. {
  2547. FFileSystem->AnnounceFileListOperation();
  2548. }
  2549. //---------------------------------------------------------------------------
  2550. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2551. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2552. TOperationSide Side, bool Ex)
  2553. {
  2554. assert(FFileSystem);
  2555. assert(FileList);
  2556. bool Result = false;
  2557. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2558. try
  2559. {
  2560. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2561. Progress.Start(Operation, Side, FileList->Count);
  2562. FOperationProgress = &Progress;
  2563. try
  2564. {
  2565. if (Side == osRemote)
  2566. {
  2567. BeginTransaction();
  2568. }
  2569. try
  2570. {
  2571. int Index = 0;
  2572. UnicodeString FileName;
  2573. bool Success;
  2574. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  2575. {
  2576. FileName = FileList->Strings[Index];
  2577. try
  2578. {
  2579. try
  2580. {
  2581. Success = false;
  2582. if (!Ex)
  2583. {
  2584. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  2585. }
  2586. else
  2587. {
  2588. // not used anymore
  2589. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  2590. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  2591. }
  2592. Success = true;
  2593. }
  2594. __finally
  2595. {
  2596. Progress.Finish(FileName, Success, OnceDoneOperation);
  2597. }
  2598. }
  2599. catch(EScpSkipFile & E)
  2600. {
  2601. SUSPEND_OPERATION (
  2602. if (!HandleException(&E)) throw;
  2603. );
  2604. }
  2605. Index++;
  2606. }
  2607. }
  2608. __finally
  2609. {
  2610. if (Side == osRemote)
  2611. {
  2612. EndTransaction();
  2613. }
  2614. }
  2615. if (Progress.Cancel == csContinue)
  2616. {
  2617. Result = true;
  2618. }
  2619. }
  2620. __finally
  2621. {
  2622. FOperationProgress = NULL;
  2623. Progress.Stop();
  2624. }
  2625. }
  2626. catch (...)
  2627. {
  2628. OnceDoneOperation = odoIdle;
  2629. // this was missing here. was it by purpose?
  2630. // without it any error message is lost
  2631. throw;
  2632. }
  2633. if (OnceDoneOperation != odoIdle)
  2634. {
  2635. CloseOnCompletion(OnceDoneOperation);
  2636. }
  2637. return Result;
  2638. }
  2639. //---------------------------------------------------------------------------
  2640. // not used anymore
  2641. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  2642. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  2643. {
  2644. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  2645. Param, Side, true);
  2646. }
  2647. //---------------------------------------------------------------------------
  2648. TStrings * __fastcall TTerminal::GetFixedPaths()
  2649. {
  2650. assert(FFileSystem != NULL);
  2651. return FFileSystem->GetFixedPaths();
  2652. }
  2653. //---------------------------------------------------------------------------
  2654. bool __fastcall TTerminal::GetResolvingSymlinks()
  2655. {
  2656. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  2657. }
  2658. //---------------------------------------------------------------------------
  2659. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  2660. {
  2661. TUsableCopyParamAttrs Result;
  2662. Result.General =
  2663. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  2664. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  2665. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  2666. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  2667. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors);
  2668. Result.Download = Result.General | cpaNoClearArchive | cpaNoRights |
  2669. cpaNoIgnorePermErrors;
  2670. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  2671. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  2672. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  2673. return Result;
  2674. }
  2675. //---------------------------------------------------------------------------
  2676. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  2677. {
  2678. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  2679. if (Result)
  2680. {
  2681. UnicodeString Path = UnixExtractFilePath(FileName);
  2682. if (Path.IsEmpty())
  2683. {
  2684. Path = CurrentDirectory;
  2685. }
  2686. Result = UnixComparePaths(Path, SessionData->RecycleBinPath);
  2687. }
  2688. return Result;
  2689. }
  2690. //---------------------------------------------------------------------------
  2691. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  2692. const TRemoteFile * File)
  2693. {
  2694. if (FileName.IsEmpty())
  2695. {
  2696. assert(File != NULL);
  2697. FileName = File->FileName;
  2698. }
  2699. if (!IsRecycledFile(FileName))
  2700. {
  2701. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  2702. (FileName, SessionData->RecycleBinPath)));
  2703. TMoveFileParams Params;
  2704. Params.Target = SessionData->RecycleBinPath;
  2705. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  2706. MoveFile(FileName, File, &Params);
  2707. }
  2708. }
  2709. //---------------------------------------------------------------------------
  2710. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  2711. const TRemoteFile * File, void * AParams)
  2712. {
  2713. if (FileName.IsEmpty() && File)
  2714. {
  2715. FileName = File->FileName;
  2716. }
  2717. if (OperationProgress && OperationProgress->Operation == foDelete)
  2718. {
  2719. if (OperationProgress->Cancel != csContinue) Abort();
  2720. OperationProgress->SetFile(FileName);
  2721. }
  2722. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  2723. bool Recycle =
  2724. FLAGCLEAR(Params, dfForceDelete) &&
  2725. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  2726. !SessionData->RecycleBinPath.IsEmpty();
  2727. if (Recycle && !IsRecycledFile(FileName))
  2728. {
  2729. RecycleFile(FileName, File);
  2730. }
  2731. else
  2732. {
  2733. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  2734. if (File) FileModified(File, FileName, true);
  2735. DoDeleteFile(FileName, File, Params);
  2736. ReactOnCommand(fsDeleteFile);
  2737. }
  2738. }
  2739. //---------------------------------------------------------------------------
  2740. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  2741. const TRemoteFile * File, int Params)
  2742. {
  2743. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  2744. try
  2745. {
  2746. assert(FFileSystem);
  2747. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  2748. FFileSystem->DeleteFile(FileName, File, Params, Action);
  2749. }
  2750. catch(Exception & E)
  2751. {
  2752. COMMAND_ERROR_ARI_ACTION
  2753. (
  2754. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  2755. DoDeleteFile(FileName, File, Params),
  2756. Action
  2757. );
  2758. }
  2759. }
  2760. //---------------------------------------------------------------------------
  2761. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  2762. {
  2763. // TODO: avoid resolving symlinks while reading subdirectories.
  2764. // Resolving does not work anyway for relative symlinks in subdirectories
  2765. // (at least for SFTP).
  2766. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  2767. }
  2768. //---------------------------------------------------------------------------
  2769. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  2770. const TRemoteFile * /*File*/, void * Params)
  2771. {
  2772. if (OnDeleteLocalFile == NULL)
  2773. {
  2774. if (!RecursiveDeleteFile(FileName, false))
  2775. {
  2776. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2777. }
  2778. }
  2779. else
  2780. {
  2781. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  2782. }
  2783. }
  2784. //---------------------------------------------------------------------------
  2785. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  2786. {
  2787. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  2788. }
  2789. //---------------------------------------------------------------------------
  2790. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  2791. const TRemoteFile * File, void * AParams)
  2792. {
  2793. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  2794. if (FileName.IsEmpty() && File)
  2795. {
  2796. FileName = File->FileName;
  2797. }
  2798. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  2799. {
  2800. if (OperationProgress->Cancel != csContinue) Abort();
  2801. OperationProgress->SetFile(FileName);
  2802. }
  2803. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  2804. (Params->Command, Params->Params, FileName)));
  2805. if (File) FileModified(File, FileName);
  2806. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  2807. Params->OutputEvent);
  2808. ReactOnCommand(fsAnyCommand);
  2809. }
  2810. //---------------------------------------------------------------------------
  2811. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  2812. const TRemoteFile * File, UnicodeString Command, int Params,
  2813. TCaptureOutputEvent OutputEvent)
  2814. {
  2815. try
  2816. {
  2817. if (IsCapable[fcAnyCommand])
  2818. {
  2819. assert(FFileSystem);
  2820. assert(fcShellAnyCommand);
  2821. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  2822. }
  2823. else
  2824. {
  2825. assert(CommandSessionOpened);
  2826. assert(FCommandSession->FSProtocol == cfsSCP);
  2827. LogEvent(L"Executing custom command on command session.");
  2828. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  2829. {
  2830. FCommandSession->CurrentDirectory = CurrentDirectory;
  2831. // We are likely in transaction, so ReadCurrentDirectory won't get called
  2832. // until transaction ends. But we need to know CurrentDirectory to
  2833. // expand !/ pattern.
  2834. // Doing this only, when current directory of the main and secondary shell differs,
  2835. // what would be the case before the first file in transation.
  2836. // Otherwise we would be reading pwd before every time as the
  2837. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  2838. if (FCommandSession->FReadCurrentDirectoryPending)
  2839. {
  2840. FCommandSession->ReadCurrentDirectory();
  2841. }
  2842. }
  2843. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  2844. Params, OutputEvent);
  2845. }
  2846. }
  2847. catch(Exception & E)
  2848. {
  2849. COMMAND_ERROR_ARI
  2850. (
  2851. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  2852. DoCustomCommandOnFile(FileName, File, Command, Params, OutputEvent)
  2853. );
  2854. }
  2855. }
  2856. //---------------------------------------------------------------------------
  2857. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  2858. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  2859. {
  2860. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  2861. {
  2862. TCustomCommandParams AParams;
  2863. AParams.Command = Command;
  2864. AParams.Params = Params;
  2865. AParams.OutputEvent = OutputEvent;
  2866. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  2867. }
  2868. else
  2869. {
  2870. UnicodeString FileList;
  2871. for (int i = 0; i < Files->Count; i++)
  2872. {
  2873. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  2874. bool Dir = File->IsDirectory && !File->IsSymLink;
  2875. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  2876. {
  2877. if (!FileList.IsEmpty())
  2878. {
  2879. FileList += L" ";
  2880. }
  2881. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  2882. }
  2883. }
  2884. TCustomCommandData Data(this);
  2885. UnicodeString Cmd =
  2886. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  2887. Complete(Command, true);
  2888. DoAnyCommand(Cmd, OutputEvent, NULL);
  2889. }
  2890. }
  2891. //---------------------------------------------------------------------------
  2892. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  2893. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  2894. {
  2895. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  2896. assert(RProperties && !RProperties->Valid.Empty());
  2897. if (FileName.IsEmpty() && File)
  2898. {
  2899. FileName = File->FileName;
  2900. }
  2901. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  2902. {
  2903. if (OperationProgress->Cancel != csContinue) Abort();
  2904. OperationProgress->SetFile(FileName);
  2905. }
  2906. if (Log->Logging)
  2907. {
  2908. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  2909. (FileName, BooleanToEngStr(RProperties->Recursive))));
  2910. if (RProperties->Valid.Contains(vpRights))
  2911. {
  2912. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  2913. }
  2914. if (RProperties->Valid.Contains(vpGroup))
  2915. {
  2916. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  2917. }
  2918. if (RProperties->Valid.Contains(vpOwner))
  2919. {
  2920. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  2921. }
  2922. if (RProperties->Valid.Contains(vpModification))
  2923. {
  2924. LogEvent(FORMAT(L" - modification: \"%s\"",
  2925. (FormatDateTime(L"dddddd tt",
  2926. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  2927. }
  2928. if (RProperties->Valid.Contains(vpLastAccess))
  2929. {
  2930. LogEvent(FORMAT(L" - last access: \"%s\"",
  2931. (FormatDateTime(L"dddddd tt",
  2932. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  2933. }
  2934. }
  2935. FileModified(File, FileName);
  2936. DoChangeFileProperties(FileName, File, RProperties);
  2937. ReactOnCommand(fsChangeProperties);
  2938. }
  2939. //---------------------------------------------------------------------------
  2940. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  2941. const TRemoteFile * File, const TRemoteProperties * Properties)
  2942. {
  2943. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  2944. try
  2945. {
  2946. assert(FFileSystem);
  2947. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  2948. }
  2949. catch(Exception & E)
  2950. {
  2951. COMMAND_ERROR_ARI_ACTION
  2952. (
  2953. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  2954. DoChangeFileProperties(FileName, File, Properties),
  2955. Action
  2956. );
  2957. }
  2958. }
  2959. //---------------------------------------------------------------------------
  2960. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  2961. const TRemoteProperties * Properties)
  2962. {
  2963. AnnounceFileListOperation();
  2964. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  2965. }
  2966. //---------------------------------------------------------------------------
  2967. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  2968. {
  2969. bool Result =
  2970. IsCapable[fcLoadingAdditionalProperties] &&
  2971. FFileSystem->LoadFilesProperties(FileList);
  2972. if (Result && SessionData->CacheDirectories &&
  2973. (FileList->Count > 0) &&
  2974. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  2975. {
  2976. AddCachedFileList(FFiles);
  2977. }
  2978. return Result;
  2979. }
  2980. //---------------------------------------------------------------------------
  2981. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  2982. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  2983. {
  2984. assert(Param);
  2985. assert(File);
  2986. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  2987. if (FileName.IsEmpty())
  2988. {
  2989. FileName = File->FileName;
  2990. }
  2991. bool AllowTransfer = (AParams->CopyParam == NULL);
  2992. if (!AllowTransfer)
  2993. {
  2994. TFileMasks::TParams MaskParams;
  2995. MaskParams.Size = File->Size;
  2996. MaskParams.Modification = File->Modification;
  2997. AllowTransfer = AParams->CopyParam->AllowTransfer(
  2998. UnixExcludeTrailingBackslash(File->FullFileName), osRemote, File->IsDirectory,
  2999. MaskParams);
  3000. }
  3001. if (AllowTransfer)
  3002. {
  3003. if (File->IsDirectory)
  3004. {
  3005. if (!File->IsSymLink)
  3006. {
  3007. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3008. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3009. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3010. }
  3011. else
  3012. {
  3013. AParams->Size += File->Size;
  3014. }
  3015. if (AParams->Stats != NULL)
  3016. {
  3017. AParams->Stats->Directories++;
  3018. }
  3019. }
  3020. else
  3021. {
  3022. AParams->Size += File->Size;
  3023. if (AParams->Stats != NULL)
  3024. {
  3025. AParams->Stats->Files++;
  3026. }
  3027. }
  3028. if ((AParams->Stats != NULL) && File->IsSymLink)
  3029. {
  3030. AParams->Stats->SymLinks++;
  3031. }
  3032. }
  3033. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  3034. {
  3035. if (OperationProgress->Cancel != csContinue) Abort();
  3036. OperationProgress->SetFile(FileName);
  3037. }
  3038. }
  3039. //---------------------------------------------------------------------------
  3040. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3041. const TRemoteFile * File, TCalculateSizeParams * Params)
  3042. {
  3043. try
  3044. {
  3045. ProcessDirectory(FileName, CalculateFileSize, Params);
  3046. }
  3047. catch(Exception & E)
  3048. {
  3049. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3050. {
  3051. COMMAND_ERROR_ARI
  3052. (
  3053. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  3054. DoCalculateDirectorySize(FileName, File, Params)
  3055. );
  3056. }
  3057. }
  3058. }
  3059. //---------------------------------------------------------------------------
  3060. void __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3061. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3062. TCalculateSizeStats * Stats)
  3063. {
  3064. TCalculateSizeParams Param;
  3065. Param.Size = 0;
  3066. Param.Params = Params;
  3067. Param.CopyParam = CopyParam;
  3068. Param.Stats = Stats;
  3069. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3070. Size = Param.Size;
  3071. }
  3072. //---------------------------------------------------------------------------
  3073. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3074. TStrings * FileList, TStrings * Checksums,
  3075. TCalculatedChecksumEvent OnCalculatedChecksum)
  3076. {
  3077. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3078. }
  3079. //---------------------------------------------------------------------------
  3080. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3081. const UnicodeString NewName)
  3082. {
  3083. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3084. DoRenameFile(FileName, NewName, false);
  3085. ReactOnCommand(fsRenameFile);
  3086. }
  3087. //---------------------------------------------------------------------------
  3088. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3089. const UnicodeString NewName, bool CheckExistence)
  3090. {
  3091. assert(File && File->Directory == FFiles);
  3092. bool Proceed = true;
  3093. // if filename doesn't contain path, we check for existence of file
  3094. if ((File->FileName != NewName) && CheckExistence &&
  3095. Configuration->ConfirmOverwriting &&
  3096. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  3097. {
  3098. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3099. if (DuplicateFile)
  3100. {
  3101. UnicodeString QuestionFmt;
  3102. if (DuplicateFile->IsDirectory)
  3103. {
  3104. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3105. }
  3106. else
  3107. {
  3108. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3109. }
  3110. TQueryParams Params(qpNeverAskAgainCheck);
  3111. unsigned int Result = QueryUser(FORMAT(QuestionFmt, (NewName)), NULL,
  3112. qaYes | qaNo, &Params);
  3113. if (Result == qaNeverAskAgain)
  3114. {
  3115. Proceed = true;
  3116. Configuration->ConfirmOverwriting = false;
  3117. }
  3118. else
  3119. {
  3120. Proceed = (Result == qaYes);
  3121. }
  3122. }
  3123. }
  3124. if (Proceed)
  3125. {
  3126. FileModified(File, File->FileName);
  3127. RenameFile(File->FileName, NewName);
  3128. }
  3129. }
  3130. //---------------------------------------------------------------------------
  3131. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3132. const UnicodeString NewName, bool Move)
  3133. {
  3134. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3135. try
  3136. {
  3137. assert(FFileSystem);
  3138. FFileSystem->RenameFile(FileName, NewName);
  3139. }
  3140. catch(Exception & E)
  3141. {
  3142. COMMAND_ERROR_ARI_ACTION
  3143. (
  3144. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  3145. DoRenameFile(FileName, NewName, Move),
  3146. Action
  3147. );
  3148. }
  3149. }
  3150. //---------------------------------------------------------------------------
  3151. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3152. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3153. {
  3154. if (OperationProgress &&
  3155. ((OperationProgress->Operation == foRemoteMove) ||
  3156. (OperationProgress->Operation == foDelete)))
  3157. {
  3158. if (OperationProgress->Cancel != csContinue) Abort();
  3159. OperationProgress->SetFile(FileName);
  3160. }
  3161. assert(Param != NULL);
  3162. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3163. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3164. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3165. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3166. FileModified(File, FileName);
  3167. DoRenameFile(FileName, NewName, true);
  3168. ReactOnCommand(fsMoveFile);
  3169. }
  3170. //---------------------------------------------------------------------------
  3171. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3172. const UnicodeString FileMask)
  3173. {
  3174. TMoveFileParams Params;
  3175. Params.Target = Target;
  3176. Params.FileMask = FileMask;
  3177. DirectoryModified(Target, true);
  3178. bool Result;
  3179. BeginTransaction();
  3180. try
  3181. {
  3182. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3183. }
  3184. __finally
  3185. {
  3186. if (Active)
  3187. {
  3188. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3189. bool PossiblyMoved = false;
  3190. // check if we was moving current directory.
  3191. // this is just optimization to avoid checking existence of current
  3192. // directory after each move operation.
  3193. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3194. {
  3195. const TRemoteFile * File =
  3196. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3197. // File can be NULL, and filename may not be full path,
  3198. // but currently this is the only way we can move (at least in GUI)
  3199. // current directory
  3200. if ((File != NULL) &&
  3201. File->IsDirectory &&
  3202. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3203. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3204. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3205. {
  3206. PossiblyMoved = true;
  3207. }
  3208. }
  3209. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3210. {
  3211. UnicodeString NearestExisting = CurrentDirectory;
  3212. do
  3213. {
  3214. NearestExisting = UnixExtractFileDir(NearestExisting);
  3215. }
  3216. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3217. ChangeDirectory(NearestExisting);
  3218. }
  3219. }
  3220. EndTransaction();
  3221. }
  3222. return Result;
  3223. }
  3224. //---------------------------------------------------------------------------
  3225. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3226. const UnicodeString NewName)
  3227. {
  3228. try
  3229. {
  3230. assert(FFileSystem);
  3231. if (IsCapable[fcRemoteCopy])
  3232. {
  3233. FFileSystem->CopyFile(FileName, NewName);
  3234. }
  3235. else
  3236. {
  3237. assert(CommandSessionOpened);
  3238. assert(FCommandSession->FSProtocol == cfsSCP);
  3239. LogEvent(L"Copying file on command session.");
  3240. FCommandSession->CurrentDirectory = CurrentDirectory;
  3241. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3242. }
  3243. }
  3244. catch(Exception & E)
  3245. {
  3246. COMMAND_ERROR_ARI
  3247. (
  3248. FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)),
  3249. DoCopyFile(FileName, NewName)
  3250. );
  3251. }
  3252. }
  3253. //---------------------------------------------------------------------------
  3254. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3255. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3256. {
  3257. if (OperationProgress && (OperationProgress->Operation == foRemoteCopy))
  3258. {
  3259. if (OperationProgress->Cancel != csContinue) Abort();
  3260. OperationProgress->SetFile(FileName);
  3261. }
  3262. assert(Param != NULL);
  3263. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3264. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3265. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3266. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3267. DoCopyFile(FileName, NewName);
  3268. ReactOnCommand(fsCopyFile);
  3269. }
  3270. //---------------------------------------------------------------------------
  3271. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3272. const UnicodeString FileMask)
  3273. {
  3274. TMoveFileParams Params;
  3275. Params.Target = Target;
  3276. Params.FileMask = FileMask;
  3277. DirectoryModified(Target, true);
  3278. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3279. }
  3280. //---------------------------------------------------------------------------
  3281. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3282. const TRemoteProperties * Properties)
  3283. {
  3284. assert(FFileSystem);
  3285. EnsureNonExistence(DirName);
  3286. FileModified(NULL, DirName);
  3287. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3288. DoCreateDirectory(DirName);
  3289. if ((Properties != NULL) && !Properties->Valid.Empty())
  3290. {
  3291. DoChangeFileProperties(DirName, NULL, Properties);
  3292. }
  3293. ReactOnCommand(fsCreateDirectory);
  3294. }
  3295. //---------------------------------------------------------------------------
  3296. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3297. {
  3298. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3299. try
  3300. {
  3301. assert(FFileSystem);
  3302. FFileSystem->CreateDirectory(DirName);
  3303. }
  3304. catch(Exception & E)
  3305. {
  3306. COMMAND_ERROR_ARI_ACTION
  3307. (
  3308. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  3309. DoCreateDirectory(DirName),
  3310. Action
  3311. );
  3312. }
  3313. }
  3314. //---------------------------------------------------------------------------
  3315. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3316. const UnicodeString PointTo, bool Symbolic)
  3317. {
  3318. assert(FFileSystem);
  3319. EnsureNonExistence(FileName);
  3320. if (SessionData->CacheDirectories)
  3321. {
  3322. DirectoryModified(CurrentDirectory, false);
  3323. }
  3324. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3325. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3326. DoCreateLink(FileName, PointTo, Symbolic);
  3327. ReactOnCommand(fsCreateDirectory);
  3328. }
  3329. //---------------------------------------------------------------------------
  3330. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3331. const UnicodeString PointTo, bool Symbolic)
  3332. {
  3333. try
  3334. {
  3335. assert(FFileSystem);
  3336. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3337. }
  3338. catch(Exception & E)
  3339. {
  3340. COMMAND_ERROR_ARI
  3341. (
  3342. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  3343. DoCreateLink(FileName, PointTo, Symbolic);
  3344. );
  3345. }
  3346. }
  3347. //---------------------------------------------------------------------------
  3348. void __fastcall TTerminal::HomeDirectory()
  3349. {
  3350. assert(FFileSystem);
  3351. try
  3352. {
  3353. LogEvent(L"Changing directory to home directory.");
  3354. FFileSystem->HomeDirectory();
  3355. ReactOnCommand(fsHomeDirectory);
  3356. }
  3357. catch (Exception &E)
  3358. {
  3359. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3360. }
  3361. }
  3362. //---------------------------------------------------------------------------
  3363. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3364. {
  3365. assert(FFileSystem);
  3366. try
  3367. {
  3368. UnicodeString CachedDirectory;
  3369. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3370. // never use directory change cache during startup, this ensures, we never
  3371. // end-up initially in non-existing directory
  3372. if ((Status == ssOpened) &&
  3373. SessionData->CacheDirectoryChanges &&
  3374. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3375. Directory, CachedDirectory))
  3376. {
  3377. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3378. (Directory, CachedDirectory)));
  3379. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3380. }
  3381. else
  3382. {
  3383. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3384. FFileSystem->ChangeDirectory(Directory);
  3385. }
  3386. FLastDirectoryChange = Directory;
  3387. ReactOnCommand(fsChangeDirectory);
  3388. }
  3389. catch (Exception &E)
  3390. {
  3391. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3392. }
  3393. }
  3394. //---------------------------------------------------------------------------
  3395. void __fastcall TTerminal::LookupUsersGroups()
  3396. {
  3397. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3398. IsCapable[fcUserGroupListing])
  3399. {
  3400. assert(FFileSystem);
  3401. try
  3402. {
  3403. FUsersGroupsLookedup = true;
  3404. LogEvent(L"Looking up groups and users.");
  3405. FFileSystem->LookupUsersGroups();
  3406. ReactOnCommand(fsLookupUsersGroups);
  3407. if (Log->Logging)
  3408. {
  3409. FGroups.Log(this, L"groups");
  3410. FMembership.Log(this, L"membership");
  3411. FUsers.Log(this, L"users");
  3412. }
  3413. }
  3414. catch (Exception &E)
  3415. {
  3416. if (!Active || (SessionData->LookupUserGroups == asOn))
  3417. {
  3418. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3419. }
  3420. }
  3421. }
  3422. }
  3423. //---------------------------------------------------------------------------
  3424. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3425. {
  3426. return !Command.Trim().IsEmpty();
  3427. }
  3428. //---------------------------------------------------------------------------
  3429. bool __fastcall TTerminal::GetCommandSessionOpened()
  3430. {
  3431. // consider secondary terminal open in "ready" state only
  3432. // so we never do keepalives on it until it is completely initialized
  3433. return (FCommandSession != NULL) &&
  3434. (FCommandSession->Status == ssOpened);
  3435. }
  3436. //---------------------------------------------------------------------------
  3437. TTerminal * __fastcall TTerminal::GetCommandSession()
  3438. {
  3439. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3440. {
  3441. SAFE_DESTROY(FCommandSession);
  3442. }
  3443. if (FCommandSession == NULL)
  3444. {
  3445. // transaction cannot be started yet to allow proper matching transaction
  3446. // levels between main and command session
  3447. assert(FInTransaction == 0);
  3448. try
  3449. {
  3450. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3451. Configuration, L"Shell");
  3452. FCommandSession->AutoReadDirectory = false;
  3453. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3454. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3455. CommandSessionData->FSProtocol = fsSCPonly;
  3456. CommandSessionData->ClearAliases = false;
  3457. CommandSessionData->UnsetNationalVars = false;
  3458. CommandSessionData->LookupUserGroups = asOff;
  3459. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3460. FCommandSession->OnQueryUser = OnQueryUser;
  3461. FCommandSession->OnPromptUser = OnPromptUser;
  3462. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3463. FCommandSession->OnProgress = OnProgress;
  3464. FCommandSession->OnFinished = OnFinished;
  3465. FCommandSession->OnInformation = OnInformation;
  3466. // do not copy OnDisplayBanner to avoid it being displayed
  3467. }
  3468. catch(...)
  3469. {
  3470. SAFE_DESTROY(FCommandSession);
  3471. throw;
  3472. }
  3473. }
  3474. return FCommandSession;
  3475. }
  3476. //---------------------------------------------------------------------------
  3477. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3478. TCaptureOutputEvent OutputEvent)
  3479. {
  3480. class TOutputProxy
  3481. {
  3482. public:
  3483. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3484. FAction(Action),
  3485. FOutputEvent(OutputEvent)
  3486. {
  3487. }
  3488. void __fastcall Output(const UnicodeString & Str, bool StdError)
  3489. {
  3490. FAction.AddOutput(Str, StdError);
  3491. if (FOutputEvent != NULL)
  3492. {
  3493. FOutputEvent(Str, StdError);
  3494. }
  3495. }
  3496. private:
  3497. TCallSessionAction & FAction;
  3498. TCaptureOutputEvent FOutputEvent;
  3499. };
  3500. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3501. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3502. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3503. }
  3504. //---------------------------------------------------------------------------
  3505. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3506. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3507. {
  3508. assert(FFileSystem);
  3509. try
  3510. {
  3511. DirectoryModified(CurrentDirectory, false);
  3512. if (IsCapable[fcAnyCommand])
  3513. {
  3514. LogEvent(L"Executing user defined command.");
  3515. FFileSystem->AnyCommand(Command, OutputEvent);
  3516. }
  3517. else
  3518. {
  3519. assert(CommandSessionOpened);
  3520. assert(FCommandSession->FSProtocol == cfsSCP);
  3521. LogEvent(L"Executing user defined command on command session.");
  3522. FCommandSession->CurrentDirectory = CurrentDirectory;
  3523. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3524. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3525. // synchronize pwd (by purpose we lose transaction optimization here)
  3526. ChangeDirectory(FCommandSession->CurrentDirectory);
  3527. }
  3528. ReactOnCommand(fsAnyCommand);
  3529. }
  3530. catch (Exception &E)
  3531. {
  3532. if (Action != NULL)
  3533. {
  3534. RollbackAction(*Action, NULL, &E);
  3535. }
  3536. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3537. else HandleExtendedException(&E);
  3538. }
  3539. }
  3540. //---------------------------------------------------------------------------
  3541. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3542. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3543. bool NoConfirmation)
  3544. {
  3545. bool Result = true;
  3546. bool Done;
  3547. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  3548. do
  3549. {
  3550. *AHandle = CreateFile(FileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  3551. NULL, CREATE_ALWAYS, CreateAttr, 0);
  3552. Done = (*AHandle != INVALID_HANDLE_VALUE);
  3553. if (!Done)
  3554. {
  3555. int FileAttr;
  3556. if (::FileExists(FileName) &&
  3557. (((FileAttr = FileGetAttr(FileName)) & (faReadOnly | faHidden)) != 0))
  3558. {
  3559. if (FLAGSET(FileAttr, faReadOnly))
  3560. {
  3561. if (OperationProgress->BatchOverwrite == boNone)
  3562. {
  3563. Result = false;
  3564. }
  3565. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  3566. {
  3567. unsigned int Answer;
  3568. SUSPEND_OPERATION
  3569. (
  3570. Answer = QueryUser(
  3571. FMTLOAD(READ_ONLY_OVERWRITE, (FileName)), NULL,
  3572. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  3573. );
  3574. switch (Answer) {
  3575. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  3576. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  3577. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  3578. case qaNo: Result = false; break;
  3579. }
  3580. }
  3581. }
  3582. else
  3583. {
  3584. assert(FLAGSET(FileAttr, faHidden));
  3585. Result = true;
  3586. }
  3587. if (Result)
  3588. {
  3589. CreateAttr |=
  3590. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  3591. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  3592. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  3593. if (FileSetAttr(FileName, FileAttr & ~(faReadOnly | faHidden)) != 0)
  3594. {
  3595. RaiseLastOSError();
  3596. }
  3597. );
  3598. }
  3599. else
  3600. {
  3601. Done = true;
  3602. }
  3603. }
  3604. else
  3605. {
  3606. RaiseLastOSError();
  3607. }
  3608. }
  3609. }
  3610. while (!Done);
  3611. return Result;
  3612. }
  3613. //---------------------------------------------------------------------------
  3614. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  3615. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3616. bool NoConfirmation)
  3617. {
  3618. assert(AHandle);
  3619. bool Result = true;
  3620. FILE_OPERATION_LOOP (FMTLOAD(CREATE_FILE_ERROR, (FileName)),
  3621. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  3622. );
  3623. return Result;
  3624. }
  3625. //---------------------------------------------------------------------------
  3626. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  3627. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  3628. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  3629. bool TryWriteReadOnly)
  3630. {
  3631. int Attrs = 0;
  3632. HANDLE Handle = 0;
  3633. FILE_OPERATION_LOOP (FMTLOAD(FILE_NOT_EXISTS, (FileName)),
  3634. Attrs = FileGetAttr(FileName);
  3635. if (Attrs == -1) RaiseLastOSError();
  3636. )
  3637. if ((Attrs & faDirectory) == 0)
  3638. {
  3639. bool NoHandle = false;
  3640. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  3641. ((Attrs & faReadOnly) != 0))
  3642. {
  3643. Access = GENERIC_READ;
  3644. NoHandle = true;
  3645. }
  3646. FILE_OPERATION_LOOP (FMTLOAD(OPENFILE_ERROR, (FileName)),
  3647. Handle = CreateFile(FileName.c_str(), Access,
  3648. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  3649. NULL, OPEN_EXISTING, 0, 0);
  3650. if (Handle == INVALID_HANDLE_VALUE)
  3651. {
  3652. Handle = 0;
  3653. RaiseLastOSError();
  3654. }
  3655. );
  3656. try
  3657. {
  3658. if (AATime || AMTime || ACTime)
  3659. {
  3660. FILETIME ATime;
  3661. FILETIME MTime;
  3662. FILETIME CTime;
  3663. // Get last file access and modification time
  3664. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  3665. if (!GetFileTime(Handle, &CTime, &ATime, &MTime)) RaiseLastOSError();
  3666. );
  3667. if (ACTime)
  3668. {
  3669. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  3670. }
  3671. if (AATime)
  3672. {
  3673. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  3674. }
  3675. if (AMTime)
  3676. {
  3677. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  3678. }
  3679. }
  3680. if (ASize)
  3681. {
  3682. // Get file size
  3683. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  3684. unsigned long LSize;
  3685. unsigned long HSize;
  3686. LSize = GetFileSize(Handle, &HSize);
  3687. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  3688. *ASize = (__int64(HSize) << 32) + LSize;
  3689. );
  3690. }
  3691. if ((AHandle == NULL) || NoHandle)
  3692. {
  3693. CloseHandle(Handle);
  3694. Handle = NULL;
  3695. }
  3696. }
  3697. catch(...)
  3698. {
  3699. CloseHandle(Handle);
  3700. throw;
  3701. }
  3702. }
  3703. if (AAttrs) *AAttrs = Attrs;
  3704. if (AHandle) *AHandle = Handle;
  3705. }
  3706. //---------------------------------------------------------------------------
  3707. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  3708. const TCopyParamType * CopyParam)
  3709. {
  3710. bool Result = true;
  3711. if (!CopyParam->AllowAnyTransfer())
  3712. {
  3713. WIN32_FIND_DATA FindData;
  3714. HANDLE Handle;
  3715. FILE_OPERATION_LOOP (FMTLOAD(FILE_NOT_EXISTS, (FileName)),
  3716. Handle = FindFirstFile(FileName.c_str(), &FindData);
  3717. if (Handle == INVALID_HANDLE_VALUE)
  3718. {
  3719. RaiseLastOSError();
  3720. }
  3721. )
  3722. ::FindClose(Handle);
  3723. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  3724. TFileMasks::TParams Params;
  3725. // SearchRec.Size in C++B2010 is __int64,
  3726. // so we should be able to use it instead of FindData.nFileSize*
  3727. Params.Size =
  3728. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  3729. FindData.nFileSizeLow;
  3730. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  3731. Result = CopyParam->AllowTransfer(FileName, osLocal, Directory, Params);
  3732. }
  3733. return Result;
  3734. }
  3735. //---------------------------------------------------------------------------
  3736. UnicodeString __fastcall TTerminal::FileUrl(const UnicodeString Protocol,
  3737. const UnicodeString FileName)
  3738. {
  3739. assert(FileName.Length() > 0);
  3740. return Protocol + L"://" + EncodeUrlChars(SessionData->SessionName) +
  3741. (FileName[1] == L'/' ? L"" : L"/") + EncodeUrlChars(FileName, L"/");
  3742. }
  3743. //---------------------------------------------------------------------------
  3744. UnicodeString __fastcall TTerminal::FileUrl(const UnicodeString FileName)
  3745. {
  3746. return FFileSystem->FileUrl(FileName);
  3747. }
  3748. //---------------------------------------------------------------------------
  3749. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  3750. const TSearchRec Rec, void * Param)
  3751. {
  3752. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  3753. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  3754. if (Directory && Params.Recursive)
  3755. {
  3756. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  3757. }
  3758. if (!Directory || Params.IncludeDirs)
  3759. {
  3760. Params.FileList->Add(FileName);
  3761. }
  3762. }
  3763. //---------------------------------------------------------------------------
  3764. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  3765. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  3766. {
  3767. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  3768. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  3769. bool AllowTransfer = (AParams->CopyParam == NULL);
  3770. // SearchRec.Size in C++B2010 is __int64,
  3771. // so we should be able to use it instead of FindData.nFileSize*
  3772. __int64 Size =
  3773. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  3774. Rec.FindData.nFileSizeLow;
  3775. if (!AllowTransfer)
  3776. {
  3777. TFileMasks::TParams MaskParams;
  3778. MaskParams.Size = Size;
  3779. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  3780. AllowTransfer = AParams->CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams);
  3781. }
  3782. if (AllowTransfer)
  3783. {
  3784. if (!Dir)
  3785. {
  3786. AParams->Size += Size;
  3787. }
  3788. else
  3789. {
  3790. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  3791. }
  3792. }
  3793. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  3794. {
  3795. if (OperationProgress->Cancel != csContinue) Abort();
  3796. OperationProgress->SetFile(FileName);
  3797. }
  3798. }
  3799. //---------------------------------------------------------------------------
  3800. void __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  3801. __int64 & Size, const TCopyParamType * CopyParam)
  3802. {
  3803. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  3804. TOnceDoneOperation OnceDoneOperation = odoIdle;
  3805. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  3806. try
  3807. {
  3808. TCalculateSizeParams Params;
  3809. Params.Size = 0;
  3810. Params.Params = 0;
  3811. Params.CopyParam = CopyParam;
  3812. assert(!FOperationProgress);
  3813. FOperationProgress = &OperationProgress;
  3814. TSearchRec Rec;
  3815. for (int Index = 0; Index < FileList->Count; Index++)
  3816. {
  3817. UnicodeString FileName = FileList->Strings[Index];
  3818. if (FileSearchRec(FileName, Rec))
  3819. {
  3820. CalculateLocalFileSize(FileName, Rec, &Params);
  3821. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  3822. }
  3823. }
  3824. Size = Params.Size;
  3825. }
  3826. __finally
  3827. {
  3828. FOperationProgress = NULL;
  3829. OperationProgress.Stop();
  3830. }
  3831. if (OnceDoneOperation != odoIdle)
  3832. {
  3833. CloseOnCompletion(OnceDoneOperation);
  3834. }
  3835. }
  3836. //---------------------------------------------------------------------------
  3837. struct TSynchronizeFileData
  3838. {
  3839. bool Modified;
  3840. bool New;
  3841. bool IsDirectory;
  3842. TSynchronizeChecklist::TItem::TFileInfo Info;
  3843. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  3844. TRemoteFile * MatchingRemoteFileFile;
  3845. int MatchingRemoteFileImageIndex;
  3846. FILETIME LocalLastWriteTime;
  3847. };
  3848. //---------------------------------------------------------------------------
  3849. const int sfFirstLevel = 0x01;
  3850. struct TSynchronizeData
  3851. {
  3852. UnicodeString LocalDirectory;
  3853. UnicodeString RemoteDirectory;
  3854. TTerminal::TSynchronizeMode Mode;
  3855. int Params;
  3856. TSynchronizeDirectory OnSynchronizeDirectory;
  3857. TSynchronizeOptions * Options;
  3858. int Flags;
  3859. TStringList * LocalFileList;
  3860. const TCopyParamType * CopyParam;
  3861. TSynchronizeChecklist * Checklist;
  3862. };
  3863. //---------------------------------------------------------------------------
  3864. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  3865. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  3866. const TCopyParamType * CopyParam, int Params,
  3867. TSynchronizeDirectory OnSynchronizeDirectory,
  3868. TSynchronizeOptions * Options)
  3869. {
  3870. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  3871. try
  3872. {
  3873. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  3874. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  3875. Checklist);
  3876. Checklist->Sort();
  3877. }
  3878. catch(...)
  3879. {
  3880. delete Checklist;
  3881. throw;
  3882. }
  3883. return Checklist;
  3884. }
  3885. //---------------------------------------------------------------------------
  3886. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  3887. {
  3888. if (FLAGSET(Params, Param))
  3889. {
  3890. AddToList(ParamsStr, Name, ", ");
  3891. }
  3892. Params &= ~Param;
  3893. }
  3894. //---------------------------------------------------------------------------
  3895. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  3896. {
  3897. UnicodeString ModeStr;
  3898. switch (Mode)
  3899. {
  3900. case smRemote:
  3901. ModeStr = L"Remote";
  3902. break;
  3903. case smLocal:
  3904. ModeStr = L"Local";
  3905. break;
  3906. case smBoth:
  3907. ModeStr = L"Both";
  3908. break;
  3909. default:
  3910. ModeStr = L"Unknown";
  3911. break;
  3912. }
  3913. return ModeStr;
  3914. }
  3915. //---------------------------------------------------------------------------
  3916. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  3917. {
  3918. UnicodeString ParamsStr;
  3919. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  3920. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  3921. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  3922. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  3923. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  3924. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  3925. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  3926. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  3927. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  3928. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  3929. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  3930. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  3931. if (Params > 0)
  3932. {
  3933. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  3934. }
  3935. return ParamsStr;
  3936. }
  3937. //---------------------------------------------------------------------------
  3938. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  3939. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  3940. const TCopyParamType * CopyParam, int Params,
  3941. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  3942. int Flags, TSynchronizeChecklist * Checklist)
  3943. {
  3944. TSynchronizeData Data;
  3945. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  3946. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  3947. Data.Mode = Mode;
  3948. Data.Params = Params;
  3949. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  3950. Data.LocalFileList = NULL;
  3951. Data.CopyParam = CopyParam;
  3952. Data.Options = Options;
  3953. Data.Flags = Flags;
  3954. Data.Checklist = Checklist;
  3955. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  3956. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  3957. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  3958. if (FLAGCLEAR(Params, spDelayProgress))
  3959. {
  3960. DoSynchronizeProgress(Data, true);
  3961. }
  3962. try
  3963. {
  3964. bool Found;
  3965. TSearchRec SearchRec;
  3966. Data.LocalFileList = new TStringList();
  3967. Data.LocalFileList->Sorted = true;
  3968. Data.LocalFileList->CaseSensitive = false;
  3969. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  3970. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  3971. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  3972. );
  3973. if (Found)
  3974. {
  3975. try
  3976. {
  3977. UnicodeString FileName;
  3978. while (Found)
  3979. {
  3980. FileName = SearchRec.Name;
  3981. // add dirs for recursive mode or when we are interested in newly
  3982. // added subdirs
  3983. // SearchRec.Size in C++B2010 is __int64,
  3984. // so we should be able to use it instead of FindData.nFileSize*
  3985. __int64 Size =
  3986. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  3987. SearchRec.FindData.nFileSizeLow;
  3988. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  3989. TFileMasks::TParams MaskParams;
  3990. MaskParams.Size = Size;
  3991. MaskParams.Modification = Modification;
  3992. UnicodeString RemoteFileName =
  3993. CopyParam->ChangeFileName(FileName, osLocal, false);
  3994. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  3995. if ((FileName != L".") && (FileName != L"..") &&
  3996. CopyParam->AllowTransfer(FullLocalFileName, osLocal,
  3997. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  3998. !FFileSystem->TemporaryTransferFile(FileName) &&
  3999. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4000. (Options == NULL) ||
  4001. Options->MatchesFilter(FileName) ||
  4002. Options->MatchesFilter(RemoteFileName)))
  4003. {
  4004. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4005. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4006. FileData->Info.FileName = FileName;
  4007. FileData->Info.Directory = Data.LocalDirectory;
  4008. FileData->Info.Modification = Modification;
  4009. FileData->Info.ModificationFmt = mfFull;
  4010. FileData->Info.Size = Size;
  4011. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4012. FileData->New = true;
  4013. FileData->Modified = false;
  4014. Data.LocalFileList->AddObject(FileName,
  4015. reinterpret_cast<TObject*>(FileData));
  4016. LogEvent(FORMAT(L"Local file '%s' [%s] [%s] included to synchronization",
  4017. (FullLocalFileName, StandardTimestamp(Modification), IntToStr(Size))));
  4018. }
  4019. else
  4020. {
  4021. LogEvent(FORMAT(L"Local file '%s' [%s] [%s] excluded from synchronization",
  4022. (FullLocalFileName, StandardTimestamp(Modification), IntToStr(Size))));
  4023. }
  4024. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  4025. Found = (FindNextChecked(SearchRec) == 0);
  4026. );
  4027. }
  4028. }
  4029. __finally
  4030. {
  4031. FindClose(SearchRec);
  4032. }
  4033. // can we expect that ProcessDirectory would take so little time
  4034. // that we can pospone showing progress window until anything actually happens?
  4035. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4036. FDirectoryCache->HasFileList(RemoteDirectory);
  4037. if (!Cached && FLAGSET(Params, spDelayProgress))
  4038. {
  4039. DoSynchronizeProgress(Data, true);
  4040. }
  4041. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4042. FLAGSET(Params, spUseCache));
  4043. TSynchronizeFileData * FileData;
  4044. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4045. {
  4046. FileData = reinterpret_cast<TSynchronizeFileData *>
  4047. (Data.LocalFileList->Objects[Index]);
  4048. // add local file either if we are going to upload it
  4049. // (i.e. if it is updated or we want to upload even new files)
  4050. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4051. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4052. bool New = (FileData->New &&
  4053. ((Mode == smLocal) ||
  4054. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4055. if (New)
  4056. {
  4057. LogEvent(FORMAT(L"Local file '%s' [%s] [%s] is new",
  4058. (FileData->Info.Directory + FileData->Info.FileName,
  4059. StandardTimestamp(FileData->Info.Modification),
  4060. IntToStr(FileData->Info.Size))));
  4061. }
  4062. if (Modified || New)
  4063. {
  4064. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4065. try
  4066. {
  4067. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4068. ChecklistItem->Local = FileData->Info;
  4069. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4070. if (Modified)
  4071. {
  4072. assert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4073. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4074. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4075. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4076. }
  4077. else
  4078. {
  4079. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4080. }
  4081. if ((Mode == smBoth) || (Mode == smRemote))
  4082. {
  4083. ChecklistItem->Action =
  4084. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4085. ChecklistItem->Checked =
  4086. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4087. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4088. FLAGSET(Params, spSubDirs));
  4089. }
  4090. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4091. {
  4092. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4093. ChecklistItem->Checked =
  4094. FLAGSET(Params, spDelete) &&
  4095. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4096. FLAGSET(Params, spSubDirs));
  4097. }
  4098. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4099. {
  4100. Data.Checklist->Add(ChecklistItem);
  4101. ChecklistItem = NULL;
  4102. }
  4103. }
  4104. __finally
  4105. {
  4106. delete ChecklistItem;
  4107. }
  4108. }
  4109. else
  4110. {
  4111. if (FileData->Modified)
  4112. {
  4113. delete FileData->MatchingRemoteFileFile;
  4114. }
  4115. }
  4116. }
  4117. }
  4118. }
  4119. __finally
  4120. {
  4121. if (Data.LocalFileList != NULL)
  4122. {
  4123. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4124. {
  4125. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4126. (Data.LocalFileList->Objects[Index]);
  4127. delete FileData;
  4128. }
  4129. delete Data.LocalFileList;
  4130. }
  4131. }
  4132. }
  4133. //---------------------------------------------------------------------------
  4134. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4135. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4136. {
  4137. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4138. TFileMasks::TParams MaskParams;
  4139. MaskParams.Size = File->Size;
  4140. MaskParams.Modification = File->Modification;
  4141. UnicodeString LocalFileName =
  4142. Data->CopyParam->ChangeFileName(File->FileName, osRemote, false);
  4143. UnicodeString FullRemoteFileName =
  4144. UnixExcludeTrailingBackslash(File->FullFileName);
  4145. if (Data->CopyParam->AllowTransfer(
  4146. FullRemoteFileName, osRemote,
  4147. File->IsDirectory, MaskParams) &&
  4148. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4149. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4150. (Data->Options == NULL) ||
  4151. Data->Options->MatchesFilter(File->FileName) ||
  4152. Data->Options->MatchesFilter(LocalFileName)))
  4153. {
  4154. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4155. try
  4156. {
  4157. ChecklistItem->IsDirectory = File->IsDirectory;
  4158. ChecklistItem->ImageIndex = File->IconIndex;
  4159. ChecklistItem->Remote.FileName = File->FileName;
  4160. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4161. ChecklistItem->Remote.Modification = File->Modification;
  4162. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4163. ChecklistItem->Remote.Size = File->Size;
  4164. bool Modified = false;
  4165. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4166. bool New = (LocalIndex < 0);
  4167. if (!New)
  4168. {
  4169. TSynchronizeFileData * LocalData =
  4170. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4171. LocalData->New = false;
  4172. if (File->IsDirectory != LocalData->IsDirectory)
  4173. {
  4174. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4175. (File->FileName)));
  4176. }
  4177. else if (!File->IsDirectory)
  4178. {
  4179. ChecklistItem->Local = LocalData->Info;
  4180. ChecklistItem->Local.Modification =
  4181. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4182. bool LocalModified = false;
  4183. // for spTimestamp+spBySize require that the file sizes are the same
  4184. // before comparing file time
  4185. int TimeCompare;
  4186. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4187. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4188. FLAGCLEAR(Data->Params, spBySize) ||
  4189. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4190. {
  4191. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4192. ChecklistItem->Remote.Modification);
  4193. }
  4194. else
  4195. {
  4196. TimeCompare = 0;
  4197. }
  4198. if (TimeCompare < 0)
  4199. {
  4200. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4201. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4202. {
  4203. Modified = true;
  4204. }
  4205. else
  4206. {
  4207. LocalModified = true;
  4208. }
  4209. }
  4210. else if (TimeCompare > 0)
  4211. {
  4212. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4213. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4214. {
  4215. LocalModified = true;
  4216. }
  4217. else
  4218. {
  4219. Modified = true;
  4220. }
  4221. }
  4222. else if (FLAGSET(Data->Params, spBySize) &&
  4223. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4224. FLAGCLEAR(Data->Params, spTimestamp))
  4225. {
  4226. Modified = true;
  4227. LocalModified = true;
  4228. }
  4229. if (LocalModified)
  4230. {
  4231. LocalData->Modified = true;
  4232. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4233. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4234. // we need this for custom commands over checklist only,
  4235. // not for sync itself
  4236. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4237. LogEvent(FORMAT(L"Local file '%s' [%s] [%s] is modified comparing to remote file '%s' [%s] [%s]",
  4238. (LocalData->Info.Directory + LocalData->Info.FileName,
  4239. StandardTimestamp(LocalData->Info.Modification),
  4240. IntToStr(LocalData->Info.Size),
  4241. FullRemoteFileName,
  4242. StandardTimestamp(File->Modification),
  4243. IntToStr(File->Size))));
  4244. }
  4245. if (Modified)
  4246. {
  4247. LogEvent(FORMAT(L"Remote file '%s' [%s] [%s] is modified comparing to local file '%s' [%s] [%s]",
  4248. (FullRemoteFileName,
  4249. StandardTimestamp(File->Modification),
  4250. IntToStr(File->Size),
  4251. LocalData->Info.Directory + LocalData->Info.FileName,
  4252. StandardTimestamp(LocalData->Info.Modification),
  4253. IntToStr(LocalData->Info.Size))));
  4254. }
  4255. }
  4256. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4257. {
  4258. DoSynchronizeCollectDirectory(
  4259. Data->LocalDirectory + LocalData->Info.FileName,
  4260. Data->RemoteDirectory + File->FileName,
  4261. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4262. Data->Options, (Data->Flags & ~sfFirstLevel),
  4263. Data->Checklist);
  4264. }
  4265. }
  4266. else
  4267. {
  4268. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4269. LogEvent(FORMAT(L"Remote file '%s' [%s] [%s] is new",
  4270. (FullRemoteFileName, StandardTimestamp(File->Modification), IntToStr(File->Size))));
  4271. }
  4272. if (New || Modified)
  4273. {
  4274. assert(!New || !Modified);
  4275. // download the file if it changed or is new and we want to have it locally
  4276. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4277. {
  4278. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4279. {
  4280. ChecklistItem->Action =
  4281. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4282. ChecklistItem->Checked =
  4283. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4284. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4285. FLAGSET(Data->Params, spSubDirs));
  4286. }
  4287. }
  4288. else if ((Data->Mode == smRemote) && New)
  4289. {
  4290. if (FLAGCLEAR(Data->Params, spTimestamp))
  4291. {
  4292. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4293. ChecklistItem->Checked =
  4294. FLAGSET(Data->Params, spDelete) &&
  4295. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4296. FLAGSET(Data->Params, spSubDirs));
  4297. }
  4298. }
  4299. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4300. {
  4301. ChecklistItem->RemoteFile = File->Duplicate();
  4302. Data->Checklist->Add(ChecklistItem);
  4303. ChecklistItem = NULL;
  4304. }
  4305. }
  4306. }
  4307. __finally
  4308. {
  4309. delete ChecklistItem;
  4310. }
  4311. }
  4312. else
  4313. {
  4314. LogEvent(FORMAT(L"Remote file '%s' [%s] [%s] excluded from synchronization",
  4315. (FullRemoteFileName, StandardTimestamp(File->Modification), IntToStr(File->Size))));
  4316. }
  4317. }
  4318. //---------------------------------------------------------------------------
  4319. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4320. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4321. const TCopyParamType * CopyParam, int Params,
  4322. TSynchronizeDirectory OnSynchronizeDirectory)
  4323. {
  4324. TSynchronizeData Data;
  4325. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4326. int CopyParams =
  4327. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4328. TCopyParamType SyncCopyParam = *CopyParam;
  4329. // when synchronizing by time, we force preserving time,
  4330. // otherwise it does not make any sense
  4331. if (FLAGCLEAR(Params, spNotByTime))
  4332. {
  4333. SyncCopyParam.PreserveTime = true;
  4334. }
  4335. TStringList * DownloadList = new TStringList();
  4336. TStringList * DeleteRemoteList = new TStringList();
  4337. TStringList * UploadList = new TStringList();
  4338. TStringList * DeleteLocalList = new TStringList();
  4339. BeginTransaction();
  4340. try
  4341. {
  4342. int IIndex = 0;
  4343. while (IIndex < Checklist->Count)
  4344. {
  4345. const TSynchronizeChecklist::TItem * ChecklistItem;
  4346. DownloadList->Clear();
  4347. DeleteRemoteList->Clear();
  4348. UploadList->Clear();
  4349. DeleteLocalList->Clear();
  4350. ChecklistItem = Checklist->Item[IIndex];
  4351. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4352. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4353. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4354. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4355. int(Params), SynchronizeParamsStr(Params))));
  4356. int Count = 0;
  4357. while ((IIndex < Checklist->Count) &&
  4358. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4359. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4360. {
  4361. ChecklistItem = Checklist->Item[IIndex];
  4362. if (ChecklistItem->Checked)
  4363. {
  4364. Count++;
  4365. if (FLAGSET(Params, spTimestamp))
  4366. {
  4367. switch (ChecklistItem->Action)
  4368. {
  4369. case TSynchronizeChecklist::saDownloadUpdate:
  4370. DownloadList->AddObject(
  4371. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4372. ChecklistItem->Remote.FileName,
  4373. (TObject *)(ChecklistItem));
  4374. break;
  4375. case TSynchronizeChecklist::saUploadUpdate:
  4376. UploadList->AddObject(
  4377. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4378. ChecklistItem->Local.FileName,
  4379. (TObject *)(ChecklistItem));
  4380. break;
  4381. default:
  4382. assert(false);
  4383. break;
  4384. }
  4385. }
  4386. else
  4387. {
  4388. switch (ChecklistItem->Action)
  4389. {
  4390. case TSynchronizeChecklist::saDownloadNew:
  4391. case TSynchronizeChecklist::saDownloadUpdate:
  4392. DownloadList->AddObject(
  4393. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4394. ChecklistItem->Remote.FileName,
  4395. ChecklistItem->RemoteFile);
  4396. break;
  4397. case TSynchronizeChecklist::saDeleteRemote:
  4398. DeleteRemoteList->AddObject(
  4399. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4400. ChecklistItem->Remote.FileName,
  4401. ChecklistItem->RemoteFile);
  4402. break;
  4403. case TSynchronizeChecklist::saUploadNew:
  4404. case TSynchronizeChecklist::saUploadUpdate:
  4405. UploadList->Add(
  4406. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4407. ChecklistItem->Local.FileName);
  4408. break;
  4409. case TSynchronizeChecklist::saDeleteLocal:
  4410. DeleteLocalList->Add(
  4411. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4412. ChecklistItem->Local.FileName);
  4413. break;
  4414. default:
  4415. assert(false);
  4416. break;
  4417. }
  4418. }
  4419. }
  4420. IIndex++;
  4421. }
  4422. // prevent showing/updating of progress dialog if there's nothing to do
  4423. if (Count > 0)
  4424. {
  4425. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4426. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4427. DoSynchronizeProgress(Data, false);
  4428. if (FLAGSET(Params, spTimestamp))
  4429. {
  4430. if (DownloadList->Count > 0)
  4431. {
  4432. ProcessFiles(DownloadList, foSetProperties,
  4433. SynchronizeLocalTimestamp, NULL, osLocal);
  4434. }
  4435. if (UploadList->Count > 0)
  4436. {
  4437. ProcessFiles(UploadList, foSetProperties,
  4438. SynchronizeRemoteTimestamp);
  4439. }
  4440. }
  4441. else
  4442. {
  4443. if ((DownloadList->Count > 0) &&
  4444. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4445. {
  4446. Abort();
  4447. }
  4448. if ((DeleteRemoteList->Count > 0) &&
  4449. !DeleteFiles(DeleteRemoteList))
  4450. {
  4451. Abort();
  4452. }
  4453. if ((UploadList->Count > 0) &&
  4454. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4455. {
  4456. Abort();
  4457. }
  4458. if ((DeleteLocalList->Count > 0) &&
  4459. !DeleteLocalFiles(DeleteLocalList))
  4460. {
  4461. Abort();
  4462. }
  4463. }
  4464. }
  4465. }
  4466. }
  4467. __finally
  4468. {
  4469. delete DownloadList;
  4470. delete DeleteRemoteList;
  4471. delete UploadList;
  4472. delete DeleteLocalList;
  4473. EndTransaction();
  4474. }
  4475. }
  4476. //---------------------------------------------------------------------------
  4477. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4478. bool Collect)
  4479. {
  4480. if (Data.OnSynchronizeDirectory != NULL)
  4481. {
  4482. bool Continue = true;
  4483. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  4484. Continue, Collect);
  4485. if (!Continue)
  4486. {
  4487. Abort();
  4488. }
  4489. }
  4490. }
  4491. //---------------------------------------------------------------------------
  4492. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  4493. const TRemoteFile * File, void * /*Param*/)
  4494. {
  4495. const TSynchronizeChecklist::TItem * ChecklistItem =
  4496. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4497. UnicodeString LocalFile =
  4498. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4499. ChecklistItem->Local.FileName;
  4500. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (LocalFile)),
  4501. HANDLE Handle;
  4502. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  4503. NULL, NULL, NULL, NULL);
  4504. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  4505. SessionData->DSTMode);
  4506. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  4507. CloseHandle(Handle);
  4508. if (!Result)
  4509. {
  4510. Abort();
  4511. }
  4512. );
  4513. }
  4514. //---------------------------------------------------------------------------
  4515. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  4516. const TRemoteFile * File, void * /*Param*/)
  4517. {
  4518. const TSynchronizeChecklist::TItem * ChecklistItem =
  4519. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4520. TRemoteProperties Properties;
  4521. Properties.Valid << vpModification;
  4522. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  4523. SessionData->DSTMode);
  4524. ChangeFileProperties(
  4525. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  4526. NULL, &Properties);
  4527. }
  4528. //---------------------------------------------------------------------------
  4529. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  4530. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  4531. {
  4532. // see DoFilesFind
  4533. FOnFindingFile = NULL;
  4534. assert(Param);
  4535. assert(File);
  4536. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  4537. if (!AParams->Cancel)
  4538. {
  4539. if (FileName.IsEmpty())
  4540. {
  4541. FileName = File->FileName;
  4542. }
  4543. TFileMasks::TParams MaskParams;
  4544. MaskParams.Size = File->Size;
  4545. MaskParams.Modification = File->Modification;
  4546. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4547. bool ImplicitMatch;
  4548. if (AParams->FileMask.Matches(FullFileName, false,
  4549. File->IsDirectory, &MaskParams, ImplicitMatch))
  4550. {
  4551. if (!ImplicitMatch)
  4552. {
  4553. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  4554. }
  4555. if (File->IsDirectory)
  4556. {
  4557. DoFilesFind(FullFileName, *AParams);
  4558. }
  4559. }
  4560. }
  4561. }
  4562. //---------------------------------------------------------------------------
  4563. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params)
  4564. {
  4565. Params.OnFindingFile(this, Directory, Params.Cancel);
  4566. if (!Params.Cancel)
  4567. {
  4568. assert(FOnFindingFile == NULL);
  4569. // ideally we should set the handler only around actually reading
  4570. // of the directory listing, so we at least reset the handler in
  4571. // FileFind
  4572. FOnFindingFile = Params.OnFindingFile;
  4573. try
  4574. {
  4575. ProcessDirectory(Directory, FileFind, &Params, false, true);
  4576. }
  4577. __finally
  4578. {
  4579. FOnFindingFile = NULL;
  4580. }
  4581. }
  4582. }
  4583. //---------------------------------------------------------------------------
  4584. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  4585. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  4586. {
  4587. TFilesFindParams Params;
  4588. Params.FileMask = FileMask;
  4589. Params.OnFileFound = OnFileFound;
  4590. Params.OnFindingFile = OnFindingFile;
  4591. Params.Cancel = false;
  4592. DoFilesFind(Directory, Params);
  4593. }
  4594. //---------------------------------------------------------------------------
  4595. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  4596. TSpaceAvailable & ASpaceAvailable)
  4597. {
  4598. assert(IsCapable[fcCheckingSpaceAvailable]);
  4599. try
  4600. {
  4601. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  4602. }
  4603. catch (Exception &E)
  4604. {
  4605. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  4606. }
  4607. }
  4608. //---------------------------------------------------------------------------
  4609. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  4610. {
  4611. return FFileSystem->GetSessionInfo();
  4612. }
  4613. //---------------------------------------------------------------------------
  4614. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  4615. {
  4616. return FFileSystem->GetFileSystemInfo(Retrieve);
  4617. }
  4618. //---------------------------------------------------------------------
  4619. UnicodeString __fastcall TTerminal::GetPassword()
  4620. {
  4621. UnicodeString Result;
  4622. // FPassword is empty also when stored password was used
  4623. if (FPassword.IsEmpty())
  4624. {
  4625. Result = SessionData->Password;
  4626. }
  4627. else
  4628. {
  4629. Result = DecryptPassword(FPassword);
  4630. }
  4631. return Result;
  4632. }
  4633. //---------------------------------------------------------------------
  4634. UnicodeString __fastcall TTerminal::GetTunnelPassword()
  4635. {
  4636. UnicodeString Result;
  4637. // FTunnelPassword is empty also when stored password was used
  4638. if (FTunnelPassword.IsEmpty())
  4639. {
  4640. Result = SessionData->TunnelPassword;
  4641. }
  4642. else
  4643. {
  4644. Result = DecryptPassword(FTunnelPassword);
  4645. }
  4646. return Result;
  4647. }
  4648. //---------------------------------------------------------------------
  4649. bool __fastcall TTerminal::GetStoredCredentialsTried()
  4650. {
  4651. bool Result;
  4652. if (FFileSystem != NULL)
  4653. {
  4654. Result = FFileSystem->GetStoredCredentialsTried();
  4655. }
  4656. else if (FSecureShell != NULL)
  4657. {
  4658. Result = FSecureShell->GetStoredCredentialsTried();
  4659. }
  4660. else
  4661. {
  4662. assert(FTunnelOpening);
  4663. Result = false;
  4664. }
  4665. return Result;
  4666. }
  4667. //---------------------------------------------------------------------------
  4668. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  4669. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  4670. {
  4671. assert(FFileSystem);
  4672. assert(FilesToCopy);
  4673. bool Result = false;
  4674. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4675. try
  4676. {
  4677. __int64 Size;
  4678. if (CopyParam->CalculateSize)
  4679. {
  4680. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  4681. CalculateLocalFilesSize(FilesToCopy, Size,
  4682. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL));
  4683. }
  4684. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4685. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  4686. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  4687. FOperationProgress = &OperationProgress;
  4688. try
  4689. {
  4690. if (CopyParam->CalculateSize)
  4691. {
  4692. OperationProgress.SetTotalSize(Size);
  4693. }
  4694. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  4695. BeginTransaction();
  4696. try
  4697. {
  4698. if (Log->Logging)
  4699. {
  4700. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  4701. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  4702. LogEvent(CopyParam->LogStr);
  4703. }
  4704. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  4705. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  4706. }
  4707. __finally
  4708. {
  4709. if (Active)
  4710. {
  4711. ReactOnCommand(fsCopyToRemote);
  4712. }
  4713. EndTransaction();
  4714. }
  4715. if (OperationProgress.Cancel == csContinue)
  4716. {
  4717. Result = true;
  4718. }
  4719. }
  4720. __finally
  4721. {
  4722. OperationProgress.Stop();
  4723. FOperationProgress = NULL;
  4724. }
  4725. }
  4726. catch (Exception &E)
  4727. {
  4728. CommandError(&E, LoadStr(TOREMOTE_COPY_ERROR));
  4729. OnceDoneOperation = odoIdle;
  4730. }
  4731. if (OnceDoneOperation != odoIdle)
  4732. {
  4733. CloseOnCompletion(OnceDoneOperation);
  4734. }
  4735. return Result;
  4736. }
  4737. //---------------------------------------------------------------------------
  4738. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  4739. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  4740. {
  4741. assert(FFileSystem);
  4742. // see scp.c: sink(), tolocal()
  4743. bool Result = false;
  4744. bool OwnsFileList = (FilesToCopy == NULL);
  4745. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4746. try
  4747. {
  4748. if (OwnsFileList)
  4749. {
  4750. FilesToCopy = new TStringList();
  4751. FilesToCopy->Assign(Files->SelectedFiles);
  4752. }
  4753. BeginTransaction();
  4754. try
  4755. {
  4756. __int64 TotalSize;
  4757. bool TotalSizeKnown = false;
  4758. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4759. if (CopyParam->CalculateSize)
  4760. {
  4761. ExceptionOnFail = true;
  4762. try
  4763. {
  4764. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  4765. CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors,
  4766. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL));
  4767. TotalSizeKnown = true;
  4768. }
  4769. __finally
  4770. {
  4771. ExceptionOnFail = false;
  4772. }
  4773. }
  4774. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  4775. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  4776. FOperationProgress = &OperationProgress;
  4777. try
  4778. {
  4779. if (TotalSizeKnown)
  4780. {
  4781. OperationProgress.SetTotalSize(TotalSize);
  4782. }
  4783. try
  4784. {
  4785. try
  4786. {
  4787. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  4788. &OperationProgress, OnceDoneOperation);
  4789. }
  4790. __finally
  4791. {
  4792. if (Active)
  4793. {
  4794. ReactOnCommand(fsCopyToLocal);
  4795. }
  4796. }
  4797. }
  4798. catch (Exception &E)
  4799. {
  4800. CommandError(&E, LoadStr(TOLOCAL_COPY_ERROR));
  4801. OnceDoneOperation = odoIdle;
  4802. }
  4803. if (OperationProgress.Cancel == csContinue)
  4804. {
  4805. Result = true;
  4806. }
  4807. }
  4808. __finally
  4809. {
  4810. FOperationProgress = NULL;
  4811. OperationProgress.Stop();
  4812. }
  4813. }
  4814. __finally
  4815. {
  4816. // If session is still active (no fatal error) we reload directory
  4817. // by calling EndTransaction
  4818. EndTransaction();
  4819. }
  4820. }
  4821. __finally
  4822. {
  4823. if (OwnsFileList) delete FilesToCopy;
  4824. }
  4825. if (OnceDoneOperation != odoIdle)
  4826. {
  4827. CloseOnCompletion(OnceDoneOperation);
  4828. }
  4829. return Result;
  4830. }
  4831. //---------------------------------------------------------------------------
  4832. void __fastcall TTerminal::ReflectSettings()
  4833. {
  4834. assert(FLog != NULL);
  4835. FLog->ReflectSettings();
  4836. assert(FActionLog != NULL);
  4837. FActionLog->ReflectSettings();
  4838. // also FTunnelLog ?
  4839. }
  4840. //---------------------------------------------------------------------------
  4841. void __fastcall TTerminal::EnableUsage()
  4842. {
  4843. FEnableSecureShellUsage = true;
  4844. }
  4845. //---------------------------------------------------------------------------
  4846. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  4847. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  4848. TTerminal(ASessionData, Configuration),
  4849. FMainTerminal(MainTerminal), FMasterPasswordTried(false),
  4850. FMasterTunnelPasswordTried(false)
  4851. {
  4852. Log->Parent = FMainTerminal->Log;
  4853. Log->Name = Name;
  4854. ActionLog->Enabled = false;
  4855. SessionData->NonPersistant();
  4856. assert(FMainTerminal != NULL);
  4857. if (!FMainTerminal->UserName.IsEmpty())
  4858. {
  4859. SessionData->UserName = FMainTerminal->UserName;
  4860. }
  4861. }
  4862. //---------------------------------------------------------------------------
  4863. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  4864. {
  4865. FMainTerminal->DirectoryLoaded(FileList);
  4866. assert(FileList != NULL);
  4867. }
  4868. //---------------------------------------------------------------------------
  4869. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  4870. bool SubDirs)
  4871. {
  4872. // clear cache of main terminal
  4873. FMainTerminal->DirectoryModified(Path, SubDirs);
  4874. }
  4875. //---------------------------------------------------------------------------
  4876. bool __fastcall TSecondaryTerminal::DoPromptUser(TSessionData * Data,
  4877. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  4878. TStrings * Results)
  4879. {
  4880. bool AResult = false;
  4881. if ((Prompts->Count == 1) && FLAGCLEAR(int(Prompts->Objects[0]), pupEcho) &&
  4882. ((Kind == pkPassword) || (Kind == pkPassphrase) || (Kind == pkKeybInteractive) ||
  4883. (Kind == pkTIS) || (Kind == pkCryptoCard)))
  4884. {
  4885. bool & PasswordTried =
  4886. FTunnelOpening ? FMasterTunnelPasswordTried : FMasterPasswordTried;
  4887. if (!PasswordTried)
  4888. {
  4889. // let's expect that the main session is already authenticated and its password
  4890. // is not written after, so no locking is necessary
  4891. // (no longer true, once the main session can be reconnected)
  4892. UnicodeString Password;
  4893. if (FTunnelOpening)
  4894. {
  4895. Password = FMainTerminal->TunnelPassword;
  4896. }
  4897. else
  4898. {
  4899. Password = FMainTerminal->Password;
  4900. }
  4901. Results->Strings[0] = Password;
  4902. if (!Results->Strings[0].IsEmpty())
  4903. {
  4904. LogEvent(L"Using remembered password of the main session.");
  4905. AResult = true;
  4906. }
  4907. PasswordTried = true;
  4908. }
  4909. }
  4910. if (!AResult)
  4911. {
  4912. AResult = TTerminal::DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  4913. }
  4914. return AResult;
  4915. }
  4916. //---------------------------------------------------------------------------
  4917. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  4918. TObjectList()
  4919. {
  4920. assert(AConfiguration);
  4921. FConfiguration = AConfiguration;
  4922. }
  4923. //---------------------------------------------------------------------------
  4924. __fastcall TTerminalList::~TTerminalList()
  4925. {
  4926. assert(Count == 0);
  4927. }
  4928. //---------------------------------------------------------------------------
  4929. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  4930. {
  4931. return new TTerminal(Data, FConfiguration);
  4932. }
  4933. //---------------------------------------------------------------------------
  4934. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  4935. {
  4936. TTerminal * Terminal = CreateTerminal(Data);
  4937. Add(Terminal);
  4938. return Terminal;
  4939. }
  4940. //---------------------------------------------------------------------------
  4941. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  4942. {
  4943. assert(IndexOf(Terminal) >= 0);
  4944. Remove(Terminal);
  4945. }
  4946. //---------------------------------------------------------------------------
  4947. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  4948. {
  4949. TTerminal * T = Terminal;
  4950. Terminal = NULL;
  4951. FreeTerminal(T);
  4952. }
  4953. //---------------------------------------------------------------------------
  4954. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  4955. {
  4956. return dynamic_cast<TTerminal *>(Items[Index]);
  4957. }
  4958. //---------------------------------------------------------------------------
  4959. void __fastcall TTerminalList::Idle()
  4960. {
  4961. TTerminal * Terminal;
  4962. for (int i = 0; i < Count; i++)
  4963. {
  4964. Terminal = Terminals[i];
  4965. if (Terminal->Status == ssOpened)
  4966. {
  4967. Terminal->Idle();
  4968. }
  4969. }
  4970. }
  4971. //---------------------------------------------------------------------------
  4972. void __fastcall TTerminalList::RecryptPasswords()
  4973. {
  4974. for (int Index = 0; Index < Count; Index++)
  4975. {
  4976. Terminals[Index]->RecryptPasswords();
  4977. }
  4978. }