Terminal.cpp 168 KB

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