Terminal.cpp 167 KB

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