Terminal.cpp 214 KB

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