Terminal.cpp 214 KB

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