Terminal.cpp 250 KB

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