Terminal.cpp 251 KB

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