Terminal.cpp 273 KB

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