Terminal.cpp 204 KB

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