Terminal.cpp 149 KB

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