Terminal.cpp 298 KB

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