Terminal.cpp 193 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259
  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->SkipToAll = true;
  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->Cancel = 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->SkipToAll = true;
  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->BatchOverwrite = 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->TransferedSize))));
  2674. }
  2675. }
  2676. //---------------------------------------------------------------------------
  2677. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2678. {
  2679. DebugAssert(FileList);
  2680. DebugAssert(FFileSystem);
  2681. TRobustOperationLoop RobustLoop(this, OperationProgress);
  2682. do
  2683. {
  2684. try
  2685. {
  2686. FFileSystem->ReadDirectory(FileList);
  2687. }
  2688. catch (Exception & E)
  2689. {
  2690. // Do not retry for initial listing of directory,
  2691. // we instead retry whole connection attempt,
  2692. // what would be done anyway (but Open is not ready for recursion).
  2693. if ((FOpening > 0) ||
  2694. !RobustLoop.TryReopen(E))
  2695. {
  2696. throw;
  2697. }
  2698. }
  2699. }
  2700. while (RobustLoop.Retry());
  2701. if (Log->Logging)
  2702. {
  2703. for (int Index = 0; Index < FileList->Count; Index++)
  2704. {
  2705. LogRemoteFile(FileList->Files[Index]);
  2706. }
  2707. }
  2708. ReactOnCommand(fsListDirectory);
  2709. }
  2710. //---------------------------------------------------------------------------
  2711. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2712. {
  2713. TRemoteFileList * FileList;
  2714. TRetryOperationLoop RetryLoop(this);
  2715. do
  2716. {
  2717. FileList = NULL;
  2718. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2719. try
  2720. {
  2721. FileList = DoReadDirectoryListing(Directory, false);
  2722. if (FileList != NULL)
  2723. {
  2724. int Index = 0;
  2725. while (Index < FileList->Count)
  2726. {
  2727. TRemoteFile * File = FileList->Files[Index];
  2728. TFileMasks::TParams Params;
  2729. Params.Size = File->Size;
  2730. Params.Modification = File->Modification;
  2731. // Have to use UnicodeString(), instead of L"", as with that
  2732. // overload with (UnicodeString, bool, bool, TParams*) wins
  2733. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  2734. {
  2735. FileList->Delete(Index);
  2736. }
  2737. else
  2738. {
  2739. Index++;
  2740. }
  2741. }
  2742. Action.FileList(FileList);
  2743. }
  2744. }
  2745. catch(Exception & E)
  2746. {
  2747. RetryLoop.Error(E, Action);
  2748. }
  2749. }
  2750. while (RetryLoop.Retry());
  2751. return FileList;
  2752. }
  2753. //---------------------------------------------------------------------------
  2754. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2755. {
  2756. TRemoteFile * File;
  2757. TRetryOperationLoop RetryLoop(this);
  2758. do
  2759. {
  2760. File = NULL;
  2761. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2762. try
  2763. {
  2764. // reset caches
  2765. AnnounceFileListOperation();
  2766. ReadFile(Path, File);
  2767. Action.File(File);
  2768. }
  2769. catch(Exception & E)
  2770. {
  2771. RetryLoop.Error(E, Action);
  2772. }
  2773. }
  2774. while (RetryLoop.Retry());
  2775. return File;
  2776. }
  2777. //---------------------------------------------------------------------------
  2778. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2779. {
  2780. TRemoteFileList * FileList = NULL;
  2781. TRetryOperationLoop RetryLoop(this);
  2782. do
  2783. {
  2784. try
  2785. {
  2786. FileList = DoReadDirectoryListing(Directory, UseCache);
  2787. }
  2788. catch(Exception & E)
  2789. {
  2790. RetryLoop.Error(E);
  2791. }
  2792. }
  2793. while (RetryLoop.Retry());
  2794. return FileList;
  2795. }
  2796. //---------------------------------------------------------------------------
  2797. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2798. {
  2799. TRemoteFileList * FileList = new TRemoteFileList();
  2800. try
  2801. {
  2802. bool Cache = UseCache && SessionData->CacheDirectories;
  2803. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2804. if (LoadedFromCache)
  2805. {
  2806. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2807. }
  2808. if (!LoadedFromCache)
  2809. {
  2810. FileList->Directory = Directory;
  2811. ExceptionOnFail = true;
  2812. try
  2813. {
  2814. ReadDirectory(FileList);
  2815. }
  2816. __finally
  2817. {
  2818. ExceptionOnFail = false;
  2819. }
  2820. if (Cache)
  2821. {
  2822. AddCachedFileList(FileList);
  2823. }
  2824. }
  2825. }
  2826. catch(...)
  2827. {
  2828. delete FileList;
  2829. throw;
  2830. }
  2831. return FileList;
  2832. }
  2833. //---------------------------------------------------------------------------
  2834. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2835. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2836. {
  2837. TRemoteFileList * FileList = NULL;
  2838. if (IgnoreErrors)
  2839. {
  2840. ExceptionOnFail = true;
  2841. try
  2842. {
  2843. try
  2844. {
  2845. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2846. }
  2847. catch(...)
  2848. {
  2849. if (!Active)
  2850. {
  2851. throw;
  2852. }
  2853. }
  2854. }
  2855. __finally
  2856. {
  2857. ExceptionOnFail = false;
  2858. }
  2859. }
  2860. else
  2861. {
  2862. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2863. }
  2864. // skip if directory listing fails and user selects "skip"
  2865. if (FileList)
  2866. {
  2867. try
  2868. {
  2869. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2870. TRemoteFile * File;
  2871. for (int Index = 0; Index < FileList->Count; Index++)
  2872. {
  2873. File = FileList->Files[Index];
  2874. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2875. {
  2876. CallBackFunc(Directory + File->FileName, File, Param);
  2877. // We should catch EScpSkipFile here as we do in ProcessFiles.
  2878. // Now we have to handle EScpSkipFile in every callback implementation.
  2879. }
  2880. }
  2881. }
  2882. __finally
  2883. {
  2884. delete FileList;
  2885. }
  2886. }
  2887. }
  2888. //---------------------------------------------------------------------------
  2889. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2890. {
  2891. try
  2892. {
  2893. CustomReadDirectory(FileList);
  2894. }
  2895. catch (Exception &E)
  2896. {
  2897. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2898. }
  2899. }
  2900. //---------------------------------------------------------------------------
  2901. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2902. TRemoteFile *& File)
  2903. {
  2904. DebugAssert(FFileSystem);
  2905. try
  2906. {
  2907. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2908. FFileSystem->ReadSymlink(SymlinkFile, File);
  2909. ReactOnCommand(fsReadSymlink);
  2910. }
  2911. catch (Exception &E)
  2912. {
  2913. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2914. }
  2915. }
  2916. //---------------------------------------------------------------------------
  2917. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2918. TRemoteFile *& File)
  2919. {
  2920. DebugAssert(FFileSystem);
  2921. File = NULL;
  2922. try
  2923. {
  2924. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2925. FFileSystem->ReadFile(FileName, File);
  2926. ReactOnCommand(fsListFile);
  2927. LogRemoteFile(File);
  2928. }
  2929. catch (Exception &E)
  2930. {
  2931. if (File) delete File;
  2932. File = NULL;
  2933. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2934. }
  2935. }
  2936. //---------------------------------------------------------------------------
  2937. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2938. {
  2939. bool Result;
  2940. TRemoteFile * File = NULL;
  2941. try
  2942. {
  2943. ExceptionOnFail = true;
  2944. try
  2945. {
  2946. ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  2947. }
  2948. __finally
  2949. {
  2950. ExceptionOnFail = false;
  2951. }
  2952. if (AFile != NULL)
  2953. {
  2954. *AFile = File;
  2955. }
  2956. else
  2957. {
  2958. delete File;
  2959. }
  2960. Result = true;
  2961. }
  2962. catch(...)
  2963. {
  2964. if (Active)
  2965. {
  2966. Result = false;
  2967. }
  2968. else
  2969. {
  2970. throw;
  2971. }
  2972. }
  2973. return Result;
  2974. }
  2975. //---------------------------------------------------------------------------
  2976. void __fastcall TTerminal::AnnounceFileListOperation()
  2977. {
  2978. FFileSystem->AnnounceFileListOperation();
  2979. }
  2980. //---------------------------------------------------------------------------
  2981. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2982. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2983. TOperationSide Side, bool Ex)
  2984. {
  2985. DebugAssert(FFileSystem);
  2986. DebugAssert(FileList);
  2987. bool Result = false;
  2988. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2989. try
  2990. {
  2991. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2992. Progress.Start(Operation, Side, FileList->Count);
  2993. FOperationProgress = &Progress;
  2994. try
  2995. {
  2996. if (Side == osRemote)
  2997. {
  2998. BeginTransaction();
  2999. }
  3000. try
  3001. {
  3002. int Index = 0;
  3003. UnicodeString FileName;
  3004. bool Success;
  3005. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  3006. {
  3007. FileName = FileList->Strings[Index];
  3008. try
  3009. {
  3010. try
  3011. {
  3012. Success = false;
  3013. if (!Ex)
  3014. {
  3015. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  3016. }
  3017. else
  3018. {
  3019. // not used anymore
  3020. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  3021. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  3022. }
  3023. Success = true;
  3024. }
  3025. __finally
  3026. {
  3027. Progress.Finish(FileName, Success, OnceDoneOperation);
  3028. }
  3029. }
  3030. catch(EScpSkipFile & E)
  3031. {
  3032. TSuspendFileOperationProgress Suspend(OperationProgress);
  3033. if (!HandleException(&E))
  3034. {
  3035. throw;
  3036. }
  3037. }
  3038. Index++;
  3039. }
  3040. }
  3041. __finally
  3042. {
  3043. if (Side == osRemote)
  3044. {
  3045. EndTransaction();
  3046. }
  3047. }
  3048. if (Progress.Cancel == csContinue)
  3049. {
  3050. Result = true;
  3051. }
  3052. }
  3053. __finally
  3054. {
  3055. FOperationProgress = NULL;
  3056. Progress.Stop();
  3057. }
  3058. }
  3059. catch (...)
  3060. {
  3061. OnceDoneOperation = odoIdle;
  3062. // this was missing here. was it by purpose?
  3063. // without it any error message is lost
  3064. throw;
  3065. }
  3066. if (OnceDoneOperation != odoIdle)
  3067. {
  3068. CloseOnCompletion(OnceDoneOperation);
  3069. }
  3070. return Result;
  3071. }
  3072. //---------------------------------------------------------------------------
  3073. // not used anymore
  3074. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3075. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3076. {
  3077. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3078. Param, Side, true);
  3079. }
  3080. //---------------------------------------------------------------------------
  3081. TStrings * __fastcall TTerminal::GetFixedPaths()
  3082. {
  3083. DebugAssert(FFileSystem != NULL);
  3084. return FFileSystem->GetFixedPaths();
  3085. }
  3086. //---------------------------------------------------------------------------
  3087. bool __fastcall TTerminal::GetResolvingSymlinks()
  3088. {
  3089. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3090. }
  3091. //---------------------------------------------------------------------------
  3092. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3093. {
  3094. TUsableCopyParamAttrs Result;
  3095. Result.General =
  3096. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3097. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3098. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3099. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3100. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3101. // the following three are never supported for download,
  3102. // so when they are not suppored for upload too,
  3103. // set them in General flags, so that they do not get enabled on
  3104. // Synchronize dialog.
  3105. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3106. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3107. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3108. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3109. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport);
  3110. Result.Download = Result.General | cpaNoClearArchive |
  3111. cpaNoIgnorePermErrors |
  3112. // May be already set in General flags, but it's unconditional here
  3113. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  3114. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3115. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3116. return Result;
  3117. }
  3118. //---------------------------------------------------------------------------
  3119. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3120. {
  3121. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3122. if (Result)
  3123. {
  3124. UnicodeString Path = UnixExtractFilePath(FileName);
  3125. if (Path.IsEmpty())
  3126. {
  3127. Path = CurrentDirectory;
  3128. }
  3129. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3130. }
  3131. return Result;
  3132. }
  3133. //---------------------------------------------------------------------------
  3134. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  3135. const TRemoteFile * File)
  3136. {
  3137. if (FileName.IsEmpty())
  3138. {
  3139. DebugAssert(File != NULL);
  3140. FileName = File->FileName;
  3141. }
  3142. if (!IsRecycledFile(FileName))
  3143. {
  3144. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3145. (FileName, SessionData->RecycleBinPath)));
  3146. TMoveFileParams Params;
  3147. Params.Target = SessionData->RecycleBinPath;
  3148. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3149. MoveFile(FileName, File, &Params);
  3150. }
  3151. }
  3152. //---------------------------------------------------------------------------
  3153. bool __fastcall TTerminal::TryStartOperationWithFile(
  3154. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3155. {
  3156. bool Result = true;
  3157. if ((OperationProgress != NULL) &&
  3158. ((OperationProgress->Operation == Operation1) ||
  3159. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3160. {
  3161. if (OperationProgress->Cancel != csContinue)
  3162. {
  3163. Result = false;
  3164. }
  3165. else
  3166. {
  3167. OperationProgress->SetFile(FileName);
  3168. }
  3169. }
  3170. return Result;
  3171. }
  3172. //---------------------------------------------------------------------------
  3173. void __fastcall TTerminal::StartOperationWithFile(
  3174. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3175. {
  3176. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3177. {
  3178. Abort();
  3179. }
  3180. }
  3181. //---------------------------------------------------------------------------
  3182. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3183. const TRemoteFile * File, void * AParams)
  3184. {
  3185. if (FileName.IsEmpty() && File)
  3186. {
  3187. FileName = File->FileName;
  3188. }
  3189. StartOperationWithFile(FileName, foDelete);
  3190. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3191. bool Recycle =
  3192. FLAGCLEAR(Params, dfForceDelete) &&
  3193. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3194. !SessionData->RecycleBinPath.IsEmpty();
  3195. if (Recycle && !IsRecycledFile(FileName))
  3196. {
  3197. RecycleFile(FileName, File);
  3198. }
  3199. else
  3200. {
  3201. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3202. FileModified(File, FileName, true);
  3203. DoDeleteFile(FileName, File, Params);
  3204. ReactOnCommand(fsDeleteFile);
  3205. }
  3206. }
  3207. //---------------------------------------------------------------------------
  3208. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3209. const TRemoteFile * File, int Params)
  3210. {
  3211. TRetryOperationLoop RetryLoop(this);
  3212. do
  3213. {
  3214. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3215. try
  3216. {
  3217. DebugAssert(FFileSystem);
  3218. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3219. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3220. }
  3221. catch(Exception & E)
  3222. {
  3223. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3224. }
  3225. }
  3226. while (RetryLoop.Retry());
  3227. }
  3228. //---------------------------------------------------------------------------
  3229. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3230. {
  3231. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3232. FUseBusyCursor = false;
  3233. // TODO: avoid resolving symlinks while reading subdirectories.
  3234. // Resolving does not work anyway for relative symlinks in subdirectories
  3235. // (at least for SFTP).
  3236. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3237. }
  3238. //---------------------------------------------------------------------------
  3239. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3240. const TRemoteFile * /*File*/, void * Params)
  3241. {
  3242. StartOperationWithFile(FileName, foDelete);
  3243. if (OnDeleteLocalFile == NULL)
  3244. {
  3245. RecursiveDeleteFileChecked(FileName, false);
  3246. }
  3247. else
  3248. {
  3249. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  3250. }
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3254. {
  3255. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3256. }
  3257. //---------------------------------------------------------------------------
  3258. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3259. const TRemoteFile * File, void * AParams)
  3260. {
  3261. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3262. if (FileName.IsEmpty() && File)
  3263. {
  3264. FileName = File->FileName;
  3265. }
  3266. StartOperationWithFile(FileName, foCustomCommand);
  3267. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3268. (Params->Command, Params->Params, FileName)));
  3269. FileModified(File, FileName);
  3270. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3271. Params->OutputEvent);
  3272. ReactOnCommand(fsAnyCommand);
  3273. }
  3274. //---------------------------------------------------------------------------
  3275. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3276. const TRemoteFile * File, UnicodeString Command, int Params,
  3277. TCaptureOutputEvent OutputEvent)
  3278. {
  3279. TRetryOperationLoop RetryLoop(this);
  3280. do
  3281. {
  3282. try
  3283. {
  3284. if (IsCapable[fcAnyCommand])
  3285. {
  3286. DebugAssert(FFileSystem);
  3287. DebugAssert(fcShellAnyCommand);
  3288. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3289. }
  3290. else
  3291. {
  3292. DebugAssert(CommandSessionOpened);
  3293. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3294. LogEvent(L"Executing custom command on command session.");
  3295. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3296. {
  3297. FCommandSession->CurrentDirectory = CurrentDirectory;
  3298. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3299. // until transaction ends. But we need to know CurrentDirectory to
  3300. // expand !/ pattern.
  3301. // Doing this only, when current directory of the main and secondary shell differs,
  3302. // what would be the case before the first file in transaction.
  3303. // Otherwise we would be reading pwd before every time as the
  3304. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3305. if (FCommandSession->FReadCurrentDirectoryPending)
  3306. {
  3307. FCommandSession->ReadCurrentDirectory();
  3308. }
  3309. }
  3310. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3311. Params, OutputEvent);
  3312. }
  3313. }
  3314. catch(Exception & E)
  3315. {
  3316. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  3317. }
  3318. }
  3319. while (RetryLoop.Retry());
  3320. }
  3321. //---------------------------------------------------------------------------
  3322. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3323. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3324. {
  3325. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3326. {
  3327. TCustomCommandParams AParams;
  3328. AParams.Command = Command;
  3329. AParams.Params = Params;
  3330. AParams.OutputEvent = OutputEvent;
  3331. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3332. }
  3333. else
  3334. {
  3335. UnicodeString FileList;
  3336. for (int i = 0; i < Files->Count; i++)
  3337. {
  3338. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3339. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  3340. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3341. {
  3342. if (!FileList.IsEmpty())
  3343. {
  3344. FileList += L" ";
  3345. }
  3346. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3347. }
  3348. }
  3349. TCustomCommandData Data(this);
  3350. UnicodeString Cmd =
  3351. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3352. Complete(Command, true);
  3353. if (!DoOnCustomCommand(Cmd))
  3354. {
  3355. DoAnyCommand(Cmd, OutputEvent, NULL);
  3356. }
  3357. }
  3358. }
  3359. //---------------------------------------------------------------------------
  3360. bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command)
  3361. {
  3362. bool Result = false;
  3363. if (FOnCustomCommand != NULL)
  3364. {
  3365. FOnCustomCommand(this, Command, Result);
  3366. }
  3367. return Result;
  3368. }
  3369. //---------------------------------------------------------------------------
  3370. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3371. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3372. {
  3373. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3374. DebugAssert(RProperties && !RProperties->Valid.Empty());
  3375. if (FileName.IsEmpty() && File)
  3376. {
  3377. FileName = File->FileName;
  3378. }
  3379. StartOperationWithFile(FileName, foSetProperties);
  3380. if (Log->Logging)
  3381. {
  3382. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3383. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3384. if (RProperties->Valid.Contains(vpRights))
  3385. {
  3386. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3387. }
  3388. if (RProperties->Valid.Contains(vpGroup))
  3389. {
  3390. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3391. }
  3392. if (RProperties->Valid.Contains(vpOwner))
  3393. {
  3394. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3395. }
  3396. if (RProperties->Valid.Contains(vpModification))
  3397. {
  3398. LogEvent(FORMAT(L" - modification: \"%s\"",
  3399. (FormatDateTime(L"dddddd tt",
  3400. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3401. }
  3402. if (RProperties->Valid.Contains(vpLastAccess))
  3403. {
  3404. LogEvent(FORMAT(L" - last access: \"%s\"",
  3405. (FormatDateTime(L"dddddd tt",
  3406. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3407. }
  3408. }
  3409. FileModified(File, FileName);
  3410. DoChangeFileProperties(FileName, File, RProperties);
  3411. ReactOnCommand(fsChangeProperties);
  3412. }
  3413. //---------------------------------------------------------------------------
  3414. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3415. const TRemoteFile * File, const TRemoteProperties * Properties)
  3416. {
  3417. TRetryOperationLoop RetryLoop(this);
  3418. do
  3419. {
  3420. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3421. try
  3422. {
  3423. DebugAssert(FFileSystem);
  3424. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3425. }
  3426. catch(Exception & E)
  3427. {
  3428. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  3429. }
  3430. }
  3431. while (RetryLoop.Retry());
  3432. }
  3433. //---------------------------------------------------------------------------
  3434. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3435. const TRemoteProperties * Properties)
  3436. {
  3437. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3438. FUseBusyCursor = false;
  3439. AnnounceFileListOperation();
  3440. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3441. }
  3442. //---------------------------------------------------------------------------
  3443. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3444. {
  3445. // see comment in TSFTPFileSystem::IsCapable
  3446. bool Result =
  3447. IsCapable[fcLoadingAdditionalProperties] &&
  3448. FFileSystem->LoadFilesProperties(FileList);
  3449. if (Result && SessionData->CacheDirectories &&
  3450. (FileList->Count > 0) &&
  3451. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3452. {
  3453. AddCachedFileList(FFiles);
  3454. }
  3455. return Result;
  3456. }
  3457. //---------------------------------------------------------------------------
  3458. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3459. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3460. {
  3461. DebugAssert(Param);
  3462. DebugAssert(File);
  3463. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3464. if (FileName.IsEmpty())
  3465. {
  3466. FileName = File->FileName;
  3467. }
  3468. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  3469. {
  3470. AParams->Result = false;
  3471. // Combined with csIgnoreErrors, this will not abort completelly, but we get called again
  3472. // with next sibling of our parent directory (and we get again to this branch, throwing again)
  3473. Abort();
  3474. }
  3475. bool AllowTransfer = (AParams->CopyParam == NULL);
  3476. if (!AllowTransfer)
  3477. {
  3478. TFileMasks::TParams MaskParams;
  3479. MaskParams.Size = File->Size;
  3480. MaskParams.Modification = File->Modification;
  3481. UnicodeString BaseFileName =
  3482. GetBaseFileName(UnixExcludeTrailingBackslash(File->FullFileName));
  3483. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3484. BaseFileName, osRemote, File->IsDirectory, MaskParams);
  3485. }
  3486. if (AllowTransfer)
  3487. {
  3488. if (File->IsDirectory)
  3489. {
  3490. if (CanRecurseToDirectory(File))
  3491. {
  3492. if (!AParams->AllowDirs)
  3493. {
  3494. AParams->Result = false;
  3495. }
  3496. else
  3497. {
  3498. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3499. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3500. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3501. }
  3502. }
  3503. if (AParams->Stats != NULL)
  3504. {
  3505. AParams->Stats->Directories++;
  3506. }
  3507. }
  3508. else
  3509. {
  3510. AParams->Size += File->Size;
  3511. if (AParams->Stats != NULL)
  3512. {
  3513. AParams->Stats->Files++;
  3514. }
  3515. }
  3516. if ((AParams->Stats != NULL) && File->IsSymLink)
  3517. {
  3518. AParams->Stats->SymLinks++;
  3519. }
  3520. }
  3521. }
  3522. //---------------------------------------------------------------------------
  3523. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3524. const TRemoteFile * /*File*/, TCalculateSizeParams * Params)
  3525. {
  3526. TRetryOperationLoop RetryLoop(this);
  3527. do
  3528. {
  3529. try
  3530. {
  3531. ProcessDirectory(FileName, CalculateFileSize, Params);
  3532. }
  3533. catch(Exception & E)
  3534. {
  3535. // We can probably replace the csIgnoreErrors with IgnoreErrors argument of the ProcessDirectory
  3536. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3537. {
  3538. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  3539. }
  3540. }
  3541. }
  3542. while (RetryLoop.Retry());
  3543. }
  3544. //---------------------------------------------------------------------------
  3545. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3546. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3547. bool AllowDirs, TCalculateSizeStats * Stats)
  3548. {
  3549. // With FTP protocol, we may use DSIZ command from
  3550. // draft-peterson-streamlined-ftp-command-extensions-10
  3551. // Implemented by Serv-U FTP.
  3552. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3553. FUseBusyCursor = false;
  3554. TCalculateSizeParams Param;
  3555. Param.Size = 0;
  3556. Param.Params = Params;
  3557. Param.CopyParam = CopyParam;
  3558. Param.Stats = Stats;
  3559. Param.AllowDirs = AllowDirs;
  3560. Param.Result = true;
  3561. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3562. Size = Param.Size;
  3563. return Param.Result;
  3564. }
  3565. //---------------------------------------------------------------------------
  3566. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3567. TStrings * FileList, TStrings * Checksums,
  3568. TCalculatedChecksumEvent OnCalculatedChecksum)
  3569. {
  3570. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3571. }
  3572. //---------------------------------------------------------------------------
  3573. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3574. const UnicodeString NewName)
  3575. {
  3576. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3577. DoRenameFile(FileName, NewName, false);
  3578. ReactOnCommand(fsRenameFile);
  3579. }
  3580. //---------------------------------------------------------------------------
  3581. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3582. const UnicodeString NewName, bool CheckExistence)
  3583. {
  3584. DebugAssert(File && File->Directory == FFiles);
  3585. bool Proceed = true;
  3586. // if filename doesn't contain path, we check for existence of file
  3587. if ((File->FileName != NewName) && CheckExistence &&
  3588. Configuration->ConfirmOverwriting &&
  3589. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3590. {
  3591. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3592. if (DuplicateFile)
  3593. {
  3594. UnicodeString QuestionFmt;
  3595. if (DuplicateFile->IsDirectory)
  3596. {
  3597. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3598. }
  3599. else
  3600. {
  3601. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3602. }
  3603. TQueryParams Params(qpNeverAskAgainCheck);
  3604. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3605. unsigned int Result = QueryUser(Question, NULL,
  3606. qaYes | qaNo, &Params);
  3607. if (Result == qaNeverAskAgain)
  3608. {
  3609. Proceed = true;
  3610. Configuration->ConfirmOverwriting = false;
  3611. }
  3612. else
  3613. {
  3614. Proceed = (Result == qaYes);
  3615. }
  3616. }
  3617. }
  3618. if (Proceed)
  3619. {
  3620. FileModified(File, File->FileName);
  3621. RenameFile(File->FileName, NewName);
  3622. }
  3623. }
  3624. //---------------------------------------------------------------------------
  3625. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3626. const UnicodeString NewName, bool Move)
  3627. {
  3628. TRetryOperationLoop RetryLoop(this);
  3629. do
  3630. {
  3631. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3632. try
  3633. {
  3634. DebugAssert(FFileSystem);
  3635. FFileSystem->RenameFile(FileName, NewName);
  3636. }
  3637. catch(Exception & E)
  3638. {
  3639. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  3640. RetryLoop.Error(E, Action, Message);
  3641. }
  3642. }
  3643. while (RetryLoop.Retry());
  3644. }
  3645. //---------------------------------------------------------------------------
  3646. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3647. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3648. {
  3649. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  3650. DebugAssert(Param != NULL);
  3651. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3652. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3653. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3654. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3655. FileModified(File, FileName);
  3656. DoRenameFile(FileName, NewName, true);
  3657. ReactOnCommand(fsMoveFile);
  3658. }
  3659. //---------------------------------------------------------------------------
  3660. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3661. const UnicodeString FileMask)
  3662. {
  3663. TMoveFileParams Params;
  3664. Params.Target = Target;
  3665. Params.FileMask = FileMask;
  3666. DirectoryModified(Target, true);
  3667. bool Result;
  3668. BeginTransaction();
  3669. try
  3670. {
  3671. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3672. }
  3673. __finally
  3674. {
  3675. if (Active)
  3676. {
  3677. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3678. bool PossiblyMoved = false;
  3679. // check if we was moving current directory.
  3680. // this is just optimization to avoid checking existence of current
  3681. // directory after each move operation.
  3682. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3683. {
  3684. const TRemoteFile * File =
  3685. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3686. // File can be NULL, and filename may not be full path,
  3687. // but currently this is the only way we can move (at least in GUI)
  3688. // current directory
  3689. if ((File != NULL) &&
  3690. File->IsDirectory &&
  3691. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3692. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3693. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3694. {
  3695. PossiblyMoved = true;
  3696. }
  3697. }
  3698. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3699. {
  3700. UnicodeString NearestExisting = CurrentDirectory;
  3701. do
  3702. {
  3703. NearestExisting = UnixExtractFileDir(NearestExisting);
  3704. }
  3705. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3706. ChangeDirectory(NearestExisting);
  3707. }
  3708. }
  3709. EndTransaction();
  3710. }
  3711. return Result;
  3712. }
  3713. //---------------------------------------------------------------------------
  3714. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3715. const UnicodeString NewName)
  3716. {
  3717. TRetryOperationLoop RetryLoop(this);
  3718. do
  3719. {
  3720. try
  3721. {
  3722. DebugAssert(FFileSystem);
  3723. if (IsCapable[fcRemoteCopy])
  3724. {
  3725. FFileSystem->CopyFile(FileName, NewName);
  3726. }
  3727. else
  3728. {
  3729. DebugAssert(CommandSessionOpened);
  3730. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3731. LogEvent(L"Copying file on command session.");
  3732. FCommandSession->CurrentDirectory = CurrentDirectory;
  3733. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3734. }
  3735. }
  3736. catch(Exception & E)
  3737. {
  3738. RetryLoop.Error(E, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  3739. }
  3740. }
  3741. while (RetryLoop.Retry());
  3742. }
  3743. //---------------------------------------------------------------------------
  3744. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3745. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3746. {
  3747. StartOperationWithFile(FileName, foRemoteCopy);
  3748. DebugAssert(Param != NULL);
  3749. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3750. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3751. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3752. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3753. DoCopyFile(FileName, NewName);
  3754. ReactOnCommand(fsCopyFile);
  3755. }
  3756. //---------------------------------------------------------------------------
  3757. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3758. const UnicodeString FileMask)
  3759. {
  3760. TMoveFileParams Params;
  3761. Params.Target = Target;
  3762. Params.FileMask = FileMask;
  3763. DirectoryModified(Target, true);
  3764. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3765. }
  3766. //---------------------------------------------------------------------------
  3767. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3768. const TRemoteProperties * Properties)
  3769. {
  3770. DebugAssert(FFileSystem);
  3771. EnsureNonExistence(DirName);
  3772. FileModified(NULL, DirName);
  3773. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3774. DoCreateDirectory(DirName);
  3775. if ((Properties != NULL) && !Properties->Valid.Empty())
  3776. {
  3777. DoChangeFileProperties(DirName, NULL, Properties);
  3778. }
  3779. ReactOnCommand(fsCreateDirectory);
  3780. }
  3781. //---------------------------------------------------------------------------
  3782. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3783. {
  3784. TRetryOperationLoop RetryLoop(this);
  3785. do
  3786. {
  3787. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3788. try
  3789. {
  3790. DebugAssert(FFileSystem);
  3791. FFileSystem->CreateDirectory(DirName);
  3792. }
  3793. catch(Exception & E)
  3794. {
  3795. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  3796. }
  3797. }
  3798. while (RetryLoop.Retry());
  3799. }
  3800. //---------------------------------------------------------------------------
  3801. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3802. const UnicodeString PointTo, bool Symbolic)
  3803. {
  3804. DebugAssert(FFileSystem);
  3805. EnsureNonExistence(FileName);
  3806. if (SessionData->CacheDirectories)
  3807. {
  3808. DirectoryModified(CurrentDirectory, false);
  3809. }
  3810. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3811. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3812. DoCreateLink(FileName, PointTo, Symbolic);
  3813. ReactOnCommand(fsCreateDirectory);
  3814. }
  3815. //---------------------------------------------------------------------------
  3816. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3817. const UnicodeString PointTo, bool Symbolic)
  3818. {
  3819. TRetryOperationLoop RetryLoop(this);
  3820. do
  3821. {
  3822. try
  3823. {
  3824. DebugAssert(FFileSystem);
  3825. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3826. }
  3827. catch(Exception & E)
  3828. {
  3829. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  3830. }
  3831. }
  3832. while (RetryLoop.Retry());
  3833. }
  3834. //---------------------------------------------------------------------------
  3835. void __fastcall TTerminal::HomeDirectory()
  3836. {
  3837. DebugAssert(FFileSystem);
  3838. try
  3839. {
  3840. LogEvent(L"Changing directory to home directory.");
  3841. FFileSystem->HomeDirectory();
  3842. ReactOnCommand(fsHomeDirectory);
  3843. }
  3844. catch (Exception &E)
  3845. {
  3846. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3847. }
  3848. }
  3849. //---------------------------------------------------------------------------
  3850. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3851. {
  3852. DebugAssert(FFileSystem);
  3853. try
  3854. {
  3855. UnicodeString CachedDirectory;
  3856. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3857. // never use directory change cache during startup, this ensures, we never
  3858. // end-up initially in non-existing directory
  3859. if ((Status == ssOpened) &&
  3860. SessionData->CacheDirectoryChanges &&
  3861. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3862. Directory, CachedDirectory))
  3863. {
  3864. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3865. (Directory, CachedDirectory)));
  3866. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3867. }
  3868. else
  3869. {
  3870. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3871. FFileSystem->ChangeDirectory(Directory);
  3872. }
  3873. FLastDirectoryChange = Directory;
  3874. ReactOnCommand(fsChangeDirectory);
  3875. }
  3876. catch (Exception &E)
  3877. {
  3878. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3879. }
  3880. }
  3881. //---------------------------------------------------------------------------
  3882. void __fastcall TTerminal::LookupUsersGroups()
  3883. {
  3884. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3885. IsCapable[fcUserGroupListing])
  3886. {
  3887. DebugAssert(FFileSystem);
  3888. try
  3889. {
  3890. FUsersGroupsLookedup = true;
  3891. LogEvent(L"Looking up groups and users.");
  3892. FFileSystem->LookupUsersGroups();
  3893. ReactOnCommand(fsLookupUsersGroups);
  3894. if (Log->Logging)
  3895. {
  3896. FGroups.Log(this, L"groups");
  3897. FMembership.Log(this, L"membership");
  3898. FUsers.Log(this, L"users");
  3899. }
  3900. }
  3901. catch (Exception &E)
  3902. {
  3903. if (!Active || (SessionData->LookupUserGroups == asOn))
  3904. {
  3905. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3906. }
  3907. }
  3908. }
  3909. }
  3910. //---------------------------------------------------------------------------
  3911. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3912. {
  3913. return !Command.Trim().IsEmpty();
  3914. }
  3915. //---------------------------------------------------------------------------
  3916. bool __fastcall TTerminal::GetCommandSessionOpened()
  3917. {
  3918. // consider secondary terminal open in "ready" state only
  3919. // so we never do keepalives on it until it is completely initialized
  3920. return (FCommandSession != NULL) &&
  3921. (FCommandSession->Status == ssOpened);
  3922. }
  3923. //---------------------------------------------------------------------------
  3924. TTerminal * __fastcall TTerminal::CreateSecondarySession(const UnicodeString & Name, TSessionData * SessionData)
  3925. {
  3926. std::unique_ptr<TTerminal> Result(new TSecondaryTerminal(this, SessionData, Configuration, Name));
  3927. Result->AutoReadDirectory = false;
  3928. Result->FExceptionOnFail = FExceptionOnFail;
  3929. Result->OnQueryUser = OnQueryUser;
  3930. Result->OnPromptUser = OnPromptUser;
  3931. Result->OnShowExtendedException = OnShowExtendedException;
  3932. Result->OnProgress = OnProgress;
  3933. Result->OnFinished = OnFinished;
  3934. Result->OnInformation = OnInformation;
  3935. Result->OnCustomCommand = OnCustomCommand;
  3936. // do not copy OnDisplayBanner to avoid it being displayed
  3937. return Result.release();
  3938. }
  3939. //---------------------------------------------------------------------------
  3940. TTerminal * __fastcall TTerminal::GetCommandSession()
  3941. {
  3942. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3943. {
  3944. SAFE_DESTROY(FCommandSession);
  3945. }
  3946. if (FCommandSession == NULL)
  3947. {
  3948. // transaction cannot be started yet to allow proper matching transaction
  3949. // levels between main and command session
  3950. DebugAssert(FInTransaction == 0);
  3951. std::unique_ptr<TSessionData> CommandSessionData(SessionData->Clone());
  3952. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3953. CommandSessionData->FSProtocol = fsSCPonly;
  3954. CommandSessionData->ClearAliases = false;
  3955. CommandSessionData->UnsetNationalVars = false;
  3956. CommandSessionData->LookupUserGroups = asOff;
  3957. FCommandSession = CreateSecondarySession(L"Shell", CommandSessionData.get());
  3958. FCommandSession->AutoReadDirectory = false;
  3959. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3960. FCommandSession->OnQueryUser = OnQueryUser;
  3961. FCommandSession->OnPromptUser = OnPromptUser;
  3962. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3963. FCommandSession->OnProgress = OnProgress;
  3964. FCommandSession->OnFinished = OnFinished;
  3965. FCommandSession->OnInformation = OnInformation;
  3966. FCommandSession->OnCustomCommand = OnCustomCommand;
  3967. // do not copy OnDisplayBanner to avoid it being displayed
  3968. }
  3969. return FCommandSession;
  3970. }
  3971. //---------------------------------------------------------------------------
  3972. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3973. TCaptureOutputEvent OutputEvent)
  3974. {
  3975. #pragma warn -inl
  3976. class TOutputProxy
  3977. {
  3978. public:
  3979. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3980. FAction(Action),
  3981. FOutputEvent(OutputEvent)
  3982. {
  3983. }
  3984. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  3985. {
  3986. switch (OutputType)
  3987. {
  3988. case cotOutput:
  3989. FAction.AddOutput(Str, false);
  3990. break;
  3991. case cotError:
  3992. FAction.AddOutput(Str, true);
  3993. break;
  3994. case cotExitCode:
  3995. FAction.ExitCode(StrToInt(Str));
  3996. break;
  3997. }
  3998. if (FOutputEvent != NULL)
  3999. {
  4000. FOutputEvent(Str, OutputType);
  4001. }
  4002. }
  4003. private:
  4004. TCallSessionAction & FAction;
  4005. TCaptureOutputEvent FOutputEvent;
  4006. };
  4007. #pragma warn .inl
  4008. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  4009. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  4010. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  4011. }
  4012. //---------------------------------------------------------------------------
  4013. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  4014. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  4015. {
  4016. DebugAssert(FFileSystem);
  4017. try
  4018. {
  4019. DirectoryModified(CurrentDirectory, false);
  4020. if (IsCapable[fcAnyCommand])
  4021. {
  4022. LogEvent(L"Executing user defined command.");
  4023. FFileSystem->AnyCommand(Command, OutputEvent);
  4024. }
  4025. else
  4026. {
  4027. DebugAssert(CommandSessionOpened);
  4028. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4029. LogEvent(L"Executing user defined command on command session.");
  4030. FCommandSession->CurrentDirectory = CurrentDirectory;
  4031. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  4032. FCommandSession->FFileSystem->ReadCurrentDirectory();
  4033. // synchronize pwd (by purpose we lose transaction optimization here)
  4034. ChangeDirectory(FCommandSession->CurrentDirectory);
  4035. }
  4036. ReactOnCommand(fsAnyCommand);
  4037. }
  4038. catch (Exception &E)
  4039. {
  4040. if (Action != NULL)
  4041. {
  4042. RollbackAction(*Action, NULL, &E);
  4043. }
  4044. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  4045. else HandleExtendedException(&E);
  4046. }
  4047. }
  4048. //---------------------------------------------------------------------------
  4049. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  4050. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4051. bool NoConfirmation)
  4052. {
  4053. bool Result = true;
  4054. bool Done;
  4055. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  4056. do
  4057. {
  4058. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  4059. NULL, CREATE_ALWAYS, CreateAttr, 0);
  4060. Done = (*AHandle != INVALID_HANDLE_VALUE);
  4061. if (!Done)
  4062. {
  4063. // save the error, otherwise it gets overwritten by call to FileExists
  4064. int LastError = GetLastError();
  4065. int FileAttr;
  4066. if (::FileExists(ApiPath(FileName)) &&
  4067. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  4068. {
  4069. if (FLAGSET(FileAttr, faReadOnly))
  4070. {
  4071. if (OperationProgress->BatchOverwrite == boNone)
  4072. {
  4073. Result = false;
  4074. }
  4075. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4076. {
  4077. unsigned int Answer;
  4078. {
  4079. TSuspendFileOperationProgress Suspend(OperationProgress);
  4080. Answer = QueryUser(
  4081. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4082. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4083. }
  4084. switch (Answer) {
  4085. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  4086. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  4087. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  4088. case qaNo: Result = false; break;
  4089. }
  4090. }
  4091. }
  4092. else
  4093. {
  4094. DebugAssert(FLAGSET(FileAttr, faHidden));
  4095. Result = true;
  4096. }
  4097. if (Result)
  4098. {
  4099. CreateAttr |=
  4100. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  4101. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  4102. FILE_OPERATION_LOOP_BEGIN
  4103. {
  4104. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  4105. {
  4106. RaiseLastOSError();
  4107. }
  4108. }
  4109. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4110. }
  4111. else
  4112. {
  4113. Done = true;
  4114. }
  4115. }
  4116. else
  4117. {
  4118. RaiseLastOSError(LastError);
  4119. }
  4120. }
  4121. }
  4122. while (!Done);
  4123. return Result;
  4124. }
  4125. //---------------------------------------------------------------------------
  4126. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  4127. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4128. bool NoConfirmation)
  4129. {
  4130. DebugAssert(AHandle);
  4131. bool Result = true;
  4132. FILE_OPERATION_LOOP_BEGIN
  4133. {
  4134. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  4135. }
  4136. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  4137. return Result;
  4138. }
  4139. //---------------------------------------------------------------------------
  4140. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  4141. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  4142. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  4143. bool TryWriteReadOnly)
  4144. {
  4145. int Attrs = 0;
  4146. HANDLE Handle = 0;
  4147. FILE_OPERATION_LOOP_BEGIN
  4148. {
  4149. UnicodeString FileNameApi = ApiPath(FileName);
  4150. Attrs = FileGetAttrFix(FileNameApi);
  4151. if (Attrs < 0)
  4152. {
  4153. RaiseLastOSError();
  4154. }
  4155. }
  4156. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4157. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  4158. {
  4159. bool NoHandle = false;
  4160. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  4161. ((Attrs & faReadOnly) != 0))
  4162. {
  4163. Access = GENERIC_READ;
  4164. NoHandle = true;
  4165. }
  4166. FILE_OPERATION_LOOP_BEGIN
  4167. {
  4168. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  4169. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  4170. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  4171. NULL, OPEN_EXISTING, Flags, 0);
  4172. if (Handle == INVALID_HANDLE_VALUE)
  4173. {
  4174. Handle = 0;
  4175. RaiseLastOSError();
  4176. }
  4177. }
  4178. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  4179. try
  4180. {
  4181. if (AATime || AMTime || ACTime)
  4182. {
  4183. FILETIME ATime;
  4184. FILETIME MTime;
  4185. FILETIME CTime;
  4186. // Get last file access and modification time
  4187. FILE_OPERATION_LOOP_BEGIN
  4188. {
  4189. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  4190. }
  4191. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4192. if (ACTime)
  4193. {
  4194. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  4195. }
  4196. if (AATime)
  4197. {
  4198. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  4199. }
  4200. if (AMTime)
  4201. {
  4202. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  4203. }
  4204. }
  4205. if (ASize)
  4206. {
  4207. // Get file size
  4208. FILE_OPERATION_LOOP_BEGIN
  4209. {
  4210. unsigned long LSize;
  4211. unsigned long HSize;
  4212. LSize = GetFileSize(Handle, &HSize);
  4213. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  4214. *ASize = (__int64(HSize) << 32) + LSize;
  4215. }
  4216. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4217. }
  4218. if ((AHandle == NULL) || NoHandle)
  4219. {
  4220. CloseHandle(Handle);
  4221. Handle = NULL;
  4222. }
  4223. }
  4224. catch(...)
  4225. {
  4226. CloseHandle(Handle);
  4227. throw;
  4228. }
  4229. }
  4230. if (AAttrs) *AAttrs = Attrs;
  4231. if (AHandle) *AHandle = Handle;
  4232. }
  4233. //---------------------------------------------------------------------------
  4234. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  4235. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  4236. {
  4237. bool Result = true;
  4238. // optimization
  4239. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  4240. {
  4241. WIN32_FIND_DATA FindData;
  4242. HANDLE Handle;
  4243. FILE_OPERATION_LOOP_BEGIN
  4244. {
  4245. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  4246. if (Handle == INVALID_HANDLE_VALUE)
  4247. {
  4248. RaiseLastOSError();
  4249. }
  4250. }
  4251. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4252. ::FindClose(Handle);
  4253. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  4254. TFileMasks::TParams Params;
  4255. // SearchRec.Size in C++B2010 is __int64,
  4256. // so we should be able to use it instead of FindData.nFileSize*
  4257. Params.Size =
  4258. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  4259. FindData.nFileSizeLow;
  4260. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  4261. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4262. if (!CopyParam->AllowTransfer(BaseFileName, osLocal, Directory, Params))
  4263. {
  4264. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  4265. Result = false;
  4266. }
  4267. else if (CopyParam->SkipTransfer(FileName, Directory))
  4268. {
  4269. OperationProgress->AddSkippedFileSize(Params.Size);
  4270. Result = false;
  4271. }
  4272. if (Result)
  4273. {
  4274. LogFileDetails(FileName, Params.Modification, Params.Size);
  4275. }
  4276. }
  4277. return Result;
  4278. }
  4279. //---------------------------------------------------------------------------
  4280. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  4281. const TSearchRec Rec, void * Param)
  4282. {
  4283. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4284. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4285. if (Directory && Params.Recursive)
  4286. {
  4287. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4288. }
  4289. if (!Directory || Params.IncludeDirs)
  4290. {
  4291. Params.FileList->Add(FileName);
  4292. if (Params.FileTimes != NULL)
  4293. {
  4294. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4295. }
  4296. }
  4297. }
  4298. //---------------------------------------------------------------------------
  4299. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4300. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4301. {
  4302. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4303. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  4304. {
  4305. AParams->Result = false;
  4306. }
  4307. else
  4308. {
  4309. try
  4310. {
  4311. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4312. bool AllowTransfer = (AParams->CopyParam == NULL);
  4313. // SearchRec.Size in C++B2010 is __int64,
  4314. // so we should be able to use it instead of FindData.nFileSize*
  4315. __int64 Size =
  4316. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4317. Rec.FindData.nFileSizeLow;
  4318. if (!AllowTransfer)
  4319. {
  4320. TFileMasks::TParams MaskParams;
  4321. MaskParams.Size = Size;
  4322. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4323. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4324. AllowTransfer = AParams->CopyParam->AllowTransfer(BaseFileName, osLocal, Dir, MaskParams);
  4325. }
  4326. if (AllowTransfer)
  4327. {
  4328. if (!Dir)
  4329. {
  4330. AParams->Size += Size;
  4331. }
  4332. else
  4333. {
  4334. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4335. }
  4336. }
  4337. }
  4338. catch (...)
  4339. {
  4340. // ignore
  4341. }
  4342. }
  4343. }
  4344. //---------------------------------------------------------------------------
  4345. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4346. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  4347. {
  4348. bool Result = false;
  4349. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4350. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4351. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4352. try
  4353. {
  4354. TCalculateSizeParams Params;
  4355. Params.Size = 0;
  4356. Params.Params = 0;
  4357. Params.CopyParam = CopyParam;
  4358. Params.Result = true;
  4359. DebugAssert(!FOperationProgress);
  4360. FOperationProgress = &OperationProgress;
  4361. for (int Index = 0; Params.Result && (Index < FileList->Count); Index++)
  4362. {
  4363. UnicodeString FileName = FileList->Strings[Index];
  4364. TSearchRec Rec;
  4365. if (FileSearchRec(FileName, Rec))
  4366. {
  4367. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4368. {
  4369. Params.Result = false;
  4370. }
  4371. else
  4372. {
  4373. CalculateLocalFileSize(FileName, Rec, &Params);
  4374. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4375. }
  4376. }
  4377. }
  4378. Size = Params.Size;
  4379. Result = Params.Result;
  4380. }
  4381. __finally
  4382. {
  4383. FOperationProgress = NULL;
  4384. OperationProgress.Stop();
  4385. }
  4386. if (OnceDoneOperation != odoIdle)
  4387. {
  4388. CloseOnCompletion(OnceDoneOperation);
  4389. }
  4390. return Result;
  4391. }
  4392. //---------------------------------------------------------------------------
  4393. struct TSynchronizeFileData
  4394. {
  4395. bool Modified;
  4396. bool New;
  4397. bool IsDirectory;
  4398. TSynchronizeChecklist::TItem::TFileInfo Info;
  4399. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4400. TRemoteFile * MatchingRemoteFileFile;
  4401. int MatchingRemoteFileImageIndex;
  4402. FILETIME LocalLastWriteTime;
  4403. };
  4404. //---------------------------------------------------------------------------
  4405. const int sfFirstLevel = 0x01;
  4406. struct TSynchronizeData
  4407. {
  4408. UnicodeString LocalDirectory;
  4409. UnicodeString RemoteDirectory;
  4410. TTerminal::TSynchronizeMode Mode;
  4411. int Params;
  4412. TSynchronizeDirectory OnSynchronizeDirectory;
  4413. TSynchronizeOptions * Options;
  4414. int Flags;
  4415. TStringList * LocalFileList;
  4416. const TCopyParamType * CopyParam;
  4417. TSynchronizeChecklist * Checklist;
  4418. };
  4419. //---------------------------------------------------------------------------
  4420. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4421. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4422. const TCopyParamType * CopyParam, int Params,
  4423. TSynchronizeDirectory OnSynchronizeDirectory,
  4424. TSynchronizeOptions * Options)
  4425. {
  4426. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4427. FUseBusyCursor = false;
  4428. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4429. try
  4430. {
  4431. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4432. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4433. Checklist);
  4434. Checklist->Sort();
  4435. }
  4436. catch(...)
  4437. {
  4438. delete Checklist;
  4439. throw;
  4440. }
  4441. return Checklist;
  4442. }
  4443. //---------------------------------------------------------------------------
  4444. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4445. {
  4446. if (FLAGSET(Params, Param))
  4447. {
  4448. AddToList(ParamsStr, Name, ", ");
  4449. }
  4450. Params &= ~Param;
  4451. }
  4452. //---------------------------------------------------------------------------
  4453. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4454. {
  4455. UnicodeString ModeStr;
  4456. switch (Mode)
  4457. {
  4458. case smRemote:
  4459. ModeStr = L"Remote";
  4460. break;
  4461. case smLocal:
  4462. ModeStr = L"Local";
  4463. break;
  4464. case smBoth:
  4465. ModeStr = L"Both";
  4466. break;
  4467. default:
  4468. ModeStr = L"Unknown";
  4469. break;
  4470. }
  4471. return ModeStr;
  4472. }
  4473. //---------------------------------------------------------------------------
  4474. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4475. {
  4476. UnicodeString ParamsStr;
  4477. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4478. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4479. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4480. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4481. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4482. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4483. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4484. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4485. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4486. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4487. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4488. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4489. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4490. if (Params > 0)
  4491. {
  4492. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4493. }
  4494. return ParamsStr;
  4495. }
  4496. //---------------------------------------------------------------------------
  4497. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4498. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4499. const TCopyParamType * CopyParam, int Params,
  4500. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4501. int Flags, TSynchronizeChecklist * Checklist)
  4502. {
  4503. TSynchronizeData Data;
  4504. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4505. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4506. Data.Mode = Mode;
  4507. Data.Params = Params;
  4508. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4509. Data.LocalFileList = NULL;
  4510. Data.CopyParam = CopyParam;
  4511. Data.Options = Options;
  4512. Data.Flags = Flags;
  4513. Data.Checklist = Checklist;
  4514. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4515. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4516. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4517. if (FLAGCLEAR(Params, spDelayProgress))
  4518. {
  4519. DoSynchronizeProgress(Data, true);
  4520. }
  4521. try
  4522. {
  4523. bool Found;
  4524. TSearchRecChecked SearchRec;
  4525. Data.LocalFileList = CreateSortedStringList();
  4526. FILE_OPERATION_LOOP_BEGIN
  4527. {
  4528. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4529. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4530. }
  4531. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4532. if (Found)
  4533. {
  4534. try
  4535. {
  4536. UnicodeString FileName;
  4537. while (Found)
  4538. {
  4539. FileName = SearchRec.Name;
  4540. // add dirs for recursive mode or when we are interested in newly
  4541. // added subdirs
  4542. // SearchRec.Size in C++B2010 is __int64,
  4543. // so we should be able to use it instead of FindData.nFileSize*
  4544. __int64 Size =
  4545. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4546. SearchRec.FindData.nFileSizeLow;
  4547. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4548. TFileMasks::TParams MaskParams;
  4549. MaskParams.Size = Size;
  4550. MaskParams.Modification = Modification;
  4551. UnicodeString RemoteFileName =
  4552. ChangeFileName(CopyParam, FileName, osLocal, false);
  4553. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4554. UnicodeString BaseFileName = GetBaseFileName(FullLocalFileName);
  4555. if ((FileName != L".") && (FileName != L"..") &&
  4556. CopyParam->AllowTransfer(BaseFileName, osLocal,
  4557. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4558. !FFileSystem->TemporaryTransferFile(FileName) &&
  4559. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4560. (Options == NULL) ||
  4561. Options->MatchesFilter(FileName) ||
  4562. Options->MatchesFilter(RemoteFileName)))
  4563. {
  4564. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4565. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4566. FileData->Info.FileName = FileName;
  4567. FileData->Info.Directory = Data.LocalDirectory;
  4568. FileData->Info.Modification = Modification;
  4569. FileData->Info.ModificationFmt = mfFull;
  4570. FileData->Info.Size = Size;
  4571. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4572. FileData->New = true;
  4573. FileData->Modified = false;
  4574. Data.LocalFileList->AddObject(FileName,
  4575. reinterpret_cast<TObject*>(FileData));
  4576. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4577. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4578. }
  4579. else
  4580. {
  4581. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4582. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4583. }
  4584. FILE_OPERATION_LOOP_BEGIN
  4585. {
  4586. Found = (FindNextChecked(SearchRec) == 0);
  4587. }
  4588. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4589. }
  4590. }
  4591. __finally
  4592. {
  4593. FindClose(SearchRec);
  4594. }
  4595. // can we expect that ProcessDirectory would take so little time
  4596. // that we can postpone showing progress window until anything actually happens?
  4597. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4598. FDirectoryCache->HasFileList(RemoteDirectory);
  4599. if (!Cached && FLAGSET(Params, spDelayProgress))
  4600. {
  4601. DoSynchronizeProgress(Data, true);
  4602. }
  4603. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4604. FLAGSET(Params, spUseCache));
  4605. TSynchronizeFileData * FileData;
  4606. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4607. {
  4608. FileData = reinterpret_cast<TSynchronizeFileData *>
  4609. (Data.LocalFileList->Objects[Index]);
  4610. // add local file either if we are going to upload it
  4611. // (i.e. if it is updated or we want to upload even new files)
  4612. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4613. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4614. bool New = (FileData->New &&
  4615. ((Mode == smLocal) ||
  4616. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4617. if (New)
  4618. {
  4619. LogEvent(FORMAT(L"Local file %s is new",
  4620. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4621. FileData->Info.Modification, FileData->Info.Size))));
  4622. }
  4623. if (Modified || New)
  4624. {
  4625. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4626. try
  4627. {
  4628. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4629. ChecklistItem->Local = FileData->Info;
  4630. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4631. if (Modified)
  4632. {
  4633. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4634. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4635. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4636. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4637. }
  4638. else
  4639. {
  4640. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4641. }
  4642. if ((Mode == smBoth) || (Mode == smRemote))
  4643. {
  4644. ChecklistItem->Action =
  4645. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4646. ChecklistItem->Checked =
  4647. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4648. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4649. FLAGSET(Params, spSubDirs));
  4650. }
  4651. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4652. {
  4653. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4654. ChecklistItem->Checked =
  4655. FLAGSET(Params, spDelete) &&
  4656. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4657. FLAGSET(Params, spSubDirs));
  4658. }
  4659. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4660. {
  4661. Data.Checklist->Add(ChecklistItem);
  4662. ChecklistItem = NULL;
  4663. }
  4664. }
  4665. __finally
  4666. {
  4667. delete ChecklistItem;
  4668. }
  4669. }
  4670. else
  4671. {
  4672. if (FileData->Modified)
  4673. {
  4674. delete FileData->MatchingRemoteFileFile;
  4675. }
  4676. }
  4677. }
  4678. }
  4679. }
  4680. __finally
  4681. {
  4682. if (Data.LocalFileList != NULL)
  4683. {
  4684. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4685. {
  4686. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4687. (Data.LocalFileList->Objects[Index]);
  4688. delete FileData;
  4689. }
  4690. delete Data.LocalFileList;
  4691. }
  4692. }
  4693. }
  4694. //---------------------------------------------------------------------------
  4695. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4696. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4697. {
  4698. try
  4699. {
  4700. DoSynchronizeCollectFile(FileName, File, Param);
  4701. }
  4702. catch(EScpSkipFile & E)
  4703. {
  4704. TSuspendFileOperationProgress Suspend(OperationProgress);
  4705. if (!HandleException(&E))
  4706. {
  4707. throw;
  4708. }
  4709. }
  4710. }
  4711. //---------------------------------------------------------------------------
  4712. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4713. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4714. {
  4715. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4716. TFileMasks::TParams MaskParams;
  4717. MaskParams.Size = File->Size;
  4718. MaskParams.Modification = File->Modification;
  4719. UnicodeString LocalFileName =
  4720. ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  4721. UnicodeString FullRemoteFileName =
  4722. UnixExcludeTrailingBackslash(File->FullFileName);
  4723. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  4724. if (Data->CopyParam->AllowTransfer(
  4725. BaseFileName, osRemote,
  4726. File->IsDirectory, MaskParams) &&
  4727. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4728. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4729. (Data->Options == NULL) ||
  4730. Data->Options->MatchesFilter(File->FileName) ||
  4731. Data->Options->MatchesFilter(LocalFileName)))
  4732. {
  4733. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4734. try
  4735. {
  4736. ChecklistItem->IsDirectory = File->IsDirectory;
  4737. ChecklistItem->ImageIndex = File->IconIndex;
  4738. ChecklistItem->Remote.FileName = File->FileName;
  4739. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4740. ChecklistItem->Remote.Modification = File->Modification;
  4741. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4742. ChecklistItem->Remote.Size = File->Size;
  4743. bool Modified = false;
  4744. bool New = false;
  4745. if (File->IsDirectory && !CanRecurseToDirectory(File))
  4746. {
  4747. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  4748. }
  4749. else
  4750. {
  4751. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4752. New = (LocalIndex < 0);
  4753. if (!New)
  4754. {
  4755. TSynchronizeFileData * LocalData =
  4756. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4757. LocalData->New = false;
  4758. if (File->IsDirectory != LocalData->IsDirectory)
  4759. {
  4760. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4761. (File->FileName)));
  4762. }
  4763. else if (!File->IsDirectory)
  4764. {
  4765. ChecklistItem->Local = LocalData->Info;
  4766. ChecklistItem->Local.Modification =
  4767. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4768. bool LocalModified = false;
  4769. // for spTimestamp+spBySize require that the file sizes are the same
  4770. // before comparing file time
  4771. int TimeCompare;
  4772. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4773. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4774. FLAGCLEAR(Data->Params, spBySize) ||
  4775. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4776. {
  4777. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4778. ChecklistItem->Remote.Modification);
  4779. }
  4780. else
  4781. {
  4782. TimeCompare = 0;
  4783. }
  4784. if (TimeCompare < 0)
  4785. {
  4786. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4787. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4788. {
  4789. Modified = true;
  4790. }
  4791. else
  4792. {
  4793. LocalModified = true;
  4794. }
  4795. }
  4796. else if (TimeCompare > 0)
  4797. {
  4798. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4799. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4800. {
  4801. LocalModified = true;
  4802. }
  4803. else
  4804. {
  4805. Modified = true;
  4806. }
  4807. }
  4808. else if (FLAGSET(Data->Params, spBySize) &&
  4809. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4810. FLAGCLEAR(Data->Params, spTimestamp))
  4811. {
  4812. Modified = true;
  4813. LocalModified = true;
  4814. }
  4815. if (LocalModified)
  4816. {
  4817. LocalData->Modified = true;
  4818. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4819. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4820. // we need this for custom commands over checklist only,
  4821. // not for sync itself
  4822. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4823. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4824. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4825. LocalData->Info.Modification, LocalData->Info.Size),
  4826. FormatFileDetailsForLog(FullRemoteFileName,
  4827. File->Modification, File->Size))));
  4828. }
  4829. if (Modified)
  4830. {
  4831. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4832. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4833. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4834. LocalData->Info.Modification, LocalData->Info.Size))));
  4835. }
  4836. }
  4837. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4838. {
  4839. DoSynchronizeCollectDirectory(
  4840. Data->LocalDirectory + LocalData->Info.FileName,
  4841. Data->RemoteDirectory + File->FileName,
  4842. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4843. Data->Options, (Data->Flags & ~sfFirstLevel),
  4844. Data->Checklist);
  4845. }
  4846. }
  4847. else
  4848. {
  4849. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4850. LogEvent(FORMAT(L"Remote file %s is new",
  4851. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4852. }
  4853. }
  4854. if (New || Modified)
  4855. {
  4856. DebugAssert(!New || !Modified);
  4857. // download the file if it changed or is new and we want to have it locally
  4858. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4859. {
  4860. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4861. {
  4862. ChecklistItem->Action =
  4863. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4864. ChecklistItem->Checked =
  4865. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4866. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4867. FLAGSET(Data->Params, spSubDirs));
  4868. }
  4869. }
  4870. else if ((Data->Mode == smRemote) && New)
  4871. {
  4872. if (FLAGCLEAR(Data->Params, spTimestamp))
  4873. {
  4874. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4875. ChecklistItem->Checked =
  4876. FLAGSET(Data->Params, spDelete) &&
  4877. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4878. FLAGSET(Data->Params, spSubDirs));
  4879. }
  4880. }
  4881. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4882. {
  4883. ChecklistItem->RemoteFile = File->Duplicate();
  4884. Data->Checklist->Add(ChecklistItem);
  4885. ChecklistItem = NULL;
  4886. }
  4887. }
  4888. }
  4889. __finally
  4890. {
  4891. delete ChecklistItem;
  4892. }
  4893. }
  4894. else
  4895. {
  4896. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4897. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4898. }
  4899. }
  4900. //---------------------------------------------------------------------------
  4901. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4902. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4903. const TCopyParamType * CopyParam, int Params,
  4904. TSynchronizeDirectory OnSynchronizeDirectory)
  4905. {
  4906. TSynchronizeData Data;
  4907. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4908. int CopyParams =
  4909. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4910. TCopyParamType SyncCopyParam = *CopyParam;
  4911. // when synchronizing by time, we force preserving time,
  4912. // otherwise it does not make any sense
  4913. if (FLAGCLEAR(Params, spNotByTime))
  4914. {
  4915. SyncCopyParam.PreserveTime = true;
  4916. }
  4917. TStringList * DownloadList = new TStringList();
  4918. TStringList * DeleteRemoteList = new TStringList();
  4919. TStringList * UploadList = new TStringList();
  4920. TStringList * DeleteLocalList = new TStringList();
  4921. BeginTransaction();
  4922. try
  4923. {
  4924. int IIndex = 0;
  4925. while (IIndex < Checklist->Count)
  4926. {
  4927. const TSynchronizeChecklist::TItem * ChecklistItem;
  4928. DownloadList->Clear();
  4929. DeleteRemoteList->Clear();
  4930. UploadList->Clear();
  4931. DeleteLocalList->Clear();
  4932. ChecklistItem = Checklist->Item[IIndex];
  4933. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4934. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4935. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4936. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4937. int(Params), SynchronizeParamsStr(Params))));
  4938. int Count = 0;
  4939. while ((IIndex < Checklist->Count) &&
  4940. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4941. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4942. {
  4943. ChecklistItem = Checklist->Item[IIndex];
  4944. if (ChecklistItem->Checked)
  4945. {
  4946. Count++;
  4947. if (FLAGSET(Params, spTimestamp))
  4948. {
  4949. switch (ChecklistItem->Action)
  4950. {
  4951. case TSynchronizeChecklist::saDownloadUpdate:
  4952. DownloadList->AddObject(
  4953. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4954. ChecklistItem->Remote.FileName,
  4955. (TObject *)(ChecklistItem));
  4956. break;
  4957. case TSynchronizeChecklist::saUploadUpdate:
  4958. UploadList->AddObject(
  4959. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4960. ChecklistItem->Local.FileName,
  4961. (TObject *)(ChecklistItem));
  4962. break;
  4963. default:
  4964. DebugFail();
  4965. break;
  4966. }
  4967. }
  4968. else
  4969. {
  4970. switch (ChecklistItem->Action)
  4971. {
  4972. case TSynchronizeChecklist::saDownloadNew:
  4973. case TSynchronizeChecklist::saDownloadUpdate:
  4974. DownloadList->AddObject(
  4975. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4976. ChecklistItem->Remote.FileName,
  4977. ChecklistItem->RemoteFile);
  4978. break;
  4979. case TSynchronizeChecklist::saDeleteRemote:
  4980. DeleteRemoteList->AddObject(
  4981. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4982. ChecklistItem->Remote.FileName,
  4983. ChecklistItem->RemoteFile);
  4984. break;
  4985. case TSynchronizeChecklist::saUploadNew:
  4986. case TSynchronizeChecklist::saUploadUpdate:
  4987. UploadList->Add(
  4988. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4989. ChecklistItem->Local.FileName);
  4990. break;
  4991. case TSynchronizeChecklist::saDeleteLocal:
  4992. DeleteLocalList->Add(
  4993. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4994. ChecklistItem->Local.FileName);
  4995. break;
  4996. default:
  4997. DebugFail();
  4998. break;
  4999. }
  5000. }
  5001. }
  5002. IIndex++;
  5003. }
  5004. // prevent showing/updating of progress dialog if there's nothing to do
  5005. if (Count > 0)
  5006. {
  5007. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  5008. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  5009. DoSynchronizeProgress(Data, false);
  5010. if (FLAGSET(Params, spTimestamp))
  5011. {
  5012. if (DownloadList->Count > 0)
  5013. {
  5014. ProcessFiles(DownloadList, foSetProperties,
  5015. SynchronizeLocalTimestamp, NULL, osLocal);
  5016. }
  5017. if (UploadList->Count > 0)
  5018. {
  5019. ProcessFiles(UploadList, foSetProperties,
  5020. SynchronizeRemoteTimestamp);
  5021. }
  5022. }
  5023. else
  5024. {
  5025. if ((DownloadList->Count > 0) &&
  5026. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  5027. {
  5028. Abort();
  5029. }
  5030. if ((DeleteRemoteList->Count > 0) &&
  5031. !DeleteFiles(DeleteRemoteList))
  5032. {
  5033. Abort();
  5034. }
  5035. if ((UploadList->Count > 0) &&
  5036. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  5037. {
  5038. Abort();
  5039. }
  5040. if ((DeleteLocalList->Count > 0) &&
  5041. !DeleteLocalFiles(DeleteLocalList))
  5042. {
  5043. Abort();
  5044. }
  5045. }
  5046. }
  5047. }
  5048. }
  5049. __finally
  5050. {
  5051. delete DownloadList;
  5052. delete DeleteRemoteList;
  5053. delete UploadList;
  5054. delete DeleteLocalList;
  5055. EndTransaction();
  5056. }
  5057. }
  5058. //---------------------------------------------------------------------------
  5059. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  5060. bool Collect)
  5061. {
  5062. if (Data.OnSynchronizeDirectory != NULL)
  5063. {
  5064. bool Continue = true;
  5065. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  5066. Continue, Collect);
  5067. if (!Continue)
  5068. {
  5069. Abort();
  5070. }
  5071. }
  5072. }
  5073. //---------------------------------------------------------------------------
  5074. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  5075. const TRemoteFile * File, void * /*Param*/)
  5076. {
  5077. const TSynchronizeChecklist::TItem * ChecklistItem =
  5078. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5079. UnicodeString LocalFile =
  5080. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5081. ChecklistItem->Local.FileName;
  5082. FILE_OPERATION_LOOP_BEGIN
  5083. {
  5084. HANDLE Handle;
  5085. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  5086. NULL, NULL, NULL, NULL);
  5087. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  5088. SessionData->DSTMode);
  5089. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  5090. int Error = GetLastError();
  5091. CloseHandle(Handle);
  5092. if (!Result)
  5093. {
  5094. RaiseLastOSError(Error);
  5095. }
  5096. }
  5097. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  5098. }
  5099. //---------------------------------------------------------------------------
  5100. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  5101. const TRemoteFile * File, void * /*Param*/)
  5102. {
  5103. const TSynchronizeChecklist::TItem * ChecklistItem =
  5104. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5105. TRemoteProperties Properties;
  5106. Properties.Valid << vpModification;
  5107. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  5108. SessionData->DSTMode);
  5109. ChangeFileProperties(
  5110. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  5111. NULL, &Properties);
  5112. }
  5113. //---------------------------------------------------------------------------
  5114. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  5115. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  5116. {
  5117. // see DoFilesFind
  5118. FOnFindingFile = NULL;
  5119. DebugAssert(Param);
  5120. DebugAssert(File);
  5121. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  5122. if (!AParams->Cancel)
  5123. {
  5124. if (FileName.IsEmpty())
  5125. {
  5126. FileName = File->FileName;
  5127. }
  5128. TFileMasks::TParams MaskParams;
  5129. MaskParams.Size = File->Size;
  5130. MaskParams.Modification = File->Modification;
  5131. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5132. bool ImplicitMatch;
  5133. // Do not use recursive include match
  5134. if (AParams->FileMask.Matches(FullFileName, false,
  5135. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  5136. {
  5137. if (!ImplicitMatch)
  5138. {
  5139. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  5140. }
  5141. if (File->IsDirectory)
  5142. {
  5143. UnicodeString RealDirectory;
  5144. if (!File->IsSymLink || File->LinkTo.IsEmpty())
  5145. {
  5146. RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
  5147. }
  5148. else
  5149. {
  5150. RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
  5151. }
  5152. if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
  5153. {
  5154. LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
  5155. }
  5156. else
  5157. {
  5158. DoFilesFind(FullFileName, *AParams, RealDirectory);
  5159. }
  5160. }
  5161. }
  5162. }
  5163. }
  5164. //---------------------------------------------------------------------------
  5165. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
  5166. {
  5167. LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
  5168. Params.OnFindingFile(this, Directory, Params.Cancel);
  5169. if (!Params.Cancel)
  5170. {
  5171. DebugAssert(FOnFindingFile == NULL);
  5172. // ideally we should set the handler only around actually reading
  5173. // of the directory listing, so we at least reset the handler in
  5174. // FileFind
  5175. FOnFindingFile = Params.OnFindingFile;
  5176. UnicodeString PrevRealDirectory = Params.RealDirectory;
  5177. try
  5178. {
  5179. Params.RealDirectory = RealDirectory;
  5180. ProcessDirectory(Directory, FileFind, &Params, false, true);
  5181. }
  5182. __finally
  5183. {
  5184. Params.RealDirectory = PrevRealDirectory;
  5185. FOnFindingFile = NULL;
  5186. }
  5187. }
  5188. }
  5189. //---------------------------------------------------------------------------
  5190. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  5191. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  5192. {
  5193. TFilesFindParams Params;
  5194. Params.FileMask = FileMask;
  5195. Params.OnFileFound = OnFileFound;
  5196. Params.OnFindingFile = OnFindingFile;
  5197. Params.Cancel = false;
  5198. Params.LoopDetector.RecordVisitedDirectory(Directory);
  5199. DoFilesFind(Directory, Params, Directory);
  5200. }
  5201. //---------------------------------------------------------------------------
  5202. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  5203. TSpaceAvailable & ASpaceAvailable)
  5204. {
  5205. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  5206. try
  5207. {
  5208. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  5209. }
  5210. catch (Exception &E)
  5211. {
  5212. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  5213. }
  5214. }
  5215. //---------------------------------------------------------------------------
  5216. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  5217. const TRemoteFile * File, void * /*Param*/)
  5218. {
  5219. StartOperationWithFile(FileName, foLock);
  5220. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  5221. FileModified(File, FileName, true);
  5222. DoLockFile(FileName, File);
  5223. ReactOnCommand(fsLock);
  5224. }
  5225. //---------------------------------------------------------------------------
  5226. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5227. {
  5228. TRetryOperationLoop RetryLoop(this);
  5229. do
  5230. {
  5231. try
  5232. {
  5233. FFileSystem->LockFile(FileName, File);
  5234. }
  5235. catch(Exception & E)
  5236. {
  5237. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  5238. }
  5239. }
  5240. while (RetryLoop.Retry());
  5241. }
  5242. //---------------------------------------------------------------------------
  5243. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  5244. const TRemoteFile * File, void * /*Param*/)
  5245. {
  5246. StartOperationWithFile(FileName, foUnlock);
  5247. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  5248. FileModified(File, FileName, true);
  5249. DoUnlockFile(FileName, File);
  5250. ReactOnCommand(fsLock);
  5251. }
  5252. //---------------------------------------------------------------------------
  5253. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5254. {
  5255. TRetryOperationLoop RetryLoop(this);
  5256. do
  5257. {
  5258. try
  5259. {
  5260. FFileSystem->UnlockFile(FileName, File);
  5261. }
  5262. catch(Exception & E)
  5263. {
  5264. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  5265. }
  5266. }
  5267. while (RetryLoop.Retry());
  5268. }
  5269. //---------------------------------------------------------------------------
  5270. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  5271. {
  5272. BeginTransaction();
  5273. try
  5274. {
  5275. ProcessFiles(FileList, foLock, LockFile, NULL);
  5276. }
  5277. __finally
  5278. {
  5279. EndTransaction();
  5280. }
  5281. }
  5282. //---------------------------------------------------------------------------
  5283. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  5284. {
  5285. BeginTransaction();
  5286. try
  5287. {
  5288. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  5289. }
  5290. __finally
  5291. {
  5292. EndTransaction();
  5293. }
  5294. }
  5295. //---------------------------------------------------------------------------
  5296. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  5297. {
  5298. return FFileSystem->GetSessionInfo();
  5299. }
  5300. //---------------------------------------------------------------------------
  5301. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  5302. {
  5303. return FFileSystem->GetFileSystemInfo(Retrieve);
  5304. }
  5305. //---------------------------------------------------------------------
  5306. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  5307. {
  5308. FFileSystem->GetSupportedChecksumAlgs(Algs);
  5309. }
  5310. //---------------------------------------------------------------------
  5311. UnicodeString __fastcall TTerminal::GetPassword()
  5312. {
  5313. UnicodeString Result;
  5314. // FRememberedPassword is empty also when stored password was used
  5315. if (FRememberedPassword.IsEmpty())
  5316. {
  5317. Result = SessionData->Password;
  5318. }
  5319. else
  5320. {
  5321. Result = RememberedPassword;
  5322. }
  5323. return Result;
  5324. }
  5325. //---------------------------------------------------------------------
  5326. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  5327. {
  5328. return DecryptPassword(FRememberedPassword);
  5329. }
  5330. //---------------------------------------------------------------------
  5331. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  5332. {
  5333. return DecryptPassword(FRememberedTunnelPassword);
  5334. }
  5335. //---------------------------------------------------------------------
  5336. bool __fastcall TTerminal::GetStoredCredentialsTried()
  5337. {
  5338. bool Result;
  5339. if (FFileSystem != NULL)
  5340. {
  5341. Result = FFileSystem->GetStoredCredentialsTried();
  5342. }
  5343. else if (FSecureShell != NULL)
  5344. {
  5345. Result = FSecureShell->GetStoredCredentialsTried();
  5346. }
  5347. else
  5348. {
  5349. DebugAssert(FTunnelOpening);
  5350. Result = false;
  5351. }
  5352. return Result;
  5353. }
  5354. //---------------------------------------------------------------------------
  5355. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  5356. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5357. {
  5358. DebugAssert(FFileSystem);
  5359. DebugAssert(FilesToCopy);
  5360. bool Result = false;
  5361. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5362. try
  5363. {
  5364. __int64 Size;
  5365. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5366. bool CalculatedSize =
  5367. CalculateLocalFilesSize(
  5368. FilesToCopy, Size,
  5369. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5370. CopyParam->CalculateSize);
  5371. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5372. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  5373. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5374. FOperationProgress = &OperationProgress;
  5375. bool CollectingUsage = false;
  5376. try
  5377. {
  5378. if (CalculatedSize)
  5379. {
  5380. if (Configuration->Usage->Collect)
  5381. {
  5382. int CounterSize = TUsage::CalculateCounterSize(Size);
  5383. Configuration->Usage->Inc(L"Uploads");
  5384. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  5385. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  5386. CollectingUsage = true;
  5387. }
  5388. OperationProgress.SetTotalSize(Size);
  5389. }
  5390. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  5391. BeginTransaction();
  5392. try
  5393. {
  5394. if (Log->Logging)
  5395. {
  5396. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  5397. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5398. LogEvent(CopyParam->LogStr);
  5399. }
  5400. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  5401. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  5402. }
  5403. __finally
  5404. {
  5405. if (Active)
  5406. {
  5407. ReactOnCommand(fsCopyToRemote);
  5408. }
  5409. EndTransaction();
  5410. }
  5411. if (OperationProgress.Cancel == csContinue)
  5412. {
  5413. Result = true;
  5414. }
  5415. }
  5416. __finally
  5417. {
  5418. if (CollectingUsage)
  5419. {
  5420. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5421. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  5422. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  5423. }
  5424. OperationProgress.Stop();
  5425. FOperationProgress = NULL;
  5426. }
  5427. }
  5428. catch (Exception &E)
  5429. {
  5430. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  5431. OnceDoneOperation = odoIdle;
  5432. }
  5433. if (OnceDoneOperation != odoIdle)
  5434. {
  5435. CloseOnCompletion(OnceDoneOperation);
  5436. }
  5437. return Result;
  5438. }
  5439. //---------------------------------------------------------------------------
  5440. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  5441. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5442. {
  5443. DebugAssert(FFileSystem);
  5444. // see scp.c: sink(), tolocal()
  5445. bool Result = false;
  5446. bool OwnsFileList = (FilesToCopy == NULL);
  5447. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5448. try
  5449. {
  5450. if (OwnsFileList)
  5451. {
  5452. FilesToCopy = new TStringList();
  5453. FilesToCopy->Assign(Files->SelectedFiles);
  5454. }
  5455. BeginTransaction();
  5456. try
  5457. {
  5458. __int64 TotalSize;
  5459. bool TotalSizeKnown = false;
  5460. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5461. ExceptionOnFail = true;
  5462. try
  5463. {
  5464. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5465. if (CalculateFilesSize(
  5466. FilesToCopy, TotalSize, csIgnoreErrors,
  5467. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5468. CopyParam->CalculateSize, NULL))
  5469. {
  5470. TotalSizeKnown = true;
  5471. }
  5472. }
  5473. __finally
  5474. {
  5475. ExceptionOnFail = false;
  5476. }
  5477. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5478. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5479. FOperationProgress = &OperationProgress;
  5480. bool CollectingUsage = false;
  5481. try
  5482. {
  5483. if (TotalSizeKnown)
  5484. {
  5485. if (Configuration->Usage->Collect)
  5486. {
  5487. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5488. Configuration->Usage->Inc(L"Downloads");
  5489. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5490. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5491. CollectingUsage = true;
  5492. }
  5493. OperationProgress.SetTotalSize(TotalSize);
  5494. }
  5495. try
  5496. {
  5497. try
  5498. {
  5499. if (Log->Logging)
  5500. {
  5501. LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  5502. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5503. LogEvent(CopyParam->LogStr);
  5504. }
  5505. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5506. &OperationProgress, OnceDoneOperation);
  5507. }
  5508. __finally
  5509. {
  5510. if (Active)
  5511. {
  5512. ReactOnCommand(fsCopyToLocal);
  5513. }
  5514. }
  5515. }
  5516. catch (Exception &E)
  5517. {
  5518. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5519. OnceDoneOperation = odoIdle;
  5520. }
  5521. if (OperationProgress.Cancel == csContinue)
  5522. {
  5523. Result = true;
  5524. }
  5525. }
  5526. __finally
  5527. {
  5528. if (CollectingUsage)
  5529. {
  5530. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5531. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5532. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5533. }
  5534. FOperationProgress = NULL;
  5535. OperationProgress.Stop();
  5536. }
  5537. }
  5538. __finally
  5539. {
  5540. // If session is still active (no fatal error) we reload directory
  5541. // by calling EndTransaction
  5542. EndTransaction();
  5543. }
  5544. }
  5545. __finally
  5546. {
  5547. if (OwnsFileList) delete FilesToCopy;
  5548. }
  5549. if (OnceDoneOperation != odoIdle)
  5550. {
  5551. CloseOnCompletion(OnceDoneOperation);
  5552. }
  5553. return Result;
  5554. }
  5555. //---------------------------------------------------------------------------
  5556. void __fastcall TTerminal::ReflectSettings()
  5557. {
  5558. DebugAssert(FLog != NULL);
  5559. FLog->ReflectSettings();
  5560. DebugAssert(FActionLog != NULL);
  5561. FActionLog->ReflectSettings();
  5562. // also FTunnelLog ?
  5563. }
  5564. //---------------------------------------------------------------------------
  5565. void __fastcall TTerminal::CollectUsage()
  5566. {
  5567. switch (SessionData->FSProtocol)
  5568. {
  5569. case fsSCPonly:
  5570. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5571. break;
  5572. case fsSFTP:
  5573. case fsSFTPonly:
  5574. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5575. break;
  5576. case fsFTP:
  5577. if (SessionData->Ftps == ftpsNone)
  5578. {
  5579. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5580. }
  5581. else
  5582. {
  5583. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5584. }
  5585. break;
  5586. case fsWebDAV:
  5587. if (SessionData->Ftps == ftpsNone)
  5588. {
  5589. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5590. }
  5591. else
  5592. {
  5593. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5594. }
  5595. break;
  5596. }
  5597. if (Configuration->Logging && Configuration->LogToFile)
  5598. {
  5599. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5600. }
  5601. if (Configuration->LogActions)
  5602. {
  5603. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5604. }
  5605. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5606. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5607. {
  5608. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5609. }
  5610. if (SessionData->ProxyMethod != ::pmNone)
  5611. {
  5612. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5613. }
  5614. if (SessionData->FtpProxyLogonType > 0)
  5615. {
  5616. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5617. }
  5618. FCollectFileSystemUsage = true;
  5619. }
  5620. //---------------------------------------------------------------------------
  5621. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5622. {
  5623. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5624. }
  5625. //---------------------------------------------------------------------------
  5626. bool __fastcall TTerminal::VerifyCertificate(
  5627. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  5628. const UnicodeString & Fingerprint,
  5629. const UnicodeString & CertificateSubject, int Failures)
  5630. {
  5631. bool Result = false;
  5632. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5633. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5634. Storage->AccessMode = smRead;
  5635. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5636. {
  5637. if (Storage->ValueExists(SiteKey))
  5638. {
  5639. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  5640. if (CertificateData == CachedCertificateData)
  5641. {
  5642. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5643. Result = true;
  5644. }
  5645. }
  5646. else if (Storage->ValueExists(Fingerprint))
  5647. {
  5648. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5649. Result = true;
  5650. }
  5651. }
  5652. if (!Result)
  5653. {
  5654. UnicodeString Buf = SessionData->HostKey;
  5655. while (!Result && !Buf.IsEmpty())
  5656. {
  5657. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5658. if (ExpectedKey == L"*")
  5659. {
  5660. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5661. Information(Message, true);
  5662. Log->Add(llException, Message);
  5663. Result = true;
  5664. }
  5665. else if (ExpectedKey == Fingerprint)
  5666. {
  5667. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5668. Result = true;
  5669. }
  5670. }
  5671. }
  5672. return Result;
  5673. }
  5674. //---------------------------------------------------------------------------
  5675. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5676. const UnicodeString & SiteKey, const UnicodeString & Fingerprint, int Failures)
  5677. {
  5678. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5679. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5680. Storage->AccessMode = smReadWrite;
  5681. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5682. {
  5683. Storage->WriteString(SiteKey, CertificateData);
  5684. }
  5685. }
  5686. //---------------------------------------------------------------------------
  5687. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  5688. {
  5689. // see SSL_get_version() in OpenSSL ssl_lib.c
  5690. if (TlsVersionStr == L"TLSv1.2")
  5691. {
  5692. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  5693. }
  5694. else if (TlsVersionStr == L"TLSv1.1")
  5695. {
  5696. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  5697. }
  5698. else if (TlsVersionStr == L"TLSv1")
  5699. {
  5700. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  5701. }
  5702. else if (TlsVersionStr == L"SSLv3")
  5703. {
  5704. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  5705. }
  5706. else if (TlsVersionStr == L"SSLv2")
  5707. {
  5708. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  5709. }
  5710. else
  5711. {
  5712. DebugFail();
  5713. }
  5714. }
  5715. //---------------------------------------------------------------------------
  5716. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  5717. {
  5718. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  5719. if (Result)
  5720. {
  5721. UnicodeString Passphrase = SessionData->Passphrase;
  5722. // Inspired by neon's ne_ssl_clicert_read
  5723. bool Retry;
  5724. do
  5725. {
  5726. Retry = false;
  5727. bool WrongPassphrase = false;
  5728. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  5729. if (WrongPassphrase)
  5730. {
  5731. if (Passphrase.IsEmpty())
  5732. {
  5733. LogEvent(L"Certificate is encrypted, need passphrase");
  5734. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  5735. }
  5736. else
  5737. {
  5738. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  5739. }
  5740. Passphrase = L"";
  5741. if (PromptUser(
  5742. SessionData, pkPassphrase,
  5743. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  5744. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  5745. {
  5746. Retry = true;
  5747. }
  5748. else
  5749. {
  5750. Result = false;
  5751. }
  5752. }
  5753. }
  5754. while (Retry);
  5755. }
  5756. return Result;
  5757. }
  5758. //---------------------------------------------------------------------------
  5759. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  5760. {
  5761. if (FSessionData->TrimVMSVersions)
  5762. {
  5763. int P = FileName.LastDelimiter(L";");
  5764. if (P > 0)
  5765. {
  5766. FileName.SetLength(P - 1);
  5767. }
  5768. }
  5769. return FileName;
  5770. }
  5771. //---------------------------------------------------------------------------
  5772. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  5773. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  5774. {
  5775. FileName = GetBaseFileName(FileName);
  5776. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  5777. return FileName;
  5778. }
  5779. //---------------------------------------------------------------------------
  5780. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  5781. {
  5782. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  5783. }
  5784. //---------------------------------------------------------------------------
  5785. bool __fastcall TTerminal::IsThisOrChild(TTerminal * Terminal)
  5786. {
  5787. return
  5788. (this == Terminal) ||
  5789. ((FCommandSession != NULL) && (FCommandSession == Terminal));
  5790. }
  5791. //---------------------------------------------------------------------------
  5792. //---------------------------------------------------------------------------
  5793. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5794. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5795. TTerminal(ASessionData, Configuration),
  5796. FMainTerminal(MainTerminal)
  5797. {
  5798. Log->Parent = FMainTerminal->Log;
  5799. Log->Name = Name;
  5800. ActionLog->Enabled = false;
  5801. SessionData->NonPersistant();
  5802. DebugAssert(FMainTerminal != NULL);
  5803. if (!FMainTerminal->UserName.IsEmpty())
  5804. {
  5805. SessionData->UserName = FMainTerminal->UserName;
  5806. }
  5807. }
  5808. //---------------------------------------------------------------------------
  5809. void __fastcall TSecondaryTerminal::UpdateFromMain()
  5810. {
  5811. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  5812. {
  5813. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  5814. }
  5815. }
  5816. //---------------------------------------------------------------------------
  5817. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5818. {
  5819. FMainTerminal->DirectoryLoaded(FileList);
  5820. DebugAssert(FileList != NULL);
  5821. }
  5822. //---------------------------------------------------------------------------
  5823. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5824. bool SubDirs)
  5825. {
  5826. // clear cache of main terminal
  5827. FMainTerminal->DirectoryModified(Path, SubDirs);
  5828. }
  5829. //---------------------------------------------------------------------------
  5830. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5831. {
  5832. return FMainTerminal;
  5833. }
  5834. //---------------------------------------------------------------------------
  5835. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5836. TObjectList()
  5837. {
  5838. DebugAssert(AConfiguration);
  5839. FConfiguration = AConfiguration;
  5840. }
  5841. //---------------------------------------------------------------------------
  5842. __fastcall TTerminalList::~TTerminalList()
  5843. {
  5844. DebugAssert(Count == 0);
  5845. }
  5846. //---------------------------------------------------------------------------
  5847. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5848. {
  5849. return new TTerminal(Data, FConfiguration);
  5850. }
  5851. //---------------------------------------------------------------------------
  5852. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5853. {
  5854. TTerminal * Terminal = CreateTerminal(Data);
  5855. Add(Terminal);
  5856. return Terminal;
  5857. }
  5858. //---------------------------------------------------------------------------
  5859. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5860. {
  5861. DebugAssert(IndexOf(Terminal) >= 0);
  5862. Remove(Terminal);
  5863. }
  5864. //---------------------------------------------------------------------------
  5865. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5866. {
  5867. TTerminal * T = Terminal;
  5868. Terminal = NULL;
  5869. FreeTerminal(T);
  5870. }
  5871. //---------------------------------------------------------------------------
  5872. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5873. {
  5874. return dynamic_cast<TTerminal *>(Items[Index]);
  5875. }
  5876. //---------------------------------------------------------------------------
  5877. void __fastcall TTerminalList::Idle()
  5878. {
  5879. TTerminal * Terminal;
  5880. for (int i = 0; i < Count; i++)
  5881. {
  5882. Terminal = Terminals[i];
  5883. if (Terminal->Status == ssOpened)
  5884. {
  5885. Terminal->Idle();
  5886. }
  5887. }
  5888. }
  5889. //---------------------------------------------------------------------------
  5890. void __fastcall TTerminalList::RecryptPasswords()
  5891. {
  5892. for (int Index = 0; Index < Count; Index++)
  5893. {
  5894. Terminals[Index]->RecryptPasswords();
  5895. }
  5896. }