Terminal.cpp 204 KB

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