Terminal.cpp 150 KB

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