Terminal.cpp 262 KB

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