Terminal.cpp 168 KB

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