Terminal.cpp 250 KB

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