Terminal.cpp 214 KB

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