Terminal.cpp 257 KB

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