Terminal.cpp 188 KB

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