Terminal.cpp 155 KB

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