Terminal.cpp 268 KB

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