Terminal.cpp 273 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683
  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. #include "FtpFileSystem.h"
  18. #include "WebDAVFileSystem.h"
  19. #include "S3FileSystem.h"
  20. #include "TextsCore.h"
  21. #include "HelpCore.h"
  22. #include "CoreMain.h"
  23. #include "Queue.h"
  24. #include "Cryptography.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. bool DontOverwrite;
  73. };
  74. //---------------------------------------------------------------------------
  75. struct TFilesFindParams
  76. {
  77. TFileMasks FileMask;
  78. TFileFoundEvent OnFileFound;
  79. TFindingFileEvent OnFindingFile;
  80. bool Cancel;
  81. TLoopDetector LoopDetector;
  82. UnicodeString RealDirectory;
  83. };
  84. //---------------------------------------------------------------------------
  85. TCalculateSizeStats::TCalculateSizeStats()
  86. {
  87. memset(this, 0, sizeof(*this));
  88. }
  89. //---------------------------------------------------------------------------
  90. TCalculateSizeParams::TCalculateSizeParams()
  91. {
  92. memset(this, 0, sizeof(*this));
  93. Result = true;
  94. AllowDirs = true;
  95. }
  96. //---------------------------------------------------------------------------
  97. TSynchronizeOptions::TSynchronizeOptions()
  98. {
  99. memset(this, 0, sizeof(*this));
  100. }
  101. //---------------------------------------------------------------------------
  102. TSynchronizeOptions::~TSynchronizeOptions()
  103. {
  104. delete Filter;
  105. }
  106. //---------------------------------------------------------------------------
  107. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  108. {
  109. int FoundIndex;
  110. bool Result;
  111. if (Filter == NULL)
  112. {
  113. Result = true;
  114. }
  115. else
  116. {
  117. Result = Filter->Find(FileName, FoundIndex);
  118. }
  119. return Result;
  120. }
  121. //---------------------------------------------------------------------------
  122. TSpaceAvailable::TSpaceAvailable()
  123. {
  124. memset(this, 0, sizeof(*this));
  125. }
  126. //---------------------------------------------------------------------------
  127. TOverwriteFileParams::TOverwriteFileParams()
  128. {
  129. SourceSize = 0;
  130. DestSize = 0;
  131. SourcePrecision = mfFull;
  132. DestPrecision = mfFull;
  133. }
  134. //---------------------------------------------------------------------------
  135. //---------------------------------------------------------------------------
  136. class TTunnelThread : public TSimpleThread
  137. {
  138. public:
  139. __fastcall TTunnelThread(TSecureShell * SecureShell);
  140. virtual __fastcall ~TTunnelThread();
  141. virtual void __fastcall Terminate();
  142. protected:
  143. virtual void __fastcall Execute();
  144. private:
  145. TSecureShell * FSecureShell;
  146. bool FTerminated;
  147. };
  148. //---------------------------------------------------------------------------
  149. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  150. FSecureShell(SecureShell),
  151. FTerminated(false)
  152. {
  153. Start();
  154. }
  155. //---------------------------------------------------------------------------
  156. __fastcall TTunnelThread::~TTunnelThread()
  157. {
  158. // close before the class's virtual functions (Terminate particularly) are lost
  159. Close();
  160. }
  161. //---------------------------------------------------------------------------
  162. void __fastcall TTunnelThread::Terminate()
  163. {
  164. FTerminated = true;
  165. }
  166. //---------------------------------------------------------------------------
  167. void __fastcall TTunnelThread::Execute()
  168. {
  169. try
  170. {
  171. while (!FTerminated)
  172. {
  173. FSecureShell->Idle(250);
  174. }
  175. }
  176. catch(...)
  177. {
  178. if (FSecureShell->Active)
  179. {
  180. FSecureShell->Close();
  181. }
  182. // do not pass exception out of thread's proc
  183. }
  184. }
  185. //---------------------------------------------------------------------------
  186. //---------------------------------------------------------------------------
  187. class TTunnelUI : public TSessionUI
  188. {
  189. public:
  190. __fastcall TTunnelUI(TTerminal * Terminal);
  191. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  192. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  193. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  194. TQueryType QueryType);
  195. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  196. Exception * E, unsigned int Answers, const TQueryParams * Params,
  197. TQueryType QueryType);
  198. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  199. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  200. TStrings * Results);
  201. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  202. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  203. virtual void __fastcall HandleExtendedException(Exception * E);
  204. virtual void __fastcall Closed();
  205. virtual void __fastcall ProcessGUI();
  206. private:
  207. TTerminal * FTerminal;
  208. unsigned int FTerminalThread;
  209. };
  210. //---------------------------------------------------------------------------
  211. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  212. {
  213. FTerminal = Terminal;
  214. FTerminalThread = GetCurrentThreadId();
  215. }
  216. //---------------------------------------------------------------------------
  217. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  218. {
  219. if (GetCurrentThreadId() == FTerminalThread)
  220. {
  221. FTerminal->Information(Str, Status);
  222. }
  223. }
  224. //---------------------------------------------------------------------------
  225. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  226. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  227. TQueryType QueryType)
  228. {
  229. unsigned int Result;
  230. if (GetCurrentThreadId() == FTerminalThread)
  231. {
  232. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  233. }
  234. else
  235. {
  236. Result = AbortAnswer(Answers);
  237. }
  238. return Result;
  239. }
  240. //---------------------------------------------------------------------------
  241. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  242. Exception * E, unsigned int Answers, const TQueryParams * Params,
  243. TQueryType QueryType)
  244. {
  245. unsigned int Result;
  246. if (GetCurrentThreadId() == FTerminalThread)
  247. {
  248. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  249. }
  250. else
  251. {
  252. Result = AbortAnswer(Answers);
  253. }
  254. return Result;
  255. }
  256. //---------------------------------------------------------------------------
  257. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  258. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  259. {
  260. bool Result;
  261. if (GetCurrentThreadId() == FTerminalThread)
  262. {
  263. if (IsAuthenticationPrompt(Kind))
  264. {
  265. Instructions =
  266. FMTLOAD(TUNNEL_INSTRUCTION2, (Data->HostName)) +
  267. (Instructions.IsEmpty() ? L"" : L"\n") +
  268. Instructions;
  269. }
  270. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  271. }
  272. else
  273. {
  274. Result = false;
  275. }
  276. return Result;
  277. }
  278. //---------------------------------------------------------------------------
  279. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  280. {
  281. if (GetCurrentThreadId() == FTerminalThread)
  282. {
  283. FTerminal->DisplayBanner(Banner);
  284. }
  285. }
  286. //---------------------------------------------------------------------------
  287. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  288. {
  289. throw ESshFatal(E, Msg, HelpKeyword);
  290. }
  291. //---------------------------------------------------------------------------
  292. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  293. {
  294. if (GetCurrentThreadId() == FTerminalThread)
  295. {
  296. FTerminal->HandleExtendedException(E);
  297. }
  298. }
  299. //---------------------------------------------------------------------------
  300. void __fastcall TTunnelUI::Closed()
  301. {
  302. // noop
  303. }
  304. //---------------------------------------------------------------------------
  305. void __fastcall TTunnelUI::ProcessGUI()
  306. {
  307. // noop
  308. }
  309. //---------------------------------------------------------------------------
  310. //---------------------------------------------------------------------------
  311. class TCallbackGuard
  312. {
  313. public:
  314. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  315. inline __fastcall ~TCallbackGuard();
  316. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  317. inline void __fastcall Verify();
  318. inline bool __fastcall Verify(Exception * E);
  319. void __fastcall Dismiss();
  320. private:
  321. ExtException * FFatalError;
  322. TTerminal * FTerminal;
  323. bool FGuarding;
  324. };
  325. //---------------------------------------------------------------------------
  326. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  327. FTerminal(Terminal),
  328. FFatalError(NULL),
  329. FGuarding(FTerminal->FCallbackGuard == NULL)
  330. {
  331. if (FGuarding)
  332. {
  333. FTerminal->FCallbackGuard = this;
  334. }
  335. }
  336. //---------------------------------------------------------------------------
  337. __fastcall TCallbackGuard::~TCallbackGuard()
  338. {
  339. if (FGuarding)
  340. {
  341. DebugAssert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  342. FTerminal->FCallbackGuard = NULL;
  343. }
  344. delete FFatalError;
  345. }
  346. //---------------------------------------------------------------------------
  347. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  348. {
  349. DebugAssert(FGuarding);
  350. // make sure we do not bother about getting back the silent abort exception
  351. // we issued ourselves. this may happen when there is an exception handler
  352. // that converts any exception to fatal one (such as in TTerminal::Open).
  353. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  354. {
  355. delete FFatalError;
  356. FFatalError = new ExtException(E, Msg, HelpKeyword);
  357. }
  358. // silently abort what we are doing.
  359. // non-silent exception would be caught probably by default application
  360. // exception handler, which may not do an appropriate action
  361. // (particularly it will not resume broken transfer).
  362. throw ECallbackGuardAbort();
  363. }
  364. //---------------------------------------------------------------------------
  365. void __fastcall TCallbackGuard::Dismiss()
  366. {
  367. DebugAssert(FFatalError == NULL);
  368. FGuarding = false;
  369. }
  370. //---------------------------------------------------------------------------
  371. void __fastcall TCallbackGuard::Verify()
  372. {
  373. if (FGuarding)
  374. {
  375. FGuarding = false;
  376. DebugAssert(FTerminal->FCallbackGuard == this);
  377. FTerminal->FCallbackGuard = NULL;
  378. if (FFatalError != NULL)
  379. {
  380. throw ESshFatal(FFatalError, L"");
  381. }
  382. }
  383. }
  384. //---------------------------------------------------------------------------
  385. bool __fastcall TCallbackGuard::Verify(Exception * E)
  386. {
  387. bool Result =
  388. (dynamic_cast<ECallbackGuardAbort *>(E) != NULL);
  389. if (Result)
  390. {
  391. DebugAssert(FGuarding && (FFatalError != NULL));
  392. Verify();
  393. }
  394. return Result;
  395. }
  396. //---------------------------------------------------------------------------
  397. //---------------------------------------------------------------------------
  398. TRobustOperationLoop::TRobustOperationLoop(
  399. TTerminal * Terminal, TFileOperationProgressType * OperationProgress, bool * AnyTransfer, bool CanRetry) :
  400. FTerminal(Terminal),
  401. FOperationProgress(OperationProgress),
  402. FRetry(false),
  403. FAnyTransfer(AnyTransfer),
  404. FCanRetry(CanRetry)
  405. {
  406. if (FAnyTransfer != NULL)
  407. {
  408. FPrevAnyTransfer = *FAnyTransfer;
  409. *FAnyTransfer = false;
  410. FStart = Now();
  411. }
  412. }
  413. //---------------------------------------------------------------------------
  414. TRobustOperationLoop::~TRobustOperationLoop()
  415. {
  416. if (FAnyTransfer != NULL)
  417. {
  418. *FAnyTransfer = FPrevAnyTransfer;
  419. }
  420. }
  421. //---------------------------------------------------------------------------
  422. bool TRobustOperationLoop::TryReopen(Exception & E)
  423. {
  424. if (!FCanRetry)
  425. {
  426. FRetry = false;
  427. }
  428. else if (dynamic_cast<ESkipFile *>(&E) != NULL)
  429. {
  430. FRetry = false;
  431. }
  432. else if (FTerminal->Active)
  433. {
  434. FTerminal->LogEvent(1, L"Session is open, will not retry transfer");
  435. FRetry = false;
  436. }
  437. else
  438. {
  439. FRetry = true;
  440. if (FAnyTransfer != NULL)
  441. {
  442. // if there was any transfer, reset the global timestamp
  443. if (*FAnyTransfer)
  444. {
  445. FStart = Now();
  446. FPrevAnyTransfer = true;
  447. *FAnyTransfer = false;
  448. }
  449. else
  450. {
  451. FRetry = FTerminal->ContinueReopen(FStart);
  452. if (!FRetry)
  453. {
  454. FTerminal->LogEvent(L"Retry interval expired, will not retry transfer");
  455. }
  456. }
  457. }
  458. if (FRetry)
  459. {
  460. FRetry =
  461. FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
  462. }
  463. }
  464. return FRetry;
  465. }
  466. //---------------------------------------------------------------------------
  467. bool TRobustOperationLoop::ShouldRetry()
  468. {
  469. return FRetry;
  470. }
  471. //---------------------------------------------------------------------------
  472. bool TRobustOperationLoop::Retry()
  473. {
  474. bool Result = FRetry;
  475. FRetry = false;
  476. return Result;
  477. }
  478. //---------------------------------------------------------------------------
  479. class TRetryOperationLoop
  480. {
  481. public:
  482. TRetryOperationLoop(TTerminal * Terminal);
  483. void Error(Exception & E);
  484. void Error(Exception & E, TSessionAction & Action);
  485. void Error(Exception & E, const UnicodeString & Message);
  486. void Error(Exception & E, TSessionAction & Action, const UnicodeString & Message);
  487. bool Retry();
  488. bool Succeeded();
  489. private:
  490. TTerminal * FTerminal;
  491. bool FRetry;
  492. bool FSucceeded;
  493. void DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message);
  494. };
  495. //---------------------------------------------------------------------------
  496. TRetryOperationLoop::TRetryOperationLoop(TTerminal * Terminal)
  497. {
  498. FTerminal = Terminal;
  499. FRetry = false;
  500. FSucceeded = true;
  501. }
  502. //---------------------------------------------------------------------------
  503. void TRetryOperationLoop::DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message)
  504. {
  505. FSucceeded = false;
  506. // Note that the action may already be canceled when RollbackAction is called
  507. unsigned int Result;
  508. try
  509. {
  510. Result = FTerminal->CommandError(&E, Message, qaRetry | qaSkip | qaAbort);
  511. }
  512. catch (Exception & E2)
  513. {
  514. if (Action != NULL)
  515. {
  516. FTerminal->RollbackAction(*Action, NULL, &E2);
  517. }
  518. throw;
  519. }
  520. switch (Result)
  521. {
  522. case qaRetry:
  523. FRetry = true;
  524. if (Action != NULL)
  525. {
  526. Action->Cancel();
  527. }
  528. break;
  529. case qaAbort:
  530. if (Action != NULL)
  531. {
  532. FTerminal->RollbackAction(*Action, NULL, &E);
  533. }
  534. Abort();
  535. break;
  536. case qaSkip:
  537. if (Action != NULL)
  538. {
  539. Action->Cancel();
  540. }
  541. break;
  542. default:
  543. DebugFail();
  544. break;
  545. }
  546. }
  547. //---------------------------------------------------------------------------
  548. void TRetryOperationLoop::Error(Exception & E)
  549. {
  550. DoError(E, NULL, UnicodeString());
  551. }
  552. //---------------------------------------------------------------------------
  553. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action)
  554. {
  555. DoError(E, &Action, UnicodeString());
  556. }
  557. //---------------------------------------------------------------------------
  558. void TRetryOperationLoop::Error(Exception & E, const UnicodeString & Message)
  559. {
  560. DoError(E, NULL, Message);
  561. }
  562. //---------------------------------------------------------------------------
  563. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action, const UnicodeString & Message)
  564. {
  565. DoError(E, &Action, Message);
  566. }
  567. //---------------------------------------------------------------------------
  568. bool TRetryOperationLoop::Retry()
  569. {
  570. bool Result = FRetry;
  571. FRetry = false;
  572. if (Result)
  573. {
  574. FSucceeded = true;
  575. }
  576. return Result;
  577. }
  578. //---------------------------------------------------------------------------
  579. bool TRetryOperationLoop::Succeeded()
  580. {
  581. return FSucceeded;
  582. }
  583. //---------------------------------------------------------------------------
  584. //---------------------------------------------------------------------------
  585. TCollectedFileList::TCollectedFileList()
  586. {
  587. }
  588. //---------------------------------------------------------------------------
  589. __fastcall TCollectedFileList::~TCollectedFileList()
  590. {
  591. for (size_t Index = 0; Index < FList.size(); Index++)
  592. {
  593. Deleting(Index);
  594. }
  595. }
  596. //---------------------------------------------------------------------------
  597. void TCollectedFileList::Deleting(int Index)
  598. {
  599. delete FList[Index].Object;
  600. }
  601. //---------------------------------------------------------------------------
  602. int TCollectedFileList::Add(const UnicodeString & FileName, TObject * Object, bool Dir)
  603. {
  604. TFileData Data;
  605. Data.FileName = FileName;
  606. Data.Object = Object;
  607. Data.Dir = Dir;
  608. Data.Recursed = true;
  609. Data.State = 0;
  610. FList.push_back(Data);
  611. return Count() - 1;
  612. }
  613. //---------------------------------------------------------------------------
  614. void TCollectedFileList::DidNotRecurse(int Index)
  615. {
  616. FList[Index].Recursed = false;
  617. }
  618. //---------------------------------------------------------------------------
  619. void TCollectedFileList::Delete(int Index)
  620. {
  621. Deleting(Index);
  622. FList.erase(FList.begin() + Index);
  623. }
  624. //---------------------------------------------------------------------------
  625. int TCollectedFileList::Count() const
  626. {
  627. return FList.size();
  628. }
  629. //---------------------------------------------------------------------------
  630. UnicodeString TCollectedFileList::GetFileName(int Index) const
  631. {
  632. return FList[Index].FileName;
  633. }
  634. //---------------------------------------------------------------------------
  635. TObject * TCollectedFileList::GetObject(int Index) const
  636. {
  637. return FList[Index].Object;
  638. }
  639. //---------------------------------------------------------------------------
  640. bool TCollectedFileList::IsDir(int Index) const
  641. {
  642. return FList[Index].Dir;
  643. }
  644. //---------------------------------------------------------------------------
  645. bool TCollectedFileList::IsRecursed(int Index) const
  646. {
  647. return FList[Index].Recursed;
  648. }
  649. //---------------------------------------------------------------------------
  650. int TCollectedFileList::GetState(int Index) const
  651. {
  652. return FList[Index].State;
  653. }
  654. //---------------------------------------------------------------------------
  655. void TCollectedFileList::SetState(int Index, int State)
  656. {
  657. FList[Index].State = State;
  658. }
  659. //---------------------------------------------------------------------------
  660. //---------------------------------------------------------------------------
  661. TParallelOperation::TParallelOperation(TOperationSide Side)
  662. {
  663. FCopyParam = NULL;
  664. FParams = 0;
  665. FProbablyEmpty = false;
  666. FClients = 0;
  667. FMainOperationProgress = NULL;
  668. DebugAssert((Side == osLocal) || (Side == osRemote));
  669. FSide = Side;
  670. FVersion = 0;
  671. }
  672. //---------------------------------------------------------------------------
  673. void TParallelOperation::Init(
  674. TStrings * AFileList, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  675. TFileOperationProgressType * MainOperationProgress, const UnicodeString & MainName)
  676. {
  677. DebugAssert(FFileList.get() == NULL);
  678. // More lists should really happen in scripting only, which does not support parallel transfers atm.
  679. // But in general the code should work with more lists anyway, it just was not tested for it.
  680. DebugAssert(AFileList->Count == 1);
  681. FFileList.reset(AFileList);
  682. FSection.reset(new TCriticalSection());
  683. FTargetDir = TargetDir;
  684. FCopyParam = CopyParam;
  685. FParams = Params;
  686. FMainOperationProgress = MainOperationProgress;
  687. FMainName = MainName;
  688. FListIndex = 0;
  689. FIndex = 0;
  690. }
  691. //---------------------------------------------------------------------------
  692. TParallelOperation::~TParallelOperation()
  693. {
  694. WaitFor();
  695. }
  696. //---------------------------------------------------------------------------
  697. bool TParallelOperation::IsInitialized()
  698. {
  699. return (FMainOperationProgress != NULL);
  700. }
  701. //---------------------------------------------------------------------------
  702. bool TParallelOperation::ShouldAddClient()
  703. {
  704. bool Result;
  705. // TTransferQueueItem::ProgressUpdated() already checks IsInitialized() before calling this
  706. if (!IsInitialized())
  707. {
  708. Result = false;
  709. }
  710. else
  711. {
  712. TGuard Guard(FSection.get());
  713. Result = !FProbablyEmpty && (FMainOperationProgress->Cancel < csCancel);
  714. }
  715. return Result;
  716. }
  717. //---------------------------------------------------------------------------
  718. void TParallelOperation::AddClient()
  719. {
  720. TGuard Guard(FSection.get());
  721. FClients++;
  722. }
  723. //---------------------------------------------------------------------------
  724. void TParallelOperation::RemoveClient()
  725. {
  726. TGuard Guard(FSection.get());
  727. FClients--;
  728. }
  729. //---------------------------------------------------------------------------
  730. void TParallelOperation::WaitFor()
  731. {
  732. // Even initialized?
  733. // Won't be, when parallel transfers were not possible (like when preserving of directory timestamps is enabled)
  734. if (FSection.get() != NULL)
  735. {
  736. bool Done;
  737. do
  738. {
  739. {
  740. TGuard Guard(FSection.get());
  741. Done = (FClients == 0);
  742. }
  743. if (!Done)
  744. {
  745. // propagate the total progress incremented by the parallel operations
  746. FMainOperationProgress->Progress();
  747. Sleep(200);
  748. }
  749. }
  750. while (!Done);
  751. FProbablyEmpty = true;
  752. }
  753. else
  754. {
  755. DebugAssert(FClients == 0);
  756. }
  757. }
  758. //---------------------------------------------------------------------------
  759. void TParallelOperation::Done(const UnicodeString & FileName, bool Dir, bool Success)
  760. {
  761. if (Dir)
  762. {
  763. TGuard Guard(FSection.get());
  764. TDirectories::iterator DirectoryIterator = FDirectories.find(FileName);
  765. if (DebugAlwaysTrue(DirectoryIterator != FDirectories.end()))
  766. {
  767. if (Success)
  768. {
  769. DebugAssert(!DirectoryIterator->second.Exists);
  770. DirectoryIterator->second.Exists = true;
  771. }
  772. else
  773. {
  774. // This is actually not useful at the moment, as when creating directory fails and "Skip" is pressed,
  775. // the current code in CopyToRemote/CreateDirectory will behave as, if it succedded, so Successs will be true here.
  776. FDirectories.erase(DirectoryIterator);
  777. if (FFileList->Count > FListIndex)
  778. {
  779. UnicodeString FileNameWithSlash;
  780. if (FSide == osLocal)
  781. {
  782. FileNameWithSlash = IncludeTrailingBackslash(FileName);
  783. }
  784. else
  785. {
  786. FileNameWithSlash = UnixIncludeTrailingBackslash(FileName);
  787. }
  788. // It can actually be a different list than the one the directory was taken from,
  789. // but that does not matter that much. It should not happen anyway, as more lists should be in scripting only.
  790. TCollectedFileList * Files = GetFileList(FListIndex);
  791. int Index = 0;
  792. while (Index < Files->Count())
  793. {
  794. if (StartsText(FileNameWithSlash, Files->GetFileName(Index)))
  795. {
  796. // We should add the file to "skip" counters in the OperationProgress,
  797. // but an interactive foreground transfer is not doing that either yet.
  798. Files->Delete(Index);
  799. // Force re-update
  800. FVersion++;
  801. if (Index < FIndex)
  802. {
  803. FIndex--;
  804. }
  805. }
  806. else
  807. {
  808. Index++;
  809. }
  810. }
  811. }
  812. }
  813. }
  814. }
  815. }
  816. //---------------------------------------------------------------------------
  817. bool TParallelOperation::CheckEnd(TCollectedFileList * Files)
  818. {
  819. bool Result = (FIndex >= Files->Count());
  820. if (Result)
  821. {
  822. FListIndex++;
  823. FIndex = 0;
  824. }
  825. return Result;
  826. }
  827. //---------------------------------------------------------------------------
  828. TCollectedFileList * TParallelOperation::GetFileList(int Index)
  829. {
  830. return DebugNotNull(dynamic_cast<TCollectedFileList *>(FFileList->Objects[Index]));
  831. }
  832. //---------------------------------------------------------------------------
  833. int TParallelOperation::GetNext(TTerminal * Terminal, UnicodeString & FileName, TObject *& Object, UnicodeString & TargetDir, bool & Dir, bool & Recursed)
  834. {
  835. TGuard Guard(FSection.get());
  836. int Result = 1;
  837. TCollectedFileList * Files;
  838. do
  839. {
  840. if (FFileList->Count > FListIndex)
  841. {
  842. Files = GetFileList(FListIndex);
  843. // can happen if the file was excluded by file mask
  844. if (CheckEnd(Files))
  845. {
  846. Files = NULL;
  847. }
  848. }
  849. else
  850. {
  851. Files = NULL;
  852. Result = -1;
  853. }
  854. }
  855. while ((Result == 1) && (Files == NULL));
  856. if (Files != NULL)
  857. {
  858. UnicodeString RootPath = FFileList->Strings[FListIndex];
  859. FileName = Files->GetFileName(FIndex);
  860. Object = Files->GetObject(FIndex);
  861. Dir = Files->IsDir(FIndex);
  862. Recursed = Files->IsRecursed(FIndex);
  863. UnicodeString DirPath;
  864. bool FirstLevel;
  865. if (FSide == osLocal)
  866. {
  867. DirPath = ExtractFileDir(FileName);
  868. FirstLevel = SamePaths(DirPath, RootPath);
  869. }
  870. else
  871. {
  872. DirPath = UnixExtractFileDir(FileName);
  873. FirstLevel = UnixSamePath(DirPath, RootPath);
  874. }
  875. if (FirstLevel)
  876. {
  877. TargetDir = FTargetDir;
  878. }
  879. else
  880. {
  881. TDirectories::const_iterator DirectoryIterator = FDirectories.find(DirPath);
  882. if (DebugAlwaysFalse(DirectoryIterator == FDirectories.end()))
  883. {
  884. throw EInvalidOperation(L"Parent path not known");
  885. }
  886. const TDirectoryData & DirectoryData = DirectoryIterator->second;
  887. if (!DirectoryData.Exists)
  888. {
  889. Result = 0; // wait for parent directory to be created
  890. }
  891. else
  892. {
  893. TargetDir = DirectoryData.OppositePath;
  894. }
  895. }
  896. if (!TargetDir.IsEmpty())
  897. {
  898. if (Dir)
  899. {
  900. TDirectoryData DirectoryData;
  901. UnicodeString OnlyFileName;
  902. if (FSide == osLocal)
  903. {
  904. OnlyFileName = ExtractFileName(FileName);
  905. }
  906. else
  907. {
  908. OnlyFileName = UnixExtractFileName(FileName);
  909. }
  910. OnlyFileName = Terminal->ChangeFileName(FCopyParam, OnlyFileName, osRemote, FirstLevel);
  911. if (FSide == osLocal)
  912. {
  913. DirectoryData.OppositePath = UnixCombinePaths(TargetDir, OnlyFileName);
  914. }
  915. else
  916. {
  917. DirectoryData.OppositePath = TPath::Combine(TargetDir, OnlyFileName);
  918. }
  919. DirectoryData.Exists = false;
  920. FDirectories.insert(std::make_pair(FileName, DirectoryData));
  921. }
  922. // The current implementation of UpdateFileList relies on this specific way of changing state
  923. // (all files before FIndex one-by-one)
  924. Files->SetState(FIndex, qfsProcessed);
  925. FIndex++;
  926. CheckEnd(Files);
  927. }
  928. }
  929. FProbablyEmpty = (FFileList->Count == FListIndex);
  930. return Result;
  931. }
  932. //---------------------------------------------------------------------------
  933. bool TParallelOperation::UpdateFileList(TQueueFileList * UpdateFileList)
  934. {
  935. TGuard Guard(FSection.get());
  936. bool Result =
  937. (UpdateFileList->FLastParallelOperation != this) ||
  938. (UpdateFileList->FLastParallelOperationVersion != FVersion);
  939. DebugAssert(FFileList->Count == 1);
  940. TCollectedFileList * Files = GetFileList(0);
  941. if (!Result && (UpdateFileList->GetCount() != Files->Count()))
  942. {
  943. DebugAssert(false);
  944. Result = true;
  945. }
  946. if (Result)
  947. {
  948. UpdateFileList->Clear();
  949. for (int Index = 0; Index < Files->Count(); Index++)
  950. {
  951. UpdateFileList->Add(Files->GetFileName(Index), Files->GetState(Index));
  952. }
  953. }
  954. else
  955. {
  956. int Index = ((FListIndex == 0) ? FIndex : Files->Count()) - 1;
  957. while ((Index >= 0) && (UpdateFileList->GetState(Index) != Files->GetState(Index)))
  958. {
  959. UpdateFileList->SetState(Index, Files->GetState(Index));
  960. Index--;
  961. Result = true;
  962. }
  963. }
  964. UpdateFileList->FLastParallelOperation = this;
  965. UpdateFileList->FLastParallelOperationVersion = FVersion;
  966. return Result;
  967. }
  968. //---------------------------------------------------------------------------
  969. //---------------------------------------------------------------------------
  970. __fastcall TTerminal::TTerminal(TSessionData * SessionData, TConfiguration * Configuration, TActionLog * ActionLog)
  971. {
  972. FConfiguration = Configuration;
  973. FSessionData = new TSessionData(L"");
  974. FSessionData->Assign(SessionData);
  975. TDateTime Started = Now(); // use the same time for session and XML log
  976. FLog = new TSessionLog(this, Started, FSessionData, Configuration);
  977. if (ActionLog != NULL)
  978. {
  979. FActionLog = ActionLog;
  980. FActionLogOwned = false;
  981. }
  982. else
  983. {
  984. FActionLog = new TActionLog(this, Started, FSessionData, Configuration);
  985. FActionLogOwned = true;
  986. }
  987. FFiles = new TRemoteDirectory(this);
  988. FExceptionOnFail = 0;
  989. FInTransaction = 0;
  990. FReadCurrentDirectoryPending = false;
  991. FReadDirectoryPending = false;
  992. FUsersGroupsLookedup = False;
  993. FTunnelLocalPortNumber = 0;
  994. FFileSystem = NULL;
  995. FSecureShell = NULL;
  996. FOnProgress = NULL;
  997. FOnFinished = NULL;
  998. FOnDeleteLocalFile = NULL;
  999. FOnReadDirectoryProgress = NULL;
  1000. FOnQueryUser = NULL;
  1001. FOnPromptUser = NULL;
  1002. FOnDisplayBanner = NULL;
  1003. FOnShowExtendedException = NULL;
  1004. FOnInformation = NULL;
  1005. FOnCustomCommand = NULL;
  1006. FOnClose = NULL;
  1007. FOnFindingFile = NULL;
  1008. FOperationProgressPersistence = NULL;
  1009. FOperationProgressOnceDoneOperation = odoIdle;
  1010. FUseBusyCursor = True;
  1011. FDirectoryCache = new TRemoteDirectoryCache();
  1012. FDirectoryChangesCache = NULL;
  1013. FFSProtocol = cfsUnknown;
  1014. FCommandSession = NULL;
  1015. FAutoReadDirectory = true;
  1016. FReadingCurrentDirectory = false;
  1017. FStatus = ssClosed;
  1018. FOpening = 0;
  1019. FTunnelThread = NULL;
  1020. FTunnel = NULL;
  1021. FTunnelData = NULL;
  1022. FTunnelLog = NULL;
  1023. FTunnelUI = NULL;
  1024. FTunnelOpening = false;
  1025. FCallbackGuard = NULL;
  1026. FNesting = 0;
  1027. FRememberedPasswordKind = TPromptKind(-1);
  1028. FSecondaryTerminals = 0;
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. __fastcall TTerminal::~TTerminal()
  1032. {
  1033. if (Active)
  1034. {
  1035. Close();
  1036. }
  1037. if (FCallbackGuard != NULL)
  1038. {
  1039. // see TTerminal::HandleExtendedException
  1040. FCallbackGuard->Dismiss();
  1041. }
  1042. DebugAssert(FTunnel == NULL);
  1043. SAFE_DESTROY(FCommandSession);
  1044. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  1045. (FDirectoryChangesCache != NULL))
  1046. {
  1047. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  1048. FDirectoryChangesCache);
  1049. }
  1050. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  1051. SAFE_DESTROY_EX(TSessionLog, FLog);
  1052. if (FActionLogOwned)
  1053. {
  1054. SAFE_DESTROY_EX(TActionLog, FActionLog);
  1055. }
  1056. else
  1057. {
  1058. FActionLog = NULL;
  1059. }
  1060. delete FFiles;
  1061. delete FDirectoryCache;
  1062. delete FDirectoryChangesCache;
  1063. SAFE_DESTROY(FSessionData);
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. void __fastcall TTerminal::Idle()
  1067. {
  1068. // Once we disconnect, do nothing, until reconnect handler
  1069. // "receives the information".
  1070. // Never go idle when called from within ::ProcessGUI() call
  1071. // as we may recurse for good, timeouting eventually.
  1072. if (Active && (FNesting == 0))
  1073. {
  1074. TAutoNestingCounter NestingCounter(FNesting);
  1075. if (Configuration->ActualLogProtocol >= 1)
  1076. {
  1077. LogEvent(L"Session upkeep");
  1078. }
  1079. DebugAssert(FFileSystem != NULL);
  1080. FFileSystem->Idle();
  1081. if (CommandSessionOpened)
  1082. {
  1083. try
  1084. {
  1085. FCommandSession->Idle();
  1086. }
  1087. catch(Exception & E)
  1088. {
  1089. // If the secondary session is dropped, ignore the error and let
  1090. // it be reconnected when needed.
  1091. // BTW, non-fatal error can hardly happen here, that's why
  1092. // it is displayed, because it can be useful to know.
  1093. if (FCommandSession->Active)
  1094. {
  1095. FCommandSession->HandleExtendedException(&E);
  1096. }
  1097. }
  1098. }
  1099. }
  1100. }
  1101. //---------------------------------------------------------------------
  1102. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  1103. {
  1104. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  1105. }
  1106. //---------------------------------------------------------------------
  1107. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  1108. {
  1109. UnicodeString Result;
  1110. try
  1111. {
  1112. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  1113. }
  1114. catch(EAbort &)
  1115. {
  1116. // silently ignore aborted prompts for master password and return empty password
  1117. }
  1118. return Result;
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. void __fastcall TTerminal::RecryptPasswords()
  1122. {
  1123. FSessionData->RecryptPasswords();
  1124. FRememberedPassword = EncryptPassword(GetRememberedPassword());
  1125. FRememberedTunnelPassword = EncryptPassword(GetRememberedTunnelPassword());
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  1129. const UnicodeString BasePath)
  1130. {
  1131. // replace this by AbsolutePath()
  1132. Path = UnixExcludeTrailingBackslash(Path);
  1133. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  1134. {
  1135. // TODO: Handle more complicated cases like "../../xxx"
  1136. if (Path == PARENTDIRECTORY)
  1137. {
  1138. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  1139. UnixExcludeTrailingBackslash(BasePath)));
  1140. }
  1141. else
  1142. {
  1143. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  1144. }
  1145. }
  1146. return Path;
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. bool __fastcall TTerminal::GetActive()
  1150. {
  1151. return (FFileSystem != NULL) && FFileSystem->GetActive();
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. void __fastcall TTerminal::Close()
  1155. {
  1156. FFileSystem->Close();
  1157. // Cannot rely on CommandSessionOpened here as Status is set to ssClosed too late
  1158. if ((FCommandSession != NULL) && FCommandSession->Active)
  1159. {
  1160. // prevent recursion
  1161. FCommandSession->OnClose = NULL;
  1162. FCommandSession->Close();
  1163. }
  1164. }
  1165. //---------------------------------------------------------------------------
  1166. void __fastcall TTerminal::ResetConnection()
  1167. {
  1168. // used to be called from Reopen(), why?
  1169. FTunnelError = L"";
  1170. FRememberedPasswordTried = false;
  1171. FRememberedTunnelPasswordTried = false;
  1172. if (FDirectoryChangesCache != NULL)
  1173. {
  1174. delete FDirectoryChangesCache;
  1175. FDirectoryChangesCache = NULL;
  1176. }
  1177. FFiles->Directory = L"";
  1178. // note that we cannot clear contained files
  1179. // as they can still be referenced in the GUI atm
  1180. }
  1181. //---------------------------------------------------------------------------
  1182. void __fastcall TTerminal::FingerprintScan(UnicodeString & SHA256, UnicodeString & SHA1, UnicodeString & MD5)
  1183. {
  1184. SessionData->FingerprintScan = true;
  1185. try
  1186. {
  1187. Open();
  1188. // we should never get here
  1189. DebugFail();
  1190. Abort();
  1191. }
  1192. catch (...)
  1193. {
  1194. if (!FFingerprintScannedSHA256.IsEmpty() ||
  1195. !FFingerprintScannedSHA1.IsEmpty() ||
  1196. !FFingerprintScannedMD5.IsEmpty())
  1197. {
  1198. SHA256 = FFingerprintScannedSHA256;
  1199. SHA1 = FFingerprintScannedSHA1;
  1200. MD5 = FFingerprintScannedMD5;
  1201. }
  1202. else
  1203. {
  1204. throw;
  1205. }
  1206. }
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. void __fastcall TTerminal::Open()
  1210. {
  1211. AnySession = true;
  1212. Configuration->Usage->Inc(L"SessionOpens");
  1213. TAutoNestingCounter OpeningCounter(FOpening);
  1214. ReflectSettings();
  1215. try
  1216. {
  1217. FEncryptKey = HexToBytes(FSessionData->EncryptKey);
  1218. if (IsEncryptingFiles())
  1219. {
  1220. ValidateEncryptKey(FEncryptKey);
  1221. }
  1222. DoInformation(L"", true, 1);
  1223. try
  1224. {
  1225. FRememberedPasswordUsed = false;
  1226. try
  1227. {
  1228. ResetConnection();
  1229. FStatus = ssOpening;
  1230. try
  1231. {
  1232. if (FFileSystem == NULL)
  1233. {
  1234. Log->AddSystemInfo();
  1235. DoInitializeLog();
  1236. Log->AddStartupInfo();
  1237. }
  1238. DebugAssert(FTunnel == NULL);
  1239. if (FSessionData->Tunnel)
  1240. {
  1241. DoInformation(LoadStr(OPEN_TUNNEL), true);
  1242. LogEvent(L"Opening tunnel.");
  1243. OpenTunnel();
  1244. Log->AddSeparator();
  1245. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  1246. DoInformation(LoadStr(USING_TUNNEL), false);
  1247. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  1248. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  1249. }
  1250. else
  1251. {
  1252. DebugAssert(FTunnelLocalPortNumber == 0);
  1253. }
  1254. if (FFileSystem == NULL)
  1255. {
  1256. if (SessionData->FSProtocol == fsFTP)
  1257. {
  1258. FFSProtocol = cfsFTP;
  1259. FFileSystem = new TFTPFileSystem(this);
  1260. FFileSystem->Open();
  1261. Log->AddSeparator();
  1262. LogEvent(L"Using FTP protocol.");
  1263. }
  1264. else if (SessionData->FSProtocol == fsWebDAV)
  1265. {
  1266. FFSProtocol = cfsWebDAV;
  1267. FFileSystem = new TWebDAVFileSystem(this);
  1268. FFileSystem->Open();
  1269. Log->AddSeparator();
  1270. LogEvent(L"Using WebDAV protocol.");
  1271. }
  1272. else if (SessionData->FSProtocol == fsS3)
  1273. {
  1274. FFSProtocol = cfsS3;
  1275. FFileSystem = new TS3FileSystem(this);
  1276. FFileSystem->Open();
  1277. Log->AddSeparator();
  1278. LogEvent(L"Using S3 protocol.");
  1279. }
  1280. else
  1281. {
  1282. DebugAssert(FSecureShell == NULL);
  1283. try
  1284. {
  1285. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  1286. try
  1287. {
  1288. // there will be only one channel in this session
  1289. FSecureShell->Simple = true;
  1290. FSecureShell->Open();
  1291. }
  1292. catch(Exception & E)
  1293. {
  1294. DebugAssert(!FSecureShell->Active);
  1295. if (SessionData->FingerprintScan)
  1296. {
  1297. FSecureShell->GetHostKeyFingerprint(FFingerprintScannedSHA256, FFingerprintScannedMD5);
  1298. FFingerprintScannedSHA1 = UnicodeString();
  1299. }
  1300. // Tunnel errors that happens only once we connect to the local port (server-side forwarding problems).
  1301. // Contrary to local side problems handled already in OpenTunnel.
  1302. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  1303. {
  1304. // the only case where we expect this to happen (first in GUI, the latter in scripting)
  1305. DebugAssert((E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR)) || (E.Message == LoadStr(NET_TRANSL_CONN_ABORTED)) || (E.Message.Pos(LoadStr(NOT_CONNECTED)) > 0));
  1306. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  1307. }
  1308. else
  1309. {
  1310. throw;
  1311. }
  1312. }
  1313. Log->AddSeparator();
  1314. if ((SessionData->FSProtocol == fsSCPonly) ||
  1315. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  1316. {
  1317. FFSProtocol = cfsSCP;
  1318. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  1319. FSecureShell = NULL; // ownership passed
  1320. LogEvent(L"Using SCP protocol.");
  1321. }
  1322. else
  1323. {
  1324. FFSProtocol = cfsSFTP;
  1325. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  1326. FSecureShell = NULL; // ownership passed
  1327. LogEvent(L"Using SFTP protocol.");
  1328. }
  1329. }
  1330. __finally
  1331. {
  1332. delete FSecureShell;
  1333. FSecureShell = NULL;
  1334. }
  1335. }
  1336. }
  1337. else
  1338. {
  1339. FFileSystem->Open();
  1340. }
  1341. }
  1342. __finally
  1343. {
  1344. if (FSessionData->Tunnel)
  1345. {
  1346. FSessionData->RollbackTunnel();
  1347. }
  1348. }
  1349. if (SessionData->CacheDirectoryChanges)
  1350. {
  1351. DebugAssert(FDirectoryChangesCache == NULL);
  1352. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  1353. Configuration->CacheDirectoryChangesMaxSize);
  1354. if (SessionData->PreserveDirectoryChanges)
  1355. {
  1356. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  1357. FDirectoryChangesCache);
  1358. }
  1359. }
  1360. DoStartup();
  1361. if (FCollectFileSystemUsage)
  1362. {
  1363. FFileSystem->CollectUsage();
  1364. FCollectFileSystemUsage = false;
  1365. }
  1366. DoInformation(LoadStr(STATUS_READY), true);
  1367. FStatus = ssOpened;
  1368. }
  1369. catch(...)
  1370. {
  1371. // rollback
  1372. if (FDirectoryChangesCache != NULL)
  1373. {
  1374. delete FDirectoryChangesCache;
  1375. FDirectoryChangesCache = NULL;
  1376. }
  1377. if (SessionData->FingerprintScan && (FFileSystem != NULL) &&
  1378. DebugAlwaysTrue(SessionData->Ftps != ftpsNone))
  1379. {
  1380. const TSessionInfo & SessionInfo = FFileSystem->GetSessionInfo();
  1381. FFingerprintScannedSHA256 = SessionInfo.CertificateFingerprintSHA256;
  1382. FFingerprintScannedSHA1 = SessionInfo.CertificateFingerprintSHA1;
  1383. FFingerprintScannedMD5 = UnicodeString();
  1384. }
  1385. if (FRememberedPasswordUsed)
  1386. {
  1387. // Particularly to prevent reusing a wrong client certificate passphrase
  1388. // in the next login attempt
  1389. FRememberedPassword = UnicodeString();
  1390. FRememberedPasswordKind = TPromptKind(-1);
  1391. FRememberedTunnelPassword = UnicodeString();
  1392. }
  1393. throw;
  1394. }
  1395. }
  1396. __finally
  1397. {
  1398. // This does not make it through, if terminal thread is abandonded,
  1399. // see also TTerminalManager::DoConnectTerminal
  1400. DoInformation(L"", true, 0);
  1401. }
  1402. }
  1403. catch(EFatal &)
  1404. {
  1405. throw;
  1406. }
  1407. catch(Exception & E)
  1408. {
  1409. // any exception while opening session is fatal
  1410. FatalError(&E, L"");
  1411. }
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  1415. {
  1416. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  1417. bool Result = (Socket != INVALID_SOCKET);
  1418. if (Result)
  1419. {
  1420. SOCKADDR_IN Address;
  1421. memset(&Address, 0, sizeof(Address));
  1422. Address.sin_family = AF_INET;
  1423. Address.sin_port = htons(static_cast<short>(PortNumber));
  1424. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1425. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  1426. closesocket(Socket);
  1427. }
  1428. return Result;
  1429. }
  1430. //---------------------------------------------------------------------------
  1431. void __fastcall TTerminal::OpenTunnel()
  1432. {
  1433. DebugAssert(FTunnelData == NULL);
  1434. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  1435. if (FTunnelLocalPortNumber == 0)
  1436. {
  1437. // Randomizing the port selection to reduce a chance of conflicts.
  1438. std::vector<int> Ports;
  1439. for (int Port = Configuration->TunnelLocalPortNumberLow; Port <= Configuration->TunnelLocalPortNumberHigh; Port++)
  1440. {
  1441. Ports.push_back(Port);
  1442. }
  1443. do
  1444. {
  1445. if (Ports.empty())
  1446. {
  1447. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  1448. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  1449. }
  1450. int Index = Random(Ports.size());
  1451. int Port = Ports[Index];
  1452. Ports.erase(&Ports.at(Index));
  1453. if (IsListenerFree(Port))
  1454. {
  1455. FTunnelLocalPortNumber = Port;
  1456. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  1457. }
  1458. }
  1459. while (FTunnelLocalPortNumber == 0);
  1460. }
  1461. try
  1462. {
  1463. FTunnelData = FSessionData->CreateTunnelData(FTunnelLocalPortNumber);
  1464. // The Started argument is not used with Parent being set
  1465. FTunnelLog = new TSessionLog(this, TDateTime(), FTunnelData, Configuration);
  1466. FTunnelLog->SetParent(FLog, L"Tunnel");
  1467. FTunnelLog->ReflectSettings();
  1468. FTunnelUI = new TTunnelUI(this);
  1469. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  1470. FTunnelOpening = true;
  1471. try
  1472. {
  1473. FTunnel->Open();
  1474. }
  1475. __finally
  1476. {
  1477. FTunnelOpening = false;
  1478. }
  1479. // When forwarding fails due to a local problem (e.g. port in use), we get the error already here, so abort asap.
  1480. // If we won't abort, particularly in case of "port in use", we may not even detect the problem,
  1481. // as the connection to the port may succeed.
  1482. // Remote-side tunnel problems are handled in TTerminal::Open().
  1483. if (!FTunnel->LastTunnelError.IsEmpty())
  1484. {
  1485. // Throw and handle with any other theoretical forwarding errors that may cause tunnel connection close
  1486. // (probably cannot happen)
  1487. EXCEPTION;
  1488. }
  1489. FTunnelThread = new TTunnelThread(FTunnel);
  1490. }
  1491. catch (Exception & E)
  1492. {
  1493. LogEvent(L"Error opening tunnel.");
  1494. CloseTunnel();
  1495. if (!FTunnelError.IsEmpty())
  1496. {
  1497. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  1498. }
  1499. else
  1500. {
  1501. throw;
  1502. }
  1503. }
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. void __fastcall TTerminal::CloseTunnel()
  1507. {
  1508. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  1509. FTunnelError = FTunnel->LastTunnelError;
  1510. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  1511. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  1512. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  1513. SAFE_DESTROY(FTunnelData);
  1514. FTunnelLocalPortNumber = 0;
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. void __fastcall TTerminal::Closed()
  1518. {
  1519. if (FTunnel != NULL)
  1520. {
  1521. CloseTunnel();
  1522. }
  1523. if (OnClose)
  1524. {
  1525. TCallbackGuard Guard(this);
  1526. try
  1527. {
  1528. OnClose(this);
  1529. Guard.Verify();
  1530. }
  1531. catch (Exception & E)
  1532. {
  1533. if (!Guard.Verify(&E))
  1534. {
  1535. throw;
  1536. }
  1537. }
  1538. }
  1539. FStatus = ssClosed;
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. void __fastcall TTerminal::ProcessGUI()
  1543. {
  1544. // Do not process GUI here, as we are called directly from a GUI loop and may
  1545. // recurse for good.
  1546. // Alternatively we may check for (FOperationProgress == NULL)
  1547. if (FNesting == 0)
  1548. {
  1549. TAutoNestingCounter NestingCounter(FNesting);
  1550. ::ProcessGUI();
  1551. }
  1552. }
  1553. //---------------------------------------------------------------------------
  1554. void __fastcall TTerminal::Progress(TFileOperationProgressType * OperationProgress)
  1555. {
  1556. if (FNesting == 0)
  1557. {
  1558. TAutoNestingCounter NestingCounter(FNesting);
  1559. OperationProgress->Progress();
  1560. }
  1561. }
  1562. //---------------------------------------------------------------------------
  1563. void __fastcall TTerminal::Reopen(int Params)
  1564. {
  1565. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  1566. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  1567. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  1568. bool PrevReadDirectoryPending = FReadDirectoryPending;
  1569. DebugAssert(!FSuspendTransaction);
  1570. bool PrevAutoReadDirectory = FAutoReadDirectory;
  1571. // here used to be a check for FExceptionOnFail being 0
  1572. // but it can happen, e.g. when we are downloading file to execute it.
  1573. // however I'm not sure why we mind having excaption-on-fail enabled here
  1574. int PrevExceptionOnFail = FExceptionOnFail;
  1575. try
  1576. {
  1577. FReadCurrentDirectoryPending = false;
  1578. FReadDirectoryPending = false;
  1579. // Not sure why we are suspeding the transaction in the first place,
  1580. // but definitelly when set while connecting auto loaded workspace session, it causes loading the directory twice.
  1581. // (when reconnecting lost connection, it's usually prevented by cached directory)
  1582. // Preventing that by suspeding transaction only when there is one.
  1583. FSuspendTransaction = (FInTransaction > 0);
  1584. FExceptionOnFail = 0;
  1585. // typically, we avoid reading directory, when there is operation ongoing,
  1586. // for file list which may reference files from current directory
  1587. if (FLAGSET(Params, ropNoReadDirectory))
  1588. {
  1589. AutoReadDirectory = false;
  1590. }
  1591. // only peek, we may not be connected at all atm,
  1592. // so make sure we do not try retrieving current directory from the server
  1593. // (particularly with FTP)
  1594. UnicodeString ACurrentDirectory = PeekCurrentDirectory();
  1595. if (!ACurrentDirectory.IsEmpty())
  1596. {
  1597. SessionData->RemoteDirectory = ACurrentDirectory;
  1598. }
  1599. if (SessionData->FSProtocol == fsSFTP)
  1600. {
  1601. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1602. }
  1603. Open();
  1604. }
  1605. __finally
  1606. {
  1607. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1608. SessionData->FSProtocol = OrigFSProtocol;
  1609. FAutoReadDirectory = PrevAutoReadDirectory;
  1610. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1611. FReadDirectoryPending = PrevReadDirectoryPending;
  1612. FSuspendTransaction = false;
  1613. FExceptionOnFail = PrevExceptionOnFail;
  1614. }
  1615. }
  1616. //---------------------------------------------------------------------------
  1617. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1618. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1619. {
  1620. bool AResult;
  1621. TStrings * Prompts = new TStringList;
  1622. TStrings * Results = new TStringList;
  1623. try
  1624. {
  1625. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1626. Results->AddObject(Result, (TObject *)MaxLen);
  1627. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1628. Result = Results->Strings[0];
  1629. }
  1630. __finally
  1631. {
  1632. delete Prompts;
  1633. delete Results;
  1634. }
  1635. return AResult;
  1636. }
  1637. //---------------------------------------------------------------------------
  1638. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1639. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1640. {
  1641. // If PromptUser is overridden in descendant class, the overridden version
  1642. // is not called when accessed via TSessionIU interface.
  1643. // So this is workaround.
  1644. // Actually no longer needed as we do not uverride DoPromptUser
  1645. // anymore in TSecondaryTerminal.
  1646. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1647. }
  1648. //---------------------------------------------------------------------------
  1649. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1650. {
  1651. return this;
  1652. }
  1653. //---------------------------------------------------------------------------
  1654. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1655. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1656. {
  1657. bool AResult = false;
  1658. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1659. if (PasswordOrPassphrasePrompt)
  1660. {
  1661. bool & PasswordTried =
  1662. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1663. if (!PasswordTried)
  1664. {
  1665. // let's expect that the main session is already authenticated and its password
  1666. // is not written after, so no locking is necessary
  1667. // (no longer true, once the main session can be reconnected)
  1668. UnicodeString APassword;
  1669. if (FTunnelOpening)
  1670. {
  1671. APassword = GetPasswordSource()->GetRememberedTunnelPassword();
  1672. }
  1673. else
  1674. {
  1675. APassword = GetPasswordSource()->GetRememberedPassword();
  1676. }
  1677. FRememberedPasswordUsed = true;
  1678. Results->Strings[0] = APassword;
  1679. if (!Results->Strings[0].IsEmpty())
  1680. {
  1681. LogEvent(L"Using remembered password.");
  1682. AResult = true;
  1683. }
  1684. PasswordTried = true;
  1685. }
  1686. }
  1687. if (!AResult)
  1688. {
  1689. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1690. {
  1691. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1692. }
  1693. if (OnPromptUser != NULL)
  1694. {
  1695. TCallbackGuard Guard(this);
  1696. try
  1697. {
  1698. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1699. Guard.Verify();
  1700. }
  1701. catch (Exception & E)
  1702. {
  1703. if (!Guard.Verify(&E))
  1704. {
  1705. throw;
  1706. }
  1707. }
  1708. }
  1709. if (AResult && PasswordOrPassphrasePrompt &&
  1710. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1711. {
  1712. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1713. if (FTunnelOpening)
  1714. {
  1715. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1716. }
  1717. else
  1718. {
  1719. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1720. GetPasswordSource()->FRememberedPasswordKind = Kind;
  1721. }
  1722. }
  1723. }
  1724. return AResult;
  1725. }
  1726. //---------------------------------------------------------------------------
  1727. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1728. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1729. TQueryType QueryType)
  1730. {
  1731. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1732. unsigned int Answer = AbortAnswer(Answers);
  1733. if (FOnQueryUser)
  1734. {
  1735. TCallbackGuard Guard(this);
  1736. try
  1737. {
  1738. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1739. Guard.Verify();
  1740. }
  1741. catch (Exception & E)
  1742. {
  1743. if (!Guard.Verify(&E))
  1744. {
  1745. throw;
  1746. }
  1747. }
  1748. }
  1749. UnicodeString Name;
  1750. if (Answer == qaNeverAskAgain)
  1751. {
  1752. Name = L"NeverAskAgain";
  1753. }
  1754. else
  1755. {
  1756. UnicodeString Caption;
  1757. AnswerNameAndCaption(Answer, Name, Caption);
  1758. }
  1759. LogEvent(FORMAT(L"Answer: %s", (Name)));
  1760. return Answer;
  1761. }
  1762. //---------------------------------------------------------------------------
  1763. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1764. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1765. TQueryType QueryType)
  1766. {
  1767. unsigned int Result;
  1768. UnicodeString ExMessage;
  1769. if (DebugAlwaysTrue(ExceptionMessageFormatted(E, ExMessage) || !Query.IsEmpty()))
  1770. {
  1771. TStrings * MoreMessages = new TStringList();
  1772. try
  1773. {
  1774. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1775. {
  1776. MoreMessages->Add(UnformatMessage(ExMessage));
  1777. }
  1778. ExtException * EE = dynamic_cast<ExtException*>(E);
  1779. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1780. {
  1781. MoreMessages->AddStrings(EE->MoreMessages);
  1782. }
  1783. // We know MoreMessages not to be NULL here,
  1784. // AppendExceptionStackTraceAndForget should never return true
  1785. // (indicating it had to create the string list)
  1786. DebugAlwaysFalse(AppendExceptionStackTraceAndForget(MoreMessages));
  1787. TQueryParams HelpKeywordOverrideParams;
  1788. if (Params != NULL)
  1789. {
  1790. HelpKeywordOverrideParams.Assign(*Params);
  1791. }
  1792. HelpKeywordOverrideParams.HelpKeyword =
  1793. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1794. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1795. MoreMessages->Count ? MoreMessages : NULL,
  1796. Answers, &HelpKeywordOverrideParams, QueryType);
  1797. }
  1798. __finally
  1799. {
  1800. delete MoreMessages;
  1801. }
  1802. }
  1803. return Result;
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1807. {
  1808. if (OnDisplayBanner != NULL)
  1809. {
  1810. unsigned int OrigParams, Params;
  1811. if (Configuration->ForceBanners ||
  1812. Configuration->ShowBanner(SessionData->SessionKey, Banner, Params))
  1813. {
  1814. bool NeverShowAgain = false;
  1815. int Options =
  1816. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1817. OrigParams = Params;
  1818. TCallbackGuard Guard(this);
  1819. try
  1820. {
  1821. OnDisplayBanner(this, SessionData->SessionName, Banner, NeverShowAgain, Options, Params);
  1822. Guard.Verify();
  1823. }
  1824. catch (Exception & E)
  1825. {
  1826. if (!Guard.Verify(&E))
  1827. {
  1828. throw;
  1829. }
  1830. }
  1831. if (!Configuration->ForceBanners && NeverShowAgain)
  1832. {
  1833. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1834. }
  1835. if (OrigParams != Params)
  1836. {
  1837. Configuration->SetBannerParams(SessionData->SessionKey, Params);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. //---------------------------------------------------------------------------
  1843. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1844. {
  1845. Log->AddException(E);
  1846. if (OnShowExtendedException != NULL)
  1847. {
  1848. TCallbackGuard Guard(this);
  1849. try
  1850. {
  1851. // the event handler may destroy 'this' ...
  1852. OnShowExtendedException(this, E, NULL);
  1853. // .. hence guard is dismissed from destructor, to make following call no-op
  1854. Guard.Verify();
  1855. }
  1856. catch (Exception & E)
  1857. {
  1858. if (!Guard.Verify(&E))
  1859. {
  1860. throw;
  1861. }
  1862. }
  1863. }
  1864. }
  1865. //---------------------------------------------------------------------------
  1866. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1867. {
  1868. Log->AddException(E);
  1869. if (OnShowExtendedException != NULL)
  1870. {
  1871. OnShowExtendedException(this, E, NULL);
  1872. }
  1873. }
  1874. //---------------------------------------------------------------------------
  1875. void __fastcall TTerminal::DoInformation(
  1876. const UnicodeString & Str, bool Status, int Phase, const UnicodeString & Additional)
  1877. {
  1878. if (OnInformation)
  1879. {
  1880. TCallbackGuard Guard(this);
  1881. try
  1882. {
  1883. OnInformation(this, Str, Status, Phase, Additional);
  1884. Guard.Verify();
  1885. }
  1886. catch (Exception & E)
  1887. {
  1888. if (!Guard.Verify(&E))
  1889. {
  1890. throw;
  1891. }
  1892. }
  1893. }
  1894. }
  1895. //---------------------------------------------------------------------------
  1896. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1897. {
  1898. DoInformation(Str, Status);
  1899. }
  1900. //---------------------------------------------------------------------------
  1901. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1902. {
  1903. if ((Configuration->ActualLogProtocol >= 1) &&
  1904. ProgressData.IsTransfer())
  1905. {
  1906. DWORD Now = GetTickCount();
  1907. if (Now - FLastProgressLogged >= 1000)
  1908. {
  1909. LogEvent(L"Transfer progress: " + ProgressData.GetLogStr(false));
  1910. FLastProgressLogged = Now;
  1911. }
  1912. }
  1913. if (ProgressData.TransferredSize > 0)
  1914. {
  1915. FFileTransferAny = true;
  1916. }
  1917. if (OnProgress != NULL)
  1918. {
  1919. TCallbackGuard Guard(this);
  1920. try
  1921. {
  1922. OnProgress(ProgressData);
  1923. Guard.Verify();
  1924. }
  1925. catch (Exception & E)
  1926. {
  1927. if (!Guard.Verify(&E))
  1928. {
  1929. throw;
  1930. }
  1931. }
  1932. }
  1933. }
  1934. //---------------------------------------------------------------------------
  1935. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1936. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1937. {
  1938. if (OnFinished != NULL)
  1939. {
  1940. TCallbackGuard Guard(this);
  1941. try
  1942. {
  1943. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1944. Guard.Verify();
  1945. }
  1946. catch (Exception & E)
  1947. {
  1948. if (!Guard.Verify(&E))
  1949. {
  1950. throw;
  1951. }
  1952. }
  1953. }
  1954. }
  1955. //---------------------------------------------------------------------------
  1956. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1957. {
  1958. for (int Index = 0; Index < fcCount; Index++)
  1959. {
  1960. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1961. }
  1962. }
  1963. //---------------------------------------------------------------------------
  1964. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1965. {
  1966. if (DebugAlwaysTrue(FFileSystem != NULL))
  1967. {
  1968. switch (Capability)
  1969. {
  1970. case fcBackgroundTransfers:
  1971. return !IsEncryptingFiles();
  1972. default:
  1973. return FFileSystem->IsCapable(Capability);
  1974. }
  1975. }
  1976. else
  1977. {
  1978. return false;
  1979. }
  1980. }
  1981. //---------------------------------------------------------------------------
  1982. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1983. {
  1984. return FFileSystem->AbsolutePath(Path, Local);
  1985. }
  1986. //---------------------------------------------------------------------------
  1987. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1988. {
  1989. bool ChangesDirectory = false;
  1990. bool ModifiesFiles = false;
  1991. switch ((TFSCommand)Cmd) {
  1992. case fsChangeDirectory:
  1993. case fsHomeDirectory:
  1994. ChangesDirectory = true;
  1995. break;
  1996. case fsCopyToRemote:
  1997. case fsDeleteFile:
  1998. case fsRenameFile:
  1999. case fsMoveFile:
  2000. case fsCopyFile:
  2001. case fsCreateDirectory:
  2002. case fsChangeMode:
  2003. case fsChangeGroup:
  2004. case fsChangeOwner:
  2005. case fsChangeProperties:
  2006. case fsLock:
  2007. ModifiesFiles = true;
  2008. break;
  2009. case fsAnyCommand:
  2010. ChangesDirectory = true;
  2011. ModifiesFiles = true;
  2012. break;
  2013. }
  2014. if (ChangesDirectory)
  2015. {
  2016. if (!InTransaction())
  2017. {
  2018. ReadCurrentDirectory();
  2019. if (AutoReadDirectory)
  2020. {
  2021. ReadDirectory(false);
  2022. }
  2023. }
  2024. else
  2025. {
  2026. FReadCurrentDirectoryPending = true;
  2027. if (AutoReadDirectory)
  2028. {
  2029. FReadDirectoryPending = true;
  2030. }
  2031. }
  2032. }
  2033. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  2034. {
  2035. if (!InTransaction())
  2036. {
  2037. ReadDirectory(true);
  2038. }
  2039. else
  2040. {
  2041. FReadDirectoryPending = true;
  2042. }
  2043. }
  2044. }
  2045. //---------------------------------------------------------------------------
  2046. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  2047. {
  2048. TerminalError(NULL, Msg);
  2049. }
  2050. //---------------------------------------------------------------------------
  2051. void __fastcall TTerminal::TerminalError(
  2052. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2053. {
  2054. throw ETerminal(E, Msg, HelpKeyword);
  2055. }
  2056. //---------------------------------------------------------------------------
  2057. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  2058. {
  2059. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  2060. DebugAssert(Fatal != NULL);
  2061. bool Result;
  2062. if ((Fatal != NULL) && Fatal->ReopenQueried)
  2063. {
  2064. Result = false;
  2065. }
  2066. else
  2067. {
  2068. LogEvent(L"Connection was lost, asking what to do.");
  2069. TQueryParams Params(qpAllowContinueOnError);
  2070. Params.Timeout = Configuration->SessionReopenAuto;
  2071. Params.TimeoutAnswer = qaRetry;
  2072. Params.TimeoutResponse = Params.TimeoutAnswer;
  2073. TQueryButtonAlias Aliases[1];
  2074. Aliases[0].Button = qaRetry;
  2075. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  2076. Params.Aliases = Aliases;
  2077. Params.AliasesCount = LENOF(Aliases);
  2078. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  2079. if (Fatal != NULL)
  2080. {
  2081. Fatal->ReopenQueried = true;
  2082. }
  2083. }
  2084. return Result;
  2085. }
  2086. //---------------------------------------------------------------------------
  2087. bool __fastcall TTerminal::ContinueReopen(TDateTime Start)
  2088. {
  2089. return
  2090. (Configuration->SessionReopenTimeout == 0) ||
  2091. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout);
  2092. }
  2093. //---------------------------------------------------------------------------
  2094. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  2095. TFileOperationProgressType * OperationProgress)
  2096. {
  2097. TSuspendFileOperationProgress Suspend(OperationProgress);
  2098. bool Result = DoQueryReopen(E);
  2099. if (Result)
  2100. {
  2101. TDateTime Start = Now();
  2102. do
  2103. {
  2104. try
  2105. {
  2106. Reopen(Params);
  2107. }
  2108. catch(Exception & E)
  2109. {
  2110. if (!Active)
  2111. {
  2112. Result =
  2113. ContinueReopen(Start) &&
  2114. DoQueryReopen(&E);
  2115. }
  2116. else
  2117. {
  2118. throw;
  2119. }
  2120. }
  2121. }
  2122. while (!Active && Result);
  2123. }
  2124. return Result;
  2125. }
  2126. //---------------------------------------------------------------------------
  2127. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  2128. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  2129. unsigned int Flags, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  2130. {
  2131. bool Result = false;
  2132. Log->AddException(&E);
  2133. unsigned int Answer;
  2134. bool AllowSkip = FLAGSET(Flags, folAllowSkip);
  2135. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  2136. if (SkipToAllPossible && OperationProgress->SkipToAll)
  2137. {
  2138. Answer = qaSkip;
  2139. }
  2140. else
  2141. {
  2142. int Answers = qaRetry | qaAbort |
  2143. FLAGMASK(AllowSkip, qaSkip) |
  2144. FLAGMASK(SkipToAllPossible, qaAll) |
  2145. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  2146. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  2147. Params.HelpKeyword = HelpKeyword;
  2148. TQueryButtonAlias Aliases[2];
  2149. int AliasCount = 0;
  2150. if (FLAGSET(Answers, qaAll))
  2151. {
  2152. Aliases[AliasCount].Button = qaAll;
  2153. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  2154. AliasCount++;
  2155. }
  2156. if (FLAGSET(Answers, qaYes))
  2157. {
  2158. Aliases[AliasCount].Button = qaYes;
  2159. Aliases[AliasCount].Alias = SpecialRetry;
  2160. AliasCount++;
  2161. }
  2162. if (AliasCount > 0)
  2163. {
  2164. Params.Aliases = Aliases;
  2165. Params.AliasesCount = AliasCount;
  2166. }
  2167. {
  2168. TSuspendFileOperationProgress Suspend(OperationProgress);
  2169. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  2170. }
  2171. if (Answer == qaAll)
  2172. {
  2173. DebugAssert(OperationProgress != NULL);
  2174. OperationProgress->SetSkipToAll();
  2175. Answer = qaSkip;
  2176. }
  2177. if (Answer == qaYes)
  2178. {
  2179. Result = true;
  2180. Answer = qaRetry;
  2181. }
  2182. }
  2183. if (Answer != qaRetry)
  2184. {
  2185. if ((Answer == qaAbort) && (OperationProgress != NULL))
  2186. {
  2187. OperationProgress->SetCancel(csCancel);
  2188. }
  2189. if (AllowSkip)
  2190. {
  2191. throw ESkipFile(&E, Message);
  2192. }
  2193. else
  2194. {
  2195. // this can happen only during file transfer with SCP
  2196. throw ExtException(&E, Message);
  2197. }
  2198. }
  2199. return Result;
  2200. }
  2201. //---------------------------------------------------------------------------
  2202. void __fastcall TTerminal::FileOperationLoopEnd(Exception & E,
  2203. TFileOperationProgressType * OperationProgress, const UnicodeString & Message,
  2204. unsigned int Flags, const UnicodeString & SpecialRetry, const UnicodeString & HelpKeyword)
  2205. {
  2206. if ((dynamic_cast<EAbort *>(&E) != NULL) ||
  2207. (dynamic_cast<ESkipFile *>(&E) != NULL) ||
  2208. (dynamic_cast<ESkipFile *>(&E) != NULL))
  2209. {
  2210. RethrowException(&E);
  2211. }
  2212. else if (dynamic_cast<EFatal *>(&E) != NULL)
  2213. {
  2214. if (FLAGCLEAR(Flags, folRetryOnFatal))
  2215. {
  2216. RethrowException(&E);
  2217. }
  2218. else
  2219. {
  2220. DebugAssert(SpecialRetry.IsEmpty());
  2221. std::unique_ptr<Exception> E2(new EFatal(&E, Message, HelpKeyword));
  2222. if (!DoQueryReopen(E2.get()))
  2223. {
  2224. RethrowException(E2.get());
  2225. }
  2226. }
  2227. }
  2228. else
  2229. {
  2230. FileOperationLoopQuery(E, OperationProgress, Message, Flags, SpecialRetry, HelpKeyword);
  2231. }
  2232. }
  2233. //---------------------------------------------------------------------------
  2234. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  2235. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  2236. const UnicodeString Message, void * Param1, void * Param2)
  2237. {
  2238. DebugAssert(CallBackFunc);
  2239. int Result;
  2240. FILE_OPERATION_LOOP_BEGIN
  2241. {
  2242. Result = CallBackFunc(Param1, Param2);
  2243. }
  2244. FILE_OPERATION_LOOP_END_EX(Message, Flags);
  2245. return Result;
  2246. }
  2247. //---------------------------------------------------------------------------
  2248. void __fastcall TTerminal::ClearCaches()
  2249. {
  2250. FDirectoryCache->Clear();
  2251. if (FDirectoryChangesCache != NULL)
  2252. {
  2253. FDirectoryChangesCache->Clear();
  2254. }
  2255. if (FCommandSession != NULL)
  2256. {
  2257. FCommandSession->ClearCaches();
  2258. }
  2259. FFileSystem->ClearCaches();
  2260. FEncryptedFileNames.clear();
  2261. FFoldersScannedForEncryptedFiles.clear();
  2262. }
  2263. //---------------------------------------------------------------------------
  2264. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  2265. bool SubDirs)
  2266. {
  2267. FDirectoryCache->ClearFileList(Path, SubDirs);
  2268. }
  2269. //---------------------------------------------------------------------------
  2270. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  2271. {
  2272. FDirectoryCache->AddFileList(FileList);
  2273. }
  2274. //---------------------------------------------------------------------------
  2275. TRemoteFileList * __fastcall TTerminal::DirectoryFileList(const UnicodeString Path, TDateTime Timestamp, bool CanLoad)
  2276. {
  2277. TRemoteFileList * Result = NULL;
  2278. if (UnixSamePath(FFiles->Directory, Path))
  2279. {
  2280. if (Timestamp < FFiles->Timestamp)
  2281. {
  2282. Result = new TRemoteFileList();
  2283. FFiles->DuplicateTo(Result);
  2284. }
  2285. }
  2286. else
  2287. {
  2288. if (FDirectoryCache->HasNewerFileList(Path, Timestamp))
  2289. {
  2290. Result = new TRemoteFileList();
  2291. DebugAlwaysTrue(FDirectoryCache->GetFileList(Path, Result));
  2292. }
  2293. // do not attempt to load file list if there is cached version,
  2294. // only absence of cached version indicates that we consider
  2295. // the directory content obsolete
  2296. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  2297. {
  2298. Result = new TRemoteFileList();
  2299. Result->Directory = Path;
  2300. try
  2301. {
  2302. ReadDirectory(Result);
  2303. }
  2304. catch(...)
  2305. {
  2306. SAFE_DESTROY(Result);
  2307. throw;
  2308. }
  2309. }
  2310. }
  2311. return Result;
  2312. }
  2313. //---------------------------------------------------------------------------
  2314. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  2315. {
  2316. DebugAssert(FFileSystem);
  2317. if (value != FFileSystem->CurrentDirectory)
  2318. {
  2319. ChangeDirectory(value);
  2320. }
  2321. }
  2322. //---------------------------------------------------------------------------
  2323. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  2324. {
  2325. if (FFileSystem != NULL)
  2326. {
  2327. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  2328. // to FCurrentDirectory, splitting the assignment to two statements
  2329. // to locate the crash more closely
  2330. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  2331. FCurrentDirectory = CurrentDirectory;
  2332. if (FCurrentDirectory.IsEmpty())
  2333. {
  2334. ReadCurrentDirectory();
  2335. }
  2336. }
  2337. return FCurrentDirectory;
  2338. }
  2339. //---------------------------------------------------------------------------
  2340. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  2341. {
  2342. if (FFileSystem)
  2343. {
  2344. FCurrentDirectory = FFileSystem->CurrentDirectory;
  2345. }
  2346. return FCurrentDirectory;
  2347. }
  2348. //---------------------------------------------------------------------------
  2349. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  2350. {
  2351. DebugAssert(FFileSystem);
  2352. LookupUsersGroups();
  2353. return &FGroups;
  2354. }
  2355. //---------------------------------------------------------------------------
  2356. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  2357. {
  2358. DebugAssert(FFileSystem);
  2359. LookupUsersGroups();
  2360. return &FUsers;
  2361. }
  2362. //---------------------------------------------------------------------------
  2363. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  2364. {
  2365. DebugAssert(FFileSystem);
  2366. LookupUsersGroups();
  2367. return &FMembership;
  2368. }
  2369. //---------------------------------------------------------------------------
  2370. UnicodeString __fastcall TTerminal::GetUserName() const
  2371. {
  2372. // in future might also be implemented to detect username similar to GetUserGroups
  2373. DebugAssert(FFileSystem != NULL);
  2374. UnicodeString Result = FFileSystem->GetUserName();
  2375. // Is empty also when stored username was used
  2376. if (Result.IsEmpty())
  2377. {
  2378. Result = SessionData->UserNameExpanded;
  2379. }
  2380. return Result;
  2381. }
  2382. //---------------------------------------------------------------------------
  2383. bool __fastcall TTerminal::GetAreCachesEmpty() const
  2384. {
  2385. return FDirectoryCache->IsEmpty &&
  2386. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  2387. }
  2388. //---------------------------------------------------------------------------
  2389. void __fastcall TTerminal::DoInitializeLog()
  2390. {
  2391. if (FOnInitializeLog)
  2392. {
  2393. TCallbackGuard Guard(this);
  2394. try
  2395. {
  2396. FOnInitializeLog(this);
  2397. Guard.Verify();
  2398. }
  2399. catch (Exception & E)
  2400. {
  2401. if (!Guard.Verify(&E))
  2402. {
  2403. throw;
  2404. }
  2405. }
  2406. }
  2407. }
  2408. //---------------------------------------------------------------------------
  2409. void __fastcall TTerminal::DoChangeDirectory()
  2410. {
  2411. if (FOnChangeDirectory)
  2412. {
  2413. TCallbackGuard Guard(this);
  2414. try
  2415. {
  2416. FOnChangeDirectory(this);
  2417. Guard.Verify();
  2418. }
  2419. catch (Exception & E)
  2420. {
  2421. if (!Guard.Verify(&E))
  2422. {
  2423. throw;
  2424. }
  2425. }
  2426. }
  2427. }
  2428. //---------------------------------------------------------------------------
  2429. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  2430. {
  2431. if (FOnReadDirectory)
  2432. {
  2433. TCallbackGuard Guard(this);
  2434. try
  2435. {
  2436. FOnReadDirectory(this, ReloadOnly);
  2437. Guard.Verify();
  2438. }
  2439. catch (Exception & E)
  2440. {
  2441. if (!Guard.Verify(&E))
  2442. {
  2443. throw;
  2444. }
  2445. }
  2446. }
  2447. }
  2448. //---------------------------------------------------------------------------
  2449. void __fastcall TTerminal::DoStartReadDirectory()
  2450. {
  2451. if (FOnStartReadDirectory)
  2452. {
  2453. TCallbackGuard Guard(this);
  2454. try
  2455. {
  2456. FOnStartReadDirectory(this);
  2457. Guard.Verify();
  2458. }
  2459. catch (Exception & E)
  2460. {
  2461. if (!Guard.Verify(&E))
  2462. {
  2463. throw;
  2464. }
  2465. }
  2466. }
  2467. }
  2468. //---------------------------------------------------------------------------
  2469. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  2470. {
  2471. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  2472. {
  2473. TCallbackGuard Guard(this);
  2474. try
  2475. {
  2476. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  2477. Guard.Verify();
  2478. }
  2479. catch (Exception & E)
  2480. {
  2481. if (!Guard.Verify(&E))
  2482. {
  2483. throw;
  2484. }
  2485. }
  2486. }
  2487. if (FOnFindingFile != NULL)
  2488. {
  2489. TCallbackGuard Guard(this);
  2490. try
  2491. {
  2492. FOnFindingFile(this, L"", Cancel);
  2493. Guard.Verify();
  2494. }
  2495. catch (Exception & E)
  2496. {
  2497. if (!Guard.Verify(&E))
  2498. {
  2499. throw;
  2500. }
  2501. }
  2502. }
  2503. }
  2504. //---------------------------------------------------------------------------
  2505. bool __fastcall TTerminal::InTransaction()
  2506. {
  2507. return (FInTransaction > 0) && !FSuspendTransaction;
  2508. }
  2509. //---------------------------------------------------------------------------
  2510. void __fastcall TTerminal::BeginTransaction()
  2511. {
  2512. if (FInTransaction == 0)
  2513. {
  2514. FReadCurrentDirectoryPending = false;
  2515. FReadDirectoryPending = false;
  2516. }
  2517. FInTransaction++;
  2518. if (FCommandSession != NULL)
  2519. {
  2520. FCommandSession->BeginTransaction();
  2521. }
  2522. }
  2523. //---------------------------------------------------------------------------
  2524. void __fastcall TTerminal::EndTransaction()
  2525. {
  2526. DoEndTransaction(false);
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  2530. {
  2531. if (FInTransaction == 0)
  2532. TerminalError(L"Can't end transaction, not in transaction");
  2533. DebugAssert(FInTransaction > 0);
  2534. FInTransaction--;
  2535. // it connection was closed due to fatal error during transaction, do nothing
  2536. if (Active)
  2537. {
  2538. if (FInTransaction == 0)
  2539. {
  2540. try
  2541. {
  2542. if (FReadCurrentDirectoryPending)
  2543. {
  2544. ReadCurrentDirectory();
  2545. }
  2546. if (FReadDirectoryPending)
  2547. {
  2548. if (Inform)
  2549. {
  2550. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true, -1, CurrentDirectory);
  2551. }
  2552. ReadDirectory(!FReadCurrentDirectoryPending);
  2553. }
  2554. }
  2555. __finally
  2556. {
  2557. FReadCurrentDirectoryPending = false;
  2558. FReadDirectoryPending = false;
  2559. }
  2560. }
  2561. }
  2562. if (FCommandSession != NULL)
  2563. {
  2564. FCommandSession->EndTransaction();
  2565. }
  2566. }
  2567. //---------------------------------------------------------------------------
  2568. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  2569. {
  2570. if (value)
  2571. {
  2572. FExceptionOnFail++;
  2573. }
  2574. else
  2575. {
  2576. if (FExceptionOnFail == 0)
  2577. throw Exception(L"ExceptionOnFail is already zero.");
  2578. FExceptionOnFail--;
  2579. }
  2580. if (FCommandSession != NULL)
  2581. {
  2582. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2583. }
  2584. }
  2585. //---------------------------------------------------------------------------
  2586. bool __fastcall TTerminal::GetExceptionOnFail() const
  2587. {
  2588. return (bool)(FExceptionOnFail > 0);
  2589. }
  2590. //---------------------------------------------------------------------------
  2591. void __fastcall TTerminal::FatalAbort()
  2592. {
  2593. FatalError(NULL, "");
  2594. }
  2595. //---------------------------------------------------------------------------
  2596. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2597. {
  2598. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  2599. if (Active || SecureShellActive)
  2600. {
  2601. // We log this instead of exception handler, because Close() would
  2602. // probably cause exception handler to loose pointer to TShellLog()
  2603. LogEvent(L"Attempt to close connection due to fatal exception:");
  2604. Log->Add(llException, Msg);
  2605. Log->AddException(E);
  2606. if (Active)
  2607. {
  2608. Close();
  2609. }
  2610. // this may happen if failure of authentication of SSH, owned by terminal yet
  2611. // (because the protocol was not decided yet), is detected by us (not by putty).
  2612. // e.g. not verified host key
  2613. if (SecureShellActive)
  2614. {
  2615. FSecureShell->Close();
  2616. }
  2617. }
  2618. if (FCallbackGuard != NULL)
  2619. {
  2620. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  2621. }
  2622. else
  2623. {
  2624. throw ESshFatal(E, Msg, HelpKeyword);
  2625. }
  2626. }
  2627. //---------------------------------------------------------------------------
  2628. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  2629. {
  2630. CommandError(E, Msg, 0);
  2631. }
  2632. //---------------------------------------------------------------------------
  2633. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  2634. unsigned int Answers, const UnicodeString HelpKeyword)
  2635. {
  2636. // may not be, particularly when TTerminal::Reopen is being called
  2637. // from within OnShowExtendedException handler
  2638. DebugAssert(FCallbackGuard == NULL);
  2639. unsigned int Result = 0;
  2640. if (E && E->InheritsFrom(__classid(EFatal)))
  2641. {
  2642. FatalError(E, Msg, HelpKeyword);
  2643. }
  2644. else if (E && E->InheritsFrom(__classid(EAbort)))
  2645. {
  2646. // resent EAbort exception
  2647. Abort();
  2648. }
  2649. else if (ExceptionOnFail)
  2650. {
  2651. throw ECommand(E, Msg, HelpKeyword);
  2652. }
  2653. else if (!Answers)
  2654. {
  2655. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  2656. try
  2657. {
  2658. HandleExtendedException(ECmd);
  2659. }
  2660. __finally
  2661. {
  2662. delete ECmd;
  2663. }
  2664. }
  2665. else
  2666. {
  2667. // small hack to enable "skip to all" for TRetryOperationLoop
  2668. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  2669. if (CanSkip && OperationProgress->SkipToAll)
  2670. {
  2671. Result = qaSkip;
  2672. }
  2673. else
  2674. {
  2675. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  2676. TQueryButtonAlias Aliases[1];
  2677. if (CanSkip)
  2678. {
  2679. Aliases[0].Button = qaAll;
  2680. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  2681. Params.Aliases = Aliases;
  2682. Params.AliasesCount = LENOF(Aliases);
  2683. Answers |= qaAll;
  2684. }
  2685. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  2686. if (Result == qaAll)
  2687. {
  2688. DebugAssert(OperationProgress != NULL);
  2689. OperationProgress->SetSkipToAll();
  2690. Result = qaSkip;
  2691. }
  2692. }
  2693. }
  2694. return Result;
  2695. }
  2696. //---------------------------------------------------------------------------
  2697. bool __fastcall TTerminal::HandleException(Exception * E)
  2698. {
  2699. if (ExceptionOnFail)
  2700. {
  2701. return false;
  2702. }
  2703. else
  2704. {
  2705. Log->AddException(E);
  2706. return true;
  2707. }
  2708. }
  2709. //---------------------------------------------------------------------------
  2710. void __fastcall TTerminal::CloseOnCompletion(
  2711. TOnceDoneOperation Operation, const UnicodeString & Message,
  2712. const UnicodeString & TargetLocalPath, const UnicodeString & DestLocalFileName)
  2713. {
  2714. if (FOperationProgressPersistence != NULL)
  2715. {
  2716. DebugAssert(Message.IsEmpty());
  2717. FOperationProgressOnceDoneOperation = Operation;
  2718. }
  2719. else
  2720. {
  2721. Configuration->Usage->Inc(L"ClosesOnCompletion");
  2722. LogEvent(L"Closing session after completed operation (as requested by user)");
  2723. Close();
  2724. throw ESshTerminate(NULL,
  2725. MainInstructions(Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message),
  2726. Operation, TargetLocalPath, DestLocalFileName);
  2727. }
  2728. }
  2729. //---------------------------------------------------------------------------
  2730. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  2731. const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  2732. {
  2733. TBatchOverwrite Result;
  2734. if (Special &&
  2735. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)))
  2736. {
  2737. Result = boResume;
  2738. }
  2739. else if (FLAGSET(Params, cpAppend))
  2740. {
  2741. Result = boAppend;
  2742. }
  2743. else if (CopyParam->NewerOnly &&
  2744. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  2745. (OperationProgress->Side != osLocal)))
  2746. {
  2747. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  2748. Result = boOlder;
  2749. }
  2750. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  2751. {
  2752. // no way to change batch overwrite mode when overwrite confirmations are off
  2753. DebugAssert(OperationProgress->BatchOverwrite == boNo);
  2754. Result = boAll;
  2755. }
  2756. else
  2757. {
  2758. Result = OperationProgress->BatchOverwrite;
  2759. if (!Special &&
  2760. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2761. {
  2762. Result = boNo;
  2763. }
  2764. }
  2765. return Result;
  2766. }
  2767. //---------------------------------------------------------------------------
  2768. bool __fastcall TTerminal::CheckRemoteFile(
  2769. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2770. {
  2771. bool Result;
  2772. OperationProgress->LockUserSelections();
  2773. try
  2774. {
  2775. Result = (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2776. }
  2777. __finally
  2778. {
  2779. OperationProgress->UnlockUserSelections();
  2780. }
  2781. return Result;
  2782. }
  2783. //---------------------------------------------------------------------------
  2784. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
  2785. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
  2786. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2787. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2788. UnicodeString Message)
  2789. {
  2790. unsigned int Result;
  2791. TBatchOverwrite BatchOverwrite;
  2792. bool CanAlternateResume =
  2793. (FileParams != NULL) &&
  2794. (FileParams->DestSize < FileParams->SourceSize) &&
  2795. !OperationProgress->AsciiTransfer;
  2796. OperationProgress->LockUserSelections();
  2797. try
  2798. {
  2799. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2800. BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  2801. bool Applicable = true;
  2802. switch (BatchOverwrite)
  2803. {
  2804. case boOlder:
  2805. Applicable = (FileParams != NULL);
  2806. break;
  2807. case boAlternateResume:
  2808. Applicable = CanAlternateResume;
  2809. break;
  2810. case boResume:
  2811. Applicable = CanAlternateResume;
  2812. break;
  2813. }
  2814. if (!Applicable)
  2815. {
  2816. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
  2817. DebugAssert(BatchOverwrite != ABatchOverwrite);
  2818. BatchOverwrite = ABatchOverwrite;
  2819. }
  2820. if (BatchOverwrite != boNo)
  2821. {
  2822. LogEvent(1, FORMAT(L"Batch operation mode [%d] is effective", (int(BatchOverwrite))));
  2823. }
  2824. else
  2825. {
  2826. // particularly with parallel transfers, the overal operation can be already cancelled by other parallel operation
  2827. if (OperationProgress->Cancel > csContinue)
  2828. {
  2829. LogEvent(1, L"Transfer cancelled in parallel operation");
  2830. Result = qaCancel;
  2831. }
  2832. else
  2833. {
  2834. if (Message.IsEmpty())
  2835. {
  2836. // Side refers to destination side here
  2837. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2838. REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
  2839. }
  2840. if (FileParams != NULL)
  2841. {
  2842. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2843. FormatSize(FileParams->SourceSize),
  2844. DefaultStr(UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision), LoadStr(TIME_UNKNOWN)),
  2845. FormatSize(FileParams->DestSize),
  2846. DefaultStr(UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision), LoadStr(TIME_UNKNOWN))));
  2847. }
  2848. if (DebugAlwaysTrue(QueryParams->HelpKeyword.IsEmpty()))
  2849. {
  2850. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2851. }
  2852. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2853. switch (Result)
  2854. {
  2855. case qaNeverAskAgain:
  2856. Configuration->ConfirmOverwriting = false;
  2857. Result = qaYes;
  2858. break;
  2859. case qaYesToAll:
  2860. BatchOverwrite = boAll;
  2861. break;
  2862. case qaAll:
  2863. BatchOverwrite = boOlder;
  2864. break;
  2865. case qaNoToAll:
  2866. BatchOverwrite = boNone;
  2867. break;
  2868. }
  2869. // we user has not selected another batch overwrite mode,
  2870. // keep the current one. note that we may get here even
  2871. // when batch overwrite was selected already, but it could not be applied
  2872. // to current transfer (see condition above)
  2873. if (BatchOverwrite != boNo)
  2874. {
  2875. OperationProgress->SetBatchOverwrite(BatchOverwrite);
  2876. }
  2877. }
  2878. }
  2879. }
  2880. __finally
  2881. {
  2882. OperationProgress->UnlockUserSelections();
  2883. }
  2884. if (BatchOverwrite != boNo)
  2885. {
  2886. switch (BatchOverwrite)
  2887. {
  2888. case boAll:
  2889. LogEvent(1, L"Overwritting all files");
  2890. Result = qaYes;
  2891. break;
  2892. case boNone:
  2893. LogEvent(1, L"Not overwritting any file");
  2894. Result = qaNo;
  2895. break;
  2896. case boOlder:
  2897. if (FileParams == NULL)
  2898. {
  2899. LogEvent(1, L"Not overwritting due to lack of file information");
  2900. Result = qaNo;
  2901. }
  2902. else
  2903. {
  2904. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2905. TDateTime ReducedSourceTimestamp =
  2906. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2907. TDateTime ReducedDestTimestamp =
  2908. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2909. Result =
  2910. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2911. qaYes : qaNo;
  2912. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2913. (StandardTimestamp(ReducedSourceTimestamp),
  2914. StandardTimestamp(ReducedDestTimestamp),
  2915. ((Result == qaYes) ? L"" : L" not"))));
  2916. }
  2917. break;
  2918. case boAlternateResume:
  2919. DebugAssert(CanAlternateResume);
  2920. LogEvent(1, L"Alternate resume mode");
  2921. Result = qaSkip; // ugh
  2922. break;
  2923. case boAppend:
  2924. LogEvent(1, L"Appending file");
  2925. Result = qaRetry;
  2926. break;
  2927. case boResume:
  2928. LogEvent(1, L"Resuming file transfer");
  2929. Result = qaRetry;
  2930. break;
  2931. }
  2932. }
  2933. return Result;
  2934. }
  2935. //---------------------------------------------------------------------------
  2936. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2937. const UnicodeString FileName, bool ClearDirectoryChange)
  2938. {
  2939. UnicodeString ParentDirectory;
  2940. UnicodeString Directory;
  2941. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2942. {
  2943. if ((File != NULL) && (File->Directory != NULL))
  2944. {
  2945. if (File->IsDirectory)
  2946. {
  2947. Directory = File->Directory->FullDirectory + File->FileName;
  2948. }
  2949. ParentDirectory = File->Directory->Directory;
  2950. }
  2951. else if (!FileName.IsEmpty())
  2952. {
  2953. ParentDirectory = UnixExtractFilePath(FileName);
  2954. if (ParentDirectory.IsEmpty())
  2955. {
  2956. ParentDirectory = CurrentDirectory;
  2957. }
  2958. // this case for scripting
  2959. if ((File != NULL) && File->IsDirectory)
  2960. {
  2961. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2962. UnixExtractFileName(File->FileName);
  2963. }
  2964. }
  2965. }
  2966. if (SessionData->CacheDirectories)
  2967. {
  2968. if (!Directory.IsEmpty())
  2969. {
  2970. DirectoryModified(Directory, true);
  2971. }
  2972. if (!ParentDirectory.IsEmpty())
  2973. {
  2974. DirectoryModified(ParentDirectory, false);
  2975. }
  2976. }
  2977. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2978. {
  2979. if (!Directory.IsEmpty())
  2980. {
  2981. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2982. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2983. }
  2984. }
  2985. }
  2986. //---------------------------------------------------------------------------
  2987. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2988. {
  2989. if (Path.IsEmpty())
  2990. {
  2991. ClearCachedFileList(CurrentDirectory, SubDirs);
  2992. }
  2993. else
  2994. {
  2995. ClearCachedFileList(Path, SubDirs);
  2996. }
  2997. }
  2998. //---------------------------------------------------------------------------
  2999. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  3000. {
  3001. AddCachedFileList(FileList);
  3002. }
  3003. //---------------------------------------------------------------------------
  3004. void __fastcall TTerminal::ReloadDirectory()
  3005. {
  3006. if (SessionData->CacheDirectories)
  3007. {
  3008. DirectoryModified(CurrentDirectory, false);
  3009. }
  3010. if (SessionData->CacheDirectoryChanges)
  3011. {
  3012. DebugAssert(FDirectoryChangesCache != NULL);
  3013. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  3014. }
  3015. ReadCurrentDirectory();
  3016. FReadCurrentDirectoryPending = false;
  3017. ReadDirectory(true);
  3018. FReadDirectoryPending = false;
  3019. }
  3020. //---------------------------------------------------------------------------
  3021. void __fastcall TTerminal::RefreshDirectory()
  3022. {
  3023. if (!SessionData->CacheDirectories)
  3024. {
  3025. LogEvent(L"Not refreshing directory, caching is off.");
  3026. }
  3027. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  3028. {
  3029. // Second parameter was added to allow (rather force) using the cache.
  3030. // Before, the directory was reloaded always, it seems useless,
  3031. // has it any reason?
  3032. ReadDirectory(true, true);
  3033. FReadDirectoryPending = false;
  3034. }
  3035. }
  3036. //---------------------------------------------------------------------------
  3037. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  3038. {
  3039. // if filename doesn't contain path, we check for existence of file
  3040. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  3041. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3042. {
  3043. TRemoteFile *File = FFiles->FindFile(FileName);
  3044. if (File)
  3045. {
  3046. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  3047. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  3048. }
  3049. }
  3050. }
  3051. //---------------------------------------------------------------------------
  3052. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  3053. {
  3054. if (Log->Logging)
  3055. {
  3056. Log->Add(llMessage, Str);
  3057. }
  3058. }
  3059. //---------------------------------------------------------------------------
  3060. void __fastcall TTerminal::LogEvent(int Level, const UnicodeString & Str)
  3061. {
  3062. if (Log->Logging && (Configuration->ActualLogProtocol >= Level))
  3063. {
  3064. Log->Add(llMessage, Str);
  3065. }
  3066. }
  3067. //---------------------------------------------------------------------------
  3068. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  3069. TFileOperationProgressType * OperationProgress, Exception * E)
  3070. {
  3071. // ESkipFile without "cancel" is file skip,
  3072. // and we do not want to record skipped actions.
  3073. // But ESkipFile with "cancel" is abort and we want to record that.
  3074. // Note that TScpFileSystem modifies the logic of RollbackAction little bit.
  3075. if ((dynamic_cast<ESkipFile *>(E) != NULL) &&
  3076. ((OperationProgress == NULL) ||
  3077. (OperationProgress->Cancel == csContinue)))
  3078. {
  3079. Action.Cancel();
  3080. }
  3081. else
  3082. {
  3083. Action.Rollback(E);
  3084. }
  3085. }
  3086. //---------------------------------------------------------------------------
  3087. void __fastcall TTerminal::DoStartup()
  3088. {
  3089. LogEvent(L"Doing startup conversation with host.");
  3090. BeginTransaction();
  3091. try
  3092. {
  3093. DoInformation(LoadStr(STATUS_STARTUP), true);
  3094. // Make sure that directory would be loaded at last
  3095. FReadCurrentDirectoryPending = true;
  3096. FReadDirectoryPending = AutoReadDirectory;
  3097. FFileSystem->DoStartup();
  3098. LookupUsersGroups();
  3099. if (!SessionData->RemoteDirectory.IsEmpty())
  3100. {
  3101. if (SessionData->UpdateDirectories)
  3102. {
  3103. ExceptionOnFail = true;
  3104. try
  3105. {
  3106. ChangeDirectory(SessionData->RemoteDirectory);
  3107. }
  3108. catch (...)
  3109. {
  3110. if (!Active || SessionData->RequireDirectories)
  3111. {
  3112. throw;
  3113. }
  3114. else
  3115. {
  3116. LogEvent(L"Configured initial remote directory cannot be opened, staying in the home directory.");
  3117. }
  3118. }
  3119. ExceptionOnFail = false;
  3120. }
  3121. else
  3122. {
  3123. ChangeDirectory(SessionData->RemoteDirectory);
  3124. }
  3125. }
  3126. }
  3127. __finally
  3128. {
  3129. DoEndTransaction(true);
  3130. }
  3131. LogEvent(L"Startup conversation with host finished.");
  3132. }
  3133. //---------------------------------------------------------------------------
  3134. void __fastcall TTerminal::ReadCurrentDirectory()
  3135. {
  3136. DebugAssert(FFileSystem);
  3137. try
  3138. {
  3139. // reset flag in case we are called externally (like from console dialog)
  3140. FReadCurrentDirectoryPending = false;
  3141. LogEvent(L"Getting current directory name.");
  3142. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  3143. FFileSystem->ReadCurrentDirectory();
  3144. ReactOnCommand(fsCurrentDirectory);
  3145. if (SessionData->CacheDirectoryChanges)
  3146. {
  3147. DebugAssert(FDirectoryChangesCache != NULL);
  3148. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  3149. {
  3150. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  3151. FLastDirectoryChange, CurrentDirectory);
  3152. }
  3153. // not to breake the cache, if the next directory change would not
  3154. // be initialized by ChangeDirectory(), which sets it
  3155. // (HomeDirectory() particularly)
  3156. FLastDirectoryChange = L"";
  3157. }
  3158. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  3159. }
  3160. catch (Exception &E)
  3161. {
  3162. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  3163. }
  3164. }
  3165. //---------------------------------------------------------------------------
  3166. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  3167. {
  3168. bool LoadedFromCache = false;
  3169. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  3170. {
  3171. if (ReloadOnly && !ForceCache)
  3172. {
  3173. LogEvent(L"Cached directory not reloaded.");
  3174. }
  3175. else
  3176. {
  3177. DoStartReadDirectory();
  3178. try
  3179. {
  3180. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  3181. }
  3182. __finally
  3183. {
  3184. DoReadDirectory(ReloadOnly);
  3185. }
  3186. if (LoadedFromCache)
  3187. {
  3188. LogEvent(L"Directory content loaded from cache.");
  3189. }
  3190. else
  3191. {
  3192. LogEvent(L"Cached Directory content has been removed.");
  3193. }
  3194. }
  3195. }
  3196. if (!LoadedFromCache)
  3197. {
  3198. DoStartReadDirectory();
  3199. FReadingCurrentDirectory = true;
  3200. bool Cancel = false; // dummy
  3201. DoReadDirectoryProgress(0, 0, Cancel);
  3202. try
  3203. {
  3204. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  3205. try
  3206. {
  3207. Files->Directory = CurrentDirectory;
  3208. CustomReadDirectory(Files);
  3209. }
  3210. __finally
  3211. {
  3212. DoReadDirectoryProgress(-1, 0, Cancel);
  3213. FReadingCurrentDirectory = false;
  3214. TRemoteDirectory * OldFiles = FFiles;
  3215. FFiles = Files;
  3216. try
  3217. {
  3218. DoReadDirectory(ReloadOnly);
  3219. }
  3220. __finally
  3221. {
  3222. // delete only after loading new files to dir view,
  3223. // not to destroy the file objects that the view holds
  3224. // (can be issue in multi threaded environment, such as when the
  3225. // terminal is reconnecting in the terminal thread)
  3226. delete OldFiles;
  3227. }
  3228. if (Active)
  3229. {
  3230. if (SessionData->CacheDirectories)
  3231. {
  3232. DirectoryLoaded(FFiles);
  3233. }
  3234. }
  3235. }
  3236. }
  3237. catch (Exception &E)
  3238. {
  3239. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  3240. }
  3241. }
  3242. }
  3243. //---------------------------------------------------------------------------
  3244. UnicodeString __fastcall TTerminal::GetRemoteFileInfo(TRemoteFile * File)
  3245. {
  3246. return
  3247. FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
  3248. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
  3249. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  3250. File->Attr));
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  3254. {
  3255. // optimization
  3256. if (Log->Logging)
  3257. {
  3258. LogEvent(GetRemoteFileInfo(File));
  3259. }
  3260. }
  3261. //---------------------------------------------------------------------------
  3262. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(
  3263. const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
  3264. {
  3265. UnicodeString Result;
  3266. // optimization
  3267. if (Log->Logging)
  3268. {
  3269. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  3270. if (LinkedFile != NULL)
  3271. {
  3272. LinkedFile = LinkedFile->Resolve(); // in case it's symlink to symlink
  3273. Result += FORMAT(L" - Link to: %s", (FormatFileDetailsForLog(LinkedFile->FileName, LinkedFile->Modification, LinkedFile->Size, NULL)));
  3274. }
  3275. }
  3276. return Result;
  3277. }
  3278. //---------------------------------------------------------------------------
  3279. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
  3280. {
  3281. // optimization
  3282. if (Log->Logging)
  3283. {
  3284. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size, LinkedFile))));
  3285. }
  3286. }
  3287. //---------------------------------------------------------------------------
  3288. void __fastcall TTerminal::LogFileDone(
  3289. TFileOperationProgressType * OperationProgress, const UnicodeString & DestFileName,
  3290. TTransferSessionAction & Action)
  3291. {
  3292. if (FDestFileName.IsEmpty())
  3293. {
  3294. FDestFileName = DestFileName;
  3295. }
  3296. else
  3297. {
  3298. FMultipleDestinationFiles = true;
  3299. }
  3300. __int64 Size = OperationProgress->TransferredSize;
  3301. // optimization
  3302. if (Log->Logging)
  3303. {
  3304. LogEvent(FORMAT("Transfer done: '%s' => '%s' [%s]", (OperationProgress->FullFileName, DestFileName, IntToStr(Size))));
  3305. }
  3306. Action.Size(Size);
  3307. }
  3308. //---------------------------------------------------------------------------
  3309. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  3310. {
  3311. DebugAssert(FileList);
  3312. DebugAssert(FFileSystem);
  3313. // To match FTP upload/download, we also limit directory listing.
  3314. // For simplicity, we limit it unconditionally, for all protocols for any kind of errors.
  3315. bool FileTransferAny = false;
  3316. TRobustOperationLoop RobustLoop(this, OperationProgress, &FileTransferAny);
  3317. do
  3318. {
  3319. try
  3320. {
  3321. // Record even an attempt, to avoid listing a directory over and over again, when it is not readable actually
  3322. if (IsEncryptingFiles())
  3323. {
  3324. FFoldersScannedForEncryptedFiles.insert(FileList->Directory);
  3325. }
  3326. FFileSystem->ReadDirectory(FileList);
  3327. }
  3328. catch (Exception & E)
  3329. {
  3330. // Do not retry for initial listing of directory,
  3331. // we instead retry whole connection attempt,
  3332. // what would be done anyway (but Open is not ready for recursion).
  3333. if ((FOpening > 0) ||
  3334. !RobustLoop.TryReopen(E))
  3335. {
  3336. throw;
  3337. }
  3338. }
  3339. }
  3340. while (RobustLoop.Retry());
  3341. if (Log->Logging && (Configuration->ActualLogProtocol >= 0))
  3342. {
  3343. for (int Index = 0; Index < FileList->Count; Index++)
  3344. {
  3345. LogRemoteFile(FileList->Files[Index]);
  3346. }
  3347. }
  3348. ReactOnCommand(fsListDirectory);
  3349. }
  3350. //---------------------------------------------------------------------------
  3351. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  3352. {
  3353. TRemoteFileList * FileList;
  3354. TRetryOperationLoop RetryLoop(this);
  3355. do
  3356. {
  3357. FileList = NULL;
  3358. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  3359. try
  3360. {
  3361. FileList = DoReadDirectoryListing(Directory, false);
  3362. if (FileList != NULL)
  3363. {
  3364. int Index = 0;
  3365. while (Index < FileList->Count)
  3366. {
  3367. TRemoteFile * File = FileList->Files[Index];
  3368. TFileMasks::TParams Params;
  3369. Params.Size = File->Resolve()->Size;
  3370. Params.Modification = File->Modification;
  3371. if (!Mask.MatchesFileName(File->FileName, false, &Params))
  3372. {
  3373. FileList->Delete(Index);
  3374. }
  3375. else
  3376. {
  3377. Index++;
  3378. }
  3379. }
  3380. Action.FileList(FileList);
  3381. }
  3382. }
  3383. catch(Exception & E)
  3384. {
  3385. RetryLoop.Error(E, Action);
  3386. }
  3387. }
  3388. while (RetryLoop.Retry());
  3389. return FileList;
  3390. }
  3391. //---------------------------------------------------------------------------
  3392. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  3393. {
  3394. TRemoteFile * File;
  3395. TRetryOperationLoop RetryLoop(this);
  3396. do
  3397. {
  3398. File = NULL;
  3399. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  3400. try
  3401. {
  3402. // reset caches
  3403. AnnounceFileListOperation();
  3404. ReadFile(Path, File);
  3405. Action.File(File);
  3406. }
  3407. catch(Exception & E)
  3408. {
  3409. RetryLoop.Error(E, Action);
  3410. }
  3411. }
  3412. while (RetryLoop.Retry());
  3413. return File;
  3414. }
  3415. //---------------------------------------------------------------------------
  3416. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3417. {
  3418. TRemoteFileList * FileList = NULL;
  3419. TRetryOperationLoop RetryLoop(this);
  3420. do
  3421. {
  3422. try
  3423. {
  3424. FileList = DoReadDirectoryListing(Directory, UseCache);
  3425. }
  3426. catch(Exception & E)
  3427. {
  3428. RetryLoop.Error(E);
  3429. }
  3430. }
  3431. while (RetryLoop.Retry());
  3432. return FileList;
  3433. }
  3434. //---------------------------------------------------------------------------
  3435. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3436. {
  3437. TRemoteFileList * FileList = new TRemoteFileList();
  3438. try
  3439. {
  3440. bool Cache = UseCache && SessionData->CacheDirectories;
  3441. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  3442. if (LoadedFromCache)
  3443. {
  3444. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  3445. }
  3446. if (!LoadedFromCache)
  3447. {
  3448. FileList->Directory = Directory;
  3449. ExceptionOnFail = true;
  3450. try
  3451. {
  3452. ReadDirectory(FileList);
  3453. }
  3454. __finally
  3455. {
  3456. ExceptionOnFail = false;
  3457. }
  3458. if (Cache)
  3459. {
  3460. AddCachedFileList(FileList);
  3461. }
  3462. }
  3463. }
  3464. catch(...)
  3465. {
  3466. delete FileList;
  3467. throw;
  3468. }
  3469. return FileList;
  3470. }
  3471. //---------------------------------------------------------------------------
  3472. bool __fastcall TTerminal::DeleteContentsIfDirectory(
  3473. const UnicodeString & FileName, const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3474. {
  3475. bool Dir = (File != NULL) && File->IsDirectory && CanRecurseToDirectory(File);
  3476. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  3477. {
  3478. try
  3479. {
  3480. ProcessDirectory(FileName, DeleteFile, &Params);
  3481. }
  3482. catch(...)
  3483. {
  3484. Action.Cancel();
  3485. throw;
  3486. }
  3487. }
  3488. return Dir && !File->IsSymLink;
  3489. }
  3490. //---------------------------------------------------------------------------
  3491. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  3492. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  3493. {
  3494. TRemoteFileList * FileList = NULL;
  3495. if (IgnoreErrors)
  3496. {
  3497. ExceptionOnFail = true;
  3498. try
  3499. {
  3500. try
  3501. {
  3502. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3503. }
  3504. catch(...)
  3505. {
  3506. if (!Active)
  3507. {
  3508. throw;
  3509. }
  3510. }
  3511. }
  3512. __finally
  3513. {
  3514. ExceptionOnFail = false;
  3515. }
  3516. }
  3517. else
  3518. {
  3519. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3520. }
  3521. // skip if directory listing fails and user selects "skip"
  3522. if (FileList)
  3523. {
  3524. try
  3525. {
  3526. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  3527. TRemoteFile * File;
  3528. for (int Index = 0; Index < FileList->Count; Index++)
  3529. {
  3530. File = FileList->Files[Index];
  3531. if (IsRealFile(File->FileName))
  3532. {
  3533. CallBackFunc(Directory + File->FileName, File, Param);
  3534. // We should catch ESkipFile here as we do in ProcessFiles.
  3535. // Now we have to handle ESkipFile in every callback implementation.
  3536. }
  3537. }
  3538. }
  3539. __finally
  3540. {
  3541. delete FileList;
  3542. }
  3543. }
  3544. }
  3545. //---------------------------------------------------------------------------
  3546. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  3547. {
  3548. try
  3549. {
  3550. CustomReadDirectory(FileList);
  3551. }
  3552. catch (Exception &E)
  3553. {
  3554. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  3555. }
  3556. }
  3557. //---------------------------------------------------------------------------
  3558. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  3559. TRemoteFile *& File)
  3560. {
  3561. DebugAssert(FFileSystem);
  3562. try
  3563. {
  3564. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  3565. FFileSystem->ReadSymlink(SymlinkFile, File);
  3566. ReactOnCommand(fsReadSymlink);
  3567. }
  3568. catch (Exception &E)
  3569. {
  3570. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  3571. }
  3572. }
  3573. //---------------------------------------------------------------------------
  3574. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  3575. TRemoteFile *& File)
  3576. {
  3577. DebugAssert(FFileSystem);
  3578. File = NULL;
  3579. try
  3580. {
  3581. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  3582. FFileSystem->ReadFile(FileName, File);
  3583. ReactOnCommand(fsListFile);
  3584. LogRemoteFile(File);
  3585. }
  3586. catch (Exception &E)
  3587. {
  3588. if (File) delete File;
  3589. File = NULL;
  3590. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3591. }
  3592. }
  3593. //---------------------------------------------------------------------------
  3594. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  3595. {
  3596. bool Result;
  3597. TRemoteFile * File = NULL;
  3598. try
  3599. {
  3600. ExceptionOnFail = true;
  3601. try
  3602. {
  3603. ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  3604. }
  3605. __finally
  3606. {
  3607. ExceptionOnFail = false;
  3608. }
  3609. if (AFile != NULL)
  3610. {
  3611. *AFile = File;
  3612. }
  3613. else
  3614. {
  3615. delete File;
  3616. }
  3617. Result = true;
  3618. }
  3619. catch(...)
  3620. {
  3621. if (Active)
  3622. {
  3623. Result = false;
  3624. }
  3625. else
  3626. {
  3627. throw;
  3628. }
  3629. }
  3630. return Result;
  3631. }
  3632. //---------------------------------------------------------------------------
  3633. void __fastcall TTerminal::AnnounceFileListOperation()
  3634. {
  3635. FFileSystem->AnnounceFileListOperation();
  3636. }
  3637. //---------------------------------------------------------------------------
  3638. void __fastcall TTerminal::OperationFinish(
  3639. TFileOperationProgressType * Progress, const void * /*Item*/, const UnicodeString & FileName,
  3640. bool Success, TOnceDoneOperation & OnceDoneOperation)
  3641. {
  3642. Progress->Finish(FileName, Success, OnceDoneOperation);
  3643. }
  3644. //---------------------------------------------------------------------------
  3645. void __fastcall TTerminal::OperationStart(
  3646. TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count)
  3647. {
  3648. OperationStart(Progress, Operation, Side, Count, false, UnicodeString(), 0, odoIdle);
  3649. }
  3650. //---------------------------------------------------------------------------
  3651. void __fastcall TTerminal::OperationStart(
  3652. TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count,
  3653. bool Temp, const UnicodeString & Directory, unsigned long CPSLimit, TOnceDoneOperation OnceDoneOperation)
  3654. {
  3655. if (FOperationProgressPersistence != NULL)
  3656. {
  3657. Progress.Restore(*FOperationProgressPersistence);
  3658. }
  3659. Progress.Start(Operation, Side, Count, Temp, Directory, CPSLimit, OnceDoneOperation);
  3660. DebugAssert(FOperationProgress == NULL);
  3661. FOperationProgress = &Progress;
  3662. }
  3663. //---------------------------------------------------------------------------
  3664. void __fastcall TTerminal::OperationStop(TFileOperationProgressType & Progress)
  3665. {
  3666. DebugAssert(FOperationProgress == &Progress);
  3667. if (FOperationProgressPersistence != NULL)
  3668. {
  3669. Progress.Store(*FOperationProgressPersistence);
  3670. }
  3671. FOperationProgress = NULL;
  3672. Progress.Stop();
  3673. }
  3674. //---------------------------------------------------------------------------
  3675. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  3676. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  3677. TOperationSide Side, bool Ex)
  3678. {
  3679. DebugAssert(FileList);
  3680. bool Result = false;
  3681. TOnceDoneOperation OnceDoneOperation = odoIdle;
  3682. try
  3683. {
  3684. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  3685. OperationStart(Progress, Operation, Side, FileList->Count);
  3686. try
  3687. {
  3688. if (Side == osRemote)
  3689. {
  3690. DebugAssert(FFileSystem != NULL);
  3691. BeginTransaction();
  3692. }
  3693. try
  3694. {
  3695. int Index = 0;
  3696. UnicodeString FileName;
  3697. bool Success;
  3698. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  3699. {
  3700. FileName = FileList->Strings[Index];
  3701. TRemoteFile * File = reinterpret_cast<TRemoteFile *>(FileList->Objects[Index]);
  3702. try
  3703. {
  3704. try
  3705. {
  3706. Success = false;
  3707. if (!Ex)
  3708. {
  3709. ProcessFile(FileName, File, Param);
  3710. }
  3711. else
  3712. {
  3713. // not used anymore
  3714. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  3715. ProcessFileEx(FileName, File, Param, Index);
  3716. }
  3717. Success = true;
  3718. }
  3719. __finally
  3720. {
  3721. OperationFinish(&Progress, File, FileName, Success, OnceDoneOperation);
  3722. }
  3723. }
  3724. catch(ESkipFile & E)
  3725. {
  3726. TSuspendFileOperationProgress Suspend(OperationProgress);
  3727. if (!HandleException(&E))
  3728. {
  3729. throw;
  3730. }
  3731. }
  3732. Index++;
  3733. }
  3734. }
  3735. __finally
  3736. {
  3737. if (Side == osRemote)
  3738. {
  3739. EndTransaction();
  3740. }
  3741. }
  3742. if (Progress.Cancel == csContinue)
  3743. {
  3744. Result = true;
  3745. }
  3746. }
  3747. __finally
  3748. {
  3749. OperationStop(Progress);
  3750. }
  3751. }
  3752. catch (...)
  3753. {
  3754. OnceDoneOperation = odoIdle;
  3755. // this was missing here. was it by purpose?
  3756. // without it any error message is lost
  3757. throw;
  3758. }
  3759. if (OnceDoneOperation != odoIdle)
  3760. {
  3761. CloseOnCompletion(OnceDoneOperation);
  3762. }
  3763. return Result;
  3764. }
  3765. //---------------------------------------------------------------------------
  3766. // not used anymore
  3767. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3768. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3769. {
  3770. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3771. Param, Side, true);
  3772. }
  3773. //---------------------------------------------------------------------------
  3774. TStrings * __fastcall TTerminal::GetFixedPaths()
  3775. {
  3776. DebugAssert(FFileSystem != NULL);
  3777. return FFileSystem->GetFixedPaths();
  3778. }
  3779. //---------------------------------------------------------------------------
  3780. bool __fastcall TTerminal::GetResolvingSymlinks()
  3781. {
  3782. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3783. }
  3784. //---------------------------------------------------------------------------
  3785. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3786. {
  3787. TUsableCopyParamAttrs Result;
  3788. Result.General =
  3789. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3790. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3791. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3792. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3793. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3794. // the following three are never supported for download,
  3795. // so when they are not suppored for upload too,
  3796. // set them in General flags, so that they do not get enabled on
  3797. // Synchronize dialog.
  3798. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3799. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3800. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3801. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3802. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport) |
  3803. FLAGMASK(!IsEncryptingFiles(), cpaNoEncryptNewFiles);
  3804. Result.Download = Result.General | cpaNoClearArchive |
  3805. cpaNoIgnorePermErrors |
  3806. // May be already set in General flags, but it's unconditional here
  3807. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM | cpaNoEncryptNewFiles;
  3808. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3809. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3810. return Result;
  3811. }
  3812. //---------------------------------------------------------------------------
  3813. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3814. {
  3815. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3816. if (Result)
  3817. {
  3818. UnicodeString Path = UnixExtractFilePath(FileName);
  3819. if (Path.IsEmpty())
  3820. {
  3821. Path = CurrentDirectory;
  3822. }
  3823. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3824. }
  3825. return Result;
  3826. }
  3827. //---------------------------------------------------------------------------
  3828. bool __fastcall TTerminal::RecycleFile(const UnicodeString & AFileName, const TRemoteFile * File)
  3829. {
  3830. UnicodeString FileName = AFileName;
  3831. if (FileName.IsEmpty())
  3832. {
  3833. DebugAssert(File != NULL);
  3834. FileName = File->FileName;
  3835. }
  3836. bool Result;
  3837. if (IsRecycledFile(FileName))
  3838. {
  3839. Result = true;
  3840. }
  3841. else
  3842. {
  3843. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3844. (FileName, SessionData->RecycleBinPath)));
  3845. TMoveFileParams Params;
  3846. Params.Target = SessionData->RecycleBinPath;
  3847. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3848. Params.DontOverwrite = false;
  3849. Result = DoMoveFile(FileName, File, &Params);
  3850. if (Result && (OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  3851. {
  3852. OperationProgress->Succeeded();
  3853. }
  3854. }
  3855. return Result;
  3856. }
  3857. //---------------------------------------------------------------------------
  3858. bool __fastcall TTerminal::TryStartOperationWithFile(
  3859. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3860. {
  3861. bool Result = true;
  3862. if ((OperationProgress != NULL) &&
  3863. ((OperationProgress->Operation == Operation1) ||
  3864. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3865. {
  3866. if (OperationProgress->Cancel != csContinue)
  3867. {
  3868. Result = false;
  3869. }
  3870. else
  3871. {
  3872. OperationProgress->SetFile(FileName);
  3873. }
  3874. }
  3875. return Result;
  3876. }
  3877. //---------------------------------------------------------------------------
  3878. void __fastcall TTerminal::StartOperationWithFile(
  3879. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3880. {
  3881. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3882. {
  3883. Abort();
  3884. }
  3885. }
  3886. //---------------------------------------------------------------------------
  3887. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3888. const TRemoteFile * File, void * AParams)
  3889. {
  3890. if (FileName.IsEmpty() && File)
  3891. {
  3892. FileName = File->FileName;
  3893. }
  3894. StartOperationWithFile(FileName, foDelete);
  3895. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3896. bool Recycle =
  3897. FLAGCLEAR(Params, dfForceDelete) &&
  3898. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3899. !SessionData->RecycleBinPath.IsEmpty();
  3900. if (Recycle && !IsRecycledFile(FileName))
  3901. {
  3902. RecycleFile(FileName, File);
  3903. }
  3904. else
  3905. {
  3906. DoDeleteFile(FileName, File, Params);
  3907. }
  3908. }
  3909. //---------------------------------------------------------------------------
  3910. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3911. const TRemoteFile * File, int Params)
  3912. {
  3913. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3914. FileModified(File, FileName, true);
  3915. TRetryOperationLoop RetryLoop(this);
  3916. do
  3917. {
  3918. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3919. try
  3920. {
  3921. DebugAssert(FFileSystem);
  3922. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3923. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3924. if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  3925. {
  3926. OperationProgress->Succeeded();
  3927. }
  3928. }
  3929. catch(Exception & E)
  3930. {
  3931. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3932. }
  3933. }
  3934. while (RetryLoop.Retry());
  3935. // Forget if file was or was not encrypted and use user preferences, if we ever recreate it.
  3936. FEncryptedFileNames.erase(AbsolutePath(FileName, true));
  3937. ReactOnCommand(fsDeleteFile);
  3938. }
  3939. //---------------------------------------------------------------------------
  3940. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3941. {
  3942. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3943. FUseBusyCursor = false;
  3944. // TODO: avoid resolving symlinks while reading subdirectories.
  3945. // Resolving does not work anyway for relative symlinks in subdirectories
  3946. // (at least for SFTP).
  3947. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3948. }
  3949. //---------------------------------------------------------------------------
  3950. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3951. const TRemoteFile * /*File*/, void * Params)
  3952. {
  3953. StartOperationWithFile(FileName, foDelete);
  3954. int Deleted;
  3955. if (OnDeleteLocalFile == NULL)
  3956. {
  3957. Deleted = RecursiveDeleteFileChecked(FileName, false);
  3958. }
  3959. else
  3960. {
  3961. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative), Deleted);
  3962. }
  3963. if (DebugAlwaysTrue((OperationProgress != NULL) && (OperationProgress->Operation == foDelete)))
  3964. {
  3965. OperationProgress->Succeeded(Deleted);
  3966. }
  3967. }
  3968. //---------------------------------------------------------------------------
  3969. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3970. {
  3971. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3972. }
  3973. //---------------------------------------------------------------------------
  3974. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3975. const TRemoteFile * File, void * AParams)
  3976. {
  3977. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3978. if (FileName.IsEmpty() && File)
  3979. {
  3980. FileName = File->FileName;
  3981. }
  3982. StartOperationWithFile(FileName, foCustomCommand);
  3983. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3984. (Params->Command, Params->Params, FileName)));
  3985. FileModified(File, FileName);
  3986. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3987. Params->OutputEvent);
  3988. ReactOnCommand(fsAnyCommand);
  3989. }
  3990. //---------------------------------------------------------------------------
  3991. TCustomFileSystem * TTerminal::GetFileSystemForCapability(TFSCapability Capability, bool NeedCurrentDirectory)
  3992. {
  3993. TCustomFileSystem * Result;
  3994. if (IsCapable[Capability])
  3995. {
  3996. DebugAssert(FFileSystem != NULL);
  3997. Result = FFileSystem;
  3998. }
  3999. else
  4000. {
  4001. DebugAssert(CommandSessionOpened);
  4002. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4003. LogEvent(L"Performing operation on command session.");
  4004. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  4005. {
  4006. FCommandSession->CurrentDirectory = CurrentDirectory;
  4007. // We are likely in transaction, so ReadCurrentDirectory won't get called
  4008. // until transaction ends. But we need to know CurrentDirectory to
  4009. // expand !/ pattern when in CustomCommandOnFiles.
  4010. // Doing this only, when current directory of the main and secondary shell differs,
  4011. // what would be the case before the first file in transaction.
  4012. // Otherwise we would be reading pwd before every time as the
  4013. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  4014. if (NeedCurrentDirectory && FCommandSession->FReadCurrentDirectoryPending)
  4015. {
  4016. FCommandSession->ReadCurrentDirectory();
  4017. }
  4018. }
  4019. Result = FCommandSession->FFileSystem;
  4020. }
  4021. return Result;
  4022. }
  4023. //---------------------------------------------------------------------------
  4024. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  4025. const TRemoteFile * File, UnicodeString Command, int Params,
  4026. TCaptureOutputEvent OutputEvent)
  4027. {
  4028. TRetryOperationLoop RetryLoop(this);
  4029. do
  4030. {
  4031. try
  4032. {
  4033. TCustomFileSystem * FileSystem = GetFileSystemForCapability(fcAnyCommand, true);
  4034. DebugAssert((FileSystem != FFileSystem) || IsCapable[fcShellAnyCommand]);
  4035. FileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  4036. }
  4037. catch(Exception & E)
  4038. {
  4039. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  4040. }
  4041. }
  4042. while (RetryLoop.Retry());
  4043. }
  4044. //---------------------------------------------------------------------------
  4045. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  4046. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  4047. {
  4048. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  4049. {
  4050. TCustomCommandParams AParams;
  4051. AParams.Command = Command;
  4052. AParams.Params = Params;
  4053. AParams.OutputEvent = OutputEvent;
  4054. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  4055. }
  4056. else
  4057. {
  4058. UnicodeString FileList;
  4059. for (int i = 0; i < Files->Count; i++)
  4060. {
  4061. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  4062. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  4063. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  4064. {
  4065. AddToShellFileListCommandLine(FileList, Files->Strings[i]);
  4066. }
  4067. }
  4068. TCustomCommandData Data(this);
  4069. UnicodeString Cmd =
  4070. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  4071. Complete(Command, true);
  4072. if (!DoOnCustomCommand(Cmd))
  4073. {
  4074. DoAnyCommand(Cmd, OutputEvent, NULL);
  4075. }
  4076. }
  4077. }
  4078. //---------------------------------------------------------------------------
  4079. bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command)
  4080. {
  4081. bool Result = false;
  4082. if (FOnCustomCommand != NULL)
  4083. {
  4084. FOnCustomCommand(this, Command, Result);
  4085. }
  4086. return Result;
  4087. }
  4088. //---------------------------------------------------------------------------
  4089. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  4090. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  4091. {
  4092. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  4093. DebugAssert(RProperties && !RProperties->Valid.Empty());
  4094. if (FileName.IsEmpty() && File)
  4095. {
  4096. FileName = File->FileName;
  4097. }
  4098. StartOperationWithFile(FileName, foSetProperties);
  4099. if (Log->Logging)
  4100. {
  4101. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  4102. (FileName, BooleanToEngStr(RProperties->Recursive))));
  4103. if (RProperties->Valid.Contains(vpRights))
  4104. {
  4105. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  4106. }
  4107. if (RProperties->Valid.Contains(vpGroup))
  4108. {
  4109. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  4110. }
  4111. if (RProperties->Valid.Contains(vpOwner))
  4112. {
  4113. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  4114. }
  4115. if (RProperties->Valid.Contains(vpModification))
  4116. {
  4117. LogEvent(FORMAT(L" - modification: \"%s\"",
  4118. (FormatDateTime(L"dddddd tt",
  4119. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  4120. }
  4121. if (RProperties->Valid.Contains(vpLastAccess))
  4122. {
  4123. LogEvent(FORMAT(L" - last access: \"%s\"",
  4124. (FormatDateTime(L"dddddd tt",
  4125. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  4126. }
  4127. }
  4128. FileModified(File, FileName);
  4129. DoChangeFileProperties(FileName, File, RProperties);
  4130. ReactOnCommand(fsChangeProperties);
  4131. }
  4132. //---------------------------------------------------------------------------
  4133. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  4134. const TRemoteFile * File, const TRemoteProperties * Properties)
  4135. {
  4136. TRetryOperationLoop RetryLoop(this);
  4137. do
  4138. {
  4139. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  4140. try
  4141. {
  4142. DebugAssert(FFileSystem);
  4143. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  4144. }
  4145. catch(Exception & E)
  4146. {
  4147. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  4148. }
  4149. }
  4150. while (RetryLoop.Retry());
  4151. }
  4152. //---------------------------------------------------------------------------
  4153. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  4154. const TRemoteProperties * Properties)
  4155. {
  4156. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4157. FUseBusyCursor = false;
  4158. AnnounceFileListOperation();
  4159. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  4160. }
  4161. //---------------------------------------------------------------------------
  4162. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  4163. {
  4164. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4165. FUseBusyCursor = false;
  4166. // see comment in TSFTPFileSystem::IsCapable
  4167. bool Result =
  4168. IsCapable[fcLoadingAdditionalProperties] &&
  4169. FFileSystem->LoadFilesProperties(FileList);
  4170. if (Result && SessionData->CacheDirectories &&
  4171. (FileList->Count > 0) &&
  4172. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  4173. {
  4174. AddCachedFileList(FFiles);
  4175. }
  4176. return Result;
  4177. }
  4178. //---------------------------------------------------------------------------
  4179. void __fastcall TTerminal::DoCalculateFileSize(UnicodeString FileName,
  4180. const TRemoteFile * File, void * Param)
  4181. {
  4182. // This is called for top-level entries only
  4183. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4184. if (AParams->Stats->FoundFiles != NULL)
  4185. {
  4186. UnicodeString DirPath = UnixExtractFilePath(UnixExcludeTrailingBackslash(File->FullFileName));
  4187. if ((DirPath != AParams->LastDirPath) ||
  4188. (AParams->Files == NULL))
  4189. {
  4190. AParams->Files = new TCollectedFileList();
  4191. AParams->LastDirPath = DirPath;
  4192. AParams->Stats->FoundFiles->AddObject(AParams->LastDirPath, AParams->Files);
  4193. }
  4194. }
  4195. __int64 PrevSize = AParams->Size;
  4196. CalculateFileSize(FileName, File, Param);
  4197. if (AParams->Stats->CalculatedSizes != NULL)
  4198. {
  4199. __int64 Size = AParams->Size - PrevSize;
  4200. AParams->Stats->CalculatedSizes->push_back(Size);
  4201. }
  4202. }
  4203. //---------------------------------------------------------------------------
  4204. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  4205. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  4206. {
  4207. DebugAssert(Param);
  4208. DebugAssert(File);
  4209. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4210. if (FileName.IsEmpty())
  4211. {
  4212. FileName = File->FileName;
  4213. }
  4214. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  4215. {
  4216. AParams->Result = false;
  4217. // Combined with csIgnoreErrors, this will not abort completelly, but we get called again
  4218. // with next sibling of our parent directory (and we get again to this branch, throwing again)
  4219. Abort();
  4220. }
  4221. if ((AParams->CopyParam == NULL) ||
  4222. DoAllowRemoteFileTransfer(File, AParams->CopyParam, FLAGSET(AParams->Params, csDisallowTemporaryTransferFiles)))
  4223. {
  4224. int CollectionIndex = -1;
  4225. if (AParams->Files != NULL)
  4226. {
  4227. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4228. CollectionIndex = AParams->Files->Add(FullFileName, File->Duplicate(), File->IsDirectory);
  4229. }
  4230. if (File->IsDirectory)
  4231. {
  4232. if (CanRecurseToDirectory(File))
  4233. {
  4234. if (!AParams->AllowDirs)
  4235. {
  4236. AParams->Result = false;
  4237. }
  4238. else if (FLAGSET(AParams->Params, csStopOnFirstFile) && (AParams->Stats->Files > 0))
  4239. {
  4240. // do not waste time recursing into a folder, if we already found some files
  4241. }
  4242. else
  4243. {
  4244. if (FLAGCLEAR(AParams->Params, csStopOnFirstFile))
  4245. {
  4246. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  4247. }
  4248. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  4249. if (!DoCalculateDirectorySize(File->FullFileName, AParams))
  4250. {
  4251. if (CollectionIndex >= 0)
  4252. {
  4253. AParams->Files->DidNotRecurse(CollectionIndex);
  4254. }
  4255. }
  4256. }
  4257. }
  4258. AParams->Stats->Directories++;
  4259. }
  4260. else
  4261. {
  4262. AParams->Size += File->Resolve()->Size;
  4263. AParams->Stats->Files++;
  4264. }
  4265. if (File->IsSymLink)
  4266. {
  4267. AParams->Stats->SymLinks++;
  4268. }
  4269. }
  4270. }
  4271. //---------------------------------------------------------------------------
  4272. bool __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString & FileName, TCalculateSizeParams * Params)
  4273. {
  4274. bool Result = false;
  4275. if (FLAGSET(Params->Params, csStopOnFirstFile) && (Configuration->ActualLogProtocol >= 1))
  4276. {
  4277. LogEvent(FORMAT(L"Checking if remote directory \"%s\" is empty", (FileName)));
  4278. }
  4279. TRetryOperationLoop RetryLoop(this);
  4280. do
  4281. {
  4282. try
  4283. {
  4284. ProcessDirectory(FileName, CalculateFileSize, Params, Params->UseCache);
  4285. Result = true;
  4286. }
  4287. catch(Exception & E)
  4288. {
  4289. // We can probably replace the csIgnoreErrors with IgnoreErrors argument of the ProcessDirectory
  4290. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  4291. {
  4292. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  4293. }
  4294. }
  4295. }
  4296. while (RetryLoop.Retry());
  4297. if (Configuration->ActualLogProtocol >= 1)
  4298. {
  4299. if (Params->Stats->Files == 0)
  4300. {
  4301. LogEvent(FORMAT(L"Remote directory \"%s\" is empty", (FileName)));
  4302. }
  4303. else
  4304. {
  4305. LogEvent(FORMAT(L"Remote directory \"%s\" is not empty", (FileName)));
  4306. }
  4307. }
  4308. return Result;
  4309. }
  4310. //---------------------------------------------------------------------------
  4311. bool TTerminal::CalculateFilesSize(TStrings * FileList, __int64 & Size, TCalculateSizeParams & Params)
  4312. {
  4313. // With FTP protocol, we may use DSIZ command from
  4314. // draft-peterson-streamlined-ftp-command-extensions-10
  4315. // Implemented by Serv-U FTP.
  4316. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4317. FUseBusyCursor = false;
  4318. ProcessFiles(FileList, foCalculateSize, DoCalculateFileSize, &Params);
  4319. Size = Params.Size;
  4320. if (Configuration->ActualLogProtocol >= 1)
  4321. {
  4322. LogEvent(FORMAT(L"Size of %d remote files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
  4323. }
  4324. return Params.Result;
  4325. }
  4326. //---------------------------------------------------------------------------
  4327. void __fastcall TTerminal::CalculateSubFoldersChecksum(
  4328. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4329. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  4330. {
  4331. // recurse into subdirectories only if we have callback function
  4332. if (OnCalculatedChecksum != NULL)
  4333. {
  4334. int Index = 0;
  4335. TOnceDoneOperation OnceDoneOperation; // unused
  4336. while ((Index < FileList->Count) && !OperationProgress->Cancel)
  4337. {
  4338. UnicodeString FileName = FileList->Strings[Index];
  4339. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]));
  4340. if (File->IsDirectory &&
  4341. CanRecurseToDirectory(File) &&
  4342. IsRealFile(File->FileName))
  4343. {
  4344. OperationProgress->SetFile(File->FileName);
  4345. std::unique_ptr<TRemoteFileList> SubFiles(CustomReadDirectoryListing(File->FullFileName, false));
  4346. if (SubFiles.get() != NULL)
  4347. {
  4348. std::unique_ptr<TStrings> SubFileList(new TStringList());
  4349. bool Success = false;
  4350. try
  4351. {
  4352. OperationProgress->SetFile(File->FileName);
  4353. for (int Index = 0; Index < SubFiles->Count; Index++)
  4354. {
  4355. TRemoteFile * SubFile = SubFiles->Files[Index];
  4356. UnicodeString SubFileName = UnixCombinePaths(FileName, SubFile->FileName);
  4357. SubFileList->AddObject(SubFileName, SubFile);
  4358. }
  4359. FFileSystem->CalculateFilesChecksum(Alg, SubFileList.get(), OnCalculatedChecksum, OperationProgress, false);
  4360. Success = true;
  4361. }
  4362. __finally
  4363. {
  4364. if (FirstLevel)
  4365. {
  4366. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  4367. }
  4368. }
  4369. }
  4370. }
  4371. Index++;
  4372. }
  4373. }
  4374. }
  4375. //---------------------------------------------------------------------------
  4376. void __fastcall TTerminal::CalculateFilesChecksum(
  4377. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum)
  4378. {
  4379. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  4380. OperationStart(Progress, foCalculateChecksum, osRemote, FileList->Count);
  4381. try
  4382. {
  4383. TCustomFileSystem * FileSystem = GetFileSystemForCapability(fcCalculatingChecksum);
  4384. UnicodeString NormalizedAlg = FileSystem->CalculateFilesChecksumInitialize(Alg);
  4385. FileSystem->CalculateFilesChecksum(NormalizedAlg, FileList, OnCalculatedChecksum, &Progress, true);
  4386. }
  4387. __finally
  4388. {
  4389. OperationStop(Progress);
  4390. }
  4391. }
  4392. //---------------------------------------------------------------------------
  4393. void __fastcall TTerminal::RenameFile(const TRemoteFile * File, const UnicodeString & NewName)
  4394. {
  4395. // Already checked in TUnixDirView::InternalEdit
  4396. if (DebugAlwaysTrue(File->FileName != NewName))
  4397. {
  4398. FileModified(File, File->FileName);
  4399. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (File->FileName, NewName)));
  4400. if (DoRenameFile(File->FileName, File, NewName, false, false))
  4401. {
  4402. ReactOnCommand(fsRenameFile);
  4403. }
  4404. }
  4405. }
  4406. //---------------------------------------------------------------------------
  4407. bool __fastcall TTerminal::DoRenameFile(
  4408. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & NewName, bool Move, bool DontOverwrite)
  4409. {
  4410. // Can be foDelete when recycling (and overwrite should not happen in this case)
  4411. bool IsBatchMove = (OperationProgress != NULL) && (OperationProgress->Operation == foRemoteMove);
  4412. TBatchOverwrite BatchOverwrite = (IsBatchMove ? OperationProgress->BatchOverwrite : boNo);
  4413. UnicodeString AbsoluteNewName = AbsolutePath(NewName, true);
  4414. bool Result = true;
  4415. bool ExistenceKnown = false;
  4416. TRemoteFile * DuplicateFile = NULL;
  4417. std::unique_ptr<TRemoteFile> DuplicateFileOwner(DuplicateFile);
  4418. if (BatchOverwrite == boNone)
  4419. {
  4420. DebugAssert(!DontOverwrite); // unsupported combination
  4421. Result = !FileExists(AbsoluteNewName);
  4422. ExistenceKnown = true;
  4423. }
  4424. else if (BatchOverwrite == boAll)
  4425. {
  4426. // noop
  4427. }
  4428. else if (DebugAlwaysTrue(BatchOverwrite == boNo) &&
  4429. Configuration->ConfirmOverwriting &&
  4430. !DontOverwrite)
  4431. {
  4432. FileExists(AbsoluteNewName, &DuplicateFile);
  4433. DuplicateFileOwner.reset(DuplicateFile);
  4434. ExistenceKnown = true;
  4435. if (DuplicateFile != NULL)
  4436. {
  4437. UnicodeString QuestionFmt;
  4438. if (DuplicateFile->IsDirectory)
  4439. {
  4440. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  4441. }
  4442. else
  4443. {
  4444. QuestionFmt = LoadStr(FILE_OVERWRITE);
  4445. }
  4446. TQueryParams Params(qpNeverAskAgainCheck);
  4447. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  4448. unsigned int Answers = qaYes | qaNo | FLAGMASK(OperationProgress != NULL, qaCancel) | FLAGMASK(IsBatchMove, qaYesToAll | qaNoToAll);
  4449. unsigned int Answer = QueryUser(Question, NULL, Answers, &Params);
  4450. switch (Answer)
  4451. {
  4452. case qaNeverAskAgain:
  4453. Configuration->ConfirmOverwriting = false;
  4454. Result = true;
  4455. break;
  4456. case qaYes:
  4457. Result = true;
  4458. break;
  4459. case qaNo:
  4460. Result = false;
  4461. break;
  4462. case qaYesToAll:
  4463. Result = true;
  4464. if (DebugAlwaysTrue(IsBatchMove))
  4465. {
  4466. OperationProgress->SetBatchOverwrite(boAll);
  4467. }
  4468. break;
  4469. case qaNoToAll:
  4470. Result = false;
  4471. if (DebugAlwaysTrue(IsBatchMove))
  4472. {
  4473. OperationProgress->SetBatchOverwrite(boNone);
  4474. }
  4475. break;
  4476. case qaCancel:
  4477. Result = false;
  4478. OperationProgress->SetCancel(csCancel);
  4479. break;
  4480. default:
  4481. Result = false;
  4482. DebugFail();
  4483. break;
  4484. }
  4485. }
  4486. }
  4487. if (Result)
  4488. {
  4489. if (!IsCapable[fcMoveOverExistingFile] && !DontOverwrite)
  4490. {
  4491. if (!ExistenceKnown)
  4492. {
  4493. FileExists(AbsoluteNewName, &DuplicateFile);
  4494. DuplicateFileOwner.reset(DuplicateFile);
  4495. }
  4496. if (DuplicateFile != NULL)
  4497. {
  4498. DoDeleteFile(AbsoluteNewName, DuplicateFile, 0);
  4499. }
  4500. }
  4501. TRetryOperationLoop RetryLoop(this);
  4502. do
  4503. {
  4504. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsoluteNewName);
  4505. try
  4506. {
  4507. DebugAssert(FFileSystem);
  4508. FFileSystem->RenameFile(FileName, File, NewName);
  4509. }
  4510. catch(Exception & E)
  4511. {
  4512. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  4513. RetryLoop.Error(E, Action, Message);
  4514. }
  4515. }
  4516. while (RetryLoop.Retry());
  4517. Result = RetryLoop.Succeeded();
  4518. }
  4519. return Result;
  4520. }
  4521. //---------------------------------------------------------------------------
  4522. bool __fastcall TTerminal::DoMoveFile(const UnicodeString & FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4523. {
  4524. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  4525. DebugAssert(Param != NULL);
  4526. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4527. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4528. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4529. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  4530. FileModified(File, FileName);
  4531. bool Result = DoRenameFile(FileName, File, NewName, true, Params.DontOverwrite);
  4532. if (Result)
  4533. {
  4534. ReactOnCommand(fsMoveFile);
  4535. }
  4536. return Result;
  4537. }
  4538. //---------------------------------------------------------------------------
  4539. void __fastcall TTerminal::MoveFile(const UnicodeString FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4540. {
  4541. DoMoveFile(FileName, File, Param);
  4542. }
  4543. //---------------------------------------------------------------------------
  4544. bool __fastcall TTerminal::MoveFiles(
  4545. TStrings * FileList, const UnicodeString & Target, const UnicodeString & FileMask, bool DontOverwrite)
  4546. {
  4547. TMoveFileParams Params;
  4548. Params.Target = Target;
  4549. Params.FileMask = FileMask;
  4550. Params.DontOverwrite = DontOverwrite;
  4551. bool Result;
  4552. BeginTransaction();
  4553. try
  4554. {
  4555. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  4556. }
  4557. __finally
  4558. {
  4559. if (Active)
  4560. {
  4561. // Only after the move, as with encryption, the folders can be read and cached before the move
  4562. // (when determining if the target exists and is encrypted)
  4563. DirectoryModified(Target, true);
  4564. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  4565. bool PossiblyMoved = false;
  4566. // check if we was moving current directory.
  4567. // this is just optimization to avoid checking existence of current
  4568. // directory after each move operation.
  4569. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  4570. {
  4571. const TRemoteFile * File =
  4572. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  4573. // File can be NULL, and filename may not be full path,
  4574. // but currently this is the only way we can move (at least in GUI)
  4575. // current directory
  4576. if ((File != NULL) &&
  4577. File->IsDirectory &&
  4578. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  4579. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  4580. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  4581. {
  4582. PossiblyMoved = true;
  4583. }
  4584. }
  4585. if (PossiblyMoved && !FileExists(CurrentDirectory))
  4586. {
  4587. UnicodeString NearestExisting = CurrentDirectory;
  4588. do
  4589. {
  4590. NearestExisting = UnixExtractFileDir(NearestExisting);
  4591. }
  4592. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  4593. ChangeDirectory(NearestExisting);
  4594. }
  4595. }
  4596. EndTransaction();
  4597. }
  4598. return Result;
  4599. }
  4600. //---------------------------------------------------------------------------
  4601. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName, const TRemoteFile * File,
  4602. const UnicodeString NewName)
  4603. {
  4604. TRetryOperationLoop RetryLoop(this);
  4605. do
  4606. {
  4607. TCpSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  4608. try
  4609. {
  4610. DebugAssert(FFileSystem);
  4611. GetFileSystemForCapability(fcRemoteCopy)->CopyFile(FileName, File, NewName);
  4612. }
  4613. catch(Exception & E)
  4614. {
  4615. RetryLoop.Error(E, Action, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  4616. }
  4617. }
  4618. while (RetryLoop.Retry());
  4619. }
  4620. //---------------------------------------------------------------------------
  4621. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  4622. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4623. {
  4624. StartOperationWithFile(FileName, foRemoteCopy);
  4625. DebugAssert(Param != NULL);
  4626. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4627. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4628. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4629. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  4630. DoCopyFile(FileName, File, NewName);
  4631. ReactOnCommand(fsCopyFile);
  4632. }
  4633. //---------------------------------------------------------------------------
  4634. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  4635. const UnicodeString FileMask)
  4636. {
  4637. TMoveFileParams Params;
  4638. Params.Target = Target;
  4639. Params.FileMask = FileMask;
  4640. Params.DontOverwrite = false; // not used
  4641. DirectoryModified(Target, true);
  4642. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  4643. }
  4644. //---------------------------------------------------------------------------
  4645. void __fastcall TTerminal::CreateDirectory(const UnicodeString & DirName, const TRemoteProperties * Properties)
  4646. {
  4647. DebugAssert(FFileSystem);
  4648. DebugAssert(Properties != NULL);
  4649. EnsureNonExistence(DirName);
  4650. FileModified(NULL, DirName);
  4651. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  4652. bool Encrypt = Properties->Valid.Contains(vpEncrypt) && Properties->Encrypt;
  4653. DoCreateDirectory(DirName, Encrypt);
  4654. TValidProperties RemainingPropeties = Properties->Valid - (TValidProperties() << vpEncrypt);
  4655. if (!RemainingPropeties.Empty() &&
  4656. (IsCapable[fcModeChanging] || IsCapable[fcOwnerChanging] || IsCapable[fcGroupChanging]))
  4657. {
  4658. DoChangeFileProperties(DirName, NULL, Properties);
  4659. }
  4660. ReactOnCommand(fsCreateDirectory);
  4661. }
  4662. //---------------------------------------------------------------------------
  4663. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString & DirName, bool Encrypt)
  4664. {
  4665. TRetryOperationLoop RetryLoop(this);
  4666. do
  4667. {
  4668. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  4669. try
  4670. {
  4671. DebugAssert(FFileSystem);
  4672. FFileSystem->CreateDirectory(DirName, Encrypt);
  4673. }
  4674. catch(Exception & E)
  4675. {
  4676. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  4677. }
  4678. }
  4679. while (RetryLoop.Retry());
  4680. }
  4681. //---------------------------------------------------------------------------
  4682. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  4683. const UnicodeString PointTo, bool Symbolic)
  4684. {
  4685. DebugAssert(FFileSystem);
  4686. EnsureNonExistence(FileName);
  4687. if (SessionData->CacheDirectories)
  4688. {
  4689. DirectoryModified(CurrentDirectory, false);
  4690. }
  4691. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  4692. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  4693. DoCreateLink(FileName, PointTo, Symbolic);
  4694. ReactOnCommand(fsCreateDirectory);
  4695. }
  4696. //---------------------------------------------------------------------------
  4697. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  4698. const UnicodeString PointTo, bool Symbolic)
  4699. {
  4700. TRetryOperationLoop RetryLoop(this);
  4701. do
  4702. {
  4703. try
  4704. {
  4705. DebugAssert(FFileSystem);
  4706. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  4707. }
  4708. catch(Exception & E)
  4709. {
  4710. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  4711. }
  4712. }
  4713. while (RetryLoop.Retry());
  4714. }
  4715. //---------------------------------------------------------------------------
  4716. void __fastcall TTerminal::HomeDirectory()
  4717. {
  4718. DebugAssert(FFileSystem);
  4719. try
  4720. {
  4721. LogEvent(L"Changing directory to home directory.");
  4722. FFileSystem->HomeDirectory();
  4723. ReactOnCommand(fsHomeDirectory);
  4724. }
  4725. catch (Exception &E)
  4726. {
  4727. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  4728. }
  4729. }
  4730. //---------------------------------------------------------------------------
  4731. UnicodeString __fastcall TTerminal::GetHomeDirectory()
  4732. {
  4733. return FFileSystem->GetHomeDirectory();
  4734. }
  4735. //---------------------------------------------------------------------------
  4736. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  4737. {
  4738. DebugAssert(FFileSystem);
  4739. try
  4740. {
  4741. UnicodeString CachedDirectory;
  4742. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  4743. // never use directory change cache during startup, this ensures, we never
  4744. // end-up initially in non-existing directory
  4745. if ((Status == ssOpened) &&
  4746. SessionData->CacheDirectoryChanges &&
  4747. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  4748. Directory, CachedDirectory))
  4749. {
  4750. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  4751. (Directory, CachedDirectory)));
  4752. FFileSystem->CachedChangeDirectory(CachedDirectory);
  4753. }
  4754. else
  4755. {
  4756. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  4757. FFileSystem->ChangeDirectory(Directory);
  4758. }
  4759. FLastDirectoryChange = Directory;
  4760. ReactOnCommand(fsChangeDirectory);
  4761. }
  4762. catch (Exception &E)
  4763. {
  4764. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  4765. }
  4766. }
  4767. //---------------------------------------------------------------------------
  4768. void __fastcall TTerminal::LookupUsersGroups()
  4769. {
  4770. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  4771. IsCapable[fcUserGroupListing])
  4772. {
  4773. DebugAssert(FFileSystem);
  4774. try
  4775. {
  4776. FUsersGroupsLookedup = true;
  4777. LogEvent(L"Looking up groups and users.");
  4778. FFileSystem->LookupUsersGroups();
  4779. ReactOnCommand(fsLookupUsersGroups);
  4780. if (Log->Logging)
  4781. {
  4782. FGroups.Log(this, L"groups");
  4783. FMembership.Log(this, L"membership");
  4784. FUsers.Log(this, L"users");
  4785. }
  4786. }
  4787. catch (Exception &E)
  4788. {
  4789. if (!Active || (SessionData->LookupUserGroups == asOn))
  4790. {
  4791. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  4792. }
  4793. }
  4794. }
  4795. }
  4796. //---------------------------------------------------------------------------
  4797. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  4798. {
  4799. return !Command.Trim().IsEmpty();
  4800. }
  4801. //---------------------------------------------------------------------------
  4802. bool __fastcall TTerminal::GetCommandSessionOpened()
  4803. {
  4804. // consider secondary terminal open in "ready" state only
  4805. // so we never do keepalives on it until it is completely initialized
  4806. return (FCommandSession != NULL) &&
  4807. (FCommandSession->Status == ssOpened);
  4808. }
  4809. //---------------------------------------------------------------------------
  4810. TTerminal * __fastcall TTerminal::CreateSecondarySession(const UnicodeString & Name, TSessionData * SessionData)
  4811. {
  4812. std::unique_ptr<TTerminal> Result(new TSecondaryTerminal(this, SessionData, Configuration, Name, ActionLog));
  4813. Result->AutoReadDirectory = false;
  4814. Result->FExceptionOnFail = FExceptionOnFail;
  4815. Result->OnQueryUser = OnQueryUser;
  4816. Result->OnPromptUser = OnPromptUser;
  4817. Result->OnShowExtendedException = OnShowExtendedException;
  4818. Result->OnProgress = OnProgress;
  4819. Result->OnFinished = OnFinished;
  4820. Result->OnInformation = OnInformation;
  4821. Result->OnCustomCommand = OnCustomCommand;
  4822. // do not copy OnDisplayBanner to avoid it being displayed
  4823. return Result.release();
  4824. }
  4825. //---------------------------------------------------------------------------
  4826. void __fastcall TTerminal::FillSessionDataForCode(TSessionData * Data)
  4827. {
  4828. const TSessionInfo & SessionInfo = GetSessionInfo();
  4829. if (!SessionInfo.HostKeyFingerprintSHA256.IsEmpty())
  4830. {
  4831. Data->HostKey = SessionInfo.HostKeyFingerprintSHA256;
  4832. }
  4833. else if (SessionInfo.CertificateVerifiedManually && DebugAlwaysTrue(!SessionInfo.CertificateFingerprintSHA256.IsEmpty()))
  4834. {
  4835. Data->HostKey = SessionInfo.CertificateFingerprintSHA256;
  4836. }
  4837. if (FTunnel != NULL)
  4838. {
  4839. const TSessionInfo & TunnelSessionInfo = FTunnel->GetSessionInfo();
  4840. if (DebugAlwaysTrue(!TunnelSessionInfo.HostKeyFingerprintSHA256.IsEmpty()))
  4841. {
  4842. Data->TunnelHostKey = TunnelSessionInfo.HostKeyFingerprintSHA256;
  4843. }
  4844. }
  4845. }
  4846. //---------------------------------------------------------------------------
  4847. void __fastcall TTerminal::UpdateSessionCredentials(TSessionData * Data)
  4848. {
  4849. Data->UserName = UserName;
  4850. Data->Password = Password;
  4851. if (!FRememberedPassword.IsEmpty() && (FRememberedPasswordKind == pkPassphrase))
  4852. {
  4853. Data->Passphrase = GetRememberedPassword();
  4854. }
  4855. }
  4856. //---------------------------------------------------------------------------
  4857. TTerminal * __fastcall TTerminal::GetCommandSession()
  4858. {
  4859. if ((FCommandSession != NULL) && !FCommandSession->Active)
  4860. {
  4861. SAFE_DESTROY(FCommandSession);
  4862. }
  4863. if (FCommandSession == NULL)
  4864. {
  4865. // transaction cannot be started yet to allow proper matching transaction
  4866. // levels between main and command session
  4867. DebugAssert(FInTransaction == 0);
  4868. std::unique_ptr<TSessionData> CommandSessionData(SessionData->Clone());
  4869. CommandSessionData->RemoteDirectory = CurrentDirectory;
  4870. CommandSessionData->FSProtocol = fsSCPonly;
  4871. CommandSessionData->ClearAliases = false;
  4872. CommandSessionData->UnsetNationalVars = false;
  4873. CommandSessionData->LookupUserGroups = asOff;
  4874. FCommandSession = CreateSecondarySession(L"Shell", CommandSessionData.get());
  4875. FCommandSession->AutoReadDirectory = false;
  4876. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  4877. FCommandSession->OnQueryUser = OnQueryUser;
  4878. FCommandSession->OnPromptUser = OnPromptUser;
  4879. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  4880. FCommandSession->OnProgress = OnProgress;
  4881. FCommandSession->OnFinished = OnFinished;
  4882. FCommandSession->OnInformation = OnInformation;
  4883. FCommandSession->OnCustomCommand = OnCustomCommand;
  4884. // do not copy OnDisplayBanner to avoid it being displayed
  4885. }
  4886. return FCommandSession;
  4887. }
  4888. //---------------------------------------------------------------------------
  4889. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  4890. TCaptureOutputEvent OutputEvent)
  4891. {
  4892. #pragma warn -inl
  4893. class TOutputProxy
  4894. {
  4895. public:
  4896. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  4897. FAction(Action),
  4898. FOutputEvent(OutputEvent)
  4899. {
  4900. }
  4901. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  4902. {
  4903. switch (OutputType)
  4904. {
  4905. case cotOutput:
  4906. FAction.AddOutput(Str, false);
  4907. break;
  4908. case cotError:
  4909. FAction.AddOutput(Str, true);
  4910. break;
  4911. case cotExitCode:
  4912. FAction.ExitCode(StrToInt(Str));
  4913. break;
  4914. }
  4915. if (FOutputEvent != NULL)
  4916. {
  4917. FOutputEvent(Str, OutputType);
  4918. }
  4919. }
  4920. private:
  4921. TCallSessionAction & FAction;
  4922. TCaptureOutputEvent FOutputEvent;
  4923. };
  4924. #pragma warn .inl
  4925. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  4926. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  4927. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  4928. }
  4929. //---------------------------------------------------------------------------
  4930. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  4931. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  4932. {
  4933. DebugAssert(FFileSystem);
  4934. try
  4935. {
  4936. DirectoryModified(CurrentDirectory, false);
  4937. LogEvent(L"Executing user defined command.");
  4938. TCustomFileSystem * FileSystem = GetFileSystemForCapability(fcAnyCommand);
  4939. FileSystem->AnyCommand(Command, OutputEvent);
  4940. if (CommandSessionOpened && (FileSystem == FCommandSession->FFileSystem))
  4941. {
  4942. FCommandSession->FFileSystem->ReadCurrentDirectory();
  4943. // synchronize pwd (by purpose we lose transaction optimization here)
  4944. ChangeDirectory(FCommandSession->CurrentDirectory);
  4945. }
  4946. ReactOnCommand(fsAnyCommand);
  4947. }
  4948. catch (Exception &E)
  4949. {
  4950. if (Action != NULL)
  4951. {
  4952. RollbackAction(*Action, NULL, &E);
  4953. }
  4954. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  4955. else HandleExtendedException(&E);
  4956. }
  4957. }
  4958. //---------------------------------------------------------------------------
  4959. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  4960. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4961. bool NoConfirmation)
  4962. {
  4963. bool Result = true;
  4964. bool Done;
  4965. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  4966. do
  4967. {
  4968. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  4969. NULL, CREATE_ALWAYS, CreateAttr, 0);
  4970. Done = (*AHandle != INVALID_HANDLE_VALUE);
  4971. if (!Done)
  4972. {
  4973. // save the error, otherwise it gets overwritten by call to FileExists
  4974. int LastError = GetLastError();
  4975. int FileAttr;
  4976. if (::FileExists(ApiPath(FileName)) &&
  4977. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  4978. {
  4979. if (FLAGSET(FileAttr, faReadOnly))
  4980. {
  4981. OperationProgress->LockUserSelections();
  4982. try
  4983. {
  4984. if (OperationProgress->BatchOverwrite == boNone)
  4985. {
  4986. Result = false;
  4987. }
  4988. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4989. {
  4990. unsigned int Answer;
  4991. {
  4992. TSuspendFileOperationProgress Suspend(OperationProgress);
  4993. Answer = QueryUser(
  4994. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4995. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4996. }
  4997. switch (Answer) {
  4998. case qaYesToAll: OperationProgress->SetBatchOverwrite(boAll); break;
  4999. case qaCancel: OperationProgress->SetCancel(csCancel); // continue on next case
  5000. case qaNoToAll: OperationProgress->SetBatchOverwrite(boNone);
  5001. case qaNo: Result = false; break;
  5002. }
  5003. }
  5004. }
  5005. __finally
  5006. {
  5007. OperationProgress->UnlockUserSelections();
  5008. }
  5009. }
  5010. else
  5011. {
  5012. DebugAssert(FLAGSET(FileAttr, faHidden));
  5013. Result = true;
  5014. }
  5015. if (Result)
  5016. {
  5017. CreateAttr |=
  5018. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  5019. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  5020. FILE_OPERATION_LOOP_BEGIN
  5021. {
  5022. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  5023. {
  5024. RaiseLastOSError();
  5025. }
  5026. }
  5027. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  5028. }
  5029. else
  5030. {
  5031. Done = true;
  5032. }
  5033. }
  5034. else
  5035. {
  5036. RaiseLastOSError(LastError);
  5037. }
  5038. }
  5039. }
  5040. while (!Done);
  5041. return Result;
  5042. }
  5043. //---------------------------------------------------------------------------
  5044. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  5045. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  5046. bool NoConfirmation)
  5047. {
  5048. DebugAssert(AHandle);
  5049. bool Result = true;
  5050. FILE_OPERATION_LOOP_BEGIN
  5051. {
  5052. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  5053. }
  5054. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  5055. return Result;
  5056. }
  5057. //---------------------------------------------------------------------------
  5058. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  5059. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  5060. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  5061. bool TryWriteReadOnly)
  5062. {
  5063. int Attrs = 0;
  5064. HANDLE Handle = 0;
  5065. FILE_OPERATION_LOOP_BEGIN
  5066. {
  5067. UnicodeString FileNameApi = ApiPath(FileName);
  5068. Attrs = FileGetAttrFix(FileNameApi);
  5069. if (Attrs < 0)
  5070. {
  5071. RaiseLastOSError();
  5072. }
  5073. }
  5074. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  5075. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  5076. {
  5077. bool NoHandle = false;
  5078. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  5079. ((Attrs & faReadOnly) != 0))
  5080. {
  5081. Access = GENERIC_READ;
  5082. NoHandle = true;
  5083. }
  5084. FILE_OPERATION_LOOP_BEGIN
  5085. {
  5086. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  5087. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  5088. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  5089. NULL, OPEN_EXISTING, Flags, 0);
  5090. if (Handle == INVALID_HANDLE_VALUE)
  5091. {
  5092. Handle = 0;
  5093. RaiseLastOSError();
  5094. }
  5095. }
  5096. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  5097. try
  5098. {
  5099. if (AATime || AMTime || ACTime)
  5100. {
  5101. FILETIME ATime;
  5102. FILETIME MTime;
  5103. FILETIME CTime;
  5104. // Get last file access and modification time
  5105. FILE_OPERATION_LOOP_BEGIN
  5106. {
  5107. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  5108. }
  5109. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  5110. if (ACTime)
  5111. {
  5112. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  5113. }
  5114. if (AATime)
  5115. {
  5116. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  5117. }
  5118. if (AMTime)
  5119. {
  5120. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  5121. }
  5122. }
  5123. if (ASize)
  5124. {
  5125. // Get file size
  5126. FILE_OPERATION_LOOP_BEGIN
  5127. {
  5128. unsigned long LSize;
  5129. unsigned long HSize;
  5130. LSize = GetFileSize(Handle, &HSize);
  5131. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  5132. *ASize = (__int64(HSize) << 32) + LSize;
  5133. }
  5134. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  5135. }
  5136. if ((AHandle == NULL) || NoHandle)
  5137. {
  5138. CloseHandle(Handle);
  5139. Handle = NULL;
  5140. }
  5141. }
  5142. catch(...)
  5143. {
  5144. CloseHandle(Handle);
  5145. throw;
  5146. }
  5147. }
  5148. if (AAttrs) *AAttrs = Attrs;
  5149. if (AHandle) *AHandle = Handle;
  5150. }
  5151. //---------------------------------------------------------------------------
  5152. void __fastcall TTerminal::OpenLocalFile(
  5153. const UnicodeString & FileName, unsigned int Access, TLocalFileHandle & Handle, bool TryWriteReadOnly)
  5154. {
  5155. Handle.FileName = FileName;
  5156. OpenLocalFile(
  5157. FileName, Access, &Handle.Attrs, &Handle.Handle, NULL, &Handle.MTime, &Handle.ATime, &Handle.Size,
  5158. TryWriteReadOnly);
  5159. Handle.Modification = UnixToDateTime(Handle.MTime, SessionData->DSTMode);
  5160. Handle.Directory = FLAGSET(Handle.Attrs, faDirectory);
  5161. }
  5162. //---------------------------------------------------------------------------
  5163. bool __fastcall TTerminal::DoAllowLocalFileTransfer(
  5164. const UnicodeString & FileName, const TSearchRecSmart & SearchRec, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5165. {
  5166. TFileMasks::TParams Params;
  5167. Params.Size = SearchRec.Size;
  5168. Params.Modification = SearchRec.GetLastWriteTime();
  5169. UnicodeString BaseFileName = GetBaseFileName(FileName);
  5170. // Note that for synchronization, we do not need to check "TSynchronizeOptions::MatchesFilter" here as
  5171. // that is checked for top-level entries only and we are never top-level here.
  5172. return
  5173. CopyParam->AllowTransfer(BaseFileName, osLocal, SearchRec.IsDirectory(), Params, SearchRec.IsHidden()) &&
  5174. (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(FileName)) &&
  5175. (!SearchRec.IsDirectory() || !CopyParam->ExcludeEmptyDirectories ||
  5176. !IsEmptyLocalDirectory(FileName, CopyParam, DisallowTemporaryTransferFiles));
  5177. }
  5178. //---------------------------------------------------------------------------
  5179. bool __fastcall TTerminal::DoAllowRemoteFileTransfer(
  5180. const TRemoteFile * File, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5181. {
  5182. TFileMasks::TParams MaskParams;
  5183. MaskParams.Size = File->Resolve()->Size;
  5184. MaskParams.Modification = File->Modification;
  5185. UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5186. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  5187. return
  5188. CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams, File->IsHidden) &&
  5189. (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(File->FileName)) &&
  5190. (!File->IsDirectory || !CopyParam->ExcludeEmptyDirectories ||
  5191. !IsEmptyRemoteDirectory(File, CopyParam, DisallowTemporaryTransferFiles));
  5192. }
  5193. //---------------------------------------------------------------------------
  5194. bool __fastcall TTerminal::AllowLocalFileTransfer(
  5195. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  5196. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  5197. {
  5198. bool Result = true;
  5199. // optimization (though in most uses of the method, the caller actually knows TSearchRec already, so it passes it here
  5200. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  5201. {
  5202. TSearchRecSmart ASearchRec;
  5203. if (SearchRec == NULL)
  5204. {
  5205. if (CopyParam->OnTransferIn != NULL)
  5206. {
  5207. ASearchRec.Clear();
  5208. }
  5209. else
  5210. {
  5211. FILE_OPERATION_LOOP_BEGIN
  5212. {
  5213. if (!FileSearchRec(FileName, ASearchRec))
  5214. {
  5215. RaiseLastOSError();
  5216. }
  5217. }
  5218. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  5219. }
  5220. SearchRec = &ASearchRec;
  5221. }
  5222. if (!DoAllowLocalFileTransfer(FileName, *SearchRec, CopyParam, false))
  5223. {
  5224. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  5225. Result = false;
  5226. }
  5227. else if (CopyParam->SkipTransfer(FileName, SearchRec->IsDirectory()))
  5228. {
  5229. OperationProgress->AddSkippedFileSize(SearchRec->Size);
  5230. Result = false;
  5231. }
  5232. if (Result)
  5233. {
  5234. LogFileDetails(FileName, SearchRec->GetLastWriteTime(), SearchRec->Size);
  5235. }
  5236. }
  5237. return Result;
  5238. }
  5239. //---------------------------------------------------------------------------
  5240. void __fastcall TTerminal::MakeLocalFileList(
  5241. const UnicodeString & FileName, const TSearchRecSmart & Rec, void * Param)
  5242. {
  5243. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  5244. if (Rec.IsDirectory() && Params.Recursive)
  5245. {
  5246. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  5247. }
  5248. if (!Rec.IsDirectory() || Params.IncludeDirs)
  5249. {
  5250. Params.FileList->Add(FileName);
  5251. if (Params.FileTimes != NULL)
  5252. {
  5253. Params.FileTimes->push_back(const_cast<TSearchRecSmart &>(Rec).TimeStamp);
  5254. }
  5255. }
  5256. }
  5257. //---------------------------------------------------------------------------
  5258. void __fastcall TTerminal::CalculateLocalFileSize(
  5259. const UnicodeString & FileName, const TSearchRecSmart & Rec, /*TCalculateSizeParams*/ void * Params)
  5260. {
  5261. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  5262. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  5263. {
  5264. AParams->Result = false;
  5265. }
  5266. else
  5267. {
  5268. try
  5269. {
  5270. if ((AParams->CopyParam == NULL) ||
  5271. DoAllowLocalFileTransfer(FileName, Rec, AParams->CopyParam, false))
  5272. {
  5273. int CollectionIndex = -1;
  5274. if (AParams->Files != NULL)
  5275. {
  5276. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5277. CollectionIndex = AParams->Files->Add(FullFileName, NULL, Rec.IsDirectory());
  5278. }
  5279. if (!Rec.IsDirectory())
  5280. {
  5281. AParams->Size += Rec.Size;
  5282. }
  5283. else
  5284. {
  5285. try
  5286. {
  5287. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  5288. }
  5289. catch (...)
  5290. {
  5291. if (CollectionIndex >= 0)
  5292. {
  5293. AParams->Files->DidNotRecurse(CollectionIndex);
  5294. }
  5295. }
  5296. }
  5297. }
  5298. }
  5299. catch (...)
  5300. {
  5301. // ignore
  5302. }
  5303. }
  5304. }
  5305. //---------------------------------------------------------------------------
  5306. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  5307. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs, TStrings * Files,
  5308. TCalculatedSizes * CalculatedSizes)
  5309. {
  5310. bool Result = false;
  5311. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5312. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5313. OperationStart(OperationProgress, foCalculateSize, osLocal, FileList->Count);
  5314. try
  5315. {
  5316. TCalculateSizeParams Params;
  5317. Params.Size = 0;
  5318. Params.Params = 0;
  5319. Params.CopyParam = CopyParam;
  5320. Params.Files = NULL;
  5321. Params.Result = true;
  5322. UnicodeString LastDirPath;
  5323. for (int Index = 0; Params.Result && (Index < FileList->Count); Index++)
  5324. {
  5325. UnicodeString FileName = FileList->Strings[Index];
  5326. TSearchRecSmart Rec;
  5327. if (FileSearchRec(FileName, Rec))
  5328. {
  5329. if (Rec.IsDirectory() && !AllowDirs)
  5330. {
  5331. Params.Result = false;
  5332. }
  5333. else
  5334. {
  5335. if (Files != NULL)
  5336. {
  5337. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5338. UnicodeString DirPath = ExtractFilePath(FullFileName);
  5339. if (DirPath != LastDirPath)
  5340. {
  5341. Params.Files = new TCollectedFileList();
  5342. LastDirPath = DirPath;
  5343. Files->AddObject(LastDirPath, Params.Files);
  5344. }
  5345. }
  5346. __int64 PrevSize = Params.Size;
  5347. CalculateLocalFileSize(FileName, Rec, &Params);
  5348. if (CalculatedSizes != NULL)
  5349. {
  5350. __int64 Size = Params.Size - PrevSize;
  5351. CalculatedSizes->push_back(Size);
  5352. }
  5353. OperationFinish(&OperationProgress, FileList->Objects[Index], FileName, true, OnceDoneOperation);
  5354. }
  5355. }
  5356. }
  5357. Size = Params.Size;
  5358. Result = Params.Result;
  5359. }
  5360. __finally
  5361. {
  5362. OperationStop(OperationProgress);
  5363. }
  5364. if (Configuration->ActualLogProtocol >= 1)
  5365. {
  5366. LogEvent(FORMAT(L"Size of %d local files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
  5367. }
  5368. if (OnceDoneOperation != odoIdle)
  5369. {
  5370. CloseOnCompletion(OnceDoneOperation);
  5371. }
  5372. return Result;
  5373. }
  5374. //---------------------------------------------------------------------------
  5375. struct TSynchronizeFileData
  5376. {
  5377. bool Modified;
  5378. bool New;
  5379. bool IsDirectory;
  5380. TSynchronizeChecklist::TItem::TFileInfo Info;
  5381. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  5382. TRemoteFile * MatchingRemoteFileFile;
  5383. int MatchingRemoteFileImageIndex;
  5384. FILETIME LocalLastWriteTime;
  5385. };
  5386. //---------------------------------------------------------------------------
  5387. const int sfFirstLevel = 0x01;
  5388. struct TSynchronizeData
  5389. {
  5390. UnicodeString LocalDirectory;
  5391. UnicodeString RemoteDirectory;
  5392. TTerminal::TSynchronizeMode Mode;
  5393. int Params;
  5394. TSynchronizeDirectory OnSynchronizeDirectory;
  5395. TSynchronizeOptions * Options;
  5396. int Flags;
  5397. TStringList * LocalFileList;
  5398. const TCopyParamType * CopyParam;
  5399. TSynchronizeChecklist * Checklist;
  5400. };
  5401. //---------------------------------------------------------------------------
  5402. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  5403. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5404. const TCopyParamType * CopyParam, int Params,
  5405. TSynchronizeDirectory OnSynchronizeDirectory,
  5406. TSynchronizeOptions * Options)
  5407. {
  5408. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  5409. FUseBusyCursor = false;
  5410. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  5411. try
  5412. {
  5413. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  5414. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  5415. Checklist);
  5416. Checklist->Sort();
  5417. }
  5418. catch(...)
  5419. {
  5420. delete Checklist;
  5421. throw;
  5422. }
  5423. return Checklist;
  5424. }
  5425. //---------------------------------------------------------------------------
  5426. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  5427. {
  5428. if (FLAGSET(Params, Param))
  5429. {
  5430. AddToList(ParamsStr, Name, ", ");
  5431. }
  5432. Params &= ~Param;
  5433. }
  5434. //---------------------------------------------------------------------------
  5435. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  5436. {
  5437. UnicodeString ModeStr;
  5438. switch (Mode)
  5439. {
  5440. case smRemote:
  5441. ModeStr = L"Remote";
  5442. break;
  5443. case smLocal:
  5444. ModeStr = L"Local";
  5445. break;
  5446. case smBoth:
  5447. ModeStr = L"Both";
  5448. break;
  5449. default:
  5450. ModeStr = L"Unknown";
  5451. break;
  5452. }
  5453. return ModeStr;
  5454. }
  5455. //---------------------------------------------------------------------------
  5456. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  5457. {
  5458. UnicodeString ParamsStr;
  5459. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  5460. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  5461. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  5462. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  5463. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  5464. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  5465. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  5466. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  5467. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  5468. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  5469. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  5470. AddFlagName(ParamsStr, Params, spCaseSensitive, L"CaseSensitive");
  5471. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  5472. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  5473. if (Params > 0)
  5474. {
  5475. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  5476. }
  5477. return ParamsStr;
  5478. }
  5479. //---------------------------------------------------------------------------
  5480. bool __fastcall TTerminal::LocalFindFirstLoop(const UnicodeString & Path, TSearchRecChecked & SearchRec)
  5481. {
  5482. bool Result;
  5483. FILE_OPERATION_LOOP_BEGIN
  5484. {
  5485. const int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  5486. Result = (FindFirstChecked(Path, FindAttrs, SearchRec) == 0);
  5487. }
  5488. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (Path)));
  5489. return Result;
  5490. }
  5491. //---------------------------------------------------------------------------
  5492. bool __fastcall TTerminal::LocalFindNextLoop(TSearchRecChecked & SearchRec)
  5493. {
  5494. bool Result;
  5495. FILE_OPERATION_LOOP_BEGIN
  5496. {
  5497. Result = (FindNextChecked(SearchRec) == 0);
  5498. }
  5499. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (SearchRec.Path)));
  5500. return Result;
  5501. }
  5502. //---------------------------------------------------------------------------
  5503. bool __fastcall TTerminal::IsEmptyLocalDirectory(
  5504. const UnicodeString & Path, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5505. {
  5506. UnicodeString Contents;
  5507. if (Configuration->ActualLogProtocol >= 1)
  5508. {
  5509. LogEvent(FORMAT(L"Checking if local directory \"%s\" is empty", (Path)));
  5510. }
  5511. TSearchRecOwned SearchRec;
  5512. if (LocalFindFirstLoop(IncludeTrailingBackslash(Path) + L"*.*", SearchRec))
  5513. {
  5514. do
  5515. {
  5516. UnicodeString FullLocalFileName = IncludeTrailingBackslash(Path) + SearchRec.Name;
  5517. if (SearchRec.IsRealFile() &&
  5518. DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true))
  5519. {
  5520. if (!SearchRec.IsDirectory() ||
  5521. !IsEmptyLocalDirectory(FullLocalFileName, CopyParam, DisallowTemporaryTransferFiles))
  5522. {
  5523. Contents = SearchRec.Name;
  5524. }
  5525. }
  5526. }
  5527. while (Contents.IsEmpty() && LocalFindNextLoop(SearchRec));
  5528. }
  5529. if (Configuration->ActualLogProtocol >= 1)
  5530. {
  5531. if (Contents.IsEmpty())
  5532. {
  5533. LogEvent(FORMAT(L"Local directory \"%s\" is empty", (Path)));
  5534. }
  5535. else
  5536. {
  5537. LogEvent(FORMAT(L"Local directory \"%s\" is not empty, it contains \"%s\"", (Path, Contents)));
  5538. }
  5539. }
  5540. return Contents.IsEmpty();
  5541. }
  5542. //---------------------------------------------------------------------------
  5543. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  5544. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5545. const TCopyParamType * CopyParam, int Params,
  5546. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  5547. int Flags, TSynchronizeChecklist * Checklist)
  5548. {
  5549. TSynchronizeData Data;
  5550. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  5551. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  5552. Data.Mode = Mode;
  5553. Data.Params = Params;
  5554. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5555. Data.LocalFileList = NULL;
  5556. Data.CopyParam = CopyParam;
  5557. Data.Options = Options;
  5558. Data.Flags = Flags;
  5559. Data.Checklist = Checklist;
  5560. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  5561. "mode = %s, params = 0x%x (%s), file mask = '%s'", (LocalDirectory, RemoteDirectory,
  5562. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params), CopyParam->IncludeFileMask.Masks)));
  5563. if (FLAGCLEAR(Params, spDelayProgress))
  5564. {
  5565. DoSynchronizeProgress(Data, true);
  5566. }
  5567. try
  5568. {
  5569. Data.LocalFileList = CreateSortedStringList(FLAGSET(Params, spCaseSensitive));
  5570. TSearchRecOwned SearchRec;
  5571. if (LocalFindFirstLoop(Data.LocalDirectory + L"*.*", SearchRec))
  5572. {
  5573. do
  5574. {
  5575. UnicodeString FileName = SearchRec.Name;
  5576. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  5577. UnicodeString RemoteFileName = ChangeFileName(CopyParam, FileName, osLocal, false);
  5578. if (SearchRec.IsRealFile() &&
  5579. DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true) &&
  5580. (FLAGCLEAR(Flags, sfFirstLevel) ||
  5581. (Options == NULL) ||
  5582. Options->MatchesFilter(FileName) ||
  5583. Options->MatchesFilter(RemoteFileName)))
  5584. {
  5585. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  5586. FileData->IsDirectory = SearchRec.IsDirectory();
  5587. FileData->Info.FileName = FileName;
  5588. FileData->Info.Directory = Data.LocalDirectory;
  5589. FileData->Info.Modification = SearchRec.GetLastWriteTime();
  5590. FileData->Info.ModificationFmt = mfFull;
  5591. FileData->Info.Size = SearchRec.Size;
  5592. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  5593. FileData->New = true;
  5594. FileData->Modified = false;
  5595. Data.LocalFileList->AddObject(FileName, reinterpret_cast<TObject*>(FileData));
  5596. LogEvent(0, FORMAT(L"Local file %s included to synchronization",
  5597. (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
  5598. }
  5599. else
  5600. {
  5601. LogEvent(0, FORMAT(L"Local file %s excluded from synchronization",
  5602. (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
  5603. }
  5604. }
  5605. while (LocalFindNextLoop(SearchRec));
  5606. SearchRec.Close();
  5607. // can we expect that ProcessDirectory would take so little time
  5608. // that we can postpone showing progress window until anything actually happens?
  5609. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  5610. FDirectoryCache->HasFileList(RemoteDirectory);
  5611. if (!Cached && FLAGSET(Params, spDelayProgress))
  5612. {
  5613. DoSynchronizeProgress(Data, true);
  5614. }
  5615. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  5616. FLAGSET(Params, spUseCache));
  5617. TSynchronizeFileData * FileData;
  5618. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5619. {
  5620. FileData = reinterpret_cast<TSynchronizeFileData *>
  5621. (Data.LocalFileList->Objects[Index]);
  5622. // add local file either if we are going to upload it
  5623. // (i.e. if it is updated or we want to upload even new files)
  5624. // or if we are going to delete it (i.e. all "new"=obsolete files)
  5625. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  5626. bool New = (FileData->New &&
  5627. ((Mode == smLocal) ||
  5628. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  5629. if (New)
  5630. {
  5631. LogEvent(FORMAT(L"Local file %s is new",
  5632. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  5633. FileData->Info.Modification, FileData->Info.Size))));
  5634. }
  5635. if (Modified || New)
  5636. {
  5637. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5638. try
  5639. {
  5640. ChecklistItem->IsDirectory = FileData->IsDirectory;
  5641. ChecklistItem->Local = FileData->Info;
  5642. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  5643. if (Modified)
  5644. {
  5645. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  5646. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  5647. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  5648. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  5649. }
  5650. else
  5651. {
  5652. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  5653. }
  5654. if ((Mode == smBoth) || (Mode == smRemote))
  5655. {
  5656. ChecklistItem->Action =
  5657. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  5658. ChecklistItem->Checked =
  5659. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  5660. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5661. FLAGSET(Params, spSubDirs));
  5662. }
  5663. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  5664. {
  5665. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  5666. ChecklistItem->Checked =
  5667. FLAGSET(Params, spDelete) &&
  5668. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5669. FLAGSET(Params, spSubDirs));
  5670. }
  5671. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5672. {
  5673. Data.Checklist->Add(ChecklistItem);
  5674. ChecklistItem = NULL;
  5675. }
  5676. }
  5677. __finally
  5678. {
  5679. delete ChecklistItem;
  5680. }
  5681. }
  5682. else
  5683. {
  5684. if (FileData->Modified)
  5685. {
  5686. delete FileData->MatchingRemoteFileFile;
  5687. }
  5688. }
  5689. }
  5690. }
  5691. }
  5692. __finally
  5693. {
  5694. if (Data.LocalFileList != NULL)
  5695. {
  5696. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5697. {
  5698. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  5699. (Data.LocalFileList->Objects[Index]);
  5700. delete FileData;
  5701. }
  5702. delete Data.LocalFileList;
  5703. }
  5704. }
  5705. }
  5706. //---------------------------------------------------------------------------
  5707. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  5708. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5709. {
  5710. try
  5711. {
  5712. DoSynchronizeCollectFile(FileName, File, Param);
  5713. }
  5714. catch(ESkipFile & E)
  5715. {
  5716. TSuspendFileOperationProgress Suspend(OperationProgress);
  5717. if (!HandleException(&E))
  5718. {
  5719. throw;
  5720. }
  5721. }
  5722. }
  5723. //---------------------------------------------------------------------------
  5724. bool __fastcall TTerminal::IsEmptyRemoteDirectory(
  5725. const TRemoteFile * File, const TCopyParamType * ACopyParam, bool DisallowTemporaryTransferFiles)
  5726. {
  5727. TCalculateSizeStats Stats;
  5728. TCopyParamType CopyParam(*ACopyParam);
  5729. CopyParam.ExcludeEmptyDirectories = false; // to avoid endless recursion
  5730. TCalculateSizeParams Params;
  5731. Params.Params = csStopOnFirstFile | csIgnoreErrors | FLAGMASK(DisallowTemporaryTransferFiles, csDisallowTemporaryTransferFiles);
  5732. Params.CopyParam = &CopyParam;
  5733. Params.Stats = &Stats;
  5734. DoCalculateDirectorySize(UnixExcludeTrailingBackslash(File->FullFileName), &Params);
  5735. return Params.Result && (Stats.Files == 0);
  5736. }
  5737. //---------------------------------------------------------------------------
  5738. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  5739. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5740. {
  5741. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  5742. // Can be NULL in scripting
  5743. if (Data->Options != NULL)
  5744. {
  5745. Data->Options->Files++;
  5746. }
  5747. UnicodeString LocalFileName = ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  5748. UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5749. if (DoAllowRemoteFileTransfer(File, Data->CopyParam, true) &&
  5750. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  5751. (Data->Options == NULL) ||
  5752. Data->Options->MatchesFilter(File->FileName) ||
  5753. Data->Options->MatchesFilter(LocalFileName)))
  5754. {
  5755. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5756. try
  5757. {
  5758. ChecklistItem->IsDirectory = File->IsDirectory;
  5759. ChecklistItem->ImageIndex = File->IconIndex;
  5760. ChecklistItem->Remote.FileName = File->FileName;
  5761. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  5762. ChecklistItem->Remote.Modification = File->Modification;
  5763. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  5764. ChecklistItem->Remote.Size = File->Resolve()->Size;
  5765. bool Modified = false;
  5766. bool New = false;
  5767. if (File->IsDirectory && !CanRecurseToDirectory(File))
  5768. {
  5769. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  5770. }
  5771. else
  5772. {
  5773. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  5774. New = (LocalIndex < 0);
  5775. if (!New)
  5776. {
  5777. TSynchronizeFileData * LocalData =
  5778. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  5779. LocalData->New = false;
  5780. if (File->IsDirectory != LocalData->IsDirectory)
  5781. {
  5782. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  5783. (File->FileName)));
  5784. }
  5785. else if (!File->IsDirectory)
  5786. {
  5787. ChecklistItem->Local = LocalData->Info;
  5788. ChecklistItem->Local.Modification =
  5789. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  5790. bool LocalModified = false;
  5791. // for spTimestamp+spBySize require that the file sizes are the same
  5792. // before comparing file time
  5793. int TimeCompare;
  5794. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  5795. (FLAGCLEAR(Data->Params, spTimestamp) ||
  5796. FLAGCLEAR(Data->Params, spBySize) ||
  5797. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  5798. {
  5799. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  5800. ChecklistItem->Remote.Modification);
  5801. }
  5802. else
  5803. {
  5804. TimeCompare = 0;
  5805. }
  5806. if (TimeCompare < 0)
  5807. {
  5808. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  5809. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  5810. {
  5811. Modified = true;
  5812. }
  5813. else
  5814. {
  5815. LocalModified = true;
  5816. }
  5817. }
  5818. else if (TimeCompare > 0)
  5819. {
  5820. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  5821. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  5822. {
  5823. LocalModified = true;
  5824. }
  5825. else
  5826. {
  5827. Modified = true;
  5828. }
  5829. }
  5830. else if (FLAGSET(Data->Params, spBySize) &&
  5831. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  5832. FLAGCLEAR(Data->Params, spTimestamp))
  5833. {
  5834. Modified = true;
  5835. LocalModified = true;
  5836. }
  5837. if (LocalModified)
  5838. {
  5839. LocalData->Modified = true;
  5840. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  5841. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  5842. // we need this for custom commands over checklist only,
  5843. // not for sync itself
  5844. LocalData->MatchingRemoteFileFile = File->Duplicate();
  5845. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  5846. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  5847. LocalData->Info.Modification, LocalData->Info.Size),
  5848. FormatFileDetailsForLog(FullRemoteFileName,
  5849. File->Modification, File->Size, File->LinkedFile))));
  5850. }
  5851. if (Modified)
  5852. {
  5853. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  5854. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile),
  5855. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  5856. LocalData->Info.Modification, LocalData->Info.Size))));
  5857. }
  5858. }
  5859. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  5860. {
  5861. DoSynchronizeCollectDirectory(
  5862. Data->LocalDirectory + LocalData->Info.FileName,
  5863. Data->RemoteDirectory + File->FileName,
  5864. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  5865. Data->Options, (Data->Flags & ~sfFirstLevel),
  5866. Data->Checklist);
  5867. }
  5868. }
  5869. else
  5870. {
  5871. ChecklistItem->Local.Directory = Data->LocalDirectory;
  5872. LogEvent(FORMAT(L"Remote file %s is new",
  5873. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  5874. }
  5875. }
  5876. if (New || Modified)
  5877. {
  5878. DebugAssert(!New || !Modified);
  5879. // download the file if it changed or is new and we want to have it locally
  5880. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  5881. {
  5882. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  5883. {
  5884. ChecklistItem->Action =
  5885. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  5886. ChecklistItem->Checked =
  5887. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  5888. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  5889. FLAGSET(Data->Params, spSubDirs));
  5890. }
  5891. }
  5892. else if ((Data->Mode == smRemote) && New)
  5893. {
  5894. if (FLAGCLEAR(Data->Params, spTimestamp))
  5895. {
  5896. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  5897. ChecklistItem->Checked =
  5898. FLAGSET(Data->Params, spDelete) &&
  5899. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  5900. FLAGSET(Data->Params, spSubDirs));
  5901. }
  5902. }
  5903. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5904. {
  5905. ChecklistItem->RemoteFile = File->Duplicate();
  5906. Data->Checklist->Add(ChecklistItem);
  5907. ChecklistItem = NULL;
  5908. }
  5909. }
  5910. }
  5911. __finally
  5912. {
  5913. delete ChecklistItem;
  5914. }
  5915. }
  5916. else
  5917. {
  5918. LogEvent(0, FORMAT(L"Remote file %s excluded from synchronization",
  5919. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  5920. }
  5921. }
  5922. //---------------------------------------------------------------------------
  5923. void __fastcall TTerminal::SynchronizeApply(
  5924. TSynchronizeChecklist * Checklist,
  5925. const TCopyParamType * CopyParam, int Params,
  5926. TSynchronizeDirectory OnSynchronizeDirectory, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5927. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems, void * Token,
  5928. TFileOperationStatistics * Statistics)
  5929. {
  5930. TSynchronizeData Data;
  5931. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5932. int CopyParams =
  5933. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  5934. TCopyParamType SyncCopyParam = *CopyParam;
  5935. // when synchronizing by time, we force preserving time,
  5936. // otherwise it does not make any sense
  5937. if (FLAGCLEAR(Params, spNotByTime))
  5938. {
  5939. SyncCopyParam.PreserveTime = true;
  5940. }
  5941. if (SyncCopyParam.CalculateSize)
  5942. {
  5943. // If we fail to collect the sizes, do not try again during an actual transfer
  5944. SyncCopyParam.CalculateSize = false;
  5945. TSynchronizeChecklist::TItemList Items;
  5946. for (int Index = 0; Index < Checklist->Count; Index++)
  5947. {
  5948. const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
  5949. // TSynchronizeChecklistDialog relies on us not to update a size of an item that had size already
  5950. // See TSynchronizeChecklistDialog::UpdatedSynchronizationChecklistItems
  5951. if (ChecklistItem->Checked && !TSynchronizeChecklist::IsItemSizeIrrelevant(ChecklistItem->Action) &&
  5952. !ChecklistItem->HasSize() && DebugAlwaysTrue(ChecklistItem->IsDirectory))
  5953. {
  5954. Items.push_back(ChecklistItem);
  5955. }
  5956. }
  5957. SynchronizeChecklistCalculateSize(Checklist, Items, &SyncCopyParam);
  5958. if (OnUpdatedSynchronizationChecklistItems != NULL)
  5959. {
  5960. OnUpdatedSynchronizationChecklistItems(Items);
  5961. }
  5962. }
  5963. BeginTransaction();
  5964. TValueRestorer<TFileOperationProgressType::TPersistence *> OperationProgressPersistenceRestorer(FOperationProgressPersistence);
  5965. TValueRestorer<TOnceDoneOperation> OperationProgressOnceDoneOperationRestorer(FOperationProgressOnceDoneOperation);
  5966. TFileOperationProgressType::TPersistence OperationProgressPersistence;
  5967. OperationProgressPersistence.Statistics = Statistics;
  5968. FOperationProgressPersistence = &OperationProgressPersistence;
  5969. try
  5970. {
  5971. int Index = 0;
  5972. while (Index < Checklist->Count)
  5973. {
  5974. const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
  5975. if (ChecklistItem->Checked)
  5976. {
  5977. if (!SamePaths(Data.LocalDirectory, ChecklistItem->Local.Directory) ||
  5978. !UnixSamePath(Data.RemoteDirectory, ChecklistItem->Remote.Directory))
  5979. {
  5980. Data.LocalDirectory = IncludeTrailingBackslash(ChecklistItem->Local.Directory);
  5981. Data.RemoteDirectory = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory);
  5982. LogEvent(
  5983. FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', params = 0x%x (%s)",
  5984. (Data.LocalDirectory, Data.RemoteDirectory, int(Params), SynchronizeParamsStr(Params))));
  5985. DoSynchronizeProgress(Data, false);
  5986. }
  5987. std::unique_ptr<TStringList> FileList(new TStringList());
  5988. UnicodeString LocalPath = IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName;
  5989. UnicodeString RemotePath = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName;
  5990. bool Result = true;
  5991. if (FLAGSET(Params, spTimestamp))
  5992. {
  5993. // used by SynchronizeLocalTimestamp and SynchronizeRemoteTimestamp
  5994. TObject * ChecklistItemToken = const_cast<TObject *>(reinterpret_cast<const TObject *>(ChecklistItem));
  5995. switch (ChecklistItem->Action)
  5996. {
  5997. case TSynchronizeChecklist::saDownloadUpdate:
  5998. FileList->AddObject(RemotePath, ChecklistItemToken);
  5999. ProcessFiles(FileList.get(), foSetProperties, SynchronizeLocalTimestamp, NULL, osLocal);
  6000. break;
  6001. case TSynchronizeChecklist::saUploadUpdate:
  6002. FileList->AddObject(LocalPath, ChecklistItemToken);
  6003. ProcessFiles(FileList.get(), foSetProperties, SynchronizeRemoteTimestamp);
  6004. break;
  6005. default:
  6006. DebugFail();
  6007. Result = false;
  6008. break;
  6009. }
  6010. }
  6011. else
  6012. {
  6013. TCopyParamType ItemCopyParam = SyncCopyParam;
  6014. ItemCopyParam.Size = ChecklistItem->HasSize() ? ChecklistItem->GetSize() : -1;
  6015. switch (ChecklistItem->Action)
  6016. {
  6017. case TSynchronizeChecklist::saDownloadNew:
  6018. case TSynchronizeChecklist::saDownloadUpdate:
  6019. FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
  6020. Result = CopyToLocal(FileList.get(), Data.LocalDirectory, &ItemCopyParam, CopyParams, NULL);
  6021. break;
  6022. case TSynchronizeChecklist::saDeleteRemote:
  6023. FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
  6024. Result = DeleteFiles(FileList.get());
  6025. break;
  6026. case TSynchronizeChecklist::saUploadNew:
  6027. case TSynchronizeChecklist::saUploadUpdate:
  6028. FileList->Add(LocalPath);
  6029. Result = CopyToRemote(FileList.get(), Data.RemoteDirectory, &ItemCopyParam, CopyParams, NULL);
  6030. break;
  6031. case TSynchronizeChecklist::saDeleteLocal:
  6032. FileList->Add(LocalPath);
  6033. Result = DeleteLocalFiles(FileList.get());
  6034. break;
  6035. default:
  6036. DebugFail();
  6037. Result = false;
  6038. break;
  6039. }
  6040. }
  6041. if (!Result)
  6042. {
  6043. Abort();
  6044. }
  6045. if (OnProcessedItem != NULL)
  6046. {
  6047. OnProcessedItem(Token, ChecklistItem);
  6048. }
  6049. }
  6050. Index++;
  6051. }
  6052. }
  6053. __finally
  6054. {
  6055. EndTransaction();
  6056. }
  6057. if (FOperationProgressOnceDoneOperation != odoIdle)
  6058. {
  6059. // Otherwise CloseOnCompletion would have no effect
  6060. OperationProgressPersistenceRestorer.Release();
  6061. CloseOnCompletion(FOperationProgressOnceDoneOperation);
  6062. }
  6063. }
  6064. //---------------------------------------------------------------------------
  6065. void __fastcall TTerminal::SynchronizeChecklistCalculateSize(
  6066. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items,
  6067. const TCopyParamType * CopyParam)
  6068. {
  6069. std::unique_ptr<TStrings> RemoteFileList(new TStringList());
  6070. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  6071. for (size_t Index = 0; Index < Items.size(); Index++)
  6072. {
  6073. const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
  6074. if (ChecklistItem->IsDirectory)
  6075. {
  6076. if (ChecklistItem->IsRemoteOnly())
  6077. {
  6078. RemoteFileList->AddObject(ChecklistItem->RemoteFile->FullFileName, ChecklistItem->RemoteFile);
  6079. }
  6080. else if (ChecklistItem->IsLocalOnly())
  6081. {
  6082. LocalFileList->Add(IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName);
  6083. }
  6084. else
  6085. {
  6086. // "update" actions are not relevant for directories
  6087. DebugFail();
  6088. }
  6089. }
  6090. }
  6091. TCalculatedSizes RemoteCalculatedSizes;
  6092. TCalculatedSizes LocalCalculatedSizes;
  6093. try
  6094. {
  6095. bool Result = true;
  6096. if (LocalFileList->Count > 0)
  6097. {
  6098. __int64 LocalSize = 0;
  6099. Result = CalculateLocalFilesSize(LocalFileList.get(), LocalSize, CopyParam, true, NULL, &LocalCalculatedSizes);
  6100. }
  6101. if (Result && (RemoteFileList->Count > 0))
  6102. {
  6103. __int64 RemoteSize = 0;
  6104. TCalculateSizeStats RemoteStats;
  6105. RemoteStats.CalculatedSizes = &RemoteCalculatedSizes;
  6106. TCalculateSizeParams Params;
  6107. Params.CopyParam = CopyParam;
  6108. Params.Stats = &RemoteStats;
  6109. CalculateFilesSize(RemoteFileList.get(), RemoteSize, Params);
  6110. }
  6111. }
  6112. __finally
  6113. {
  6114. size_t LocalIndex = 0;
  6115. size_t RemoteIndex = 0;
  6116. for (size_t Index = 0; Index < Items.size(); Index++)
  6117. {
  6118. const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
  6119. if (ChecklistItem->IsDirectory)
  6120. {
  6121. __int64 Size = -1;
  6122. if (ChecklistItem->IsRemoteOnly())
  6123. {
  6124. if (RemoteIndex < RemoteCalculatedSizes.size())
  6125. {
  6126. Size = RemoteCalculatedSizes[RemoteIndex];
  6127. }
  6128. RemoteIndex++;
  6129. }
  6130. else if (ChecklistItem->IsLocalOnly())
  6131. {
  6132. if (LocalIndex < LocalCalculatedSizes.size())
  6133. {
  6134. Size = LocalCalculatedSizes[LocalIndex];
  6135. }
  6136. LocalIndex++;
  6137. }
  6138. else
  6139. {
  6140. // "update" actions are not relevant for directories
  6141. DebugFail();
  6142. }
  6143. if (Size >= 0)
  6144. {
  6145. Checklist->UpdateDirectorySize(ChecklistItem, Size);
  6146. }
  6147. }
  6148. }
  6149. DebugAssert(RemoteIndex >= RemoteCalculatedSizes.size());
  6150. DebugAssert(LocalIndex >= LocalCalculatedSizes.size());
  6151. }
  6152. }
  6153. //---------------------------------------------------------------------------
  6154. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  6155. bool Collect)
  6156. {
  6157. if (Data.OnSynchronizeDirectory != NULL)
  6158. {
  6159. bool Continue = true;
  6160. Data.OnSynchronizeDirectory(
  6161. Data.LocalDirectory, Data.RemoteDirectory, Continue, Collect, Data.Options);
  6162. if (!Continue)
  6163. {
  6164. Abort();
  6165. }
  6166. }
  6167. }
  6168. //---------------------------------------------------------------------------
  6169. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  6170. const TRemoteFile * File, void * /*Param*/)
  6171. {
  6172. const TSynchronizeChecklist::TItem * ChecklistItem =
  6173. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  6174. UnicodeString LocalFile =
  6175. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  6176. ChecklistItem->Local.FileName;
  6177. FILE_OPERATION_LOOP_BEGIN
  6178. {
  6179. HANDLE Handle;
  6180. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  6181. NULL, NULL, NULL, NULL);
  6182. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  6183. SessionData->DSTMode);
  6184. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  6185. int Error = GetLastError();
  6186. CloseHandle(Handle);
  6187. if (!Result)
  6188. {
  6189. RaiseLastOSError(Error);
  6190. }
  6191. }
  6192. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  6193. }
  6194. //---------------------------------------------------------------------------
  6195. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  6196. const TRemoteFile * File, void * /*Param*/)
  6197. {
  6198. const TSynchronizeChecklist::TItem * ChecklistItem =
  6199. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  6200. TRemoteProperties Properties;
  6201. Properties.Valid << vpModification;
  6202. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  6203. SessionData->DSTMode);
  6204. ChangeFileProperties(
  6205. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  6206. NULL, &Properties);
  6207. }
  6208. //---------------------------------------------------------------------------
  6209. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  6210. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  6211. {
  6212. // see DoFilesFind
  6213. FOnFindingFile = NULL;
  6214. DebugAssert(Param);
  6215. DebugAssert(File);
  6216. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  6217. if (!AParams->Cancel)
  6218. {
  6219. if (FileName.IsEmpty())
  6220. {
  6221. FileName = File->FileName;
  6222. }
  6223. TFileMasks::TParams MaskParams;
  6224. MaskParams.Size = File->Resolve()->Size;
  6225. MaskParams.Modification = File->Modification;
  6226. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  6227. bool ImplicitMatch;
  6228. // Do not use recursive include match
  6229. if (AParams->FileMask.Matches(FullFileName, false,
  6230. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  6231. {
  6232. if (!ImplicitMatch)
  6233. {
  6234. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  6235. }
  6236. if (File->IsDirectory)
  6237. {
  6238. UnicodeString RealDirectory;
  6239. if (!File->IsSymLink || File->LinkTo.IsEmpty())
  6240. {
  6241. RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
  6242. }
  6243. else
  6244. {
  6245. RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
  6246. }
  6247. if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
  6248. {
  6249. LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
  6250. }
  6251. else
  6252. {
  6253. DoFilesFind(FullFileName, *AParams, RealDirectory);
  6254. }
  6255. }
  6256. }
  6257. }
  6258. }
  6259. //---------------------------------------------------------------------------
  6260. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
  6261. {
  6262. LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
  6263. Params.OnFindingFile(this, Directory, Params.Cancel);
  6264. if (!Params.Cancel)
  6265. {
  6266. DebugAssert(FOnFindingFile == NULL);
  6267. // ideally we should set the handler only around actually reading
  6268. // of the directory listing, so we at least reset the handler in
  6269. // FileFind
  6270. FOnFindingFile = Params.OnFindingFile;
  6271. UnicodeString PrevRealDirectory = Params.RealDirectory;
  6272. try
  6273. {
  6274. Params.RealDirectory = RealDirectory;
  6275. ProcessDirectory(Directory, FileFind, &Params, false, true);
  6276. }
  6277. __finally
  6278. {
  6279. Params.RealDirectory = PrevRealDirectory;
  6280. FOnFindingFile = NULL;
  6281. }
  6282. }
  6283. }
  6284. //---------------------------------------------------------------------------
  6285. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  6286. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  6287. {
  6288. TFilesFindParams Params;
  6289. Params.FileMask = FileMask;
  6290. Params.FileMask.NoImplicitMatchWithDirExcludeMask = true;
  6291. Params.FileMask.AllDirsAreImplicitlyIncluded = true;
  6292. Params.OnFileFound = OnFileFound;
  6293. Params.OnFindingFile = OnFindingFile;
  6294. Params.Cancel = false;
  6295. Params.LoopDetector.RecordVisitedDirectory(Directory);
  6296. DoFilesFind(Directory, Params, Directory);
  6297. }
  6298. //---------------------------------------------------------------------------
  6299. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  6300. TSpaceAvailable & ASpaceAvailable)
  6301. {
  6302. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  6303. try
  6304. {
  6305. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  6306. }
  6307. catch (Exception &E)
  6308. {
  6309. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  6310. }
  6311. }
  6312. //---------------------------------------------------------------------------
  6313. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  6314. const TRemoteFile * File, void * /*Param*/)
  6315. {
  6316. StartOperationWithFile(FileName, foLock);
  6317. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  6318. FileModified(File, FileName, true);
  6319. DoLockFile(FileName, File);
  6320. ReactOnCommand(fsLock);
  6321. }
  6322. //---------------------------------------------------------------------------
  6323. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  6324. {
  6325. TRetryOperationLoop RetryLoop(this);
  6326. do
  6327. {
  6328. try
  6329. {
  6330. FFileSystem->LockFile(FileName, File);
  6331. }
  6332. catch(Exception & E)
  6333. {
  6334. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  6335. }
  6336. }
  6337. while (RetryLoop.Retry());
  6338. }
  6339. //---------------------------------------------------------------------------
  6340. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  6341. const TRemoteFile * File, void * /*Param*/)
  6342. {
  6343. StartOperationWithFile(FileName, foUnlock);
  6344. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  6345. FileModified(File, FileName, true);
  6346. DoUnlockFile(FileName, File);
  6347. ReactOnCommand(fsLock);
  6348. }
  6349. //---------------------------------------------------------------------------
  6350. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  6351. {
  6352. TRetryOperationLoop RetryLoop(this);
  6353. do
  6354. {
  6355. try
  6356. {
  6357. FFileSystem->UnlockFile(FileName, File);
  6358. }
  6359. catch(Exception & E)
  6360. {
  6361. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  6362. }
  6363. }
  6364. while (RetryLoop.Retry());
  6365. }
  6366. //---------------------------------------------------------------------------
  6367. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  6368. {
  6369. BeginTransaction();
  6370. try
  6371. {
  6372. ProcessFiles(FileList, foLock, LockFile, NULL);
  6373. }
  6374. __finally
  6375. {
  6376. EndTransaction();
  6377. }
  6378. }
  6379. //---------------------------------------------------------------------------
  6380. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  6381. {
  6382. BeginTransaction();
  6383. try
  6384. {
  6385. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  6386. }
  6387. __finally
  6388. {
  6389. EndTransaction();
  6390. }
  6391. }
  6392. //---------------------------------------------------------------------------
  6393. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  6394. {
  6395. return FFileSystem->GetSessionInfo();
  6396. }
  6397. //---------------------------------------------------------------------------
  6398. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  6399. {
  6400. return FFileSystem->GetFileSystemInfo(Retrieve);
  6401. }
  6402. //---------------------------------------------------------------------
  6403. TStrings * TTerminal::GetShellChecksumAlgDefs()
  6404. {
  6405. if (FShellChecksumAlgDefs.get() == NULL)
  6406. {
  6407. UnicodeString ChecksumCommandsDef = Configuration->ChecksumCommands;
  6408. if (ChecksumCommandsDef.IsEmpty())
  6409. {
  6410. UnicodeString Delimiter(L",");
  6411. AddToList(ChecksumCommandsDef, Sha512ChecksumAlg + L"=sha512sum", Delimiter);
  6412. AddToList(ChecksumCommandsDef, Sha384ChecksumAlg + L"=sha384sum", Delimiter);
  6413. AddToList(ChecksumCommandsDef, Sha256ChecksumAlg + L"=sha256sum", Delimiter);
  6414. AddToList(ChecksumCommandsDef, Sha224ChecksumAlg + L"=sha224sum", Delimiter);
  6415. AddToList(ChecksumCommandsDef, Sha1ChecksumAlg + L"=sha1sum", Delimiter);
  6416. AddToList(ChecksumCommandsDef, Md5ChecksumAlg + L"=md5sums", Delimiter);
  6417. }
  6418. FShellChecksumAlgDefs.reset(new TStringList());
  6419. FShellChecksumAlgDefs->CommaText = ChecksumCommandsDef;
  6420. }
  6421. return FShellChecksumAlgDefs.get();
  6422. }
  6423. //---------------------------------------------------------------------
  6424. void TTerminal::GetShellChecksumAlgs(TStrings * Algs)
  6425. {
  6426. TStrings * AlgDefs = GetShellChecksumAlgDefs();
  6427. for (int Index = 0; Index < AlgDefs->Count; Index++)
  6428. {
  6429. Algs->Add(AlgDefs->Names[Index]);
  6430. }
  6431. }
  6432. //---------------------------------------------------------------------
  6433. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  6434. {
  6435. if (!IsCapable[fcCalculatingChecksum] && IsCapable[fcSecondaryShell])
  6436. {
  6437. // Both return the same anyway
  6438. if (CommandSessionOpened)
  6439. {
  6440. FCommandSession->GetSupportedChecksumAlgs(Algs);
  6441. }
  6442. else
  6443. {
  6444. GetShellChecksumAlgs(Algs);
  6445. }
  6446. }
  6447. else
  6448. {
  6449. FFileSystem->GetSupportedChecksumAlgs(Algs);
  6450. }
  6451. }
  6452. //---------------------------------------------------------------------
  6453. UnicodeString __fastcall TTerminal::GetPassword()
  6454. {
  6455. UnicodeString Result;
  6456. // FRememberedPassword is empty also when stored password was used
  6457. if (FRememberedPassword.IsEmpty())
  6458. {
  6459. Result = SessionData->Password;
  6460. }
  6461. else if (FRememberedPasswordKind != pkPassphrase)
  6462. {
  6463. Result = GetRememberedPassword();
  6464. }
  6465. return Result;
  6466. }
  6467. //---------------------------------------------------------------------
  6468. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  6469. {
  6470. return DecryptPassword(FRememberedPassword);
  6471. }
  6472. //---------------------------------------------------------------------
  6473. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  6474. {
  6475. return DecryptPassword(FRememberedTunnelPassword);
  6476. }
  6477. //---------------------------------------------------------------------
  6478. bool __fastcall TTerminal::GetStoredCredentialsTried()
  6479. {
  6480. bool Result;
  6481. if (FFileSystem != NULL)
  6482. {
  6483. Result = FFileSystem->GetStoredCredentialsTried();
  6484. }
  6485. else if (FSecureShell != NULL)
  6486. {
  6487. Result = FSecureShell->GetStoredCredentialsTried();
  6488. }
  6489. else
  6490. {
  6491. DebugAssert(FTunnelOpening);
  6492. Result = false;
  6493. }
  6494. return Result;
  6495. }
  6496. //---------------------------------------------------------------------------
  6497. int __fastcall TTerminal::CopyToParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6498. {
  6499. UnicodeString FileName;
  6500. TObject * Object;
  6501. UnicodeString TargetDir;
  6502. bool Dir;
  6503. bool Recursed;
  6504. int Result = ParallelOperation->GetNext(this, FileName, Object, TargetDir, Dir, Recursed);
  6505. if (Result > 0)
  6506. {
  6507. std::unique_ptr<TStrings> FilesToCopy(new TStringList());
  6508. FilesToCopy->AddObject(FileName, Object);
  6509. // OnceDoneOperation is not supported
  6510. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6511. int Params = ParallelOperation->Params;
  6512. // If we failed to recurse the directory when enumerating, recurse now (typically only to show the recursion error)
  6513. if (Dir && Recursed)
  6514. {
  6515. Params = Params | cpNoRecurse;
  6516. }
  6517. int Prev = OperationProgress->FilesFinishedSuccessfully;
  6518. DebugAssert((FOperationProgress == OperationProgress) || (FOperationProgress == NULL));
  6519. TFileOperationProgressType * PrevOperationProgress = FOperationProgress;
  6520. try
  6521. {
  6522. FOperationProgress = OperationProgress;
  6523. if (ParallelOperation->Side == osLocal)
  6524. {
  6525. FFileSystem->CopyToRemote(
  6526. FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
  6527. }
  6528. else if (DebugAlwaysTrue(ParallelOperation->Side == osRemote))
  6529. {
  6530. FFileSystem->CopyToLocal(
  6531. FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
  6532. }
  6533. }
  6534. __finally
  6535. {
  6536. bool Success = (Prev < OperationProgress->FilesFinishedSuccessfully);
  6537. ParallelOperation->Done(FileName, Dir, Success);
  6538. // Not to fail an assertion in OperationStop when called from CopyToRemote or CopyToLocal,
  6539. // when FOperationProgress is already OperationProgress.
  6540. FOperationProgress = PrevOperationProgress;
  6541. }
  6542. }
  6543. return Result;
  6544. }
  6545. //---------------------------------------------------------------------------
  6546. bool __fastcall TTerminal::CanParallel(
  6547. const TCopyParamType * CopyParam, int Params, TParallelOperation * ParallelOperation)
  6548. {
  6549. return
  6550. (ParallelOperation != NULL) &&
  6551. FFileSystem->IsCapable(fcParallelTransfers) &&
  6552. // parallel transfer is not implemented for operations needed to be done on a folder
  6553. // after all its files are processed
  6554. FLAGCLEAR(Params, cpDelete) &&
  6555. (!CopyParam->PreserveTime || !CopyParam->PreserveTimeDirs);
  6556. }
  6557. //---------------------------------------------------------------------------
  6558. void __fastcall TTerminal::CopyParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6559. {
  6560. try
  6561. {
  6562. bool Continue = true;
  6563. do
  6564. {
  6565. int GotNext = CopyToParallel(ParallelOperation, OperationProgress);
  6566. if (GotNext < 0)
  6567. {
  6568. Continue = false;
  6569. }
  6570. else if (GotNext == 0)
  6571. {
  6572. Sleep(100);
  6573. }
  6574. }
  6575. while (Continue && !OperationProgress->Cancel);
  6576. }
  6577. __finally
  6578. {
  6579. OperationProgress->SetDone();
  6580. ParallelOperation->WaitFor();
  6581. }
  6582. }
  6583. //---------------------------------------------------------------------------
  6584. void __fastcall TTerminal::LogParallelTransfer(TParallelOperation * ParallelOperation)
  6585. {
  6586. LogEvent(
  6587. FORMAT("Adding a parallel transfer to the transfer started on the connection \"%s\"",
  6588. (ParallelOperation->MainName)));
  6589. }
  6590. //---------------------------------------------------------------------------
  6591. void __fastcall TTerminal::LogTotalTransferDetails(
  6592. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  6593. TFileOperationProgressType * OperationProgress, bool Parallel, TStrings * Files)
  6594. {
  6595. if (Log->Logging)
  6596. {
  6597. UnicodeString TargetSide = ((OperationProgress->Side == osLocal) ? L"remote" : L"local");
  6598. UnicodeString S =
  6599. FORMAT(
  6600. L"Copying %d files/directories to %s directory \"%s\"",
  6601. (OperationProgress->Count, TargetSide, TargetDir));
  6602. if (Parallel && DebugAlwaysTrue(Files != NULL))
  6603. {
  6604. int Count = 0;
  6605. for (int Index = 0; Index < Files->Count; Index++)
  6606. {
  6607. TCollectedFileList * FileList = dynamic_cast<TCollectedFileList *>(Files->Objects[Index]);
  6608. Count += FileList->Count();
  6609. }
  6610. S += FORMAT(L" - in parallel, with %d total files", (Count));
  6611. }
  6612. if (OperationProgress->TotalSizeSet)
  6613. {
  6614. S += FORMAT(L" - total size: %s", (FormatSize(OperationProgress->TotalSize)));
  6615. }
  6616. LogEvent(S);
  6617. LogEvent(0, CopyParam->LogStr);
  6618. }
  6619. }
  6620. //---------------------------------------------------------------------------
  6621. void __fastcall TTerminal::LogTotalTransferDone(TFileOperationProgressType * OperationProgress)
  6622. {
  6623. LogEvent(L"Copying finished: " + OperationProgress->GetLogStr(true));
  6624. }
  6625. //---------------------------------------------------------------------------
  6626. bool __fastcall TTerminal::CopyToRemote(
  6627. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6628. TParallelOperation * ParallelOperation)
  6629. {
  6630. DebugAssert(FFileSystem);
  6631. DebugAssert(FilesToCopy);
  6632. bool Result = false;
  6633. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6634. if ((CopyParam->OnTransferIn != NULL) && !FFileSystem->IsCapable(fcTransferIn))
  6635. {
  6636. throw Exception(LoadStr(NOTSUPPORTED));
  6637. }
  6638. try
  6639. {
  6640. __int64 Size;
  6641. std::unique_ptr<TStringList> Files;
  6642. bool ACanParallel =
  6643. CanParallel(CopyParam, Params, ParallelOperation) &&
  6644. !CopyParam->ClearArchive;
  6645. if (ACanParallel)
  6646. {
  6647. Files.reset(new TStringList());
  6648. Files->OwnsObjects = true;
  6649. }
  6650. bool CalculatedSize;
  6651. if ((CopyParam->Size >= 0) &&
  6652. DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
  6653. {
  6654. Size = CopyParam->Size;
  6655. CalculatedSize = true;
  6656. }
  6657. else
  6658. {
  6659. bool CalculateSize = ACanParallel || CopyParam->CalculateSize;
  6660. CalculatedSize = CalculateLocalFilesSize(FilesToCopy, Size, CopyParam, CalculateSize, Files.get(), NULL);
  6661. }
  6662. FLastProgressLogged = GetTickCount();
  6663. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  6664. OperationStart(
  6665. OperationProgress, (Params & cpDelete ? foMove : foCopy), osLocal,
  6666. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
  6667. bool CollectingUsage = false;
  6668. try
  6669. {
  6670. if (CalculatedSize)
  6671. {
  6672. if (Configuration->Usage->Collect)
  6673. {
  6674. int CounterSize = TUsage::CalculateCounterSize(Size);
  6675. Configuration->Usage->Inc(L"Uploads");
  6676. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  6677. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  6678. CollectingUsage = true;
  6679. }
  6680. OperationProgress.SetTotalSize(Size);
  6681. }
  6682. BeginTransaction();
  6683. try
  6684. {
  6685. bool Parallel = ACanParallel && CalculatedSize;
  6686. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  6687. if (Parallel)
  6688. {
  6689. // OnceDoneOperation is not supported
  6690. ParallelOperation->Init(Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name);
  6691. CopyParallel(ParallelOperation, &OperationProgress);
  6692. }
  6693. else
  6694. {
  6695. FFileSystem->CopyToRemote(
  6696. FilesToCopy, TargetDir, CopyParam, Params, &OperationProgress, OnceDoneOperation);
  6697. }
  6698. LogTotalTransferDone(&OperationProgress);
  6699. }
  6700. __finally
  6701. {
  6702. if (Active)
  6703. {
  6704. ReactOnCommand(fsCopyToRemote);
  6705. }
  6706. EndTransaction();
  6707. }
  6708. if (OperationProgress.Cancel == csContinue)
  6709. {
  6710. Result = true;
  6711. }
  6712. }
  6713. __finally
  6714. {
  6715. if (CollectingUsage)
  6716. {
  6717. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  6718. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  6719. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  6720. }
  6721. OperationStop(OperationProgress);
  6722. }
  6723. }
  6724. catch (Exception &E)
  6725. {
  6726. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  6727. OnceDoneOperation = odoIdle;
  6728. }
  6729. if (OnceDoneOperation != odoIdle)
  6730. {
  6731. CloseOnCompletion(OnceDoneOperation);
  6732. }
  6733. return Result;
  6734. }
  6735. //---------------------------------------------------------------------------
  6736. void __fastcall TTerminal::DoCopyToRemote(
  6737. TStrings * FilesToCopy, const UnicodeString & ATargetDir, const TCopyParamType * CopyParam, int Params,
  6738. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  6739. {
  6740. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  6741. FFileSystem->TransferOnDirectory(ATargetDir, CopyParam, Params);
  6742. // Must be local resolving, as this is outside of robust loop
  6743. UnicodeString TargetDir = AbsolutePath(ATargetDir, true);
  6744. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  6745. int Index = 0;
  6746. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  6747. {
  6748. bool Success = false;
  6749. UnicodeString FileName = FilesToCopy->Strings[Index];
  6750. TSearchRecSmart * SearchRec = NULL;
  6751. if (FilesToCopy->Objects[Index] != NULL)
  6752. {
  6753. TLocalFile * LocalFile = dynamic_cast<TLocalFile *>(FilesToCopy->Objects[Index]);
  6754. SearchRec = &LocalFile->SearchRec;
  6755. }
  6756. try
  6757. {
  6758. try
  6759. {
  6760. if (SessionData->CacheDirectories)
  6761. {
  6762. DirectoryModified(TargetDir, false);
  6763. if (DirectoryExists(ApiPath(FileName)))
  6764. {
  6765. UnicodeString FileNameOnly = ExtractFileName(FileName);
  6766. DirectoryModified(FullTargetDir + FileNameOnly, true);
  6767. }
  6768. }
  6769. SourceRobust(FileName, SearchRec, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  6770. Success = true;
  6771. }
  6772. catch (ESkipFile & E)
  6773. {
  6774. TSuspendFileOperationProgress Suspend(OperationProgress);
  6775. if (!HandleException(&E))
  6776. {
  6777. throw;
  6778. }
  6779. }
  6780. }
  6781. __finally
  6782. {
  6783. OperationFinish(OperationProgress, FilesToCopy->Objects[Index], FileName, Success, OnceDoneOperation);
  6784. }
  6785. Index++;
  6786. }
  6787. }
  6788. //---------------------------------------------------------------------------
  6789. void __fastcall TTerminal::SourceRobust(
  6790. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  6791. const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6792. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6793. {
  6794. TUploadSessionAction Action(ActionLog);
  6795. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  6796. bool CanRetry = (CopyParam->OnTransferIn == NULL);
  6797. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
  6798. do
  6799. {
  6800. bool ChildError = false;
  6801. try
  6802. {
  6803. Source(FileName, SearchRec, TargetDir, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  6804. }
  6805. catch (Exception & E)
  6806. {
  6807. if (!RobustLoop.TryReopen(E))
  6808. {
  6809. if (!ChildError)
  6810. {
  6811. RollbackAction(Action, OperationProgress, &E);
  6812. }
  6813. throw;
  6814. }
  6815. }
  6816. if (RobustLoop.ShouldRetry())
  6817. {
  6818. OperationProgress->RollbackTransfer();
  6819. Action.Restart();
  6820. // prevent overwrite and resume confirmations (should not be set for directories!)
  6821. Params |= cpNoConfirmation;
  6822. // enable resume even if we are uploading into new directory
  6823. Flags &= ~tfNewDirectory;
  6824. Flags |= tfAutoResume;
  6825. }
  6826. }
  6827. while (RobustLoop.Retry());
  6828. }
  6829. //---------------------------------------------------------------------------
  6830. bool __fastcall TTerminal::CreateTargetDirectory(
  6831. const UnicodeString & DirectoryPath, int Attrs, const TCopyParamType * CopyParam)
  6832. {
  6833. TRemoteFile * File = NULL;
  6834. bool DoCreate =
  6835. !FileExists(DirectoryPath, &File) ||
  6836. !File->IsDirectory; // just try to create and make it fail
  6837. delete File;
  6838. if (DoCreate)
  6839. {
  6840. TRemoteProperties Properties;
  6841. // Do not even try with FTP, as while theoretically it supports setting permissions of created folders and it will try,
  6842. // it most likely fail as most FTP servers do not support SITE CHMOD.
  6843. if (CopyParam->PreserveRights && IsCapable[fcModeChangingUpload])
  6844. {
  6845. Properties.Valid = Properties.Valid << vpRights;
  6846. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  6847. }
  6848. Properties.Valid = Properties.Valid << vpEncrypt;
  6849. Properties.Encrypt = CopyParam->EncryptNewFiles;
  6850. CreateDirectory(DirectoryPath, &Properties);
  6851. }
  6852. return DoCreate;
  6853. }
  6854. //---------------------------------------------------------------------------
  6855. void __fastcall TTerminal::DirectorySource(
  6856. const UnicodeString & DirectoryName, const UnicodeString & TargetDir, const UnicodeString & DestDirectoryName,
  6857. int Attrs, const TCopyParamType * CopyParam, int Params,
  6858. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6859. {
  6860. FFileSystem->TransferOnDirectory(TargetDir, CopyParam, Params);
  6861. UnicodeString DestFullName = TargetDir + DestDirectoryName;
  6862. OperationProgress->SetFile(DirectoryName);
  6863. bool PostCreateDir = FLAGCLEAR(Flags, tfPreCreateDir);
  6864. // WebDAV, SFTP and S3
  6865. if (!PostCreateDir)
  6866. {
  6867. // This is originally a code for WebDAV, SFTP used a slightly different logic,
  6868. // but functionally it should be very similar.
  6869. if (CreateTargetDirectory(DestFullName, Attrs, CopyParam))
  6870. {
  6871. Flags |= tfNewDirectory;
  6872. }
  6873. }
  6874. bool DoRecurse = FLAGCLEAR(Params, cpNoRecurse);
  6875. if (DoRecurse)
  6876. {
  6877. TSearchRecOwned SearchRec;
  6878. bool FindOK = LocalFindFirstLoop(DirectoryName + L"*.*", SearchRec);
  6879. while (FindOK && !OperationProgress->Cancel)
  6880. {
  6881. UnicodeString FileName = DirectoryName + SearchRec.Name;
  6882. try
  6883. {
  6884. if (SearchRec.IsRealFile())
  6885. {
  6886. // Not sure if we need the trailing slash here, but we cannot use it in CreateTargetDirectory.
  6887. // At least FTP cannot handle it, when setting the new directory permissions.
  6888. UnicodeString ATargetDir = UnixIncludeTrailingBackslash(DestFullName);
  6889. SourceRobust(FileName, &SearchRec, ATargetDir, CopyParam, Params, OperationProgress, (Flags & ~(tfFirstLevel | tfAutoResume)));
  6890. // FTP: if any file got uploaded (i.e. there were any file in the directory and at least one was not skipped),
  6891. // do not try to create the directory, as it should be already created by FZAPI during upload
  6892. PostCreateDir = false;
  6893. }
  6894. }
  6895. catch (ESkipFile &E)
  6896. {
  6897. // If ESkipFile occurs, just log it and continue with next file
  6898. TSuspendFileOperationProgress Suspend(OperationProgress);
  6899. // here a message to user was displayed, which was not appropriate
  6900. // when user refused to overwrite the file in subdirectory.
  6901. // hopefully it won't be missing in other situations.
  6902. if (!HandleException(&E))
  6903. {
  6904. throw;
  6905. }
  6906. }
  6907. FindOK = LocalFindNextLoop(SearchRec);
  6908. }
  6909. SearchRec.Close();
  6910. }
  6911. // FTP
  6912. if (PostCreateDir)
  6913. {
  6914. CreateTargetDirectory(DestFullName, Attrs, CopyParam);
  6915. }
  6916. // Paralell transfers (cpNoRecurse) won't be allowed if any of these are set anyway (see CanParallel).
  6917. // Exception is ClearArchive, which is does not prevent parallel transfer, but is silently ignored for directories.
  6918. if (DoRecurse && !OperationProgress->Cancel)
  6919. {
  6920. // TODO : Delete also read-only directories.
  6921. // TODO : Show error message on failure.
  6922. if (IsCapable[fcPreservingTimestampDirs] && CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  6923. {
  6924. TRemoteProperties Properties;
  6925. Properties.Valid << vpModification;
  6926. OpenLocalFile(
  6927. ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
  6928. &Properties.Modification, &Properties.LastAccess, NULL);
  6929. ChangeFileProperties(DestFullName, NULL, &Properties);
  6930. }
  6931. if (FLAGSET(Params, cpDelete))
  6932. {
  6933. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  6934. RemoveDir(ApiPath(DirectoryName));
  6935. }
  6936. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  6937. {
  6938. FILE_OPERATION_LOOP_BEGIN
  6939. {
  6940. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  6941. }
  6942. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  6943. }
  6944. }
  6945. }
  6946. //---------------------------------------------------------------------------
  6947. void __fastcall TTerminal::SelectTransferMode(
  6948. const UnicodeString & BaseFileName, TOperationSide Side, const TCopyParamType * CopyParam,
  6949. const TFileMasks::TParams & MaskParams)
  6950. {
  6951. bool AsciiTransfer = IsCapable[fcTextMode] && CopyParam->UseAsciiTransfer(BaseFileName, Side, MaskParams);
  6952. OperationProgress->SetAsciiTransfer(AsciiTransfer);
  6953. UnicodeString ModeName = (OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary");
  6954. LogEvent(0, FORMAT(L"%s transfer mode selected.", (ModeName)));
  6955. }
  6956. //---------------------------------------------------------------------------
  6957. void __fastcall TTerminal::SelectSourceTransferMode(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam)
  6958. {
  6959. // Will we use ASCII or BINARY file transfer?
  6960. TFileMasks::TParams MaskParams;
  6961. MaskParams.Size = Handle.Size;
  6962. MaskParams.Modification = Handle.Modification;
  6963. UnicodeString BaseFileName = GetBaseFileName(Handle.FileName);
  6964. SelectTransferMode(BaseFileName, osLocal, CopyParam, MaskParams);
  6965. }
  6966. //---------------------------------------------------------------------------
  6967. void __fastcall TTerminal::UpdateSource(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam, int Params)
  6968. {
  6969. // TODO: Delete also read-only files.
  6970. if (FLAGSET(Params, cpDelete))
  6971. {
  6972. if (!Handle.Directory)
  6973. {
  6974. LogEvent(FORMAT(L"Deleting successfully uploaded source file \"%s\".", (Handle.FileName)));
  6975. FILE_OPERATION_LOOP_BEGIN
  6976. {
  6977. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(Handle.FileName)));
  6978. }
  6979. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (Handle.FileName)));
  6980. }
  6981. }
  6982. else if (CopyParam->ClearArchive && FLAGSET(Handle.Attrs, faArchive))
  6983. {
  6984. FILE_OPERATION_LOOP_BEGIN
  6985. {
  6986. THROWOSIFFALSE(FileSetAttr(ApiPath(Handle.FileName), (Handle.Attrs & ~faArchive)) == 0);
  6987. }
  6988. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (Handle.FileName)));
  6989. }
  6990. }
  6991. //---------------------------------------------------------------------------
  6992. void __fastcall TTerminal::Source(
  6993. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  6994. const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6995. TFileOperationProgressType * OperationProgress, unsigned int Flags, TUploadSessionAction & Action, bool & ChildError)
  6996. {
  6997. UnicodeString ActionFileName = FileName;
  6998. if (CopyParam->OnTransferIn == NULL)
  6999. {
  7000. ActionFileName = ExpandUNCFileName(ActionFileName);
  7001. }
  7002. Action.FileName(ActionFileName);
  7003. OperationProgress->SetFile(FileName, false);
  7004. if (!AllowLocalFileTransfer(FileName, SearchRec, CopyParam, OperationProgress))
  7005. {
  7006. throw ESkipFile();
  7007. }
  7008. TLocalFileHandle Handle;
  7009. if (CopyParam->OnTransferIn == NULL)
  7010. {
  7011. OpenLocalFile(FileName, GENERIC_READ, Handle);
  7012. }
  7013. else
  7014. {
  7015. Handle.FileName = FileName;
  7016. }
  7017. OperationProgress->SetFileInProgress();
  7018. UnicodeString DestFileName =
  7019. ChangeFileName(CopyParam, ExtractFileName(FileName), osLocal, FLAGSET(Flags, tfFirstLevel));
  7020. if (Handle.Directory)
  7021. {
  7022. Action.Cancel();
  7023. DirectorySource(
  7024. IncludeTrailingBackslash(FileName), TargetDir, DestFileName, Handle.Attrs,
  7025. CopyParam, Params, OperationProgress, Flags);
  7026. }
  7027. else
  7028. {
  7029. if (CopyParam->OnTransferIn != NULL)
  7030. {
  7031. LogEvent(FORMAT(L"Streaming \"%s\" to remote directory started.", (FileName)));
  7032. }
  7033. else
  7034. {
  7035. LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  7036. OperationProgress->SetLocalSize(Handle.Size);
  7037. // Suppose same data size to transfer as to read
  7038. // (not true with ASCII transfer)
  7039. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  7040. }
  7041. if (IsCapable[fcTextMode])
  7042. {
  7043. SelectSourceTransferMode(Handle, CopyParam);
  7044. }
  7045. FFileSystem->Source(
  7046. Handle, TargetDir, DestFileName, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  7047. LogFileDone(OperationProgress, AbsolutePath(TargetDir + DestFileName, true), Action);
  7048. OperationProgress->Succeeded();
  7049. }
  7050. Handle.Release();
  7051. UpdateSource(Handle, CopyParam, Params);
  7052. }
  7053. //---------------------------------------------------------------------------
  7054. bool __fastcall TTerminal::CopyToLocal(
  7055. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7056. TParallelOperation * ParallelOperation)
  7057. {
  7058. DebugAssert(FFileSystem);
  7059. // see scp.c: sink(), tolocal()
  7060. bool Result = false;
  7061. DebugAssert(FilesToCopy != NULL);
  7062. TOnceDoneOperation OnceDoneOperation = odoIdle;
  7063. if ((CopyParam->OnTransferOut != NULL) && !FFileSystem->IsCapable(fcTransferOut))
  7064. {
  7065. throw Exception(LoadStr(NOTSUPPORTED));
  7066. }
  7067. FDestFileName = L"";
  7068. FMultipleDestinationFiles = false;
  7069. BeginTransaction();
  7070. try
  7071. {
  7072. __int64 TotalSize;
  7073. bool TotalSizeKnown = false;
  7074. FLastProgressLogged = GetTickCount();
  7075. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  7076. std::unique_ptr<TStringList> Files;
  7077. bool ACanParallel = CanParallel(CopyParam, Params, ParallelOperation);
  7078. if (ACanParallel)
  7079. {
  7080. Files.reset(new TStringList());
  7081. Files->OwnsObjects = true;
  7082. }
  7083. if ((CopyParam->Size >= 0) &&
  7084. DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
  7085. {
  7086. TotalSize = CopyParam->Size;
  7087. TotalSizeKnown = true;
  7088. }
  7089. else
  7090. {
  7091. ExceptionOnFail = true;
  7092. try
  7093. {
  7094. TCalculateSizeStats Stats;
  7095. Stats.FoundFiles = Files.get();
  7096. TCalculateSizeParams Params;
  7097. Params.Params = csIgnoreErrors;
  7098. Params.CopyParam = CopyParam;
  7099. Params.AllowDirs = ACanParallel || CopyParam->CalculateSize;
  7100. Params.Stats = &Stats;
  7101. if (CalculateFilesSize(FilesToCopy, TotalSize, Params))
  7102. {
  7103. TotalSizeKnown = true;
  7104. }
  7105. }
  7106. __finally
  7107. {
  7108. ExceptionOnFail = false;
  7109. }
  7110. }
  7111. OperationStart(OperationProgress, (Params & cpDelete ? foMove : foCopy), osRemote,
  7112. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
  7113. bool CollectingUsage = false;
  7114. try
  7115. {
  7116. if (TotalSizeKnown)
  7117. {
  7118. if (Configuration->Usage->Collect)
  7119. {
  7120. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  7121. Configuration->Usage->Inc(L"Downloads");
  7122. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  7123. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  7124. CollectingUsage = true;
  7125. }
  7126. OperationProgress.SetTotalSize(TotalSize);
  7127. }
  7128. try
  7129. {
  7130. try
  7131. {
  7132. bool Parallel = ACanParallel && TotalSizeKnown;
  7133. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  7134. if (Parallel)
  7135. {
  7136. // OnceDoneOperation is not supported
  7137. ParallelOperation->Init(Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name);
  7138. CopyParallel(ParallelOperation, &OperationProgress);
  7139. }
  7140. else
  7141. {
  7142. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  7143. &OperationProgress, OnceDoneOperation);
  7144. }
  7145. LogTotalTransferDone(&OperationProgress);
  7146. }
  7147. __finally
  7148. {
  7149. if (Active)
  7150. {
  7151. ReactOnCommand(fsCopyToLocal);
  7152. }
  7153. }
  7154. }
  7155. catch (Exception &E)
  7156. {
  7157. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  7158. OnceDoneOperation = odoIdle;
  7159. }
  7160. if (OperationProgress.Cancel == csContinue)
  7161. {
  7162. Result = true;
  7163. }
  7164. }
  7165. __finally
  7166. {
  7167. if (CollectingUsage)
  7168. {
  7169. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  7170. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  7171. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  7172. }
  7173. OperationStop(OperationProgress);
  7174. }
  7175. Files.reset(NULL);
  7176. }
  7177. __finally
  7178. {
  7179. // If session is still active (no fatal error) we reload directory
  7180. // by calling EndTransaction
  7181. EndTransaction();
  7182. }
  7183. if (OnceDoneOperation != odoIdle)
  7184. {
  7185. UnicodeString DestFileName;
  7186. if (!FMultipleDestinationFiles)
  7187. {
  7188. DestFileName = FDestFileName;
  7189. }
  7190. CloseOnCompletion(OnceDoneOperation, UnicodeString(), TargetDir, DestFileName);
  7191. }
  7192. return Result;
  7193. }
  7194. //---------------------------------------------------------------------------
  7195. void __fastcall TTerminal::DoCopyToLocal(
  7196. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7197. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  7198. {
  7199. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  7200. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  7201. int Index = 0;
  7202. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  7203. {
  7204. bool Success = false;
  7205. UnicodeString FileName = FilesToCopy->Strings[Index];
  7206. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  7207. try
  7208. {
  7209. try
  7210. {
  7211. UnicodeString AbsoluteFileName = AbsolutePath(FileName, true);
  7212. SinkRobust(AbsoluteFileName, File, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  7213. Success = true;
  7214. }
  7215. catch (ESkipFile & E)
  7216. {
  7217. TSuspendFileOperationProgress Suspend(OperationProgress);
  7218. if (!HandleException(&E))
  7219. {
  7220. throw;
  7221. }
  7222. }
  7223. }
  7224. __finally
  7225. {
  7226. OperationFinish(OperationProgress, File, FileName, Success, OnceDoneOperation);
  7227. }
  7228. Index++;
  7229. }
  7230. }
  7231. //---------------------------------------------------------------------------
  7232. void __fastcall TTerminal::SinkRobust(
  7233. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  7234. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  7235. {
  7236. TDownloadSessionAction Action(ActionLog);
  7237. try
  7238. {
  7239. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  7240. bool CanRetry = (CopyParam->OnTransferOut == NULL);
  7241. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
  7242. bool Sunk = false;
  7243. do
  7244. {
  7245. try
  7246. {
  7247. // If connection is lost while deleting the file, so not retry download on the next round.
  7248. // The file may not exist anymore and the download attempt might overwrite the (only) local copy.
  7249. if (!Sunk)
  7250. {
  7251. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags, Action);
  7252. Sunk = true;
  7253. }
  7254. if (FLAGSET(Params, cpDelete))
  7255. {
  7256. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  7257. // If file is directory, do not delete it recursively, because it should be
  7258. // empty already. If not, it should not be deleted (some files were
  7259. // skipped or some new files were copied to it, while we were downloading)
  7260. int Params = dfNoRecursive;
  7261. DeleteFile(FileName, File, &Params);
  7262. }
  7263. }
  7264. catch (Exception & E)
  7265. {
  7266. if (!RobustLoop.TryReopen(E))
  7267. {
  7268. if (!Sunk)
  7269. {
  7270. RollbackAction(Action, OperationProgress, &E);
  7271. }
  7272. throw;
  7273. }
  7274. }
  7275. if (RobustLoop.ShouldRetry())
  7276. {
  7277. OperationProgress->RollbackTransfer();
  7278. Action.Restart();
  7279. DebugAssert(File != NULL);
  7280. if (!File->IsDirectory)
  7281. {
  7282. // prevent overwrite and resume confirmations
  7283. Params |= cpNoConfirmation;
  7284. Flags |= tfAutoResume;
  7285. }
  7286. }
  7287. }
  7288. while (RobustLoop.Retry());
  7289. }
  7290. __finally
  7291. {
  7292. // Once we issue <download> we must terminate the data stream
  7293. if (Action.IsValid() && (CopyParam->OnTransferOut != NULL) && DebugAlwaysTrue(IsCapable[fcTransferOut]))
  7294. {
  7295. CopyParam->OnTransferOut(this, NULL, 0);
  7296. }
  7297. }
  7298. }
  7299. //---------------------------------------------------------------------------
  7300. struct TSinkFileParams
  7301. {
  7302. UnicodeString TargetDir;
  7303. const TCopyParamType * CopyParam;
  7304. int Params;
  7305. TFileOperationProgressType * OperationProgress;
  7306. bool Skipped;
  7307. unsigned int Flags;
  7308. };
  7309. //---------------------------------------------------------------------------
  7310. void __fastcall TTerminal::Sink(
  7311. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  7312. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags,
  7313. TDownloadSessionAction & Action)
  7314. {
  7315. Action.FileName(FileName);
  7316. DebugAssert(File);
  7317. if (!DoAllowRemoteFileTransfer(File, CopyParam, false))
  7318. {
  7319. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  7320. throw ESkipFile();
  7321. }
  7322. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  7323. {
  7324. OperationProgress->AddSkippedFileSize(File->Resolve()->Size);
  7325. throw ESkipFile();
  7326. }
  7327. LogFileDetails(FileName, File->Modification, File->Size, File->LinkedFile);
  7328. OperationProgress->SetFile(FileName);
  7329. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  7330. UnicodeString DestFileName = ChangeFileName(CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
  7331. UnicodeString DestFullName = TargetDir + DestFileName;
  7332. if (File->IsDirectory)
  7333. {
  7334. Action.Cancel();
  7335. if (CanRecurseToDirectory(File))
  7336. {
  7337. FILE_OPERATION_LOOP_BEGIN
  7338. {
  7339. int Attrs = FileGetAttrFix(ApiPath(DestFullName));
  7340. if (FLAGCLEAR(Attrs, faDirectory))
  7341. {
  7342. EXCEPTION;
  7343. }
  7344. }
  7345. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  7346. FILE_OPERATION_LOOP_BEGIN
  7347. {
  7348. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  7349. }
  7350. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  7351. if (FLAGCLEAR(Params, cpNoRecurse))
  7352. {
  7353. TSinkFileParams SinkFileParams;
  7354. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  7355. SinkFileParams.CopyParam = CopyParam;
  7356. SinkFileParams.Params = Params;
  7357. SinkFileParams.OperationProgress = OperationProgress;
  7358. SinkFileParams.Skipped = false;
  7359. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  7360. ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  7361. FFileSystem->DirectorySunk(DestFullName, File, CopyParam);
  7362. // Do not delete directory if some of its files were skip.
  7363. // Throw "skip file" for the directory to avoid attempt to deletion
  7364. // of any parent directory
  7365. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  7366. {
  7367. throw ESkipFile();
  7368. }
  7369. }
  7370. }
  7371. else
  7372. {
  7373. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
  7374. }
  7375. }
  7376. else
  7377. {
  7378. if (CopyParam->OnTransferOut != NULL)
  7379. {
  7380. LogEvent(FORMAT(L"Streaming \"%s\" to local machine started.", (FileName)));
  7381. }
  7382. else
  7383. {
  7384. LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  7385. }
  7386. // Will we use ASCII or BINARY file transfer?
  7387. UnicodeString BaseFileName = GetBaseFileName(FileName);
  7388. const TRemoteFile * UltimateFile = File->Resolve();
  7389. TFileMasks::TParams MaskParams;
  7390. MaskParams.Size = UltimateFile->Size;
  7391. MaskParams.Modification = File->Modification;
  7392. SelectTransferMode(BaseFileName, osRemote, CopyParam, MaskParams);
  7393. // Suppose same data size to transfer as to write
  7394. // (not true with ASCII transfer)
  7395. __int64 TransferSize = UltimateFile->Size;
  7396. OperationProgress->SetLocalSize(TransferSize);
  7397. if (IsFileEncrypted(FileName))
  7398. {
  7399. TransferSize += TEncryption::GetOverhead();
  7400. }
  7401. OperationProgress->SetTransferSize(TransferSize);
  7402. int Attrs;
  7403. UnicodeString LogFileName;
  7404. if (CopyParam->OnTransferOut != NULL)
  7405. {
  7406. Attrs = -1;
  7407. LogFileName = L"-";
  7408. }
  7409. else
  7410. {
  7411. FILE_OPERATION_LOOP_BEGIN
  7412. {
  7413. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  7414. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  7415. {
  7416. EXCEPTION;
  7417. }
  7418. }
  7419. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  7420. LogFileName = ExpandUNCFileName(DestFullName);
  7421. }
  7422. FFileSystem->Sink(
  7423. FileName, File, TargetDir, DestFileName, Attrs, CopyParam, Params, OperationProgress, Flags, Action);
  7424. LogFileDone(OperationProgress, LogFileName, Action);
  7425. OperationProgress->Succeeded();
  7426. }
  7427. }
  7428. //---------------------------------------------------------------------------
  7429. void __fastcall TTerminal::UpdateTargetAttrs(
  7430. const UnicodeString & DestFullName, const TRemoteFile * File, const TCopyParamType * CopyParam, int Attrs)
  7431. {
  7432. if (Attrs == -1)
  7433. {
  7434. Attrs = faArchive;
  7435. }
  7436. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  7437. if ((NewAttrs & Attrs) != NewAttrs)
  7438. {
  7439. FILE_OPERATION_LOOP_BEGIN
  7440. {
  7441. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  7442. }
  7443. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  7444. }
  7445. }
  7446. //---------------------------------------------------------------------------
  7447. void __fastcall TTerminal::UpdateTargetTime(HANDLE Handle, TDateTime Modification, TDSTMode DSTMode)
  7448. {
  7449. LogEvent(FORMAT(L"Preserving timestamp [%s]", (StandardTimestamp(Modification))));
  7450. FILETIME WrTime = DateTimeToFileTime(Modification, DSTMode);
  7451. if (!SetFileTime(Handle, NULL, NULL, &WrTime))
  7452. {
  7453. int Error = GetLastError();
  7454. LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s", (SysErrorMessageForError(Error))));
  7455. }
  7456. }
  7457. //---------------------------------------------------------------------------
  7458. void __fastcall TTerminal::SinkFile(UnicodeString FileName, const TRemoteFile * File, void * Param)
  7459. {
  7460. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  7461. DebugAssert(Params->OperationProgress != NULL);
  7462. try
  7463. {
  7464. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  7465. Params->Params, Params->OperationProgress, Params->Flags);
  7466. }
  7467. catch (ESkipFile & E)
  7468. {
  7469. Params->Skipped = true;
  7470. {
  7471. TSuspendFileOperationProgress Suspend(Params->OperationProgress);
  7472. if (!HandleException(&E))
  7473. {
  7474. throw;
  7475. }
  7476. }
  7477. if (Params->OperationProgress->Cancel)
  7478. {
  7479. Abort();
  7480. }
  7481. }
  7482. }
  7483. //---------------------------------------------------------------------------
  7484. void __fastcall TTerminal::ReflectSettings()
  7485. {
  7486. DebugAssert(FLog != NULL);
  7487. FLog->ReflectSettings();
  7488. if (FActionLogOwned)
  7489. {
  7490. DebugAssert(FActionLog != NULL);
  7491. FActionLog->ReflectSettings();
  7492. }
  7493. // also FTunnelLog ?
  7494. }
  7495. //---------------------------------------------------------------------------
  7496. void __fastcall TTerminal::CollectUsage()
  7497. {
  7498. switch (SessionData->FSProtocol)
  7499. {
  7500. case fsSCPonly:
  7501. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  7502. break;
  7503. case fsSFTP:
  7504. case fsSFTPonly:
  7505. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  7506. break;
  7507. case fsFTP:
  7508. if (SessionData->Ftps == ftpsNone)
  7509. {
  7510. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  7511. }
  7512. else
  7513. {
  7514. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  7515. }
  7516. break;
  7517. case fsWebDAV:
  7518. if (SessionData->Ftps == ftpsNone)
  7519. {
  7520. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  7521. }
  7522. else
  7523. {
  7524. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  7525. }
  7526. break;
  7527. case fsS3:
  7528. Configuration->Usage->Inc(L"OpenedSessionsS3");
  7529. break;
  7530. }
  7531. if (Configuration->Logging && Configuration->LogToFile)
  7532. {
  7533. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  7534. }
  7535. if (Configuration->LogActions)
  7536. {
  7537. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  7538. }
  7539. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  7540. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  7541. {
  7542. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  7543. }
  7544. if (SessionData->ProxyMethod != ::pmNone)
  7545. {
  7546. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  7547. }
  7548. if (SessionData->FtpProxyLogonType > 0)
  7549. {
  7550. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  7551. }
  7552. if (IsEncryptingFiles())
  7553. {
  7554. Configuration->Usage->Inc(L"OpenedSessionsEncrypted");
  7555. }
  7556. FCollectFileSystemUsage = true;
  7557. }
  7558. //---------------------------------------------------------------------------
  7559. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  7560. {
  7561. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  7562. }
  7563. //---------------------------------------------------------------------------
  7564. bool __fastcall TTerminal::VerifyCertificate(
  7565. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  7566. const UnicodeString & FingerprintSHA1, const UnicodeString & FingerprintSHA256,
  7567. const UnicodeString & CertificateSubject, int Failures)
  7568. {
  7569. bool Result = false;
  7570. UnicodeString CertificateDataSHA1 = FormatCertificateData(FingerprintSHA1, Failures);
  7571. UnicodeString CertificateDataSHA256 = FormatCertificateData(FingerprintSHA256, Failures);
  7572. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  7573. Storage->AccessMode = smRead;
  7574. if (Storage->OpenSubKey(CertificateStorageKey, false))
  7575. {
  7576. if (Storage->ValueExists(SiteKey))
  7577. {
  7578. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  7579. if (SameChecksum(CertificateDataSHA1, CachedCertificateData, false) ||
  7580. SameChecksum(CertificateDataSHA256, CachedCertificateData, false))
  7581. {
  7582. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  7583. Result = true;
  7584. }
  7585. }
  7586. else if (Storage->ValueExists(FingerprintSHA1) || Storage->ValueExists(FingerprintSHA256))
  7587. {
  7588. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  7589. Result = true;
  7590. }
  7591. }
  7592. if (!Result)
  7593. {
  7594. UnicodeString Buf = SessionData->HostKey;
  7595. while (!Result && !Buf.IsEmpty())
  7596. {
  7597. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  7598. if (ExpectedKey == L"*")
  7599. {
  7600. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  7601. Information(Message, true);
  7602. Log->Add(llException, Message);
  7603. Result = true;
  7604. }
  7605. else if (SameChecksum(ExpectedKey, FingerprintSHA1, false) ||
  7606. SameChecksum(ExpectedKey, FingerprintSHA256, false))
  7607. {
  7608. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  7609. Result = true;
  7610. }
  7611. }
  7612. }
  7613. return Result;
  7614. }
  7615. //---------------------------------------------------------------------------
  7616. bool __fastcall TTerminal::ConfirmCertificate(
  7617. TSessionInfo & SessionInfo, int Failures, const UnicodeString & CertificateStorageKey, bool CanRemember)
  7618. {
  7619. TClipboardHandler ClipboardHandler;
  7620. ClipboardHandler.Text =
  7621. FORMAT(L"SHA-256: %s\nSHA-1: %s", (SessionInfo.CertificateFingerprintSHA256, SessionInfo.CertificateFingerprintSHA1));
  7622. TQueryButtonAlias Aliases[1];
  7623. Aliases[0].Button = qaRetry;
  7624. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  7625. Aliases[0].ActionAlias = LoadStr(COPY_CERTIFICATE_ACTION);
  7626. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  7627. TQueryParams Params(qpWaitInBatch);
  7628. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  7629. Params.NoBatchAnswers = qaYes | qaRetry;
  7630. Params.Aliases = Aliases;
  7631. Params.AliasesCount = LENOF(Aliases);
  7632. unsigned int Answer =
  7633. QueryUser(
  7634. FMTLOAD(VERIFY_CERT_PROMPT3, (SessionInfo.Certificate)),
  7635. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  7636. bool Result;
  7637. switch (Answer)
  7638. {
  7639. case qaYes:
  7640. CacheCertificate(
  7641. CertificateStorageKey, SessionData->SiteKey,
  7642. SessionInfo.CertificateFingerprintSHA1, SessionInfo.CertificateFingerprintSHA256, Failures);
  7643. Result = true;
  7644. break;
  7645. case qaNo:
  7646. Result = true;
  7647. break;
  7648. case qaCancel:
  7649. Configuration->Usage->Inc(L"HostNotVerified");
  7650. Result = false;
  7651. break;
  7652. default:
  7653. DebugFail();
  7654. Result = false;
  7655. break;
  7656. }
  7657. // Cache only if the certificate was accepted manually
  7658. if (Result && CanRemember)
  7659. {
  7660. Configuration->RememberLastFingerprint(
  7661. SessionData->SiteKey, TlsFingerprintType, SessionInfo.CertificateFingerprintSHA256);
  7662. }
  7663. return Result;
  7664. }
  7665. //---------------------------------------------------------------------------
  7666. void __fastcall TTerminal::CacheCertificate(
  7667. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  7668. const UnicodeString & DebugUsedArg(FingerprintSHA1), const UnicodeString & FingerprintSHA256, int Failures)
  7669. {
  7670. UnicodeString CertificateData = FormatCertificateData(FingerprintSHA256, Failures);
  7671. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  7672. Storage->AccessMode = smReadWrite;
  7673. if (Storage->OpenSubKey(CertificateStorageKey, true))
  7674. {
  7675. Storage->WriteString(SiteKey, CertificateData);
  7676. }
  7677. }
  7678. //---------------------------------------------------------------------------
  7679. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  7680. {
  7681. // see SSL_get_version() in OpenSSL ssl_lib.c
  7682. if (TlsVersionStr == L"TLSv1.3")
  7683. {
  7684. Configuration->Usage->Inc(L"OpenedSessionsTLS13");
  7685. }
  7686. else if (TlsVersionStr == L"TLSv1.2")
  7687. {
  7688. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  7689. }
  7690. else if (TlsVersionStr == L"TLSv1.1")
  7691. {
  7692. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  7693. }
  7694. else if (TlsVersionStr == L"TLSv1")
  7695. {
  7696. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  7697. }
  7698. else if (TlsVersionStr == L"SSLv3")
  7699. {
  7700. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  7701. }
  7702. else if (TlsVersionStr == L"SSLv2")
  7703. {
  7704. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  7705. }
  7706. else
  7707. {
  7708. DebugFail();
  7709. }
  7710. }
  7711. //---------------------------------------------------------------------------
  7712. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  7713. {
  7714. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  7715. if (Result)
  7716. {
  7717. UnicodeString Passphrase = SessionData->Passphrase;
  7718. // Inspired by neon's ne_ssl_clicert_read
  7719. bool Retry;
  7720. do
  7721. {
  7722. Retry = false;
  7723. bool WrongPassphrase;
  7724. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  7725. if (WrongPassphrase)
  7726. {
  7727. if (Passphrase.IsEmpty())
  7728. {
  7729. LogEvent(L"Certificate is encrypted, need passphrase");
  7730. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  7731. }
  7732. else
  7733. {
  7734. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  7735. }
  7736. Passphrase = L"";
  7737. if (PromptUser(
  7738. SessionData, pkPassphrase,
  7739. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  7740. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  7741. {
  7742. Retry = true;
  7743. }
  7744. else
  7745. {
  7746. Result = false;
  7747. }
  7748. }
  7749. }
  7750. while (Retry);
  7751. }
  7752. return Result;
  7753. }
  7754. //---------------------------------------------------------------------------
  7755. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  7756. {
  7757. if (FSessionData->TrimVMSVersions)
  7758. {
  7759. int P = FileName.LastDelimiter(L";");
  7760. if (P > 0)
  7761. {
  7762. FileName.SetLength(P - 1);
  7763. }
  7764. }
  7765. return FileName;
  7766. }
  7767. //---------------------------------------------------------------------------
  7768. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  7769. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  7770. {
  7771. FileName = GetBaseFileName(FileName);
  7772. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  7773. return FileName;
  7774. }
  7775. //---------------------------------------------------------------------------
  7776. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  7777. {
  7778. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  7779. }
  7780. //---------------------------------------------------------------------------
  7781. TTerminal::TEncryptedFileNames::const_iterator __fastcall TTerminal::GetEncryptedFileName(const UnicodeString & Path)
  7782. {
  7783. UnicodeString FileDir = UnixExtractFileDir(Path);
  7784. // If we haven't been in this folder yet, read it to collect mapping to encrypted file names.
  7785. if (FFoldersScannedForEncryptedFiles.find(FileDir) == FFoldersScannedForEncryptedFiles.end())
  7786. {
  7787. try
  7788. {
  7789. delete DoReadDirectoryListing(FileDir, true);
  7790. }
  7791. catch (Exception & E)
  7792. {
  7793. if (!Active)
  7794. {
  7795. throw;
  7796. }
  7797. if (FEncryptedFileNames.find(Path) == FEncryptedFileNames.end())
  7798. {
  7799. FEncryptedFileNames.insert(std::make_pair(Path, UnixExtractFileName(Path)));
  7800. LogEvent(2, FORMAT(L"Name of file '%s' assumed not to be encrypted", (Path)));
  7801. }
  7802. }
  7803. FFoldersScannedForEncryptedFiles.insert(FileDir);
  7804. }
  7805. TEncryptedFileNames::const_iterator Result = FEncryptedFileNames.find(Path);
  7806. return Result;
  7807. }
  7808. //---------------------------------------------------------------------------
  7809. bool __fastcall TTerminal::IsFileEncrypted(const UnicodeString & Path, bool EncryptNewFiles)
  7810. {
  7811. // can be optimized
  7812. bool Result = (EncryptFileName(Path, EncryptNewFiles) != Path);
  7813. return Result;
  7814. }
  7815. //---------------------------------------------------------------------------
  7816. UnicodeString __fastcall TTerminal::EncryptFileName(const UnicodeString & Path, bool EncryptNewFiles)
  7817. {
  7818. UnicodeString Result = Path;
  7819. if (IsEncryptingFiles() && !IsUnixRootPath(Path))
  7820. {
  7821. UnicodeString FileName = UnixExtractFileName(Path);
  7822. UnicodeString FileDir = UnixExtractFileDir(Path);
  7823. if (!FileName.IsEmpty() && IsRealFile(FileName))
  7824. {
  7825. TEncryptedFileNames::const_iterator I = GetEncryptedFileName(Path);
  7826. if (I != FEncryptedFileNames.end())
  7827. {
  7828. FileName = I->second;
  7829. }
  7830. else if (EncryptNewFiles)
  7831. {
  7832. TEncryption Encryption(FEncryptKey);
  7833. FileName = Encryption.EncryptFileName(FileName);
  7834. FEncryptedFileNames.insert(std::make_pair(Path, FileName));
  7835. LogEvent(2, FORMAT(L"Name of file '%s' encrypted as '%s'", (Path, FileName)));
  7836. }
  7837. }
  7838. FileDir = EncryptFileName(FileDir, EncryptNewFiles);
  7839. Result = UnixCombinePaths(FileDir, FileName);
  7840. }
  7841. return Result;
  7842. }
  7843. //---------------------------------------------------------------------------
  7844. UnicodeString __fastcall TTerminal::DecryptFileName(const UnicodeString & Path, bool DecryptFullPath, bool DontCache)
  7845. {
  7846. UnicodeString Result = Path;
  7847. if (IsEncryptingFiles() && !IsUnixRootPath(Path))
  7848. {
  7849. UnicodeString FileName = UnixExtractFileName(Path);
  7850. UnicodeString FileNameEncrypted = FileName;
  7851. bool Encrypted = TEncryption::IsEncryptedFileName(FileName);
  7852. if (Encrypted)
  7853. {
  7854. TEncryption Encryption(FEncryptKey);
  7855. FileName = Encryption.DecryptFileName(FileName);
  7856. }
  7857. if (Encrypted || DecryptFullPath) // DecryptFullPath is just an optimization
  7858. {
  7859. UnicodeString FileDir = UnixExtractFileDir(Path);
  7860. FileDir = DecryptFileName(FileDir, DecryptFullPath, DontCache);
  7861. Result = UnixCombinePaths(FileDir, FileName);
  7862. }
  7863. TEncryptedFileNames::iterator Iter = FEncryptedFileNames.find(Result);
  7864. bool NotCached = (Iter == FEncryptedFileNames.end());
  7865. if (!DontCache && (Encrypted || NotCached))
  7866. {
  7867. if (Encrypted && (NotCached || (Iter->second != FileNameEncrypted)))
  7868. {
  7869. LogEvent(2, FORMAT(L"Name of file '%s' decrypted from '%s'", (Result, FileNameEncrypted)));
  7870. }
  7871. // This may overwrite another variant of encryption
  7872. FEncryptedFileNames[Result] = FileNameEncrypted;
  7873. }
  7874. }
  7875. return Result;
  7876. }
  7877. //---------------------------------------------------------------------------
  7878. TRemoteFile * TTerminal::CheckRights(const UnicodeString & EntryType, const UnicodeString & FileName, bool & WrongRights)
  7879. {
  7880. std::unique_ptr<TRemoteFile> FileOwner;
  7881. TRemoteFile * File;
  7882. try
  7883. {
  7884. LogEvent(FORMAT(L"Checking %s \"%s\"...", (LowerCase(EntryType), FileName)));
  7885. ReadFile(FileName, File);
  7886. FileOwner.reset(File);
  7887. int ForbiddenRights = TRights::rfGroupWrite | TRights::rfOtherWrite;
  7888. if ((File->Rights->Number & ForbiddenRights) != 0)
  7889. {
  7890. LogEvent(FORMAT(L"%s \"%s\" exists, but has incorrect permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  7891. WrongRights = true;
  7892. }
  7893. else
  7894. {
  7895. LogEvent(FORMAT(L"%s \"%s\" exists and has correct permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  7896. }
  7897. }
  7898. catch (Exception & E)
  7899. {
  7900. }
  7901. return FileOwner.release();
  7902. }
  7903. //---------------------------------------------------------------------------
  7904. UnicodeString TTerminal::UploadPublicKey(const UnicodeString & FileName)
  7905. {
  7906. UnicodeString Result;
  7907. UnicodeString TemporaryDir;
  7908. bool PrevAutoReadDirectory = AutoReadDirectory;
  7909. bool PrevExceptionOnFail = ExceptionOnFail;
  7910. UnicodeString AuthorizedKeysFilePath = FORMAT(L"%s/%s", (OpensshFolderName, OpensshAuthorizedKeysFileName));
  7911. try
  7912. {
  7913. AutoReadDirectory = false;
  7914. ExceptionOnFail = true;
  7915. Log->AddSeparator();
  7916. UnicodeString Comment;
  7917. bool UnusedHasCertificate;
  7918. UnicodeString Line = GetPublicKeyLine(FileName, Comment, UnusedHasCertificate);
  7919. LogEvent(FORMAT(L"Adding public key line to \"%s\" file:\n%s", (AuthorizedKeysFilePath, Line)));
  7920. UnicodeString SshFolderAbsolutePath = UnixIncludeTrailingBackslash(GetHomeDirectory()) + OpensshFolderName;
  7921. bool WrongRights = false;
  7922. std::unique_ptr<TRemoteFile> SshFolderFile(CheckRights(L"Folder", SshFolderAbsolutePath, WrongRights));
  7923. if (SshFolderFile.get() == NULL)
  7924. {
  7925. TRights SshFolderRights;
  7926. SshFolderRights.Number = TRights::rfUserRead | TRights::rfUserWrite | TRights::rfUserExec;
  7927. TRemoteProperties SshFolderProperties;
  7928. SshFolderProperties.Rights = SshFolderRights;
  7929. SshFolderProperties.Valid = TValidProperties() << vpRights;
  7930. LogEvent(FORMAT(L"Trying to create \"%s\" folder with permissions %s...", (OpensshFolderName, SshFolderRights.Octal)));
  7931. CreateDirectory(SshFolderAbsolutePath, &SshFolderProperties);
  7932. }
  7933. TemporaryDir = ExcludeTrailingBackslash(Configuration->TemporaryDir());
  7934. if (!ForceDirectories(ApiPath(TemporaryDir)))
  7935. {
  7936. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TemporaryDir)));
  7937. }
  7938. UnicodeString TemporaryAuthorizedKeysFile = IncludeTrailingBackslash(TemporaryDir) + OpensshAuthorizedKeysFileName;
  7939. UnicodeString AuthorizedKeysFileAbsolutePath = UnixIncludeTrailingBackslash(SshFolderAbsolutePath) + OpensshAuthorizedKeysFileName;
  7940. bool Updated = true;
  7941. TCopyParamType CopyParam; // Use factory defaults
  7942. CopyParam.ResumeSupport = rsOff; // not to break the permissions
  7943. CopyParam.PreserveTime = false; // not needed
  7944. UnicodeString AuthorizedKeys;
  7945. std::unique_ptr<TRemoteFile> AuthorizedKeysFileFile(CheckRights(L"File", AuthorizedKeysFileAbsolutePath, WrongRights));
  7946. if (AuthorizedKeysFileFile.get() != NULL)
  7947. {
  7948. AuthorizedKeysFileFile->FullFileName = AuthorizedKeysFileAbsolutePath;
  7949. std::unique_ptr<TStrings> Files(new TStringList());
  7950. Files->AddObject(AuthorizedKeysFileAbsolutePath, AuthorizedKeysFileFile.get());
  7951. LogEvent(FORMAT(L"Downloading current \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  7952. CopyToLocal(Files.get(), TemporaryDir, &CopyParam, cpNoConfirmation, NULL);
  7953. // Overload with Encoding parameter work incorrectly, when used on a file without BOM
  7954. AuthorizedKeys = TFile::ReadAllText(TemporaryAuthorizedKeysFile);
  7955. std::unique_ptr<TStrings> AuthorizedKeysLines(TextToStringList(AuthorizedKeys));
  7956. int P = Line.Pos(L" ");
  7957. if (DebugAlwaysTrue(P > 0))
  7958. {
  7959. P = PosEx(L" ", Line, P + 1);
  7960. }
  7961. UnicodeString Prefix = Line.SubString(1, P); // including the space
  7962. for (int Index = 0; Index < AuthorizedKeysLines->Count; Index++)
  7963. {
  7964. if (StartsStr(Prefix, AuthorizedKeysLines->Strings[Index]))
  7965. {
  7966. LogEvent(FORMAT(L"\"%s\" file already contains public key line:\n%s", (OpensshAuthorizedKeysFileName, AuthorizedKeysLines->Strings[Index])));
  7967. Updated = false;
  7968. }
  7969. }
  7970. if (Updated)
  7971. {
  7972. LogEvent(FORMAT(L"\"%s\" file does not contain the public key line yet.", (OpensshAuthorizedKeysFileName)));
  7973. if (!EndsStr(L"\n", AuthorizedKeys))
  7974. {
  7975. LogEvent(FORMAT(L"Adding missing trailing new line to \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  7976. AuthorizedKeys += L"\n";
  7977. }
  7978. }
  7979. }
  7980. else
  7981. {
  7982. LogEvent(FORMAT(L"Creating new \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  7983. CopyParam.PreserveRights = true;
  7984. CopyParam.Rights.Number = TRights::rfUserRead | TRights::rfUserWrite;
  7985. }
  7986. if (Updated)
  7987. {
  7988. AuthorizedKeys += Line + L"\n";
  7989. // Overload without Encoding parameter uses TEncoding::UTF8, but does not write BOM, what we want
  7990. TFile::WriteAllText(TemporaryAuthorizedKeysFile, AuthorizedKeys);
  7991. std::unique_ptr<TStrings> Files(new TStringList());
  7992. Files->Add(TemporaryAuthorizedKeysFile);
  7993. LogEvent(FORMAT(L"Uploading updated \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  7994. CopyToRemote(Files.get(), SshFolderAbsolutePath, &CopyParam, cpNoConfirmation, NULL);
  7995. }
  7996. Result = FMTLOAD(PUBLIC_KEY_UPLOADED, (Comment));
  7997. if (WrongRights)
  7998. {
  7999. Result += L"\n\n" + FMTLOAD(PUBLIC_KEY_PERMISSIONS, (AuthorizedKeysFilePath));
  8000. }
  8001. }
  8002. __finally
  8003. {
  8004. AutoReadDirectory = PrevAutoReadDirectory;
  8005. ExceptionOnFail = PrevExceptionOnFail;
  8006. if (!TemporaryDir.IsEmpty())
  8007. {
  8008. RecursiveDeleteFile(ExcludeTrailingBackslash(TemporaryDir), false);
  8009. }
  8010. }
  8011. return Result;
  8012. }
  8013. //---------------------------------------------------------------------------
  8014. bool TTerminal::IsValidFile(TRemoteFile * File)
  8015. {
  8016. return
  8017. !File->FileName.IsEmpty() &&
  8018. (IsUnixRootPath(File->FileName) || UnixExtractFileDir(File->FileName).IsEmpty());
  8019. }
  8020. //---------------------------------------------------------------------------
  8021. //---------------------------------------------------------------------------
  8022. __fastcall TSecondaryTerminal::TSecondaryTerminal(
  8023. TTerminal * MainTerminal, TSessionData * ASessionData, TConfiguration * Configuration,
  8024. const UnicodeString & Name, TActionLog * ActionLog) :
  8025. TTerminal(ASessionData, Configuration, ActionLog),
  8026. FMainTerminal(MainTerminal)
  8027. {
  8028. Log->SetParent(FMainTerminal->Log, Name);
  8029. SessionData->NonPersistant();
  8030. DebugAssert(FMainTerminal != NULL);
  8031. FMainTerminal->FSecondaryTerminals++;
  8032. if (SessionData->TunnelLocalPortNumber != 0)
  8033. {
  8034. SessionData->TunnelLocalPortNumber = SessionData->TunnelLocalPortNumber + FMainTerminal->FSecondaryTerminals;
  8035. }
  8036. if (!FMainTerminal->UserName.IsEmpty())
  8037. {
  8038. SessionData->UserName = FMainTerminal->UserName;
  8039. }
  8040. }
  8041. //---------------------------------------------------------------------------
  8042. void __fastcall TSecondaryTerminal::UpdateFromMain()
  8043. {
  8044. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  8045. {
  8046. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  8047. }
  8048. }
  8049. //---------------------------------------------------------------------------
  8050. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  8051. {
  8052. FMainTerminal->DirectoryLoaded(FileList);
  8053. DebugAssert(FileList != NULL);
  8054. }
  8055. //---------------------------------------------------------------------------
  8056. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  8057. bool SubDirs)
  8058. {
  8059. // clear cache of main terminal
  8060. FMainTerminal->DirectoryModified(Path, SubDirs);
  8061. }
  8062. //---------------------------------------------------------------------------
  8063. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  8064. {
  8065. return FMainTerminal;
  8066. }
  8067. //---------------------------------------------------------------------------
  8068. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  8069. TObjectList()
  8070. {
  8071. DebugAssert(AConfiguration);
  8072. FConfiguration = AConfiguration;
  8073. }
  8074. //---------------------------------------------------------------------------
  8075. __fastcall TTerminalList::~TTerminalList()
  8076. {
  8077. DebugAssert(Count == 0);
  8078. }
  8079. //---------------------------------------------------------------------------
  8080. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  8081. {
  8082. return new TTerminal(Data, FConfiguration);
  8083. }
  8084. //---------------------------------------------------------------------------
  8085. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  8086. {
  8087. TTerminal * Terminal = CreateTerminal(Data);
  8088. Add(Terminal);
  8089. return Terminal;
  8090. }
  8091. //---------------------------------------------------------------------------
  8092. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  8093. {
  8094. DebugAssert(IndexOf(Terminal) >= 0);
  8095. Remove(Terminal);
  8096. }
  8097. //---------------------------------------------------------------------------
  8098. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  8099. {
  8100. TTerminal * T = Terminal;
  8101. Terminal = NULL;
  8102. FreeTerminal(T);
  8103. }
  8104. //---------------------------------------------------------------------------
  8105. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  8106. {
  8107. return dynamic_cast<TTerminal *>(Items[Index]);
  8108. }
  8109. //---------------------------------------------------------------------------
  8110. void __fastcall TTerminalList::RecryptPasswords()
  8111. {
  8112. for (int Index = 0; Index < Count; Index++)
  8113. {
  8114. Terminals[Index]->RecryptPasswords();
  8115. }
  8116. }
  8117. //---------------------------------------------------------------------------
  8118. //---------------------------------------------------------------------------
  8119. TLocalFileHandle::TLocalFileHandle()
  8120. {
  8121. Handle = 0;
  8122. Attrs = 0;
  8123. MTime = 0;
  8124. ATime = 0;
  8125. Size = 0;
  8126. Directory = false;
  8127. }
  8128. //---------------------------------------------------------------------------
  8129. TLocalFileHandle::~TLocalFileHandle()
  8130. {
  8131. Release();
  8132. }
  8133. //---------------------------------------------------------------------------
  8134. void TLocalFileHandle::Release()
  8135. {
  8136. if (Handle != 0)
  8137. {
  8138. Close();
  8139. }
  8140. }
  8141. //---------------------------------------------------------------------------
  8142. void TLocalFileHandle::Dismiss()
  8143. {
  8144. if (DebugAlwaysTrue(Handle != 0))
  8145. {
  8146. Handle = 0;
  8147. }
  8148. }
  8149. //---------------------------------------------------------------------------
  8150. void TLocalFileHandle::Close()
  8151. {
  8152. if (DebugAlwaysTrue(Handle != 0))
  8153. {
  8154. CloseHandle(Handle);
  8155. Dismiss();
  8156. }
  8157. }