1
0

Terminal.cpp 292 KB

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