Terminal.cpp 256 KB

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