Terminal.cpp 215 KB

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