Terminal.cpp 247 KB

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