Terminal.cpp 149 KB

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