Terminal.cpp 149 KB

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