Terminal.cpp 127 KB

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