Terminal.cpp 150 KB

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