Terminal.cpp 302 KB

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