Terminal.cpp 215 KB

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