Terminal.cpp 253 KB

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