Terminal.cpp 209 KB

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