Terminal.cpp 193 KB

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