Terminal.cpp 249 KB

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