Terminal.cpp 205 KB

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