Terminal.cpp 144 KB

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