Terminal.cpp 260 KB

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