Terminal.cpp 240 KB

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