Terminal.cpp 292 KB

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