Terminal.cpp 165 KB

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