1
0

Terminal.cpp 266 KB

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