Terminal.cpp 241 KB

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