1
0

Terminal.cpp 275 KB

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