Terminal.cpp 212 KB

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