Terminal.cpp 298 KB

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