Terminal.cpp 245 KB

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