Terminal.cpp 192 KB

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