Terminal.cpp 250 KB

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