Terminal.cpp 256 KB

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