Terminal.cpp 217 KB

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