Terminal.cpp 254 KB

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