Terminal.cpp 252 KB

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