Terminal.cpp 241 KB

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