123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226 |
- //---------------------------------------------------------------------------
- #include <vcl.h>
- #pragma hdrstop
- #include "Terminal.h"
- #include <SysUtils.hpp>
- #include <FileCtrl.hpp>
- #include <StrUtils.hpp>
- #include <System.IOUtils.hpp>
- #include "Common.h"
- #include "PuttyTools.h"
- #include "FileBuffer.h"
- #include "Interface.h"
- #include "RemoteFiles.h"
- #include "SecureShell.h"
- #include "ScpFileSystem.h"
- #include "SftpFileSystem.h"
- #include "FtpFileSystem.h"
- #include "WebDAVFileSystem.h"
- #include "S3FileSystem.h"
- #include "TextsCore.h"
- #include "HelpCore.h"
- #include "CoreMain.h"
- #include "Queue.h"
- #include "Cryptography.h"
- #include <openssl/pkcs12.h>
- #include <openssl/err.h>
- #ifndef AUTO_WINSOCK
- #include <winsock2.h>
- #endif
- //---------------------------------------------------------------------------
- #pragma package(smart_init)
- //---------------------------------------------------------------------------
- #define FILE_OPERATION_LOOP_TERMINAL this
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- class TLoopDetector
- {
- public:
- __fastcall TLoopDetector();
- void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
- bool __fastcall IsUnvisitedDirectory(const UnicodeString & Directory);
- private:
- std::unique_ptr<TStringList> FVisitedDirectories;
- };
- //---------------------------------------------------------------------------
- __fastcall TLoopDetector::TLoopDetector()
- {
- FVisitedDirectories.reset(CreateSortedStringList());
- }
- //---------------------------------------------------------------------------
- void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
- {
- UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
- FVisitedDirectories->Add(VisitedDirectory);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TLoopDetector::IsUnvisitedDirectory(const UnicodeString & Directory)
- {
- bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
- if (Result)
- {
- RecordVisitedDirectory(Directory);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- struct TMoveFileParams
- {
- UnicodeString Target;
- UnicodeString FileMask;
- };
- //---------------------------------------------------------------------------
- struct TFilesFindParams
- {
- TFileMasks FileMask;
- TFileFoundEvent OnFileFound;
- TFindingFileEvent OnFindingFile;
- bool Cancel;
- TLoopDetector LoopDetector;
- UnicodeString RealDirectory;
- };
- //---------------------------------------------------------------------------
- TCalculateSizeStats::TCalculateSizeStats()
- {
- memset(this, 0, sizeof(*this));
- }
- //---------------------------------------------------------------------------
- TCalculateSizeParams::TCalculateSizeParams()
- {
- memset(this, 0, sizeof(*this));
- Result = true;
- AllowDirs = true;
- }
- //---------------------------------------------------------------------------
- TSynchronizeOptions::TSynchronizeOptions()
- {
- memset(this, 0, sizeof(*this));
- }
- //---------------------------------------------------------------------------
- TSynchronizeOptions::~TSynchronizeOptions()
- {
- delete Filter;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
- {
- int FoundIndex;
- bool Result;
- if (Filter == NULL)
- {
- Result = true;
- }
- else
- {
- Result = Filter->Find(FileName, FoundIndex);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- TSpaceAvailable::TSpaceAvailable()
- {
- memset(this, 0, sizeof(*this));
- }
- //---------------------------------------------------------------------------
- TOverwriteFileParams::TOverwriteFileParams()
- {
- SourceSize = 0;
- DestSize = 0;
- SourcePrecision = mfFull;
- DestPrecision = mfFull;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- class TTunnelThread : public TSimpleThread
- {
- public:
- __fastcall TTunnelThread(TSecureShell * SecureShell);
- virtual __fastcall ~TTunnelThread();
- virtual void __fastcall Terminate();
- protected:
- virtual void __fastcall Execute();
- private:
- TSecureShell * FSecureShell;
- bool FTerminated;
- };
- //---------------------------------------------------------------------------
- __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
- FSecureShell(SecureShell),
- FTerminated(false)
- {
- Start();
- }
- //---------------------------------------------------------------------------
- __fastcall TTunnelThread::~TTunnelThread()
- {
- // close before the class's virtual functions (Terminate particularly) are lost
- Close();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelThread::Terminate()
- {
- FTerminated = true;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelThread::Execute()
- {
- try
- {
- while (!FTerminated)
- {
- FSecureShell->Idle(250);
- }
- }
- catch(...)
- {
- if (FSecureShell->Active)
- {
- FSecureShell->Close();
- }
- // do not pass exception out of thread's proc
- }
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- class TTunnelUI : public TSessionUI
- {
- public:
- __fastcall TTunnelUI(TTerminal * Terminal);
- virtual void __fastcall Information(const UnicodeString & Str, bool Status);
- virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
- TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
- TQueryType QueryType);
- virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
- Exception * E, unsigned int Answers, const TQueryParams * Params,
- TQueryType QueryType);
- virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
- UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
- TStrings * Results);
- virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
- virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
- virtual void __fastcall HandleExtendedException(Exception * E);
- virtual void __fastcall Closed();
- virtual void __fastcall ProcessGUI();
- private:
- TTerminal * FTerminal;
- unsigned int FTerminalThread;
- };
- //---------------------------------------------------------------------------
- __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
- {
- FTerminal = Terminal;
- FTerminalThread = GetCurrentThreadId();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
- {
- if (GetCurrentThreadId() == FTerminalThread)
- {
- FTerminal->Information(Str, Status);
- }
- }
- //---------------------------------------------------------------------------
- unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
- TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
- TQueryType QueryType)
- {
- unsigned int Result;
- if (GetCurrentThreadId() == FTerminalThread)
- {
- Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
- }
- else
- {
- Result = AbortAnswer(Answers);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
- Exception * E, unsigned int Answers, const TQueryParams * Params,
- TQueryType QueryType)
- {
- unsigned int Result;
- if (GetCurrentThreadId() == FTerminalThread)
- {
- Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
- }
- else
- {
- Result = AbortAnswer(Answers);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
- UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
- {
- bool Result;
- if (GetCurrentThreadId() == FTerminalThread)
- {
- if (IsAuthenticationPrompt(Kind))
- {
- Instructions =
- FMTLOAD(TUNNEL_INSTRUCTION2, (Data->HostName)) +
- (Instructions.IsEmpty() ? L"" : L"\n") +
- Instructions;
- }
- Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
- }
- else
- {
- Result = false;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
- {
- if (GetCurrentThreadId() == FTerminalThread)
- {
- FTerminal->DisplayBanner(Banner);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
- {
- throw ESshFatal(E, Msg, HelpKeyword);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
- {
- if (GetCurrentThreadId() == FTerminalThread)
- {
- FTerminal->HandleExtendedException(E);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelUI::Closed()
- {
- // noop
- }
- //---------------------------------------------------------------------------
- void __fastcall TTunnelUI::ProcessGUI()
- {
- // noop
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- class TCallbackGuard
- {
- public:
- inline __fastcall TCallbackGuard(TTerminal * FTerminal);
- inline __fastcall ~TCallbackGuard();
- void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
- inline void __fastcall Verify();
- inline bool __fastcall Verify(Exception * E);
- void __fastcall Dismiss();
- private:
- ExtException * FFatalError;
- TTerminal * FTerminal;
- bool FGuarding;
- };
- //---------------------------------------------------------------------------
- __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
- FTerminal(Terminal),
- FFatalError(NULL),
- FGuarding(FTerminal->FCallbackGuard == NULL)
- {
- if (FGuarding)
- {
- FTerminal->FCallbackGuard = this;
- }
- }
- //---------------------------------------------------------------------------
- __fastcall TCallbackGuard::~TCallbackGuard()
- {
- if (FGuarding)
- {
- DebugAssert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
- FTerminal->FCallbackGuard = NULL;
- }
- delete FFatalError;
- }
- //---------------------------------------------------------------------------
- void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
- {
- DebugAssert(FGuarding);
- // make sure we do not bother about getting back the silent abort exception
- // we issued ourselves. this may happen when there is an exception handler
- // that converts any exception to fatal one (such as in TTerminal::Open).
- if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
- {
- delete FFatalError;
- FFatalError = new ExtException(E, Msg, HelpKeyword);
- }
- // silently abort what we are doing.
- // non-silent exception would be caught probably by default application
- // exception handler, which may not do an appropriate action
- // (particularly it will not resume broken transfer).
- throw ECallbackGuardAbort();
- }
- //---------------------------------------------------------------------------
- void __fastcall TCallbackGuard::Dismiss()
- {
- DebugAssert(FFatalError == NULL);
- FGuarding = false;
- }
- //---------------------------------------------------------------------------
- void __fastcall TCallbackGuard::Verify()
- {
- if (FGuarding)
- {
- FGuarding = false;
- DebugAssert(FTerminal->FCallbackGuard == this);
- FTerminal->FCallbackGuard = NULL;
- if (FFatalError != NULL)
- {
- throw ESshFatal(FFatalError, L"");
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TCallbackGuard::Verify(Exception * E)
- {
- bool Result =
- (dynamic_cast<ECallbackGuardAbort *>(E) != NULL);
- if (Result)
- {
- DebugAssert(FGuarding && (FFatalError != NULL));
- Verify();
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- TRobustOperationLoop::TRobustOperationLoop(
- TTerminal * Terminal, TFileOperationProgressType * OperationProgress, bool * AnyTransfer, bool CanRetry) :
- FTerminal(Terminal),
- FOperationProgress(OperationProgress),
- FRetry(false),
- FAnyTransfer(AnyTransfer),
- FCanRetry(CanRetry)
- {
- if (FAnyTransfer != NULL)
- {
- FPrevAnyTransfer = *FAnyTransfer;
- *FAnyTransfer = false;
- FStart = Now();
- }
- }
- //---------------------------------------------------------------------------
- TRobustOperationLoop::~TRobustOperationLoop()
- {
- if (FAnyTransfer != NULL)
- {
- *FAnyTransfer = FPrevAnyTransfer;
- }
- }
- //---------------------------------------------------------------------------
- bool TRobustOperationLoop::TryReopen(Exception & E)
- {
- FRetry = FCanRetry && !FTerminal->Active;
- if (!FCanRetry)
- {
- FRetry = false;
- }
- else if (FTerminal->Active)
- {
- FTerminal->LogEvent(1, L"Session is open, will not retry transfer");
- FRetry = false;
- }
- else
- {
- FRetry = true;
- if (FAnyTransfer != NULL)
- {
- // if there was any transfer, reset the global timestamp
- if (*FAnyTransfer)
- {
- FStart = Now();
- FPrevAnyTransfer = true;
- *FAnyTransfer = false;
- }
- else
- {
- FRetry = FTerminal->ContinueReopen(FStart);
- if (!FRetry)
- {
- FTerminal->LogEvent(L"Retry interval expired, will not retry transfer");
- }
- }
- }
- if (FRetry)
- {
- FRetry =
- FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
- }
- }
- return FRetry;
- }
- //---------------------------------------------------------------------------
- bool TRobustOperationLoop::ShouldRetry()
- {
- return FRetry;
- }
- //---------------------------------------------------------------------------
- bool TRobustOperationLoop::Retry()
- {
- bool Result = FRetry;
- FRetry = false;
- return Result;
- }
- //---------------------------------------------------------------------------
- class TRetryOperationLoop
- {
- public:
- TRetryOperationLoop(TTerminal * Terminal);
- void Error(Exception & E);
- void Error(Exception & E, TSessionAction & Action);
- void Error(Exception & E, const UnicodeString & Message);
- void Error(Exception & E, TSessionAction & Action, const UnicodeString & Message);
- bool Retry();
- bool Succeeded();
- private:
- TTerminal * FTerminal;
- bool FRetry;
- bool FSucceeded;
- void DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message);
- };
- //---------------------------------------------------------------------------
- TRetryOperationLoop::TRetryOperationLoop(TTerminal * Terminal)
- {
- FTerminal = Terminal;
- FRetry = false;
- FSucceeded = true;
- }
- //---------------------------------------------------------------------------
- void TRetryOperationLoop::DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message)
- {
- FSucceeded = false;
- // Note that the action may already be canceled when RollbackAction is called
- unsigned int Result;
- try
- {
- Result = FTerminal->CommandError(&E, Message, qaRetry | qaSkip | qaAbort);
- }
- catch (Exception & E2)
- {
- if (Action != NULL)
- {
- FTerminal->RollbackAction(*Action, NULL, &E2);
- }
- throw;
- }
- switch (Result)
- {
- case qaRetry:
- FRetry = true;
- if (Action != NULL)
- {
- Action->Cancel();
- }
- break;
- case qaAbort:
- if (Action != NULL)
- {
- FTerminal->RollbackAction(*Action, NULL, &E);
- }
- Abort();
- break;
- case qaSkip:
- if (Action != NULL)
- {
- Action->Cancel();
- }
- break;
- default:
- DebugFail();
- break;
- }
- }
- //---------------------------------------------------------------------------
- void TRetryOperationLoop::Error(Exception & E)
- {
- DoError(E, NULL, UnicodeString());
- }
- //---------------------------------------------------------------------------
- void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action)
- {
- DoError(E, &Action, UnicodeString());
- }
- //---------------------------------------------------------------------------
- void TRetryOperationLoop::Error(Exception & E, const UnicodeString & Message)
- {
- DoError(E, NULL, Message);
- }
- //---------------------------------------------------------------------------
- void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action, const UnicodeString & Message)
- {
- DoError(E, &Action, Message);
- }
- //---------------------------------------------------------------------------
- bool TRetryOperationLoop::Retry()
- {
- bool Result = FRetry;
- FRetry = false;
- if (Result)
- {
- FSucceeded = true;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool TRetryOperationLoop::Succeeded()
- {
- return FSucceeded;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- TCollectedFileList::TCollectedFileList()
- {
- }
- //---------------------------------------------------------------------------
- int TCollectedFileList::Add(const UnicodeString & FileName, TObject * Object, bool Dir)
- {
- TFileData Data;
- Data.FileName = FileName;
- Data.Object = Object;
- Data.Dir = Dir;
- Data.Recursed = true;
- FList.push_back(Data);
- return Count() - 1;
- }
- //---------------------------------------------------------------------------
- void TCollectedFileList::DidNotRecurse(int Index)
- {
- FList[Index].Recursed = false;
- }
- //---------------------------------------------------------------------------
- void TCollectedFileList::Delete(int Index)
- {
- FList.erase(FList.begin() + Index);
- }
- //---------------------------------------------------------------------------
- int TCollectedFileList::Count() const
- {
- return FList.size();
- }
- //---------------------------------------------------------------------------
- UnicodeString TCollectedFileList::GetFileName(int Index) const
- {
- return FList[Index].FileName;
- }
- //---------------------------------------------------------------------------
- TObject * TCollectedFileList::GetObject(int Index) const
- {
- return FList[Index].Object;
- }
- //---------------------------------------------------------------------------
- bool TCollectedFileList::IsDir(int Index) const
- {
- return FList[Index].Dir;
- }
- //---------------------------------------------------------------------------
- bool TCollectedFileList::IsRecursed(int Index) const
- {
- return FList[Index].Recursed;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- TParallelOperation::TParallelOperation(TOperationSide Side)
- {
- FCopyParam = NULL;
- FParams = 0;
- FProbablyEmpty = false;
- FClients = 0;
- FMainOperationProgress = NULL;
- DebugAssert((Side == osLocal) || (Side == osRemote));
- FSide = Side;
- }
- //---------------------------------------------------------------------------
- void TParallelOperation::Init(
- TStrings * AFileList, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * MainOperationProgress, const UnicodeString & MainName)
- {
- DebugAssert(FFileList.get() == NULL);
- // More lists should really happen in scripting only, which does not support parallel transfers atm.
- // But in general the code should work with more lists anyway, it just was not tested for it.
- DebugAssert(AFileList->Count == 1);
- FFileList.reset(AFileList);
- FSection.reset(new TCriticalSection());
- FTargetDir = TargetDir;
- FCopyParam = CopyParam;
- FParams = Params;
- FMainOperationProgress = MainOperationProgress;
- FMainName = MainName;
- FIndex = 0;
- }
- //---------------------------------------------------------------------------
- TParallelOperation::~TParallelOperation()
- {
- WaitFor();
- }
- //---------------------------------------------------------------------------
- bool TParallelOperation::IsInitialized()
- {
- return (FMainOperationProgress != NULL);
- }
- //---------------------------------------------------------------------------
- bool TParallelOperation::ShouldAddClient()
- {
- bool Result;
- // TTransferQueueItem::ProgressUpdated() already checks IsInitialized() before calling this
- if (!IsInitialized())
- {
- Result = false;
- }
- else
- {
- TGuard Guard(FSection.get());
- Result = !FProbablyEmpty && (FMainOperationProgress->Cancel < csCancel);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void TParallelOperation::AddClient()
- {
- TGuard Guard(FSection.get());
- FClients++;
- }
- //---------------------------------------------------------------------------
- void TParallelOperation::RemoveClient()
- {
- TGuard Guard(FSection.get());
- FClients--;
- }
- //---------------------------------------------------------------------------
- void TParallelOperation::WaitFor()
- {
- // Even initialized?
- // Won't be, when parallel transfers were not possible (like when preserving of directory timestamps is enabled)
- if (FSection.get() != NULL)
- {
- bool Done;
- do
- {
- {
- TGuard Guard(FSection.get());
- Done = (FClients == 0);
- }
- if (!Done)
- {
- // propagate the total progress incremented by the parallel operations
- FMainOperationProgress->Progress();
- Sleep(200);
- }
- }
- while (!Done);
- FProbablyEmpty = true;
- }
- else
- {
- DebugAssert(FClients == 0);
- }
- }
- //---------------------------------------------------------------------------
- void TParallelOperation::Done(const UnicodeString & FileName, bool Dir, bool Success)
- {
- if (Dir)
- {
- TGuard Guard(FSection.get());
- TDirectories::iterator DirectoryIterator = FDirectories.find(FileName);
- if (DebugAlwaysTrue(DirectoryIterator != FDirectories.end()))
- {
- if (Success)
- {
- DebugAssert(!DirectoryIterator->second.Exists);
- DirectoryIterator->second.Exists = true;
- }
- else
- {
- // This is actually not useful at the moment, as when creating directory fails and "Skip" is pressed,
- // the current code in CopyToRemote/CreateDirectory will behave as, if it succedded, so Successs will be true here.
- FDirectories.erase(DirectoryIterator);
- if (FFileList->Count > 0)
- {
- UnicodeString FileNameWithSlash;
- if (FSide == osLocal)
- {
- FileNameWithSlash = IncludeTrailingBackslash(FileName);
- }
- else
- {
- FileNameWithSlash = UnixIncludeTrailingBackslash(FileName);
- }
- // It can actually be a different list than the one the directory was taken from,
- // but that does not matter that much. It should not happen anyway, as more lists should be in scripting only.
- TCollectedFileList * Files = DebugNotNull(dynamic_cast<TCollectedFileList *>(FFileList->Objects[0]));
- int Index = 0;
- while (Index < Files->Count())
- {
- if (StartsText(FileNameWithSlash, Files->GetFileName(Index)))
- {
- // We should add the file to "skip" counters in the OperationProgress,
- // but an interactive foreground transfer is not doing that either yet.
- Files->Delete(Index);
- if (Index < FIndex)
- {
- FIndex--;
- }
- }
- else
- {
- Index++;
- }
- }
- }
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- bool TParallelOperation::CheckEnd(TCollectedFileList * Files)
- {
- bool Result = (FIndex >= Files->Count());
- if (Result)
- {
- FFileList->Delete(0);
- FIndex = 0;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- int TParallelOperation::GetNext(TTerminal * Terminal, UnicodeString & FileName, TObject *& Object, UnicodeString & TargetDir, bool & Dir, bool & Recursed)
- {
- TGuard Guard(FSection.get());
- int Result = 1;
- TCollectedFileList * Files;
- do
- {
- if (FFileList->Count > 0)
- {
- Files = DebugNotNull(dynamic_cast<TCollectedFileList *>(FFileList->Objects[0]));
- // can happen if the file was excluded by file mask
- if (CheckEnd(Files))
- {
- Files = NULL;
- }
- }
- else
- {
- Files = NULL;
- Result = -1;
- }
- }
- while ((Result == 1) && (Files == NULL));
- if (Files != NULL)
- {
- UnicodeString RootPath = FFileList->Strings[0];
- FileName = Files->GetFileName(FIndex);
- Object = Files->GetObject(FIndex);
- Dir = Files->IsDir(FIndex);
- Recursed = Files->IsRecursed(FIndex);
- UnicodeString DirPath;
- bool FirstLevel;
- if (FSide == osLocal)
- {
- DirPath = ExtractFileDir(FileName);
- FirstLevel = SamePaths(DirPath, RootPath);
- }
- else
- {
- DirPath = UnixExtractFileDir(FileName);
- FirstLevel = UnixSamePath(DirPath, RootPath);
- }
- if (FirstLevel)
- {
- TargetDir = FTargetDir;
- }
- else
- {
- TDirectories::const_iterator DirectoryIterator = FDirectories.find(DirPath);
- if (DebugAlwaysFalse(DirectoryIterator == FDirectories.end()))
- {
- throw EInvalidOperation(L"Parent path not known");
- }
- const TDirectoryData & DirectoryData = DirectoryIterator->second;
- if (!DirectoryData.Exists)
- {
- Result = 0; // wait for parent directory to be created
- }
- else
- {
- TargetDir = DirectoryData.OppositePath;
- }
- }
- if (!TargetDir.IsEmpty())
- {
- if (Dir)
- {
- TDirectoryData DirectoryData;
- UnicodeString OnlyFileName;
- if (FSide == osLocal)
- {
- OnlyFileName = ExtractFileName(FileName);
- }
- else
- {
- OnlyFileName = UnixExtractFileName(FileName);
- }
- OnlyFileName = Terminal->ChangeFileName(FCopyParam, OnlyFileName, osRemote, FirstLevel);
- if (FSide == osLocal)
- {
- DirectoryData.OppositePath = UnixCombinePaths(TargetDir, OnlyFileName);
- }
- else
- {
- DirectoryData.OppositePath = TPath::Combine(TargetDir, OnlyFileName);
- }
- DirectoryData.Exists = false;
- FDirectories.insert(std::make_pair(FileName, DirectoryData));
- }
- FIndex++;
- CheckEnd(Files);
- }
- }
- FProbablyEmpty = (FFileList->Count == 0);
- return Result;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- __fastcall TTerminal::TTerminal(TSessionData * SessionData,
- TConfiguration * Configuration)
- {
- FConfiguration = Configuration;
- FSessionData = new TSessionData(L"");
- FSessionData->Assign(SessionData);
- TDateTime Started = Now(); // use the same time for session and XML log
- FLog = new TSessionLog(this, Started, FSessionData, Configuration);
- FActionLog = new TActionLog(this, Started, FSessionData, Configuration);
- FFiles = new TRemoteDirectory(this);
- FExceptionOnFail = 0;
- FInTransaction = 0;
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- FUsersGroupsLookedup = False;
- FTunnelLocalPortNumber = 0;
- FFileSystem = NULL;
- FSecureShell = NULL;
- FOnProgress = NULL;
- FOnFinished = NULL;
- FOnDeleteLocalFile = NULL;
- FOnReadDirectoryProgress = NULL;
- FOnQueryUser = NULL;
- FOnPromptUser = NULL;
- FOnDisplayBanner = NULL;
- FOnShowExtendedException = NULL;
- FOnInformation = NULL;
- FOnCustomCommand = NULL;
- FOnClose = NULL;
- FOnFindingFile = NULL;
- FOperationProgressPersistence = NULL;
- FOperationProgressOnceDoneOperation = odoIdle;
- FUseBusyCursor = True;
- FLockDirectory = L"";
- FDirectoryCache = new TRemoteDirectoryCache();
- FDirectoryChangesCache = NULL;
- FFSProtocol = cfsUnknown;
- FCommandSession = NULL;
- FAutoReadDirectory = true;
- FReadingCurrentDirectory = false;
- FStatus = ssClosed;
- FOpening = 0;
- FTunnelThread = NULL;
- FTunnel = NULL;
- FTunnelData = NULL;
- FTunnelLog = NULL;
- FTunnelUI = NULL;
- FTunnelOpening = false;
- FCallbackGuard = NULL;
- FNesting = 0;
- FRememberedPasswordKind = TPromptKind(-1);
- }
- //---------------------------------------------------------------------------
- __fastcall TTerminal::~TTerminal()
- {
- if (Active)
- {
- Close();
- }
- if (FCallbackGuard != NULL)
- {
- // see TTerminal::HandleExtendedException
- FCallbackGuard->Dismiss();
- }
- DebugAssert(FTunnel == NULL);
- SAFE_DESTROY(FCommandSession);
- if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
- (FDirectoryChangesCache != NULL))
- {
- Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
- FDirectoryChangesCache);
- }
- SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
- SAFE_DESTROY_EX(TSessionLog, FLog);
- SAFE_DESTROY_EX(TActionLog, FActionLog);
- delete FFiles;
- delete FDirectoryCache;
- delete FDirectoryChangesCache;
- SAFE_DESTROY(FSessionData);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Idle()
- {
- // Once we disconnect, do nothing, until reconnect handler
- // "receives the information".
- // Never go idle when called from within ::ProcessGUI() call
- // as we may recurse for good, timeouting eventually.
- if (Active && (FNesting == 0))
- {
- TAutoNestingCounter NestingCounter(FNesting);
- if (Configuration->ActualLogProtocol >= 1)
- {
- LogEvent(L"Session upkeep");
- }
- DebugAssert(FFileSystem != NULL);
- FFileSystem->Idle();
- if (CommandSessionOpened)
- {
- try
- {
- FCommandSession->Idle();
- }
- catch(Exception & E)
- {
- // If the secondary session is dropped, ignore the error and let
- // it be reconnected when needed.
- // BTW, non-fatal error can hardly happen here, that's why
- // it is displayed, because it can be useful to know.
- if (FCommandSession->Active)
- {
- FCommandSession->HandleExtendedException(&E);
- }
- }
- }
- }
- }
- //---------------------------------------------------------------------
- RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
- {
- return Configuration->EncryptPassword(Password, SessionData->SessionName);
- }
- //---------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
- {
- UnicodeString Result;
- try
- {
- Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
- }
- catch(EAbort &)
- {
- // silently ignore aborted prompts for master password and return empty password
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RecryptPasswords()
- {
- FSessionData->RecryptPasswords();
- FRememberedPassword = EncryptPassword(GetRememberedPassword());
- FRememberedTunnelPassword = EncryptPassword(GetRememberedTunnelPassword());
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
- const UnicodeString BasePath)
- {
- // replace this by AbsolutePath()
- Path = UnixExcludeTrailingBackslash(Path);
- if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
- {
- // TODO: Handle more complicated cases like "../../xxx"
- if (Path == PARENTDIRECTORY)
- {
- Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
- UnixExcludeTrailingBackslash(BasePath)));
- }
- else
- {
- Path = UnixIncludeTrailingBackslash(BasePath) + Path;
- }
- }
- return Path;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetActive()
- {
- return (FFileSystem != NULL) && FFileSystem->GetActive();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Close()
- {
- FFileSystem->Close();
- // Cannot rely on CommandSessionOpened here as Status is set to ssClosed too late
- if ((FCommandSession != NULL) && FCommandSession->Active)
- {
- // prevent recursion
- FCommandSession->OnClose = NULL;
- FCommandSession->Close();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ResetConnection()
- {
- // used to be called from Reopen(), why?
- FTunnelError = L"";
- FRememberedPasswordTried = false;
- FRememberedTunnelPasswordTried = false;
- if (FDirectoryChangesCache != NULL)
- {
- delete FDirectoryChangesCache;
- FDirectoryChangesCache = NULL;
- }
- FFiles->Directory = L"";
- // note that we cannot clear contained files
- // as they can still be referenced in the GUI atm
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FingerprintScan(UnicodeString & SHA256, UnicodeString & SHA1, UnicodeString & MD5)
- {
- SessionData->FingerprintScan = true;
- try
- {
- Open();
- // we should never get here
- DebugFail();
- Abort();
- }
- catch (...)
- {
- if (!FFingerprintScannedSHA256.IsEmpty() ||
- !FFingerprintScannedSHA1.IsEmpty() ||
- !FFingerprintScannedMD5.IsEmpty())
- {
- SHA256 = FFingerprintScannedSHA256;
- SHA1 = FFingerprintScannedSHA1;
- MD5 = FFingerprintScannedMD5;
- }
- else
- {
- throw;
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Open()
- {
- TAutoNestingCounter OpeningCounter(FOpening);
- ReflectSettings();
- try
- {
- FEncryptKey = HexToBytes(FSessionData->EncryptKey);
- if (IsEncryptingFiles())
- {
- ValidateEncryptKey(FEncryptKey);
- }
- DoInformation(L"", true, 1);
- try
- {
- try
- {
- ResetConnection();
- FStatus = ssOpening;
- try
- {
- if (FFileSystem == NULL)
- {
- Log->AddSystemInfo();
- DoInitializeLog();
- Log->AddStartupInfo();
- }
- DebugAssert(FTunnel == NULL);
- if (FSessionData->Tunnel)
- {
- DoInformation(LoadStr(OPEN_TUNNEL), true);
- LogEvent(L"Opening tunnel.");
- OpenTunnel();
- Log->AddSeparator();
- FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
- DoInformation(LoadStr(USING_TUNNEL), false);
- LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
- (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
- }
- else
- {
- DebugAssert(FTunnelLocalPortNumber == 0);
- }
- if (FFileSystem == NULL)
- {
- if (SessionData->FSProtocol == fsFTP)
- {
- FFSProtocol = cfsFTP;
- FFileSystem = new TFTPFileSystem(this);
- FFileSystem->Open();
- Log->AddSeparator();
- LogEvent(L"Using FTP protocol.");
- }
- else if (SessionData->FSProtocol == fsWebDAV)
- {
- FFSProtocol = cfsWebDAV;
- FFileSystem = new TWebDAVFileSystem(this);
- FFileSystem->Open();
- Log->AddSeparator();
- LogEvent(L"Using WebDAV protocol.");
- }
- else if (SessionData->FSProtocol == fsS3)
- {
- FFSProtocol = cfsS3;
- FFileSystem = new TS3FileSystem(this);
- FFileSystem->Open();
- Log->AddSeparator();
- LogEvent(L"Using S3 protocol.");
- }
- else
- {
- DebugAssert(FSecureShell == NULL);
- try
- {
- FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
- try
- {
- // there will be only one channel in this session
- FSecureShell->Simple = true;
- FSecureShell->Open();
- }
- catch(Exception & E)
- {
- DebugAssert(!FSecureShell->Active);
- if (SessionData->FingerprintScan)
- {
- FSecureShell->GetHostKeyFingerprint(FFingerprintScannedSHA256, FFingerprintScannedMD5);
- FFingerprintScannedSHA1 = UnicodeString();
- }
- if (!FSecureShell->Active && !FTunnelError.IsEmpty())
- {
- // the only case where we expect this to happen
- DebugAssert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
- FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
- }
- else
- {
- throw;
- }
- }
- Log->AddSeparator();
- if ((SessionData->FSProtocol == fsSCPonly) ||
- (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
- {
- FFSProtocol = cfsSCP;
- FFileSystem = new TSCPFileSystem(this, FSecureShell);
- FSecureShell = NULL; // ownership passed
- LogEvent(L"Using SCP protocol.");
- }
- else
- {
- FFSProtocol = cfsSFTP;
- FFileSystem = new TSFTPFileSystem(this, FSecureShell);
- FSecureShell = NULL; // ownership passed
- LogEvent(L"Using SFTP protocol.");
- }
- }
- __finally
- {
- delete FSecureShell;
- FSecureShell = NULL;
- }
- }
- }
- else
- {
- FFileSystem->Open();
- }
- }
- __finally
- {
- if (FSessionData->Tunnel)
- {
- FSessionData->RollbackTunnel();
- }
- }
- if (SessionData->CacheDirectoryChanges)
- {
- DebugAssert(FDirectoryChangesCache == NULL);
- FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
- Configuration->CacheDirectoryChangesMaxSize);
- if (SessionData->PreserveDirectoryChanges)
- {
- Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
- FDirectoryChangesCache);
- }
- }
- DoStartup();
- if (FCollectFileSystemUsage)
- {
- FFileSystem->CollectUsage();
- FCollectFileSystemUsage = false;
- }
- DoInformation(LoadStr(STATUS_READY), true);
- FStatus = ssOpened;
- }
- catch(...)
- {
- // rollback
- if (FDirectoryChangesCache != NULL)
- {
- delete FDirectoryChangesCache;
- FDirectoryChangesCache = NULL;
- }
- if (SessionData->FingerprintScan && (FFileSystem != NULL) &&
- DebugAlwaysTrue(SessionData->Ftps != ftpsNone))
- {
- const TSessionInfo & SessionInfo = FFileSystem->GetSessionInfo();
- FFingerprintScannedSHA256 = SessionInfo.CertificateFingerprintSHA256;
- FFingerprintScannedSHA1 = SessionInfo.CertificateFingerprintSHA1;
- FFingerprintScannedMD5 = UnicodeString();
- }
- // Particularly to prevent reusing a wrong client certificate passphrase
- // in the next login attempt
- FRememberedPassword = UnicodeString();
- FRememberedPasswordKind = TPromptKind(-1);
- FRememberedTunnelPassword = UnicodeString();
- throw;
- }
- }
- __finally
- {
- // This does not make it through, if terminal thread is abandonded,
- // see also TTerminalManager::DoConnectTerminal
- DoInformation(L"", true, 0);
- }
- }
- catch(EFatal &)
- {
- throw;
- }
- catch(Exception & E)
- {
- // any exception while opening session is fatal
- FatalError(&E, L"");
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
- {
- SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
- bool Result = (Socket != INVALID_SOCKET);
- if (Result)
- {
- SOCKADDR_IN Address;
- memset(&Address, 0, sizeof(Address));
- Address.sin_family = AF_INET;
- Address.sin_port = htons(static_cast<short>(PortNumber));
- Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
- closesocket(Socket);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OpenTunnel()
- {
- DebugAssert(FTunnelData == NULL);
- FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
- if (FTunnelLocalPortNumber == 0)
- {
- FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
- while (!IsListenerFree(FTunnelLocalPortNumber))
- {
- FTunnelLocalPortNumber++;
- if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
- {
- FTunnelLocalPortNumber = 0;
- FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
- (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
- }
- }
- LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
- }
- try
- {
- FTunnelData = new TSessionData(L"");
- FTunnelData->Assign(StoredSessions->DefaultSettings);
- FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
- FTunnelData->Tunnel = false;
- FTunnelData->HostName = FSessionData->TunnelHostName;
- FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
- FTunnelData->UserName = FSessionData->TunnelUserName;
- FTunnelData->Password = FSessionData->TunnelPassword;
- FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
- UnicodeString HostName = FSessionData->HostNameExpanded;
- if (IsIPv6Literal(HostName))
- {
- HostName = EscapeIPv6Literal(HostName);
- }
- FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
- (FTunnelLocalPortNumber, HostName, FSessionData->PortNumber));
- FTunnelData->HostKey = FSessionData->TunnelHostKey;
- // inherit proxy options on the main session
- FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
- FTunnelData->ProxyHost = FSessionData->ProxyHost;
- FTunnelData->ProxyPort = FSessionData->ProxyPort;
- FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
- FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
- FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
- FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
- FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
- FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
- // inherit most SSH options of the main session (except for private key and bugs)
- FTunnelData->Compression = FSessionData->Compression;
- FTunnelData->SshProt = FSessionData->SshProt;
- FTunnelData->CipherList = FSessionData->CipherList;
- FTunnelData->Ssh2DES = FSessionData->Ssh2DES;
- FTunnelData->KexList = FSessionData->KexList;
- FTunnelData->RekeyData = FSessionData->RekeyData;
- FTunnelData->RekeyTime = FSessionData->RekeyTime;
- FTunnelData->SshNoUserAuth = FSessionData->SshNoUserAuth;
- FTunnelData->AuthGSSAPI = FSessionData->AuthGSSAPI;
- FTunnelData->AuthGSSAPIKEX = FSessionData->AuthGSSAPIKEX;
- FTunnelData->GSSAPIFwdTGT = FSessionData->GSSAPIFwdTGT;
- FTunnelData->TryAgent = FSessionData->TryAgent;
- FTunnelData->AgentFwd = FSessionData->AgentFwd;
- FTunnelData->AuthTIS = FSessionData->AuthTIS;
- FTunnelData->AuthKI = FSessionData->AuthKI;
- FTunnelData->AuthKIPassword = FSessionData->AuthKIPassword;
- // The Started argument is not used with Parent being set
- FTunnelLog = new TSessionLog(this, TDateTime(), FTunnelData, Configuration);
- FTunnelLog->SetParent(FLog, L"Tunnel");
- FTunnelLog->ReflectSettings();
- FTunnelUI = new TTunnelUI(this);
- FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
- FTunnelOpening = true;
- try
- {
- FTunnel->Open();
- }
- __finally
- {
- FTunnelOpening = false;
- }
- FTunnelThread = new TTunnelThread(FTunnel);
- }
- catch(...)
- {
- CloseTunnel();
- throw;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CloseTunnel()
- {
- SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
- FTunnelError = FTunnel->LastTunnelError;
- SAFE_DESTROY_EX(TSecureShell, FTunnel);
- SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
- SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
- SAFE_DESTROY(FTunnelData);
- FTunnelLocalPortNumber = 0;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Closed()
- {
- if (FTunnel != NULL)
- {
- CloseTunnel();
- }
- if (OnClose)
- {
- TCallbackGuard Guard(this);
- try
- {
- OnClose(this);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- FStatus = ssClosed;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ProcessGUI()
- {
- // Do not process GUI here, as we are called directly from a GUI loop and may
- // recurse for good.
- // Alternatively we may check for (FOperationProgress == NULL)
- if (FNesting == 0)
- {
- TAutoNestingCounter NestingCounter(FNesting);
- ::ProcessGUI();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Progress(TFileOperationProgressType * OperationProgress)
- {
- if (FNesting == 0)
- {
- TAutoNestingCounter NestingCounter(FNesting);
- OperationProgress->Progress();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Reopen(int Params)
- {
- TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
- UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
- bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
- bool PrevReadDirectoryPending = FReadDirectoryPending;
- DebugAssert(!FSuspendTransaction);
- bool PrevAutoReadDirectory = FAutoReadDirectory;
- // here used to be a check for FExceptionOnFail being 0
- // but it can happen, e.g. when we are downloading file to execute it.
- // however I'm not sure why we mind having excaption-on-fail enabled here
- int PrevExceptionOnFail = FExceptionOnFail;
- try
- {
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- FSuspendTransaction = true;
- FExceptionOnFail = 0;
- // typically, we avoid reading directory, when there is operation ongoing,
- // for file list which may reference files from current directory
- if (FLAGSET(Params, ropNoReadDirectory))
- {
- AutoReadDirectory = false;
- }
- // only peek, we may not be connected at all atm,
- // so make sure we do not try retrieving current directory from the server
- // (particularly with FTP)
- UnicodeString ACurrentDirectory = PeekCurrentDirectory();
- if (!ACurrentDirectory.IsEmpty())
- {
- SessionData->RemoteDirectory = ACurrentDirectory;
- }
- if (SessionData->FSProtocol == fsSFTP)
- {
- SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
- }
- Open();
- }
- __finally
- {
- SessionData->RemoteDirectory = PrevRemoteDirectory;
- SessionData->FSProtocol = OrigFSProtocol;
- FAutoReadDirectory = PrevAutoReadDirectory;
- FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
- FReadDirectoryPending = PrevReadDirectoryPending;
- FSuspendTransaction = false;
- FExceptionOnFail = PrevExceptionOnFail;
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
- UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
- {
- bool AResult;
- TStrings * Prompts = new TStringList;
- TStrings * Results = new TStringList;
- try
- {
- Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
- Results->AddObject(Result, (TObject *)MaxLen);
- AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
- Result = Results->Strings[0];
- }
- __finally
- {
- delete Prompts;
- delete Results;
- }
- return AResult;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
- UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
- {
- // If PromptUser is overridden in descendant class, the overridden version
- // is not called when accessed via TSessionIU interface.
- // So this is workaround.
- // Actually no longer needed as we do not uverride DoPromptUser
- // anymore in TSecondaryTerminal.
- return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminal::GetPasswordSource()
- {
- return this;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
- UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
- {
- bool AResult = false;
- bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
- if (PasswordOrPassphrasePrompt)
- {
- bool & PasswordTried =
- FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
- if (!PasswordTried)
- {
- // let's expect that the main session is already authenticated and its password
- // is not written after, so no locking is necessary
- // (no longer true, once the main session can be reconnected)
- UnicodeString APassword;
- if (FTunnelOpening)
- {
- APassword = GetPasswordSource()->GetRememberedTunnelPassword();
- }
- else
- {
- APassword = GetPasswordSource()->GetRememberedPassword();
- }
- Results->Strings[0] = APassword;
- if (!Results->Strings[0].IsEmpty())
- {
- LogEvent(L"Using remembered password.");
- AResult = true;
- }
- PasswordTried = true;
- }
- }
- if (!AResult)
- {
- if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
- {
- Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
- }
- if (OnPromptUser != NULL)
- {
- TCallbackGuard Guard(this);
- try
- {
- OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- if (AResult && PasswordOrPassphrasePrompt &&
- (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
- {
- RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
- if (FTunnelOpening)
- {
- GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
- }
- else
- {
- GetPasswordSource()->FRememberedPassword = EncryptedPassword;
- GetPasswordSource()->FRememberedPasswordKind = Kind;
- }
- }
- }
- return AResult;
- }
- //---------------------------------------------------------------------------
- unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
- TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
- TQueryType QueryType)
- {
- LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
- unsigned int Answer = AbortAnswer(Answers);
- if (FOnQueryUser)
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- return Answer;
- }
- //---------------------------------------------------------------------------
- unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
- Exception * E, unsigned int Answers, const TQueryParams * Params,
- TQueryType QueryType)
- {
- unsigned int Result;
- UnicodeString ExMessage;
- if (DebugAlwaysTrue(ExceptionMessageFormatted(E, ExMessage) || !Query.IsEmpty()))
- {
- TStrings * MoreMessages = new TStringList();
- try
- {
- if (!ExMessage.IsEmpty() && !Query.IsEmpty())
- {
- MoreMessages->Add(UnformatMessage(ExMessage));
- }
- ExtException * EE = dynamic_cast<ExtException*>(E);
- if ((EE != NULL) && (EE->MoreMessages != NULL))
- {
- MoreMessages->AddStrings(EE->MoreMessages);
- }
- // We know MoreMessages not to be NULL here,
- // AppendExceptionStackTraceAndForget should never return true
- // (indicating it had to create the string list)
- DebugAlwaysFalse(AppendExceptionStackTraceAndForget(MoreMessages));
- TQueryParams HelpKeywordOverrideParams;
- if (Params != NULL)
- {
- HelpKeywordOverrideParams.Assign(*Params);
- }
- HelpKeywordOverrideParams.HelpKeyword =
- MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
- Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
- MoreMessages->Count ? MoreMessages : NULL,
- Answers, &HelpKeywordOverrideParams, QueryType);
- }
- __finally
- {
- delete MoreMessages;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
- {
- if (OnDisplayBanner != NULL)
- {
- unsigned int OrigParams, Params;
- if (Configuration->ForceBanners ||
- Configuration->ShowBanner(SessionData->SessionKey, Banner, Params))
- {
- bool NeverShowAgain = false;
- int Options =
- FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
- OrigParams = Params;
- TCallbackGuard Guard(this);
- try
- {
- OnDisplayBanner(this, SessionData->SessionName, Banner, NeverShowAgain, Options, Params);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- if (!Configuration->ForceBanners && NeverShowAgain)
- {
- Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
- }
- if (OrigParams != Params)
- {
- Configuration->SetBannerParams(SessionData->SessionKey, Params);
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::HandleExtendedException(Exception * E)
- {
- Log->AddException(E);
- if (OnShowExtendedException != NULL)
- {
- TCallbackGuard Guard(this);
- try
- {
- // the event handler may destroy 'this' ...
- OnShowExtendedException(this, E, NULL);
- // .. hence guard is dismissed from destructor, to make following call no-op
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ShowExtendedException(Exception * E)
- {
- Log->AddException(E);
- if (OnShowExtendedException != NULL)
- {
- OnShowExtendedException(this, E, NULL);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
- int Phase)
- {
- if (OnInformation)
- {
- TCallbackGuard Guard(this);
- try
- {
- OnInformation(this, Str, Status, Phase);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
- {
- DoInformation(Str, Status);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
- {
- if ((Configuration->ActualLogProtocol >= 1) &&
- ((ProgressData.Operation == foCopy) || (ProgressData.Operation == foMove)))
- {
- DWORD Now = GetTickCount();
- if (Now - FLastProgressLogged >= 1000)
- {
- LogEvent(L"Transfer progress: " + ProgressData.GetLogStr(false));
- FLastProgressLogged = Now;
- }
- }
- if (ProgressData.TransferredSize > 0)
- {
- FFileTransferAny = true;
- }
- if (OnProgress != NULL)
- {
- TCallbackGuard Guard(this);
- try
- {
- OnProgress(ProgressData);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
- const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
- {
- if (OnFinished != NULL)
- {
- TCallbackGuard Guard(this);
- try
- {
- OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
- {
- for (int Index = 0; Index < fcCount; Index++)
- {
- FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
- {
- if (DebugAlwaysTrue(FFileSystem != NULL))
- {
- switch (Capability)
- {
- case fcBackgroundTransfers:
- return !IsEncryptingFiles();
- default:
- return FFileSystem->IsCapable(Capability);
- }
- }
- else
- {
- return false;
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
- {
- return FFileSystem->AbsolutePath(Path, Local);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
- {
- bool ChangesDirectory = false;
- bool ModifiesFiles = false;
- switch ((TFSCommand)Cmd) {
- case fsChangeDirectory:
- case fsHomeDirectory:
- ChangesDirectory = true;
- break;
- case fsCopyToRemote:
- case fsDeleteFile:
- case fsRenameFile:
- case fsMoveFile:
- case fsCopyFile:
- case fsCreateDirectory:
- case fsChangeMode:
- case fsChangeGroup:
- case fsChangeOwner:
- case fsChangeProperties:
- case fsLock:
- ModifiesFiles = true;
- break;
- case fsAnyCommand:
- ChangesDirectory = true;
- ModifiesFiles = true;
- break;
- }
- if (ChangesDirectory)
- {
- if (!InTransaction())
- {
- ReadCurrentDirectory();
- if (AutoReadDirectory)
- {
- ReadDirectory(false);
- }
- }
- else
- {
- FReadCurrentDirectoryPending = true;
- if (AutoReadDirectory)
- {
- FReadDirectoryPending = true;
- }
- }
- }
- else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
- {
- if (!InTransaction())
- {
- ReadDirectory(true);
- }
- else
- {
- FReadDirectoryPending = true;
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::TerminalError(UnicodeString Msg)
- {
- TerminalError(NULL, Msg);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::TerminalError(
- Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
- {
- throw ETerminal(E, Msg, HelpKeyword);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoQueryReopen(Exception * E)
- {
- EFatal * Fatal = dynamic_cast<EFatal *>(E);
- DebugAssert(Fatal != NULL);
- bool Result;
- if ((Fatal != NULL) && Fatal->ReopenQueried)
- {
- Result = false;
- }
- else
- {
- LogEvent(L"Connection was lost, asking what to do.");
- TQueryParams Params(qpAllowContinueOnError);
- Params.Timeout = Configuration->SessionReopenAuto;
- Params.TimeoutAnswer = qaRetry;
- TQueryButtonAlias Aliases[1];
- Aliases[0].Button = qaRetry;
- Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
- Params.Aliases = Aliases;
- Params.AliasesCount = LENOF(Aliases);
- Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
- if (Fatal != NULL)
- {
- Fatal->ReopenQueried = true;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::ContinueReopen(TDateTime Start)
- {
- return
- (Configuration->SessionReopenTimeout == 0) ||
- (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
- TFileOperationProgressType * OperationProgress)
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- bool Result = DoQueryReopen(E);
- if (Result)
- {
- TDateTime Start = Now();
- do
- {
- try
- {
- Reopen(Params);
- }
- catch(Exception & E)
- {
- if (!Active)
- {
- Result =
- ContinueReopen(Start) &&
- DoQueryReopen(&E);
- }
- else
- {
- throw;
- }
- }
- }
- while (!Active && Result);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
- TFileOperationProgressType * OperationProgress, const UnicodeString Message,
- unsigned int Flags, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
- {
- bool Result = false;
- Log->AddException(&E);
- unsigned int Answer;
- bool AllowSkip = FLAGSET(Flags, folAllowSkip);
- bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
- if (SkipToAllPossible && OperationProgress->SkipToAll)
- {
- Answer = qaSkip;
- }
- else
- {
- int Answers = qaRetry | qaAbort |
- FLAGMASK(AllowSkip, qaSkip) |
- FLAGMASK(SkipToAllPossible, qaAll) |
- FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
- TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
- Params.HelpKeyword = HelpKeyword;
- TQueryButtonAlias Aliases[2];
- int AliasCount = 0;
- if (FLAGSET(Answers, qaAll))
- {
- Aliases[AliasCount].Button = qaAll;
- Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
- AliasCount++;
- }
- if (FLAGSET(Answers, qaYes))
- {
- Aliases[AliasCount].Button = qaYes;
- Aliases[AliasCount].Alias = SpecialRetry;
- AliasCount++;
- }
- if (AliasCount > 0)
- {
- Params.Aliases = Aliases;
- Params.AliasesCount = AliasCount;
- }
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
- }
- if (Answer == qaAll)
- {
- DebugAssert(OperationProgress != NULL);
- OperationProgress->SetSkipToAll();
- Answer = qaSkip;
- }
- if (Answer == qaYes)
- {
- Result = true;
- Answer = qaRetry;
- }
- }
- if (Answer != qaRetry)
- {
- if ((Answer == qaAbort) && (OperationProgress != NULL))
- {
- OperationProgress->SetCancel(csCancel);
- }
- if (AllowSkip)
- {
- throw ESkipFile(&E, Message);
- }
- else
- {
- // this can happen only during file transfer with SCP
- throw ExtException(&E, Message);
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FileOperationLoopEnd(Exception & E,
- TFileOperationProgressType * OperationProgress, const UnicodeString & Message,
- unsigned int Flags, const UnicodeString & SpecialRetry, const UnicodeString & HelpKeyword)
- {
- if ((dynamic_cast<EAbort *>(&E) != NULL) ||
- (dynamic_cast<ESkipFile *>(&E) != NULL) ||
- (dynamic_cast<ESkipFile *>(&E) != NULL))
- {
- RethrowException(&E);
- }
- else if (dynamic_cast<EFatal *>(&E) != NULL)
- {
- if (FLAGCLEAR(Flags, folRetryOnFatal))
- {
- RethrowException(&E);
- }
- else
- {
- DebugAssert(SpecialRetry.IsEmpty());
- std::unique_ptr<Exception> E2(new EFatal(&E, Message, HelpKeyword));
- if (!DoQueryReopen(E2.get()))
- {
- RethrowException(E2.get());
- }
- }
- }
- else
- {
- FileOperationLoopQuery(E, OperationProgress, Message, Flags, SpecialRetry, HelpKeyword);
- }
- }
- //---------------------------------------------------------------------------
- int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
- TFileOperationProgressType * OperationProgress, unsigned int Flags,
- const UnicodeString Message, void * Param1, void * Param2)
- {
- DebugAssert(CallBackFunc);
- int Result;
- FILE_OPERATION_LOOP_BEGIN
- {
- Result = CallBackFunc(Param1, Param2);
- }
- FILE_OPERATION_LOOP_END_EX(Message, Flags);
- return Result;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
- {
- if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
- {
- if (Lock)
- {
- if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
- {
- Path.Delete(1, FLockDirectory.Length());
- if (Path.IsEmpty()) Path = L"/";
- }
- }
- else
- {
- Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
- }
- }
- return Path;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ClearCaches()
- {
- FDirectoryCache->Clear();
- if (FDirectoryChangesCache != NULL)
- {
- FDirectoryChangesCache->Clear();
- }
- if (FCommandSession != NULL)
- {
- FCommandSession->ClearCaches();
- }
- FFileSystem->ClearCaches();
- FEncryptedFileNames.clear();
- FFoldersScannedForEncryptedFiles.clear();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
- bool SubDirs)
- {
- FDirectoryCache->ClearFileList(Path, SubDirs);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
- {
- FDirectoryCache->AddFileList(FileList);
- }
- //---------------------------------------------------------------------------
- TRemoteFileList * __fastcall TTerminal::DirectoryFileList(const UnicodeString Path, TDateTime Timestamp, bool CanLoad)
- {
- TRemoteFileList * Result = NULL;
- if (UnixSamePath(FFiles->Directory, Path))
- {
- if (Timestamp < FFiles->Timestamp)
- {
- Result = new TRemoteFileList();
- FFiles->DuplicateTo(Result);
- }
- }
- else
- {
- if (FDirectoryCache->HasNewerFileList(Path, Timestamp))
- {
- Result = new TRemoteFileList();
- DebugAlwaysTrue(FDirectoryCache->GetFileList(Path, Result));
- }
- // do not attempt to load file list if there is cached version,
- // only absence of cached version indicates that we consider
- // the directory content obsolete
- else if (CanLoad && !FDirectoryCache->HasFileList(Path))
- {
- Result = new TRemoteFileList();
- Result->Directory = Path;
- try
- {
- ReadDirectory(Result);
- }
- catch(...)
- {
- SAFE_DESTROY(Result);
- throw;
- }
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
- {
- DebugAssert(FFileSystem);
- value = TranslateLockedPath(value, false);
- if (value != FFileSystem->CurrentDirectory)
- {
- ChangeDirectory(value);
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetCurrentDirectory()
- {
- if (FFileSystem != NULL)
- {
- // there's occasional crash when assigning FFileSystem->CurrentDirectory
- // to FCurrentDirectory, splitting the assignment to two statemets
- // to locate the crash more closely
- UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
- FCurrentDirectory = CurrentDirectory;
- if (FCurrentDirectory.IsEmpty())
- {
- ReadCurrentDirectory();
- }
- }
- UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
- return Result;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
- {
- if (FFileSystem)
- {
- FCurrentDirectory = FFileSystem->CurrentDirectory;
- }
- UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
- return Result;
- }
- //---------------------------------------------------------------------------
- const TRemoteTokenList * __fastcall TTerminal::GetGroups()
- {
- DebugAssert(FFileSystem);
- LookupUsersGroups();
- return &FGroups;
- }
- //---------------------------------------------------------------------------
- const TRemoteTokenList * __fastcall TTerminal::GetUsers()
- {
- DebugAssert(FFileSystem);
- LookupUsersGroups();
- return &FUsers;
- }
- //---------------------------------------------------------------------------
- const TRemoteTokenList * __fastcall TTerminal::GetMembership()
- {
- DebugAssert(FFileSystem);
- LookupUsersGroups();
- return &FMembership;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetUserName() const
- {
- // in future might also be implemented to detect username similar to GetUserGroups
- DebugAssert(FFileSystem != NULL);
- UnicodeString Result = FFileSystem->GetUserName();
- // Is empty also when stored username was used
- if (Result.IsEmpty())
- {
- Result = SessionData->UserNameExpanded;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetAreCachesEmpty() const
- {
- return FDirectoryCache->IsEmpty &&
- ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoInitializeLog()
- {
- if (FOnInitializeLog)
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnInitializeLog(this);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoChangeDirectory()
- {
- if (FOnChangeDirectory)
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnChangeDirectory(this);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
- {
- if (FOnReadDirectory)
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnReadDirectory(this, ReloadOnly);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoStartReadDirectory()
- {
- if (FOnStartReadDirectory)
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnStartReadDirectory(this);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
- {
- if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- if (FOnFindingFile != NULL)
- {
- TCallbackGuard Guard(this);
- try
- {
- FOnFindingFile(this, L"", Cancel);
- Guard.Verify();
- }
- catch (Exception & E)
- {
- if (!Guard.Verify(&E))
- {
- throw;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::InTransaction()
- {
- return (FInTransaction > 0) && !FSuspendTransaction;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::BeginTransaction()
- {
- if (FInTransaction == 0)
- {
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- }
- FInTransaction++;
- if (FCommandSession != NULL)
- {
- FCommandSession->BeginTransaction();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::EndTransaction()
- {
- DoEndTransaction(false);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoEndTransaction(bool Inform)
- {
- if (FInTransaction == 0)
- TerminalError(L"Can't end transaction, not in transaction");
- DebugAssert(FInTransaction > 0);
- FInTransaction--;
- // it connection was closed due to fatal error during transaction, do nothing
- if (Active)
- {
- if (FInTransaction == 0)
- {
- try
- {
- if (FReadCurrentDirectoryPending)
- {
- ReadCurrentDirectory();
- }
- if (FReadDirectoryPending)
- {
- if (Inform)
- {
- DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
- }
- ReadDirectory(!FReadCurrentDirectoryPending);
- }
- }
- __finally
- {
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- }
- }
- }
- if (FCommandSession != NULL)
- {
- FCommandSession->EndTransaction();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SetExceptionOnFail(bool value)
- {
- if (value)
- {
- FExceptionOnFail++;
- }
- else
- {
- if (FExceptionOnFail == 0)
- throw Exception(L"ExceptionOnFail is already zero.");
- FExceptionOnFail--;
- }
- if (FCommandSession != NULL)
- {
- FCommandSession->FExceptionOnFail = FExceptionOnFail;
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetExceptionOnFail() const
- {
- return (bool)(FExceptionOnFail > 0);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FatalAbort()
- {
- FatalError(NULL, "");
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
- {
- bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
- if (Active || SecureShellActive)
- {
- // We log this instead of exception handler, because Close() would
- // probably cause exception handler to loose pointer to TShellLog()
- LogEvent(L"Attempt to close connection due to fatal exception:");
- Log->Add(llException, Msg);
- Log->AddException(E);
- if (Active)
- {
- Close();
- }
- // this may happen if failure of authentication of SSH, owned by terminal yet
- // (because the protocol was not decided yet), is detected by us (not by putty).
- // e.g. not verified host key
- if (SecureShellActive)
- {
- FSecureShell->Close();
- }
- }
- if (FCallbackGuard != NULL)
- {
- FCallbackGuard->FatalError(E, Msg, HelpKeyword);
- }
- else
- {
- throw ESshFatal(E, Msg, HelpKeyword);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
- {
- CommandError(E, Msg, 0);
- }
- //---------------------------------------------------------------------------
- unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
- unsigned int Answers, const UnicodeString HelpKeyword)
- {
- // may not be, particularly when TTerminal::Reopen is being called
- // from within OnShowExtendedException handler
- DebugAssert(FCallbackGuard == NULL);
- unsigned int Result = 0;
- if (E && E->InheritsFrom(__classid(EFatal)))
- {
- FatalError(E, Msg, HelpKeyword);
- }
- else if (E && E->InheritsFrom(__classid(EAbort)))
- {
- // resent EAbort exception
- Abort();
- }
- else if (ExceptionOnFail)
- {
- throw ECommand(E, Msg, HelpKeyword);
- }
- else if (!Answers)
- {
- ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
- try
- {
- HandleExtendedException(ECmd);
- }
- __finally
- {
- delete ECmd;
- }
- }
- else
- {
- // small hack to enable "skip to all" for TRetryOperationLoop
- bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
- if (CanSkip && OperationProgress->SkipToAll)
- {
- Result = qaSkip;
- }
- else
- {
- TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
- TQueryButtonAlias Aliases[1];
- if (CanSkip)
- {
- Aliases[0].Button = qaAll;
- Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
- Params.Aliases = Aliases;
- Params.AliasesCount = LENOF(Aliases);
- Answers |= qaAll;
- }
- Result = QueryUserException(Msg, E, Answers, &Params, qtError);
- if (Result == qaAll)
- {
- DebugAssert(OperationProgress != NULL);
- OperationProgress->SetSkipToAll();
- Result = qaSkip;
- }
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::HandleException(Exception * E)
- {
- if (ExceptionOnFail)
- {
- return false;
- }
- else
- {
- Log->AddException(E);
- return true;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CloseOnCompletion(
- TOnceDoneOperation Operation, const UnicodeString & Message,
- const UnicodeString & TargetLocalPath, const UnicodeString & DestLocalFileName)
- {
- if (FOperationProgressPersistence != NULL)
- {
- DebugAssert(Message.IsEmpty());
- FOperationProgressOnceDoneOperation = Operation;
- }
- else
- {
- Configuration->Usage->Inc(L"ClosesOnCompletion");
- LogEvent(L"Closing session after completed operation (as requested by user)");
- Close();
- throw ESshTerminate(NULL,
- MainInstructions(Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message),
- Operation, TargetLocalPath, DestLocalFileName);
- }
- }
- //---------------------------------------------------------------------------
- TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
- const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
- {
- TBatchOverwrite Result;
- if (Special &&
- (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)))
- {
- Result = boResume;
- }
- else if (FLAGSET(Params, cpAppend))
- {
- Result = boAppend;
- }
- else if (CopyParam->NewerOnly &&
- (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
- (OperationProgress->Side != osLocal)))
- {
- // no way to change batch overwrite mode when CopyParam->NewerOnly is on
- Result = boOlder;
- }
- else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
- {
- // no way to change batch overwrite mode when overwrite confirmations are off
- DebugAssert(OperationProgress->BatchOverwrite == boNo);
- Result = boAll;
- }
- else
- {
- Result = OperationProgress->BatchOverwrite;
- if (!Special &&
- ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
- {
- Result = boNo;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CheckRemoteFile(
- const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
- {
- bool Result;
- OperationProgress->LockUserSelections();
- try
- {
- Result = (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
- }
- __finally
- {
- OperationProgress->UnlockUserSelections();
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
- const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
- const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
- TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
- UnicodeString Message)
- {
- unsigned int Result;
- TBatchOverwrite BatchOverwrite;
- bool CanAlternateResume =
- (FileParams != NULL) &&
- (FileParams->DestSize < FileParams->SourceSize) &&
- !OperationProgress->AsciiTransfer;
- OperationProgress->LockUserSelections();
- try
- {
- // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
- BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
- bool Applicable = true;
- switch (BatchOverwrite)
- {
- case boOlder:
- Applicable = (FileParams != NULL);
- break;
- case boAlternateResume:
- Applicable = CanAlternateResume;
- break;
- case boResume:
- Applicable = CanAlternateResume;
- break;
- }
- if (!Applicable)
- {
- TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
- DebugAssert(BatchOverwrite != ABatchOverwrite);
- BatchOverwrite = ABatchOverwrite;
- }
- if (BatchOverwrite == boNo)
- {
- // particularly with parallel transfers, the overal operation can be already cancelled by other parallel operation
- if (OperationProgress->Cancel > csContinue)
- {
- Result = qaCancel;
- }
- else
- {
- if (Message.IsEmpty())
- {
- // Side refers to destination side here
- Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
- REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
- }
- if (FileParams != NULL)
- {
- Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
- FormatSize(FileParams->SourceSize),
- DefaultStr(UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision), LoadStr(TIME_UNKNOWN)),
- FormatSize(FileParams->DestSize),
- DefaultStr(UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision), LoadStr(TIME_UNKNOWN))));
- }
- if (DebugAlwaysTrue(QueryParams->HelpKeyword.IsEmpty()))
- {
- QueryParams->HelpKeyword = HELP_OVERWRITE;
- }
- Result = QueryUser(Message, NULL, Answers, QueryParams);
- switch (Result)
- {
- case qaNeverAskAgain:
- Configuration->ConfirmOverwriting = false;
- Result = qaYes;
- break;
- case qaYesToAll:
- BatchOverwrite = boAll;
- break;
- case qaAll:
- BatchOverwrite = boOlder;
- break;
- case qaNoToAll:
- BatchOverwrite = boNone;
- break;
- }
- // we user has not selected another batch overwrite mode,
- // keep the current one. note that we may get here even
- // when batch overwrite was selected already, but it could not be applied
- // to current transfer (see condition above)
- if (BatchOverwrite != boNo)
- {
- OperationProgress->SetBatchOverwrite(BatchOverwrite);
- }
- }
- }
- }
- __finally
- {
- OperationProgress->UnlockUserSelections();
- }
- if (BatchOverwrite != boNo)
- {
- switch (BatchOverwrite)
- {
- case boAll:
- Result = qaYes;
- break;
- case boNone:
- Result = qaNo;
- break;
- case boOlder:
- if (FileParams == NULL)
- {
- Result = qaNo;
- }
- else
- {
- TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
- TDateTime ReducedSourceTimestamp =
- ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
- TDateTime ReducedDestTimestamp =
- ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
- Result =
- (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
- qaYes : qaNo;
- LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
- (StandardTimestamp(ReducedSourceTimestamp),
- StandardTimestamp(ReducedDestTimestamp),
- ((Result == qaYes) ? L"" : L" not"))));
- }
- break;
- case boAlternateResume:
- DebugAssert(CanAlternateResume);
- Result = qaSkip; // ugh
- break;
- case boAppend:
- Result = qaRetry;
- break;
- case boResume:
- Result = qaRetry;
- break;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FileModified(const TRemoteFile * File,
- const UnicodeString FileName, bool ClearDirectoryChange)
- {
- UnicodeString ParentDirectory;
- UnicodeString Directory;
- if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
- {
- if ((File != NULL) && (File->Directory != NULL))
- {
- if (File->IsDirectory)
- {
- Directory = File->Directory->FullDirectory + File->FileName;
- }
- ParentDirectory = File->Directory->Directory;
- }
- else if (!FileName.IsEmpty())
- {
- ParentDirectory = UnixExtractFilePath(FileName);
- if (ParentDirectory.IsEmpty())
- {
- ParentDirectory = CurrentDirectory;
- }
- // this case for scripting
- if ((File != NULL) && File->IsDirectory)
- {
- Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
- UnixExtractFileName(File->FileName);
- }
- }
- }
- if (SessionData->CacheDirectories)
- {
- if (!Directory.IsEmpty())
- {
- DirectoryModified(Directory, true);
- }
- if (!ParentDirectory.IsEmpty())
- {
- DirectoryModified(ParentDirectory, false);
- }
- }
- if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
- {
- if (!Directory.IsEmpty())
- {
- FDirectoryChangesCache->ClearDirectoryChange(Directory);
- FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
- {
- if (Path.IsEmpty())
- {
- ClearCachedFileList(CurrentDirectory, SubDirs);
- }
- else
- {
- ClearCachedFileList(Path, SubDirs);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
- {
- AddCachedFileList(FileList);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReloadDirectory()
- {
- if (SessionData->CacheDirectories)
- {
- DirectoryModified(CurrentDirectory, false);
- }
- if (SessionData->CacheDirectoryChanges)
- {
- DebugAssert(FDirectoryChangesCache != NULL);
- FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
- }
- ReadCurrentDirectory();
- FReadCurrentDirectoryPending = false;
- ReadDirectory(true);
- FReadDirectoryPending = false;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RefreshDirectory()
- {
- if (!SessionData->CacheDirectories)
- {
- LogEvent(L"Not refreshing directory, caching is off.");
- }
- else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
- {
- // Second parameter was added to allow (rather force) using the cache.
- // Before, the directory was reloaded always, it seems useless,
- // has it any reason?
- ReadDirectory(true, true);
- FReadDirectoryPending = false;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
- {
- // if filename doesn't contain path, we check for existence of file
- if ((UnixExtractFileDir(FileName).IsEmpty()) &&
- UnixSamePath(CurrentDirectory, FFiles->Directory))
- {
- TRemoteFile *File = FFiles->FindFile(FileName);
- if (File)
- {
- if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
- else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
- {
- if (Log->Logging)
- {
- Log->Add(llMessage, Str);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogEvent(int Level, const UnicodeString & Str)
- {
- if (Log->Logging && (Configuration->ActualLogProtocol >= Level))
- {
- Log->Add(llMessage, Str);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
- TFileOperationProgressType * OperationProgress, Exception * E)
- {
- // ESkipFile without "cancel" is file skip,
- // and we do not want to record skipped actions.
- // But ESkipFile with "cancel" is abort and we want to record that.
- // Note that TScpFileSystem modifies the logic of RollbackAction little bit.
- if ((dynamic_cast<ESkipFile *>(E) != NULL) &&
- ((OperationProgress == NULL) ||
- (OperationProgress->Cancel == csContinue)))
- {
- Action.Cancel();
- }
- else
- {
- Action.Rollback(E);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoStartup()
- {
- LogEvent(L"Doing startup conversation with host.");
- BeginTransaction();
- try
- {
- DoInformation(LoadStr(STATUS_STARTUP), true);
- // Make sure that directory would be loaded at last
- FReadCurrentDirectoryPending = true;
- FReadDirectoryPending = AutoReadDirectory;
- FFileSystem->DoStartup();
- LookupUsersGroups();
- if (!SessionData->RemoteDirectory.IsEmpty())
- {
- if (SessionData->UpdateDirectories)
- {
- ExceptionOnFail = true;
- try
- {
- ChangeDirectory(SessionData->RemoteDirectory);
- }
- catch (...)
- {
- if (!Active)
- {
- LogEvent(L"Configured initial remote directory cannot be opened, staying in the home directory.");
- throw;
- }
- }
- ExceptionOnFail = false;
- }
- else
- {
- ChangeDirectory(SessionData->RemoteDirectory);
- }
- }
- }
- __finally
- {
- DoEndTransaction(true);
- }
- LogEvent(L"Startup conversation with host finished.");
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadCurrentDirectory()
- {
- DebugAssert(FFileSystem);
- try
- {
- // reset flag in case we are called externally (like from console dialog)
- FReadCurrentDirectoryPending = false;
- LogEvent(L"Getting current directory name.");
- UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
- FFileSystem->ReadCurrentDirectory();
- ReactOnCommand(fsCurrentDirectory);
- if (SessionData->CacheDirectoryChanges)
- {
- DebugAssert(FDirectoryChangesCache != NULL);
- if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
- {
- FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
- FLastDirectoryChange, CurrentDirectory);
- }
- // not to breake the cache, if the next directory change would not
- // be initialized by ChangeDirectory(), which sets it
- // (HomeDirectory() particularly)
- FLastDirectoryChange = L"";
- }
- if (OldDirectory.IsEmpty())
- {
- FLockDirectory = (SessionData->LockInHome ?
- FFileSystem->CurrentDirectory : UnicodeString(L""));
- }
- if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
- {
- bool LoadedFromCache = false;
- if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
- {
- if (ReloadOnly && !ForceCache)
- {
- LogEvent(L"Cached directory not reloaded.");
- }
- else
- {
- DoStartReadDirectory();
- try
- {
- LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
- }
- __finally
- {
- DoReadDirectory(ReloadOnly);
- }
- if (LoadedFromCache)
- {
- LogEvent(L"Directory content loaded from cache.");
- }
- else
- {
- LogEvent(L"Cached Directory content has been removed.");
- }
- }
- }
- if (!LoadedFromCache)
- {
- DoStartReadDirectory();
- FReadingCurrentDirectory = true;
- bool Cancel = false; // dummy
- DoReadDirectoryProgress(0, 0, Cancel);
- try
- {
- TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
- try
- {
- Files->Directory = CurrentDirectory;
- CustomReadDirectory(Files);
- }
- __finally
- {
- DoReadDirectoryProgress(-1, 0, Cancel);
- FReadingCurrentDirectory = false;
- TRemoteDirectory * OldFiles = FFiles;
- FFiles = Files;
- try
- {
- DoReadDirectory(ReloadOnly);
- }
- __finally
- {
- // delete only after loading new files to dir view,
- // not to destroy the file objects that the view holds
- // (can be issue in multi threaded environment, such as when the
- // terminal is reconnecting in the terminal thread)
- delete OldFiles;
- }
- if (Active)
- {
- if (SessionData->CacheDirectories)
- {
- DirectoryLoaded(FFiles);
- }
- }
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
- }
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetRemoteFileInfo(TRemoteFile * File)
- {
- return
- FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
- (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
- File->Owner.LogText, File->Group.LogText, File->Rights->Text,
- File->Attr));
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
- {
- // optimization
- if (Log->Logging)
- {
- LogEvent(GetRemoteFileInfo(File));
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(
- const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
- {
- UnicodeString Result;
- // optimization
- if (Log->Logging)
- {
- Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
- if (LinkedFile != NULL)
- {
- LinkedFile = LinkedFile->Resolve(); // in case it's symlink to symlink
- Result += FORMAT(L" - Link to: %s", (FormatFileDetailsForLog(LinkedFile->FileName, LinkedFile->Modification, LinkedFile->Size, NULL)));
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
- {
- // optimization
- if (Log->Logging)
- {
- LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size, LinkedFile))));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress, const UnicodeString & DestFileName)
- {
- if (FDestFileName.IsEmpty())
- {
- FDestFileName = DestFileName;
- }
- else
- {
- FMultipleDestinationFiles = true;
- }
- // optimization
- if (Log->Logging)
- {
- LogEvent(FORMAT("Transfer done: '%s' => '%s' [%s]", (OperationProgress->FullFileName, DestFileName, IntToStr(OperationProgress->TransferredSize))));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
- {
- DebugAssert(FileList);
- DebugAssert(FFileSystem);
- // To match FTP upload/download, we also limit directory listing.
- // For simiplicity, we limit it unconditionally, for all protocols for any kind of errors.
- bool FileTransferAny = false;
- TRobustOperationLoop RobustLoop(this, OperationProgress, &FileTransferAny);
- do
- {
- try
- {
- // Record even an attempt, to avoid listing a directory over and over again, when it is not readable actually
- if (IsEncryptingFiles())
- {
- FFoldersScannedForEncryptedFiles.insert(FileList->Directory);
- }
- FFileSystem->ReadDirectory(FileList);
- }
- catch (Exception & E)
- {
- // Do not retry for initial listing of directory,
- // we instead retry whole connection attempt,
- // what would be done anyway (but Open is not ready for recursion).
- if ((FOpening > 0) ||
- !RobustLoop.TryReopen(E))
- {
- throw;
- }
- }
- }
- while (RobustLoop.Retry());
- if (Log->Logging && (Configuration->ActualLogProtocol >= 0))
- {
- for (int Index = 0; Index < FileList->Count; Index++)
- {
- LogRemoteFile(FileList->Files[Index]);
- }
- }
- ReactOnCommand(fsListDirectory);
- }
- //---------------------------------------------------------------------------
- TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
- {
- TRemoteFileList * FileList;
- TRetryOperationLoop RetryLoop(this);
- do
- {
- FileList = NULL;
- TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
- try
- {
- FileList = DoReadDirectoryListing(Directory, false);
- if (FileList != NULL)
- {
- int Index = 0;
- while (Index < FileList->Count)
- {
- TRemoteFile * File = FileList->Files[Index];
- TFileMasks::TParams Params;
- Params.Size = File->Resolve()->Size;
- Params.Modification = File->Modification;
- // Have to use UnicodeString(), instead of L"", as with that
- // overload with (UnicodeString, bool, bool, TParams*) wins
- if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
- {
- FileList->Delete(Index);
- }
- else
- {
- Index++;
- }
- }
- Action.FileList(FileList);
- }
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, Action);
- }
- }
- while (RetryLoop.Retry());
- return FileList;
- }
- //---------------------------------------------------------------------------
- TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
- {
- TRemoteFile * File;
- TRetryOperationLoop RetryLoop(this);
- do
- {
- File = NULL;
- TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
- try
- {
- // reset caches
- AnnounceFileListOperation();
- ReadFile(Path, File);
- Action.File(File);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, Action);
- }
- }
- while (RetryLoop.Retry());
- return File;
- }
- //---------------------------------------------------------------------------
- TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
- {
- TRemoteFileList * FileList = NULL;
- TRetryOperationLoop RetryLoop(this);
- do
- {
- try
- {
- FileList = DoReadDirectoryListing(Directory, UseCache);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E);
- }
- }
- while (RetryLoop.Retry());
- return FileList;
- }
- //---------------------------------------------------------------------------
- TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
- {
- TRemoteFileList * FileList = new TRemoteFileList();
- try
- {
- bool Cache = UseCache && SessionData->CacheDirectories;
- bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
- if (LoadedFromCache)
- {
- LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
- }
- if (!LoadedFromCache)
- {
- FileList->Directory = Directory;
- ExceptionOnFail = true;
- try
- {
- ReadDirectory(FileList);
- }
- __finally
- {
- ExceptionOnFail = false;
- }
- if (Cache)
- {
- AddCachedFileList(FileList);
- }
- }
- }
- catch(...)
- {
- delete FileList;
- throw;
- }
- return FileList;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DeleteContentsIfDirectory(
- const UnicodeString & FileName, const TRemoteFile * File, int Params, TRmSessionAction & Action)
- {
- bool Dir = (File != NULL) && File->IsDirectory && CanRecurseToDirectory(File);
- if (Dir && FLAGCLEAR(Params, dfNoRecursive))
- {
- try
- {
- ProcessDirectory(FileName, DeleteFile, &Params);
- }
- catch(...)
- {
- Action.Cancel();
- throw;
- }
- }
- return Dir && !File->IsSymLink;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
- TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
- {
- TRemoteFileList * FileList = NULL;
- if (IgnoreErrors)
- {
- ExceptionOnFail = true;
- try
- {
- try
- {
- FileList = CustomReadDirectoryListing(DirName, UseCache);
- }
- catch(...)
- {
- if (!Active)
- {
- throw;
- }
- }
- }
- __finally
- {
- ExceptionOnFail = false;
- }
- }
- else
- {
- FileList = CustomReadDirectoryListing(DirName, UseCache);
- }
- // skip if directory listing fails and user selects "skip"
- if (FileList)
- {
- try
- {
- UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
- TRemoteFile * File;
- for (int Index = 0; Index < FileList->Count; Index++)
- {
- File = FileList->Files[Index];
- if (IsRealFile(File->FileName))
- {
- CallBackFunc(Directory + File->FileName, File, Param);
- // We should catch ESkipFile here as we do in ProcessFiles.
- // Now we have to handle ESkipFile in every callback implementation.
- }
- }
- }
- __finally
- {
- delete FileList;
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
- {
- try
- {
- CustomReadDirectory(FileList);
- }
- catch (Exception &E)
- {
- CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
- TRemoteFile *& File)
- {
- DebugAssert(FFileSystem);
- try
- {
- LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
- FFileSystem->ReadSymlink(SymlinkFile, File);
- ReactOnCommand(fsReadSymlink);
- }
- catch (Exception &E)
- {
- CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
- TRemoteFile *& File)
- {
- DebugAssert(FFileSystem);
- File = NULL;
- try
- {
- LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
- FFileSystem->ReadFile(FileName, File);
- ReactOnCommand(fsListFile);
- LogRemoteFile(File);
- }
- catch (Exception &E)
- {
- if (File) delete File;
- File = NULL;
- CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
- {
- bool Result;
- TRemoteFile * File = NULL;
- try
- {
- ExceptionOnFail = true;
- try
- {
- ReadFile(UnixExcludeTrailingBackslash(FileName), File);
- }
- __finally
- {
- ExceptionOnFail = false;
- }
- if (AFile != NULL)
- {
- *AFile = File;
- }
- else
- {
- delete File;
- }
- Result = true;
- }
- catch(...)
- {
- if (Active)
- {
- Result = false;
- }
- else
- {
- throw;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::AnnounceFileListOperation()
- {
- FFileSystem->AnnounceFileListOperation();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OperationFinish(
- TFileOperationProgressType * Progress, const void * /*Item*/, const UnicodeString & FileName,
- bool Success, TOnceDoneOperation & OnceDoneOperation)
- {
- Progress->Finish(FileName, Success, OnceDoneOperation);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OperationStart(
- TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count)
- {
- OperationStart(Progress, Operation, Side, Count, false, UnicodeString(), 0, odoIdle);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OperationStart(
- TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count,
- bool Temp, const UnicodeString & Directory, unsigned long CPSLimit, TOnceDoneOperation OnceDoneOperation)
- {
- if (FOperationProgressPersistence != NULL)
- {
- Progress.Restore(*FOperationProgressPersistence);
- }
- Progress.Start(Operation, Side, Count, Temp, Directory, CPSLimit, OnceDoneOperation);
- DebugAssert(FOperationProgress == NULL);
- FOperationProgress = &Progress;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OperationStop(TFileOperationProgressType & Progress)
- {
- DebugAssert(FOperationProgress == &Progress);
- if (FOperationProgressPersistence != NULL)
- {
- Progress.Store(*FOperationProgressPersistence);
- }
- FOperationProgress = NULL;
- Progress.Stop();
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
- TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
- TOperationSide Side, bool Ex)
- {
- DebugAssert(FileList);
- bool Result = false;
- TOnceDoneOperation OnceDoneOperation = odoIdle;
- try
- {
- TFileOperationProgressType Progress(&DoProgress, &DoFinished);
- OperationStart(Progress, Operation, Side, FileList->Count);
- try
- {
- if (Side == osRemote)
- {
- DebugAssert(FFileSystem != NULL);
- BeginTransaction();
- }
- try
- {
- int Index = 0;
- UnicodeString FileName;
- bool Success;
- while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
- {
- FileName = FileList->Strings[Index];
- TRemoteFile * File = reinterpret_cast<TRemoteFile *>(FileList->Objects[Index]);
- try
- {
- try
- {
- Success = false;
- if (!Ex)
- {
- ProcessFile(FileName, File, Param);
- }
- else
- {
- // not used anymore
- TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
- ProcessFileEx(FileName, File, Param, Index);
- }
- Success = true;
- }
- __finally
- {
- OperationFinish(&Progress, File, FileName, Success, OnceDoneOperation);
- }
- }
- catch(ESkipFile & E)
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- if (!HandleException(&E))
- {
- throw;
- }
- }
- Index++;
- }
- }
- __finally
- {
- if (Side == osRemote)
- {
- EndTransaction();
- }
- }
- if (Progress.Cancel == csContinue)
- {
- Result = true;
- }
- }
- __finally
- {
- OperationStop(Progress);
- }
- }
- catch (...)
- {
- OnceDoneOperation = odoIdle;
- // this was missing here. was it by purpose?
- // without it any error message is lost
- throw;
- }
- if (OnceDoneOperation != odoIdle)
- {
- CloseOnCompletion(OnceDoneOperation);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- // not used anymore
- bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
- TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
- {
- return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
- Param, Side, true);
- }
- //---------------------------------------------------------------------------
- TStrings * __fastcall TTerminal::GetFixedPaths()
- {
- DebugAssert(FFileSystem != NULL);
- return FFileSystem->GetFixedPaths();
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetResolvingSymlinks()
- {
- return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
- }
- //---------------------------------------------------------------------------
- TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
- {
- TUsableCopyParamAttrs Result;
- Result.General =
- FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
- FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
- FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
- FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
- FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
- // the following three are never supported for download,
- // so when they are not suppored for upload too,
- // set them in General flags, so that they do not get enabled on
- // Synchronize dialog.
- FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
- FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
- FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
- FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
- FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport) |
- FLAGMASK(!IsEncryptingFiles(), cpaNoEncryptNewFiles);
- Result.Download = Result.General | cpaNoClearArchive |
- cpaNoIgnorePermErrors |
- // May be already set in General flags, but it's unconditional here
- cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM | cpaNoEncryptNewFiles;
- Result.Upload = Result.General | cpaNoPreserveReadOnly |
- FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
- {
- bool Result = !SessionData->RecycleBinPath.IsEmpty();
- if (Result)
- {
- UnicodeString Path = UnixExtractFilePath(FileName);
- if (Path.IsEmpty())
- {
- Path = CurrentDirectory;
- }
- Result = UnixSamePath(Path, SessionData->RecycleBinPath);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::RecycleFile(const UnicodeString & AFileName, const TRemoteFile * File)
- {
- UnicodeString FileName = AFileName;
- if (FileName.IsEmpty())
- {
- DebugAssert(File != NULL);
- FileName = File->FileName;
- }
- bool Result;
- if (IsRecycledFile(FileName))
- {
- Result = true;
- }
- else
- {
- LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
- (FileName, SessionData->RecycleBinPath)));
- TMoveFileParams Params;
- Params.Target = SessionData->RecycleBinPath;
- Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
- Result = DoMoveFile(FileName, File, &Params);
- if (Result && (OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
- {
- OperationProgress->Succeeded();
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::TryStartOperationWithFile(
- const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
- {
- bool Result = true;
- if ((OperationProgress != NULL) &&
- ((OperationProgress->Operation == Operation1) ||
- ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
- {
- if (OperationProgress->Cancel != csContinue)
- {
- Result = false;
- }
- else
- {
- OperationProgress->SetFile(FileName);
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::StartOperationWithFile(
- const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
- {
- if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
- {
- Abort();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
- const TRemoteFile * File, void * AParams)
- {
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- StartOperationWithFile(FileName, foDelete);
- int Params = (AParams != NULL) ? *((int*)AParams) : 0;
- bool Recycle =
- FLAGCLEAR(Params, dfForceDelete) &&
- (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
- !SessionData->RecycleBinPath.IsEmpty();
- if (Recycle && !IsRecycledFile(FileName))
- {
- RecycleFile(FileName, File);
- }
- else
- {
- LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
- FileModified(File, FileName, true);
- DoDeleteFile(FileName, File, Params);
- // Forget if file was or was not encrypted and use user preferences, if we ever recreate it.
- FEncryptedFileNames.erase(AbsolutePath(FileName, true));
- ReactOnCommand(fsDeleteFile);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
- const TRemoteFile * File, int Params)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
- try
- {
- DebugAssert(FFileSystem);
- // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
- FFileSystem->DeleteFile(FileName, File, Params, Action);
- if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
- {
- OperationProgress->Succeeded();
- }
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
- {
- TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
- FUseBusyCursor = false;
- // TODO: avoid resolving symlinks while reading subdirectories.
- // Resolving does not work anyway for relative symlinks in subdirectories
- // (at least for SFTP).
- return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
- const TRemoteFile * /*File*/, void * Params)
- {
- StartOperationWithFile(FileName, foDelete);
- int Deleted;
- if (OnDeleteLocalFile == NULL)
- {
- Deleted = RecursiveDeleteFileChecked(FileName, false);
- }
- else
- {
- OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative), Deleted);
- }
- if (DebugAlwaysTrue((OperationProgress != NULL) && (OperationProgress->Operation == foDelete)))
- {
- OperationProgress->Succeeded(Deleted);
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
- {
- return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
- const TRemoteFile * File, void * AParams)
- {
- TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- StartOperationWithFile(FileName, foCustomCommand);
- LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
- (Params->Command, Params->Params, FileName)));
- FileModified(File, FileName);
- DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
- Params->OutputEvent);
- ReactOnCommand(fsAnyCommand);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
- const TRemoteFile * File, UnicodeString Command, int Params,
- TCaptureOutputEvent OutputEvent)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- try
- {
- if (IsCapable[fcAnyCommand])
- {
- DebugAssert(FFileSystem);
- DebugAssert(fcShellAnyCommand);
- FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
- }
- else
- {
- DebugAssert(CommandSessionOpened);
- DebugAssert(FCommandSession->FSProtocol == cfsSCP);
- LogEvent(L"Executing custom command on command session.");
- if (FCommandSession->CurrentDirectory != CurrentDirectory)
- {
- FCommandSession->CurrentDirectory = CurrentDirectory;
- // We are likely in transaction, so ReadCurrentDirectory won't get called
- // until transaction ends. But we need to know CurrentDirectory to
- // expand !/ pattern.
- // Doing this only, when current directory of the main and secondary shell differs,
- // what would be the case before the first file in transaction.
- // Otherwise we would be reading pwd before every time as the
- // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
- if (FCommandSession->FReadCurrentDirectoryPending)
- {
- FCommandSession->ReadCurrentDirectory();
- }
- }
- FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
- Params, OutputEvent);
- }
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
- int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
- {
- if (!TRemoteCustomCommand().IsFileListCommand(Command))
- {
- TCustomCommandParams AParams;
- AParams.Command = Command;
- AParams.Params = Params;
- AParams.OutputEvent = OutputEvent;
- ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
- }
- else
- {
- UnicodeString FileList;
- for (int i = 0; i < Files->Count; i++)
- {
- TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
- bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
- if (!Dir || FLAGSET(Params, ccApplyToDirectories))
- {
- if (!FileList.IsEmpty())
- {
- FileList += L" ";
- }
- FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
- }
- }
- TCustomCommandData Data(this);
- UnicodeString Cmd =
- TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
- Complete(Command, true);
- if (!DoOnCustomCommand(Cmd))
- {
- DoAnyCommand(Cmd, OutputEvent, NULL);
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command)
- {
- bool Result = false;
- if (FOnCustomCommand != NULL)
- {
- FOnCustomCommand(this, Command, Result);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
- const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
- {
- TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
- DebugAssert(RProperties && !RProperties->Valid.Empty());
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- StartOperationWithFile(FileName, foSetProperties);
- if (Log->Logging)
- {
- LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
- (FileName, BooleanToEngStr(RProperties->Recursive))));
- if (RProperties->Valid.Contains(vpRights))
- {
- LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
- }
- if (RProperties->Valid.Contains(vpGroup))
- {
- LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
- }
- if (RProperties->Valid.Contains(vpOwner))
- {
- LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
- }
- if (RProperties->Valid.Contains(vpModification))
- {
- LogEvent(FORMAT(L" - modification: \"%s\"",
- (FormatDateTime(L"dddddd tt",
- UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
- }
- if (RProperties->Valid.Contains(vpLastAccess))
- {
- LogEvent(FORMAT(L" - last access: \"%s\"",
- (FormatDateTime(L"dddddd tt",
- UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
- }
- }
- FileModified(File, FileName);
- DoChangeFileProperties(FileName, File, RProperties);
- ReactOnCommand(fsChangeProperties);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
- const TRemoteFile * File, const TRemoteProperties * Properties)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
- try
- {
- DebugAssert(FFileSystem);
- FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
- const TRemoteProperties * Properties)
- {
- TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
- FUseBusyCursor = false;
- AnnounceFileListOperation();
- ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
- {
- // see comment in TSFTPFileSystem::IsCapable
- bool Result =
- IsCapable[fcLoadingAdditionalProperties] &&
- FFileSystem->LoadFilesProperties(FileList);
- if (Result && SessionData->CacheDirectories &&
- (FileList->Count > 0) &&
- (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
- {
- AddCachedFileList(FFiles);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCalculateFileSize(UnicodeString FileName,
- const TRemoteFile * File, void * Param)
- {
- // This is called for top-level entries only
- TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
- if (AParams->Stats->FoundFiles != NULL)
- {
- UnicodeString DirPath = UnixExtractFilePath(UnixExcludeTrailingBackslash(File->FullFileName));
- if ((DirPath != AParams->LastDirPath) ||
- (AParams->Files == NULL))
- {
- AParams->Files = new TCollectedFileList();
- AParams->LastDirPath = DirPath;
- AParams->Stats->FoundFiles->AddObject(AParams->LastDirPath, AParams->Files);
- }
- }
- __int64 PrevSize = AParams->Size;
- CalculateFileSize(FileName, File, Param);
- if (AParams->Stats->CalculatedSizes != NULL)
- {
- __int64 Size = AParams->Size - PrevSize;
- AParams->Stats->CalculatedSizes->push_back(Size);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
- const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
- {
- DebugAssert(Param);
- DebugAssert(File);
- TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
- if (FileName.IsEmpty())
- {
- FileName = File->FileName;
- }
- if (!TryStartOperationWithFile(FileName, foCalculateSize))
- {
- AParams->Result = false;
- // Combined with csIgnoreErrors, this will not abort completelly, but we get called again
- // with next sibling of our parent directory (and we get again to this branch, throwing again)
- Abort();
- }
- if ((AParams->CopyParam == NULL) ||
- DoAllowRemoteFileTransfer(File, AParams->CopyParam, FLAGSET(AParams->Params, csDisallowTemporaryTransferFiles)))
- {
- int CollectionIndex = -1;
- if (AParams->Files != NULL)
- {
- UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
- CollectionIndex = AParams->Files->Add(FullFileName, File->Duplicate(), File->IsDirectory);
- }
- if (File->IsDirectory)
- {
- if (CanRecurseToDirectory(File))
- {
- if (!AParams->AllowDirs)
- {
- AParams->Result = false;
- }
- else if (FLAGSET(AParams->Params, csStopOnFirstFile) && (AParams->Stats->Files > 0))
- {
- // do not waste time recursing into a folder, if we already found some files
- }
- else
- {
- if (FLAGCLEAR(AParams->Params, csStopOnFirstFile))
- {
- LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
- }
- // pass in full path so we get it back in file list for AllowTransfer() exclusion
- if (!DoCalculateDirectorySize(File->FullFileName, AParams))
- {
- if (CollectionIndex >= 0)
- {
- AParams->Files->DidNotRecurse(CollectionIndex);
- }
- }
- }
- }
- AParams->Stats->Directories++;
- }
- else
- {
- AParams->Size += File->Resolve()->Size;
- AParams->Stats->Files++;
- }
- if (File->IsSymLink)
- {
- AParams->Stats->SymLinks++;
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString & FileName, TCalculateSizeParams * Params)
- {
- bool Result = false;
- if (FLAGSET(Params->Params, csStopOnFirstFile) && (Configuration->ActualLogProtocol >= 1))
- {
- LogEvent(FORMAT(L"Checking if remote directory \"%s\" is empty", (FileName)));
- }
- TRetryOperationLoop RetryLoop(this);
- do
- {
- try
- {
- ProcessDirectory(FileName, CalculateFileSize, Params);
- Result = true;
- }
- catch(Exception & E)
- {
- // We can probably replace the csIgnoreErrors with IgnoreErrors argument of the ProcessDirectory
- if (!Active || ((Params->Params & csIgnoreErrors) == 0))
- {
- RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
- }
- }
- }
- while (RetryLoop.Retry());
- if (Configuration->ActualLogProtocol >= 1)
- {
- if (Params->Stats->Files == 0)
- {
- LogEvent(FORMAT(L"Remote directory \"%s\" is empty", (FileName)));
- }
- else
- {
- LogEvent(FORMAT(L"Remote directory \"%s\" is not empty", (FileName)));
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
- __int64 & Size, int Params, const TCopyParamType * CopyParam,
- bool AllowDirs, TCalculateSizeStats & Stats)
- {
- // With FTP protocol, we may use DSIZ command from
- // draft-peterson-streamlined-ftp-command-extensions-10
- // Implemented by Serv-U FTP.
- TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
- FUseBusyCursor = false;
- TCalculateSizeParams Param;
- Param.Params = Params;
- Param.CopyParam = CopyParam;
- Param.Stats = &Stats;
- Param.AllowDirs = AllowDirs;
- ProcessFiles(FileList, foCalculateSize, DoCalculateFileSize, &Param);
- Size = Param.Size;
- if (Configuration->ActualLogProtocol >= 1)
- {
- LogEvent(FORMAT(L"Size of %d remote files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
- }
- return Param.Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
- TStrings * FileList, TStrings * Checksums,
- TCalculatedChecksumEvent OnCalculatedChecksum)
- {
- FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
- const UnicodeString NewName, bool CheckExistence)
- {
- DebugAssert(File && File->Directory == FFiles);
- bool Proceed = true;
- // if filename doesn't contain path, we check for existence of file
- if ((File->FileName != NewName) && CheckExistence &&
- Configuration->ConfirmOverwriting &&
- UnixSamePath(CurrentDirectory, FFiles->Directory))
- {
- TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
- if (DuplicateFile)
- {
- UnicodeString QuestionFmt;
- if (DuplicateFile->IsDirectory)
- {
- QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
- }
- else
- {
- QuestionFmt = LoadStr(FILE_OVERWRITE);
- }
- TQueryParams Params(qpNeverAskAgainCheck);
- UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
- unsigned int Result = QueryUser(Question, NULL,
- qaYes | qaNo, &Params);
- if (Result == qaNeverAskAgain)
- {
- Proceed = true;
- Configuration->ConfirmOverwriting = false;
- }
- else
- {
- Proceed = (Result == qaYes);
- }
- }
- }
- if (Proceed)
- {
- FileModified(File, File->FileName);
- LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (File->FileName, NewName)));
- DoRenameFile(File->FileName, File, NewName, false);
- ReactOnCommand(fsRenameFile);
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoRenameFile(const UnicodeString FileName, const TRemoteFile * File,
- const UnicodeString NewName, bool Move)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
- try
- {
- DebugAssert(FFileSystem);
- FFileSystem->RenameFile(FileName, File, NewName);
- }
- catch(Exception & E)
- {
- UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
- RetryLoop.Error(E, Action, Message);
- }
- }
- while (RetryLoop.Retry());
- return RetryLoop.Succeeded();
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoMoveFile(const UnicodeString & FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
- {
- StartOperationWithFile(FileName, foRemoteMove, foDelete);
- DebugAssert(Param != NULL);
- const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
- UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
- MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
- LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
- FileModified(File, FileName);
- bool Result = DoRenameFile(FileName, File, NewName, true);
- if (Result)
- {
- ReactOnCommand(fsMoveFile);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::MoveFile(const UnicodeString FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
- {
- DoMoveFile(FileName, File, Param);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
- const UnicodeString FileMask)
- {
- TMoveFileParams Params;
- Params.Target = Target;
- Params.FileMask = FileMask;
- DirectoryModified(Target, true);
- bool Result;
- BeginTransaction();
- try
- {
- Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
- }
- __finally
- {
- if (Active)
- {
- UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
- bool PossiblyMoved = false;
- // check if we was moving current directory.
- // this is just optimization to avoid checking existence of current
- // directory after each move operation.
- for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
- {
- const TRemoteFile * File =
- dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
- // File can be NULL, and filename may not be full path,
- // but currently this is the only way we can move (at least in GUI)
- // current directory
- if ((File != NULL) &&
- File->IsDirectory &&
- ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
- ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
- (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
- {
- PossiblyMoved = true;
- }
- }
- if (PossiblyMoved && !FileExists(CurrentDirectory))
- {
- UnicodeString NearestExisting = CurrentDirectory;
- do
- {
- NearestExisting = UnixExtractFileDir(NearestExisting);
- }
- while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
- ChangeDirectory(NearestExisting);
- }
- }
- EndTransaction();
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName, const TRemoteFile * File,
- const UnicodeString NewName)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- TCpSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
- try
- {
- DebugAssert(FFileSystem);
- if (IsCapable[fcRemoteCopy])
- {
- FFileSystem->CopyFile(FileName, File, NewName);
- }
- else
- {
- DebugAssert(CommandSessionOpened);
- DebugAssert(FCommandSession->FSProtocol == cfsSCP);
- LogEvent(L"Copying file on command session.");
- FCommandSession->CurrentDirectory = CurrentDirectory;
- FCommandSession->FFileSystem->CopyFile(FileName, File, NewName);
- }
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, Action, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
- const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
- {
- StartOperationWithFile(FileName, foRemoteCopy);
- DebugAssert(Param != NULL);
- const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
- UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
- MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
- LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
- DoCopyFile(FileName, File, NewName);
- ReactOnCommand(fsCopyFile);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
- const UnicodeString FileMask)
- {
- TMoveFileParams Params;
- Params.Target = Target;
- Params.FileMask = FileMask;
- DirectoryModified(Target, true);
- return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CreateDirectory(const UnicodeString & DirName, const TRemoteProperties * Properties)
- {
- DebugAssert(FFileSystem);
- DebugAssert(Properties != NULL);
- EnsureNonExistence(DirName);
- FileModified(NULL, DirName);
- LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
- bool Encrypt = Properties->Valid.Contains(vpEncrypt) && Properties->Encrypt;
- DoCreateDirectory(DirName, Encrypt);
- TValidProperties RemainingPropeties = Properties->Valid - (TValidProperties() << vpEncrypt);
- if (!RemainingPropeties.Empty())
- {
- DoChangeFileProperties(DirName, NULL, Properties);
- }
- ReactOnCommand(fsCreateDirectory);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCreateDirectory(const UnicodeString & DirName, bool Encrypt)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
- try
- {
- DebugAssert(FFileSystem);
- FFileSystem->CreateDirectory(DirName, Encrypt);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
- const UnicodeString PointTo, bool Symbolic)
- {
- DebugAssert(FFileSystem);
- EnsureNonExistence(FileName);
- if (SessionData->CacheDirectories)
- {
- DirectoryModified(CurrentDirectory, false);
- }
- LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
- (FileName, PointTo, BooleanToEngStr(Symbolic))));
- DoCreateLink(FileName, PointTo, Symbolic);
- ReactOnCommand(fsCreateDirectory);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
- const UnicodeString PointTo, bool Symbolic)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- try
- {
- DebugAssert(FFileSystem);
- FFileSystem->CreateLink(FileName, PointTo, Symbolic);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::HomeDirectory()
- {
- DebugAssert(FFileSystem);
- try
- {
- LogEvent(L"Changing directory to home directory.");
- FFileSystem->HomeDirectory();
- ReactOnCommand(fsHomeDirectory);
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetHomeDirectory()
- {
- return FFileSystem->GetHomeDirectory();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
- {
- DebugAssert(FFileSystem);
- try
- {
- UnicodeString CachedDirectory;
- DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
- // never use directory change cache during startup, this ensures, we never
- // end-up initially in non-existing directory
- if ((Status == ssOpened) &&
- SessionData->CacheDirectoryChanges &&
- FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
- Directory, CachedDirectory))
- {
- LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
- (Directory, CachedDirectory)));
- FFileSystem->CachedChangeDirectory(CachedDirectory);
- }
- else
- {
- LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
- FFileSystem->ChangeDirectory(Directory);
- }
- FLastDirectoryChange = Directory;
- ReactOnCommand(fsChangeDirectory);
- }
- catch (Exception &E)
- {
- CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LookupUsersGroups()
- {
- if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
- IsCapable[fcUserGroupListing])
- {
- DebugAssert(FFileSystem);
- try
- {
- FUsersGroupsLookedup = true;
- LogEvent(L"Looking up groups and users.");
- FFileSystem->LookupUsersGroups();
- ReactOnCommand(fsLookupUsersGroups);
- if (Log->Logging)
- {
- FGroups.Log(this, L"groups");
- FMembership.Log(this, L"membership");
- FUsers.Log(this, L"users");
- }
- }
- catch (Exception &E)
- {
- if (!Active || (SessionData->LookupUserGroups == asOn))
- {
- CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
- {
- return !Command.Trim().IsEmpty();
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetCommandSessionOpened()
- {
- // consider secondary terminal open in "ready" state only
- // so we never do keepalives on it until it is completely initialized
- return (FCommandSession != NULL) &&
- (FCommandSession->Status == ssOpened);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminal::CreateSecondarySession(const UnicodeString & Name, TSessionData * SessionData)
- {
- std::unique_ptr<TTerminal> Result(new TSecondaryTerminal(this, SessionData, Configuration, Name));
- Result->AutoReadDirectory = false;
- Result->FExceptionOnFail = FExceptionOnFail;
- Result->OnQueryUser = OnQueryUser;
- Result->OnPromptUser = OnPromptUser;
- Result->OnShowExtendedException = OnShowExtendedException;
- Result->OnProgress = OnProgress;
- Result->OnFinished = OnFinished;
- Result->OnInformation = OnInformation;
- Result->OnCustomCommand = OnCustomCommand;
- // do not copy OnDisplayBanner to avoid it being displayed
- return Result.release();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FillSessionDataForCode(TSessionData * Data)
- {
- const TSessionInfo & SessionInfo = GetSessionInfo();
- if (!SessionInfo.HostKeyFingerprintSHA256.IsEmpty())
- {
- Data->HostKey = SessionInfo.HostKeyFingerprintSHA256;
- }
- else if (SessionInfo.CertificateVerifiedManually && DebugAlwaysTrue(!SessionInfo.CertificateFingerprintSHA256.IsEmpty()))
- {
- Data->HostKey = SessionInfo.CertificateFingerprintSHA256;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::UpdateSessionCredentials(TSessionData * Data)
- {
- Data->UserName = UserName;
- Data->Password = Password;
- if (!FRememberedPassword.IsEmpty() && (FRememberedPasswordKind == pkPassphrase))
- {
- Data->Passphrase = GetRememberedPassword();
- }
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminal::GetCommandSession()
- {
- if ((FCommandSession != NULL) && !FCommandSession->Active)
- {
- SAFE_DESTROY(FCommandSession);
- }
- if (FCommandSession == NULL)
- {
- // transaction cannot be started yet to allow proper matching transaction
- // levels between main and command session
- DebugAssert(FInTransaction == 0);
- std::unique_ptr<TSessionData> CommandSessionData(SessionData->Clone());
- CommandSessionData->RemoteDirectory = CurrentDirectory;
- CommandSessionData->FSProtocol = fsSCPonly;
- CommandSessionData->ClearAliases = false;
- CommandSessionData->UnsetNationalVars = false;
- CommandSessionData->LookupUserGroups = asOff;
- FCommandSession = CreateSecondarySession(L"Shell", CommandSessionData.get());
- FCommandSession->AutoReadDirectory = false;
- FCommandSession->FExceptionOnFail = FExceptionOnFail;
- FCommandSession->OnQueryUser = OnQueryUser;
- FCommandSession->OnPromptUser = OnPromptUser;
- FCommandSession->OnShowExtendedException = OnShowExtendedException;
- FCommandSession->OnProgress = OnProgress;
- FCommandSession->OnFinished = OnFinished;
- FCommandSession->OnInformation = OnInformation;
- FCommandSession->OnCustomCommand = OnCustomCommand;
- // do not copy OnDisplayBanner to avoid it being displayed
- }
- return FCommandSession;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
- TCaptureOutputEvent OutputEvent)
- {
- #pragma warn -inl
- class TOutputProxy
- {
- public:
- __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
- FAction(Action),
- FOutputEvent(OutputEvent)
- {
- }
- void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
- {
- switch (OutputType)
- {
- case cotOutput:
- FAction.AddOutput(Str, false);
- break;
- case cotError:
- FAction.AddOutput(Str, true);
- break;
- case cotExitCode:
- FAction.ExitCode(StrToInt(Str));
- break;
- }
- if (FOutputEvent != NULL)
- {
- FOutputEvent(Str, OutputType);
- }
- }
- private:
- TCallSessionAction & FAction;
- TCaptureOutputEvent FOutputEvent;
- };
- #pragma warn .inl
- TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
- TOutputProxy ProxyOutputEvent(Action, OutputEvent);
- DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
- TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
- {
- DebugAssert(FFileSystem);
- try
- {
- DirectoryModified(CurrentDirectory, false);
- if (IsCapable[fcAnyCommand])
- {
- LogEvent(L"Executing user defined command.");
- FFileSystem->AnyCommand(Command, OutputEvent);
- }
- else
- {
- DebugAssert(CommandSessionOpened);
- DebugAssert(FCommandSession->FSProtocol == cfsSCP);
- LogEvent(L"Executing user defined command on command session.");
- FCommandSession->CurrentDirectory = CurrentDirectory;
- FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
- FCommandSession->FFileSystem->ReadCurrentDirectory();
- // synchronize pwd (by purpose we lose transaction optimization here)
- ChangeDirectory(FCommandSession->CurrentDirectory);
- }
- ReactOnCommand(fsAnyCommand);
- }
- catch (Exception &E)
- {
- if (Action != NULL)
- {
- RollbackAction(*Action, NULL, &E);
- }
- if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
- else HandleExtendedException(&E);
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
- TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
- bool NoConfirmation)
- {
- bool Result = true;
- bool Done;
- unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
- do
- {
- *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
- NULL, CREATE_ALWAYS, CreateAttr, 0);
- Done = (*AHandle != INVALID_HANDLE_VALUE);
- if (!Done)
- {
- // save the error, otherwise it gets overwritten by call to FileExists
- int LastError = GetLastError();
- int FileAttr;
- if (::FileExists(ApiPath(FileName)) &&
- (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
- {
- if (FLAGSET(FileAttr, faReadOnly))
- {
- OperationProgress->LockUserSelections();
- try
- {
- if (OperationProgress->BatchOverwrite == boNone)
- {
- Result = false;
- }
- else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
- {
- unsigned int Answer;
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- Answer = QueryUser(
- MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
- qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
- }
- switch (Answer) {
- case qaYesToAll: OperationProgress->SetBatchOverwrite(boAll); break;
- case qaCancel: OperationProgress->SetCancel(csCancel); // continue on next case
- case qaNoToAll: OperationProgress->SetBatchOverwrite(boNone);
- case qaNo: Result = false; break;
- }
- }
- }
- __finally
- {
- OperationProgress->UnlockUserSelections();
- }
- }
- else
- {
- DebugAssert(FLAGSET(FileAttr, faHidden));
- Result = true;
- }
- if (Result)
- {
- CreateAttr |=
- FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
- FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
- FILE_OPERATION_LOOP_BEGIN
- {
- if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
- {
- RaiseLastOSError();
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
- }
- else
- {
- Done = true;
- }
- }
- else
- {
- RaiseLastOSError(LastError);
- }
- }
- }
- while (!Done);
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
- TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
- bool NoConfirmation)
- {
- DebugAssert(AHandle);
- bool Result = true;
- FILE_OPERATION_LOOP_BEGIN
- {
- Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
- unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
- __int64 * AMTime, __int64 * AATime, __int64 * ASize,
- bool TryWriteReadOnly)
- {
- int Attrs = 0;
- HANDLE Handle = 0;
- FILE_OPERATION_LOOP_BEGIN
- {
- UnicodeString FileNameApi = ApiPath(FileName);
- Attrs = FileGetAttrFix(FileNameApi);
- if (Attrs < 0)
- {
- RaiseLastOSError();
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
- if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
- {
- bool NoHandle = false;
- if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
- ((Attrs & faReadOnly) != 0))
- {
- Access = GENERIC_READ;
- NoHandle = true;
- }
- FILE_OPERATION_LOOP_BEGIN
- {
- DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
- Handle = CreateFile(ApiPath(FileName).c_str(), Access,
- Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
- NULL, OPEN_EXISTING, Flags, 0);
- if (Handle == INVALID_HANDLE_VALUE)
- {
- Handle = 0;
- RaiseLastOSError();
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
- try
- {
- if (AATime || AMTime || ACTime)
- {
- FILETIME ATime;
- FILETIME MTime;
- FILETIME CTime;
- // Get last file access and modification time
- FILE_OPERATION_LOOP_BEGIN
- {
- THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
- if (ACTime)
- {
- *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
- }
- if (AATime)
- {
- *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
- }
- if (AMTime)
- {
- *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
- }
- }
- if (ASize)
- {
- // Get file size
- FILE_OPERATION_LOOP_BEGIN
- {
- unsigned long LSize;
- unsigned long HSize;
- LSize = GetFileSize(Handle, &HSize);
- if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
- *ASize = (__int64(HSize) << 32) + LSize;
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
- }
- if ((AHandle == NULL) || NoHandle)
- {
- CloseHandle(Handle);
- Handle = NULL;
- }
- }
- catch(...)
- {
- CloseHandle(Handle);
- throw;
- }
- }
- if (AAttrs) *AAttrs = Attrs;
- if (AHandle) *AHandle = Handle;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OpenLocalFile(
- const UnicodeString & FileName, unsigned int Access, TLocalFileHandle & Handle, bool TryWriteReadOnly)
- {
- Handle.FileName = FileName;
- OpenLocalFile(
- FileName, Access, &Handle.Attrs, &Handle.Handle, NULL, &Handle.MTime, &Handle.ATime, &Handle.Size,
- TryWriteReadOnly);
- Handle.Modification = UnixToDateTime(Handle.MTime, SessionData->DSTMode);
- Handle.Directory = FLAGSET(Handle.Attrs, faDirectory);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoAllowLocalFileTransfer(
- const UnicodeString & FileName, const TSearchRecSmart & SearchRec, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
- {
- TFileMasks::TParams Params;
- Params.Size = SearchRec.Size;
- Params.Modification = SearchRec.GetLastWriteTime();
- UnicodeString BaseFileName = GetBaseFileName(FileName);
- // Note that for synchronization, we do not need to check "TSynchronizeOptions::MatchesFilter" here as
- // that is checked for top-level entries only and we are never top-level here.
- return
- CopyParam->AllowTransfer(BaseFileName, osLocal, SearchRec.IsDirectory(), Params, SearchRec.IsHidden()) &&
- (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(FileName)) &&
- (!SearchRec.IsDirectory() || !CopyParam->ExcludeEmptyDirectories ||
- !IsEmptyLocalDirectory(FileName, CopyParam, DisallowTemporaryTransferFiles));
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DoAllowRemoteFileTransfer(
- const TRemoteFile * File, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
- {
- TFileMasks::TParams MaskParams;
- MaskParams.Size = File->Resolve()->Size;
- MaskParams.Modification = File->Modification;
- UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
- UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
- return
- CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams, File->IsHidden) &&
- (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(File->FileName)) &&
- (!File->IsDirectory || !CopyParam->ExcludeEmptyDirectories ||
- !IsEmptyRemoteDirectory(File, CopyParam, DisallowTemporaryTransferFiles));
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::AllowLocalFileTransfer(
- const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
- const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
- {
- bool Result = true;
- // optimization (though in most uses of the method, the caller actually knows TSearchRec already, so it passes it here
- if (Log->Logging || !CopyParam->AllowAnyTransfer())
- {
- TSearchRecSmart ASearchRec;
- if (SearchRec == NULL)
- {
- if (CopyParam->OnTransferIn != NULL)
- {
- ASearchRec.Clear();
- }
- else
- {
- FILE_OPERATION_LOOP_BEGIN
- {
- if (!FileSearchRec(FileName, ASearchRec))
- {
- RaiseLastOSError();
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
- }
- SearchRec = &ASearchRec;
- }
- if (!DoAllowLocalFileTransfer(FileName, *SearchRec, CopyParam, false))
- {
- LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
- Result = false;
- }
- else if (CopyParam->SkipTransfer(FileName, SearchRec->IsDirectory()))
- {
- OperationProgress->AddSkippedFileSize(SearchRec->Size);
- Result = false;
- }
- if (Result)
- {
- LogFileDetails(FileName, SearchRec->GetLastWriteTime(), SearchRec->Size);
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::MakeLocalFileList(
- const UnicodeString & FileName, const TSearchRecSmart & Rec, void * Param)
- {
- TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
- if (Rec.IsDirectory() && Params.Recursive)
- {
- ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
- }
- if (!Rec.IsDirectory() || Params.IncludeDirs)
- {
- Params.FileList->Add(FileName);
- if (Params.FileTimes != NULL)
- {
- Params.FileTimes->push_back(const_cast<TSearchRecSmart &>(Rec).TimeStamp);
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateLocalFileSize(
- const UnicodeString & FileName, const TSearchRecSmart & Rec, /*TCalculateSizeParams*/ void * Params)
- {
- TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
- if (!TryStartOperationWithFile(FileName, foCalculateSize))
- {
- AParams->Result = false;
- }
- else
- {
- try
- {
- if ((AParams->CopyParam == NULL) ||
- DoAllowLocalFileTransfer(FileName, Rec, AParams->CopyParam, false))
- {
- int CollectionIndex = -1;
- if (AParams->Files != NULL)
- {
- UnicodeString FullFileName = ::ExpandFileName(FileName);
- CollectionIndex = AParams->Files->Add(FullFileName, NULL, Rec.IsDirectory());
- }
- if (!Rec.IsDirectory())
- {
- AParams->Size += Rec.Size;
- }
- else
- {
- try
- {
- ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
- }
- catch (...)
- {
- if (CollectionIndex >= 0)
- {
- AParams->Files->DidNotRecurse(CollectionIndex);
- }
- }
- }
- }
- }
- catch (...)
- {
- // ignore
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
- __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs, TStrings * Files,
- TCalculatedSizes * CalculatedSizes)
- {
- bool Result = false;
- TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
- TOnceDoneOperation OnceDoneOperation = odoIdle;
- OperationStart(OperationProgress, foCalculateSize, osLocal, FileList->Count);
- try
- {
- TCalculateSizeParams Params;
- Params.Size = 0;
- Params.Params = 0;
- Params.CopyParam = CopyParam;
- Params.Files = NULL;
- Params.Result = true;
- UnicodeString LastDirPath;
- for (int Index = 0; Params.Result && (Index < FileList->Count); Index++)
- {
- UnicodeString FileName = FileList->Strings[Index];
- TSearchRecSmart Rec;
- if (FileSearchRec(FileName, Rec))
- {
- if (Rec.IsDirectory() && !AllowDirs)
- {
- Params.Result = false;
- }
- else
- {
- if (Files != NULL)
- {
- UnicodeString FullFileName = ::ExpandFileName(FileName);
- UnicodeString DirPath = ExtractFilePath(FullFileName);
- if (DirPath != LastDirPath)
- {
- Params.Files = new TCollectedFileList();
- LastDirPath = DirPath;
- Files->AddObject(LastDirPath, Params.Files);
- }
- }
- __int64 PrevSize = Params.Size;
- CalculateLocalFileSize(FileName, Rec, &Params);
- if (CalculatedSizes != NULL)
- {
- __int64 Size = Params.Size - PrevSize;
- CalculatedSizes->push_back(Size);
- }
- OperationFinish(&OperationProgress, FileList->Objects[Index], FileName, true, OnceDoneOperation);
- }
- }
- }
- Size = Params.Size;
- Result = Params.Result;
- }
- __finally
- {
- OperationStop(OperationProgress);
- }
- if (Configuration->ActualLogProtocol >= 1)
- {
- LogEvent(FORMAT(L"Size of %d local files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
- }
- if (OnceDoneOperation != odoIdle)
- {
- CloseOnCompletion(OnceDoneOperation);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- struct TSynchronizeFileData
- {
- bool Modified;
- bool New;
- bool IsDirectory;
- TSynchronizeChecklist::TItem::TFileInfo Info;
- TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
- TRemoteFile * MatchingRemoteFileFile;
- int MatchingRemoteFileImageIndex;
- FILETIME LocalLastWriteTime;
- };
- //---------------------------------------------------------------------------
- const int sfFirstLevel = 0x01;
- struct TSynchronizeData
- {
- UnicodeString LocalDirectory;
- UnicodeString RemoteDirectory;
- TTerminal::TSynchronizeMode Mode;
- int Params;
- TSynchronizeDirectory OnSynchronizeDirectory;
- TSynchronizeOptions * Options;
- int Flags;
- TStringList * LocalFileList;
- const TCopyParamType * CopyParam;
- TSynchronizeChecklist * Checklist;
- };
- //---------------------------------------------------------------------------
- TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
- const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
- const TCopyParamType * CopyParam, int Params,
- TSynchronizeDirectory OnSynchronizeDirectory,
- TSynchronizeOptions * Options)
- {
- TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
- FUseBusyCursor = false;
- TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
- try
- {
- DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
- CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
- Checklist);
- Checklist->Sort();
- }
- catch(...)
- {
- delete Checklist;
- throw;
- }
- return Checklist;
- }
- //---------------------------------------------------------------------------
- static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
- {
- if (FLAGSET(Params, Param))
- {
- AddToList(ParamsStr, Name, ", ");
- }
- Params &= ~Param;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
- {
- UnicodeString ModeStr;
- switch (Mode)
- {
- case smRemote:
- ModeStr = L"Remote";
- break;
- case smLocal:
- ModeStr = L"Local";
- break;
- case smBoth:
- ModeStr = L"Both";
- break;
- default:
- ModeStr = L"Unknown";
- break;
- }
- return ModeStr;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
- {
- UnicodeString ParamsStr;
- AddFlagName(ParamsStr, Params, spDelete, L"Delete");
- AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
- AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
- AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
- AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
- AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
- AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
- AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
- AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
- AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
- AddFlagName(ParamsStr, Params, spBySize, L"BySize");
- AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
- AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
- if (Params > 0)
- {
- AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
- }
- return ParamsStr;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::LocalFindFirstLoop(const UnicodeString & Path, TSearchRecChecked & SearchRec)
- {
- bool Result;
- FILE_OPERATION_LOOP_BEGIN
- {
- const int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
- Result = (FindFirstChecked(Path, FindAttrs, SearchRec) == 0);
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (Path)));
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::LocalFindNextLoop(TSearchRecChecked & SearchRec)
- {
- bool Result;
- FILE_OPERATION_LOOP_BEGIN
- {
- Result = (FindNextChecked(SearchRec) == 0);
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (SearchRec.Path)));
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::IsEmptyLocalDirectory(
- const UnicodeString & Path, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
- {
- UnicodeString Contents;
- if (Configuration->ActualLogProtocol >= 1)
- {
- LogEvent(FORMAT(L"Checking if local directory \"%s\" is empty", (Path)));
- }
- TSearchRecOwned SearchRec;
- if (LocalFindFirstLoop(IncludeTrailingBackslash(Path) + L"*.*", SearchRec))
- {
- do
- {
- UnicodeString FullLocalFileName = IncludeTrailingBackslash(Path) + SearchRec.Name;
- if (SearchRec.IsRealFile() &&
- DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true))
- {
- if (!SearchRec.IsDirectory() ||
- !IsEmptyLocalDirectory(FullLocalFileName, CopyParam, DisallowTemporaryTransferFiles))
- {
- Contents = SearchRec.Name;
- }
- }
- }
- while (Contents.IsEmpty() && LocalFindNextLoop(SearchRec));
- }
- if (Configuration->ActualLogProtocol >= 1)
- {
- if (Contents.IsEmpty())
- {
- LogEvent(FORMAT(L"Local directory \"%s\" is empty", (Path)));
- }
- else
- {
- LogEvent(FORMAT(L"Local directory \"%s\" is not empty, it contains \"%s\"", (Path, Contents)));
- }
- }
- return Contents.IsEmpty();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
- const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
- const TCopyParamType * CopyParam, int Params,
- TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
- int Flags, TSynchronizeChecklist * Checklist)
- {
- TSynchronizeData Data;
- Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
- Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
- Data.Mode = Mode;
- Data.Params = Params;
- Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
- Data.LocalFileList = NULL;
- Data.CopyParam = CopyParam;
- Data.Options = Options;
- Data.Flags = Flags;
- Data.Checklist = Checklist;
- LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
- "mode = %s, params = 0x%x (%s), file mask = '%s'", (LocalDirectory, RemoteDirectory,
- SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params), CopyParam->IncludeFileMask.Masks)));
- if (FLAGCLEAR(Params, spDelayProgress))
- {
- DoSynchronizeProgress(Data, true);
- }
- try
- {
- Data.LocalFileList = CreateSortedStringList();
- TSearchRecOwned SearchRec;
- if (LocalFindFirstLoop(Data.LocalDirectory + L"*.*", SearchRec))
- {
- do
- {
- UnicodeString FileName = SearchRec.Name;
- UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
- UnicodeString RemoteFileName = ChangeFileName(CopyParam, FileName, osLocal, false);
- if (SearchRec.IsRealFile() &&
- DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true) &&
- (FLAGCLEAR(Flags, sfFirstLevel) ||
- (Options == NULL) ||
- Options->MatchesFilter(FileName) ||
- Options->MatchesFilter(RemoteFileName)))
- {
- TSynchronizeFileData * FileData = new TSynchronizeFileData;
- FileData->IsDirectory = SearchRec.IsDirectory();
- FileData->Info.FileName = FileName;
- FileData->Info.Directory = Data.LocalDirectory;
- FileData->Info.Modification = SearchRec.GetLastWriteTime();
- FileData->Info.ModificationFmt = mfFull;
- FileData->Info.Size = SearchRec.Size;
- FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
- FileData->New = true;
- FileData->Modified = false;
- Data.LocalFileList->AddObject(FileName, reinterpret_cast<TObject*>(FileData));
- LogEvent(0, FORMAT(L"Local file %s included to synchronization",
- (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
- }
- else
- {
- LogEvent(0, FORMAT(L"Local file %s excluded from synchronization",
- (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
- }
- }
- while (LocalFindNextLoop(SearchRec));
- SearchRec.Close();
- // can we expect that ProcessDirectory would take so little time
- // that we can postpone showing progress window until anything actually happens?
- bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
- FDirectoryCache->HasFileList(RemoteDirectory);
- if (!Cached && FLAGSET(Params, spDelayProgress))
- {
- DoSynchronizeProgress(Data, true);
- }
- ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
- FLAGSET(Params, spUseCache));
- TSynchronizeFileData * FileData;
- for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
- {
- FileData = reinterpret_cast<TSynchronizeFileData *>
- (Data.LocalFileList->Objects[Index]);
- // add local file either if we are going to upload it
- // (i.e. if it is updated or we want to upload even new files)
- // or if we are going to delete it (i.e. all "new"=obsolete files)
- bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
- bool New = (FileData->New &&
- ((Mode == smLocal) ||
- (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
- if (New)
- {
- LogEvent(FORMAT(L"Local file %s is new",
- (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
- FileData->Info.Modification, FileData->Info.Size))));
- }
- if (Modified || New)
- {
- TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
- try
- {
- ChecklistItem->IsDirectory = FileData->IsDirectory;
- ChecklistItem->Local = FileData->Info;
- ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
- if (Modified)
- {
- DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
- ChecklistItem->Remote = FileData->MatchingRemoteFile;
- ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
- ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
- }
- else
- {
- ChecklistItem->Remote.Directory = Data.RemoteDirectory;
- }
- if ((Mode == smBoth) || (Mode == smRemote))
- {
- ChecklistItem->Action =
- (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
- ChecklistItem->Checked =
- (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
- (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
- FLAGSET(Params, spSubDirs));
- }
- else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
- {
- ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
- ChecklistItem->Checked =
- FLAGSET(Params, spDelete) &&
- (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
- FLAGSET(Params, spSubDirs));
- }
- if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
- {
- Data.Checklist->Add(ChecklistItem);
- ChecklistItem = NULL;
- }
- }
- __finally
- {
- delete ChecklistItem;
- }
- }
- else
- {
- if (FileData->Modified)
- {
- delete FileData->MatchingRemoteFileFile;
- }
- }
- }
- }
- }
- __finally
- {
- if (Data.LocalFileList != NULL)
- {
- for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
- {
- TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
- (Data.LocalFileList->Objects[Index]);
- delete FileData;
- }
- delete Data.LocalFileList;
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
- const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
- {
- try
- {
- DoSynchronizeCollectFile(FileName, File, Param);
- }
- catch(ESkipFile & E)
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- if (!HandleException(&E))
- {
- throw;
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::IsEmptyRemoteDirectory(
- const TRemoteFile * File, const TCopyParamType * ACopyParam, bool DisallowTemporaryTransferFiles)
- {
- TCalculateSizeStats Stats;
- TCopyParamType CopyParam(*ACopyParam);
- CopyParam.ExcludeEmptyDirectories = false; // to avoid endless recursion
- TCalculateSizeParams Params;
- Params.Params = csStopOnFirstFile | csIgnoreErrors | FLAGMASK(DisallowTemporaryTransferFiles, csDisallowTemporaryTransferFiles);
- Params.CopyParam = &CopyParam;
- Params.Stats = &Stats;
- DoCalculateDirectorySize(UnixExcludeTrailingBackslash(File->FullFileName), &Params);
- return Params.Result && (Stats.Files == 0);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
- const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
- {
- TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
- // Can be NULL in scripting
- if (Data->Options != NULL)
- {
- Data->Options->Files++;
- }
- UnicodeString LocalFileName = ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
- UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
- if (DoAllowRemoteFileTransfer(File, Data->CopyParam, true) &&
- (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
- (Data->Options == NULL) ||
- Data->Options->MatchesFilter(File->FileName) ||
- Data->Options->MatchesFilter(LocalFileName)))
- {
- TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
- try
- {
- ChecklistItem->IsDirectory = File->IsDirectory;
- ChecklistItem->ImageIndex = File->IconIndex;
- ChecklistItem->Remote.FileName = File->FileName;
- ChecklistItem->Remote.Directory = Data->RemoteDirectory;
- ChecklistItem->Remote.Modification = File->Modification;
- ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
- ChecklistItem->Remote.Size = File->Resolve()->Size;
- bool Modified = false;
- bool New = false;
- if (File->IsDirectory && !CanRecurseToDirectory(File))
- {
- LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
- }
- else
- {
- int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
- New = (LocalIndex < 0);
- if (!New)
- {
- TSynchronizeFileData * LocalData =
- reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
- LocalData->New = false;
- if (File->IsDirectory != LocalData->IsDirectory)
- {
- LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
- (File->FileName)));
- }
- else if (!File->IsDirectory)
- {
- ChecklistItem->Local = LocalData->Info;
- ChecklistItem->Local.Modification =
- ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
- bool LocalModified = false;
- // for spTimestamp+spBySize require that the file sizes are the same
- // before comparing file time
- int TimeCompare;
- if (FLAGCLEAR(Data->Params, spNotByTime) &&
- (FLAGCLEAR(Data->Params, spTimestamp) ||
- FLAGCLEAR(Data->Params, spBySize) ||
- (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
- {
- TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
- ChecklistItem->Remote.Modification);
- }
- else
- {
- TimeCompare = 0;
- }
- if (TimeCompare < 0)
- {
- if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
- (Data->Mode == smBoth) || (Data->Mode == smLocal))
- {
- Modified = true;
- }
- else
- {
- LocalModified = true;
- }
- }
- else if (TimeCompare > 0)
- {
- if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
- (Data->Mode == smBoth) || (Data->Mode == smRemote))
- {
- LocalModified = true;
- }
- else
- {
- Modified = true;
- }
- }
- else if (FLAGSET(Data->Params, spBySize) &&
- (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
- FLAGCLEAR(Data->Params, spTimestamp))
- {
- Modified = true;
- LocalModified = true;
- }
- if (LocalModified)
- {
- LocalData->Modified = true;
- LocalData->MatchingRemoteFile = ChecklistItem->Remote;
- LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
- // we need this for custom commands over checklist only,
- // not for sync itself
- LocalData->MatchingRemoteFileFile = File->Duplicate();
- LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
- (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
- LocalData->Info.Modification, LocalData->Info.Size),
- FormatFileDetailsForLog(FullRemoteFileName,
- File->Modification, File->Size, File->LinkedFile))));
- }
- if (Modified)
- {
- LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
- (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile),
- FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
- LocalData->Info.Modification, LocalData->Info.Size))));
- }
- }
- else if (FLAGCLEAR(Data->Params, spNoRecurse))
- {
- DoSynchronizeCollectDirectory(
- Data->LocalDirectory + LocalData->Info.FileName,
- Data->RemoteDirectory + File->FileName,
- Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
- Data->Options, (Data->Flags & ~sfFirstLevel),
- Data->Checklist);
- }
- }
- else
- {
- ChecklistItem->Local.Directory = Data->LocalDirectory;
- LogEvent(FORMAT(L"Remote file %s is new",
- (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
- }
- }
- if (New || Modified)
- {
- DebugAssert(!New || !Modified);
- // download the file if it changed or is new and we want to have it locally
- if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
- {
- if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
- {
- ChecklistItem->Action =
- (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
- ChecklistItem->Checked =
- (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
- (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
- FLAGSET(Data->Params, spSubDirs));
- }
- }
- else if ((Data->Mode == smRemote) && New)
- {
- if (FLAGCLEAR(Data->Params, spTimestamp))
- {
- ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
- ChecklistItem->Checked =
- FLAGSET(Data->Params, spDelete) &&
- (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
- FLAGSET(Data->Params, spSubDirs));
- }
- }
- if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
- {
- ChecklistItem->RemoteFile = File->Duplicate();
- Data->Checklist->Add(ChecklistItem);
- ChecklistItem = NULL;
- }
- }
- }
- __finally
- {
- delete ChecklistItem;
- }
- }
- else
- {
- LogEvent(0, FORMAT(L"Remote file %s excluded from synchronization",
- (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SynchronizeApply(
- TSynchronizeChecklist * Checklist,
- const TCopyParamType * CopyParam, int Params,
- TSynchronizeDirectory OnSynchronizeDirectory, TProcessedSynchronizationChecklistItem OnProcessedItem,
- TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems, void * Token,
- TFileOperationStatistics * Statistics)
- {
- TSynchronizeData Data;
- Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
- int CopyParams =
- FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
- TCopyParamType SyncCopyParam = *CopyParam;
- // when synchronizing by time, we force preserving time,
- // otherwise it does not make any sense
- if (FLAGCLEAR(Params, spNotByTime))
- {
- SyncCopyParam.PreserveTime = true;
- }
- if (SyncCopyParam.CalculateSize)
- {
- // If we fail to collect the sizes, do not try again during an actual transfer
- SyncCopyParam.CalculateSize = false;
- TSynchronizeChecklist::TItemList Items;
- for (int Index = 0; Index < Checklist->Count; Index++)
- {
- const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
- // TSynchronizeChecklistDialog relies on us not to update a size of an item that had size already
- // See TSynchronizeChecklistDialog::UpdatedSynchronizationChecklistItems
- if (ChecklistItem->Checked && !TSynchronizeChecklist::IsItemSizeIrrelevant(ChecklistItem->Action) &&
- !ChecklistItem->HasSize() && DebugAlwaysTrue(ChecklistItem->IsDirectory))
- {
- Items.push_back(ChecklistItem);
- }
- }
- SynchronizeChecklistCalculateSize(Checklist, Items, &SyncCopyParam);
- if (OnUpdatedSynchronizationChecklistItems != NULL)
- {
- OnUpdatedSynchronizationChecklistItems(Items);
- }
- }
- BeginTransaction();
- TValueRestorer<TFileOperationProgressType::TPersistence *> OperationProgressPersistenceRestorer(FOperationProgressPersistence);
- TValueRestorer<TOnceDoneOperation> OperationProgressOnceDoneOperationRestorer(FOperationProgressOnceDoneOperation);
- TFileOperationProgressType::TPersistence OperationProgressPersistence;
- OperationProgressPersistence.Statistics = Statistics;
- FOperationProgressPersistence = &OperationProgressPersistence;
- try
- {
- int Index = 0;
- while (Index < Checklist->Count)
- {
- const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
- if (ChecklistItem->Checked)
- {
- if (!SamePaths(Data.LocalDirectory, ChecklistItem->Local.Directory) ||
- !UnixSamePath(Data.RemoteDirectory, ChecklistItem->Remote.Directory))
- {
- Data.LocalDirectory = IncludeTrailingBackslash(ChecklistItem->Local.Directory);
- Data.RemoteDirectory = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory);
- LogEvent(
- FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', params = 0x%x (%s)",
- (Data.LocalDirectory, Data.RemoteDirectory, int(Params), SynchronizeParamsStr(Params))));
- DoSynchronizeProgress(Data, false);
- }
- std::unique_ptr<TStringList> FileList(new TStringList());
- UnicodeString LocalPath = IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName;
- UnicodeString RemotePath = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName;
- bool Result = true;
- if (FLAGSET(Params, spTimestamp))
- {
- // used by SynchronizeLocalTimestamp and SynchronizeRemoteTimestamp
- TObject * ChecklistItemToken = const_cast<TObject *>(reinterpret_cast<const TObject *>(ChecklistItem));
- switch (ChecklistItem->Action)
- {
- case TSynchronizeChecklist::saDownloadUpdate:
- FileList->AddObject(RemotePath, ChecklistItemToken);
- ProcessFiles(FileList.get(), foSetProperties, SynchronizeLocalTimestamp, NULL, osLocal);
- break;
- case TSynchronizeChecklist::saUploadUpdate:
- FileList->AddObject(LocalPath, ChecklistItemToken);
- ProcessFiles(FileList.get(), foSetProperties, SynchronizeRemoteTimestamp);
- break;
- default:
- DebugFail();
- Result = false;
- break;
- }
- }
- else
- {
- TCopyParamType ItemCopyParam = SyncCopyParam;
- ItemCopyParam.Size = ChecklistItem->HasSize() ? ChecklistItem->GetSize() : -1;
- switch (ChecklistItem->Action)
- {
- case TSynchronizeChecklist::saDownloadNew:
- case TSynchronizeChecklist::saDownloadUpdate:
- FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
- Result = CopyToLocal(FileList.get(), Data.LocalDirectory, &ItemCopyParam, CopyParams, NULL);
- break;
- case TSynchronizeChecklist::saDeleteRemote:
- FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
- Result = DeleteFiles(FileList.get());
- break;
- case TSynchronizeChecklist::saUploadNew:
- case TSynchronizeChecklist::saUploadUpdate:
- FileList->Add(LocalPath);
- Result = CopyToRemote(FileList.get(), Data.RemoteDirectory, &ItemCopyParam, CopyParams, NULL);
- break;
- case TSynchronizeChecklist::saDeleteLocal:
- FileList->Add(LocalPath);
- Result = DeleteLocalFiles(FileList.get());
- break;
- default:
- DebugFail();
- Result = false;
- break;
- }
- }
- if (!Result)
- {
- Abort();
- }
- if (OnProcessedItem != NULL)
- {
- OnProcessedItem(Token, ChecklistItem);
- }
- }
- Index++;
- }
- }
- __finally
- {
- EndTransaction();
- }
- if (FOperationProgressOnceDoneOperation != odoIdle)
- {
- // Otherwise CloseOnCompletion would have no effect
- OperationProgressPersistenceRestorer.Release();
- CloseOnCompletion(FOperationProgressOnceDoneOperation);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SynchronizeChecklistCalculateSize(
- TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items,
- const TCopyParamType * CopyParam)
- {
- std::unique_ptr<TStrings> RemoteFileList(new TStringList());
- std::unique_ptr<TStrings> LocalFileList(new TStringList());
- for (size_t Index = 0; Index < Items.size(); Index++)
- {
- const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
- if (ChecklistItem->IsDirectory)
- {
- if (ChecklistItem->IsRemoteOnly())
- {
- RemoteFileList->AddObject(ChecklistItem->RemoteFile->FullFileName, ChecklistItem->RemoteFile);
- }
- else if (ChecklistItem->IsLocalOnly())
- {
- LocalFileList->Add(IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName);
- }
- else
- {
- // "update" actions are not relevant for directories
- DebugFail();
- }
- }
- }
- TCalculatedSizes RemoteCalculatedSizes;
- TCalculatedSizes LocalCalculatedSizes;
- try
- {
- bool Result = true;
- if (LocalFileList->Count > 0)
- {
- __int64 LocalSize = 0;
- Result = CalculateLocalFilesSize(LocalFileList.get(), LocalSize, CopyParam, true, NULL, &LocalCalculatedSizes);
- }
- if (Result && (RemoteFileList->Count > 0))
- {
- __int64 RemoteSize = 0;
- TCalculateSizeStats RemoteStats;
- RemoteStats.CalculatedSizes = &RemoteCalculatedSizes;
- CalculateFilesSize(RemoteFileList.get(), RemoteSize, 0, CopyParam, true, RemoteStats);
- }
- }
- __finally
- {
- size_t LocalIndex = 0;
- size_t RemoteIndex = 0;
- for (size_t Index = 0; Index < Items.size(); Index++)
- {
- const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
- if (ChecklistItem->IsDirectory)
- {
- __int64 Size = -1;
- if (ChecklistItem->IsRemoteOnly())
- {
- if (RemoteIndex < RemoteCalculatedSizes.size())
- {
- Size = RemoteCalculatedSizes[RemoteIndex];
- }
- RemoteIndex++;
- }
- else if (ChecklistItem->IsLocalOnly())
- {
- if (LocalIndex < LocalCalculatedSizes.size())
- {
- Size = LocalCalculatedSizes[LocalIndex];
- }
- LocalIndex++;
- }
- else
- {
- // "update" actions are not relevant for directories
- DebugFail();
- }
- if (Size >= 0)
- {
- Checklist->UpdateDirectorySize(ChecklistItem, Size);
- }
- }
- }
- DebugAssert(RemoteIndex >= RemoteCalculatedSizes.size());
- DebugAssert(LocalIndex >= LocalCalculatedSizes.size());
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
- bool Collect)
- {
- if (Data.OnSynchronizeDirectory != NULL)
- {
- bool Continue = true;
- Data.OnSynchronizeDirectory(
- Data.LocalDirectory, Data.RemoteDirectory, Continue, Collect, Data.Options);
- if (!Continue)
- {
- Abort();
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
- const TRemoteFile * File, void * /*Param*/)
- {
- const TSynchronizeChecklist::TItem * ChecklistItem =
- reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
- UnicodeString LocalFile =
- IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
- ChecklistItem->Local.FileName;
- FILE_OPERATION_LOOP_BEGIN
- {
- HANDLE Handle;
- OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
- NULL, NULL, NULL, NULL);
- FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
- SessionData->DSTMode);
- bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
- int Error = GetLastError();
- CloseHandle(Handle);
- if (!Result)
- {
- RaiseLastOSError(Error);
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
- const TRemoteFile * File, void * /*Param*/)
- {
- const TSynchronizeChecklist::TItem * ChecklistItem =
- reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
- TRemoteProperties Properties;
- Properties.Valid << vpModification;
- Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
- SessionData->DSTMode);
- ChangeFileProperties(
- UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
- NULL, &Properties);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FileFind(UnicodeString FileName,
- const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
- {
- // see DoFilesFind
- FOnFindingFile = NULL;
- DebugAssert(Param);
- DebugAssert(File);
- TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
- if (!AParams->Cancel)
- {
- if (FileName.IsEmpty())
- {
- FileName = File->FileName;
- }
- TFileMasks::TParams MaskParams;
- MaskParams.Size = File->Resolve()->Size;
- MaskParams.Modification = File->Modification;
- UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
- bool ImplicitMatch;
- // Do not use recursive include match
- if (AParams->FileMask.Matches(FullFileName, false,
- File->IsDirectory, &MaskParams, false, ImplicitMatch))
- {
- if (!ImplicitMatch)
- {
- AParams->OnFileFound(this, FileName, File, AParams->Cancel);
- }
- if (File->IsDirectory)
- {
- UnicodeString RealDirectory;
- if (!File->IsSymLink || File->LinkTo.IsEmpty())
- {
- RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
- }
- else
- {
- RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
- }
- if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
- {
- LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
- }
- else
- {
- DoFilesFind(FullFileName, *AParams, RealDirectory);
- }
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
- {
- LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
- Params.OnFindingFile(this, Directory, Params.Cancel);
- if (!Params.Cancel)
- {
- DebugAssert(FOnFindingFile == NULL);
- // ideally we should set the handler only around actually reading
- // of the directory listing, so we at least reset the handler in
- // FileFind
- FOnFindingFile = Params.OnFindingFile;
- UnicodeString PrevRealDirectory = Params.RealDirectory;
- try
- {
- Params.RealDirectory = RealDirectory;
- ProcessDirectory(Directory, FileFind, &Params, false, true);
- }
- __finally
- {
- Params.RealDirectory = PrevRealDirectory;
- FOnFindingFile = NULL;
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
- TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
- {
- TFilesFindParams Params;
- Params.FileMask = FileMask;
- Params.FileMask.NoImplicitMatchWithDirExcludeMask = true;
- Params.FileMask.AllDirsAreImplicitlyIncluded = true;
- Params.OnFileFound = OnFileFound;
- Params.OnFindingFile = OnFindingFile;
- Params.Cancel = false;
- Params.LoopDetector.RecordVisitedDirectory(Directory);
- DoFilesFind(Directory, Params, Directory);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
- TSpaceAvailable & ASpaceAvailable)
- {
- DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
- try
- {
- FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
- }
- catch (Exception &E)
- {
- CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LockFile(const UnicodeString FileName,
- const TRemoteFile * File, void * /*Param*/)
- {
- StartOperationWithFile(FileName, foLock);
- LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
- FileModified(File, FileName, true);
- DoLockFile(FileName, File);
- ReactOnCommand(fsLock);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- try
- {
- FFileSystem->LockFile(FileName, File);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
- const TRemoteFile * File, void * /*Param*/)
- {
- StartOperationWithFile(FileName, foUnlock);
- LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
- FileModified(File, FileName, true);
- DoUnlockFile(FileName, File);
- ReactOnCommand(fsLock);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
- {
- TRetryOperationLoop RetryLoop(this);
- do
- {
- try
- {
- FFileSystem->UnlockFile(FileName, File);
- }
- catch(Exception & E)
- {
- RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
- }
- }
- while (RetryLoop.Retry());
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LockFiles(TStrings * FileList)
- {
- BeginTransaction();
- try
- {
- ProcessFiles(FileList, foLock, LockFile, NULL);
- }
- __finally
- {
- EndTransaction();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
- {
- BeginTransaction();
- try
- {
- ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
- }
- __finally
- {
- EndTransaction();
- }
- }
- //---------------------------------------------------------------------------
- const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
- {
- return FFileSystem->GetSessionInfo();
- }
- //---------------------------------------------------------------------------
- const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
- {
- return FFileSystem->GetFileSystemInfo(Retrieve);
- }
- //---------------------------------------------------------------------
- void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
- {
- FFileSystem->GetSupportedChecksumAlgs(Algs);
- }
- //---------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetPassword()
- {
- UnicodeString Result;
- // FRememberedPassword is empty also when stored password was used
- if (FRememberedPassword.IsEmpty())
- {
- Result = SessionData->Password;
- }
- else if (FRememberedPasswordKind != pkPassphrase)
- {
- Result = GetRememberedPassword();
- }
- return Result;
- }
- //---------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetRememberedPassword()
- {
- return DecryptPassword(FRememberedPassword);
- }
- //---------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
- {
- return DecryptPassword(FRememberedTunnelPassword);
- }
- //---------------------------------------------------------------------
- bool __fastcall TTerminal::GetStoredCredentialsTried()
- {
- bool Result;
- if (FFileSystem != NULL)
- {
- Result = FFileSystem->GetStoredCredentialsTried();
- }
- else if (FSecureShell != NULL)
- {
- Result = FSecureShell->GetStoredCredentialsTried();
- }
- else
- {
- DebugAssert(FTunnelOpening);
- Result = false;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- int __fastcall TTerminal::CopyToParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
- {
- UnicodeString FileName;
- TObject * Object;
- UnicodeString TargetDir;
- bool Dir;
- bool Recursed;
- int Result = ParallelOperation->GetNext(this, FileName, Object, TargetDir, Dir, Recursed);
- if (Result > 0)
- {
- std::unique_ptr<TStrings> FilesToCopy(new TStringList());
- FilesToCopy->AddObject(FileName, Object);
- if (ParallelOperation->Side == osLocal)
- {
- TargetDir = TranslateLockedPath(TargetDir, false);
- }
- // OnceDoneOperation is not supported
- TOnceDoneOperation OnceDoneOperation = odoIdle;
- int Params = ParallelOperation->Params;
- // If we failed to recurse the directory when enumerating, recurse now (typically only to show the recursion error)
- if (Dir && Recursed)
- {
- Params = Params | cpNoRecurse;
- }
- int Prev = OperationProgress->FilesFinishedSuccessfully;
- DebugAssert((FOperationProgress == OperationProgress) || (FOperationProgress == NULL));
- TFileOperationProgressType * PrevOperationProgress = FOperationProgress;
- try
- {
- FOperationProgress = OperationProgress;
- if (ParallelOperation->Side == osLocal)
- {
- FFileSystem->CopyToRemote(
- FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
- }
- else if (DebugAlwaysTrue(ParallelOperation->Side == osRemote))
- {
- FFileSystem->CopyToLocal(
- FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
- }
- }
- __finally
- {
- bool Success = (Prev < OperationProgress->FilesFinishedSuccessfully);
- ParallelOperation->Done(FileName, Dir, Success);
- // Not to fail an assertion in OperationStop when called from CopyToRemote or CopyToLocal,
- // when FOperationProgress is already OperationProgress.
- FOperationProgress = PrevOperationProgress;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CanParallel(
- const TCopyParamType * CopyParam, int Params, TParallelOperation * ParallelOperation)
- {
- return
- (ParallelOperation != NULL) &&
- FFileSystem->IsCapable(fcParallelTransfers) &&
- // parallel transfer is not implemented for operations needed to be done on a folder
- // after all its files are processed
- FLAGCLEAR(Params, cpDelete) &&
- (!CopyParam->PreserveTime || !CopyParam->PreserveTimeDirs);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CopyParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
- {
- try
- {
- bool Continue = true;
- do
- {
- int GotNext = CopyToParallel(ParallelOperation, OperationProgress);
- if (GotNext < 0)
- {
- Continue = false;
- }
- else if (GotNext == 0)
- {
- Sleep(100);
- }
- }
- while (Continue && !OperationProgress->Cancel);
- }
- __finally
- {
- OperationProgress->SetDone();
- ParallelOperation->WaitFor();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogParallelTransfer(TParallelOperation * ParallelOperation)
- {
- LogEvent(
- FORMAT("Adding a parallel transfer to the transfer started on the connection \"%s\"",
- (ParallelOperation->MainName)));
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogTotalTransferDetails(
- const UnicodeString TargetDir, const TCopyParamType * CopyParam,
- TFileOperationProgressType * OperationProgress, bool Parallel, TStrings * Files)
- {
- if (Log->Logging)
- {
- UnicodeString TargetSide = ((OperationProgress->Side == osLocal) ? L"remote" : L"local");
- UnicodeString S =
- FORMAT(
- L"Copying %d files/directories to %s directory \"%s\"",
- (OperationProgress->Count, TargetSide, TargetDir));
- if (Parallel && DebugAlwaysTrue(Files != NULL))
- {
- int Count = 0;
- for (int Index = 0; Index < Files->Count; Index++)
- {
- TCollectedFileList * FileList = dynamic_cast<TCollectedFileList *>(Files->Objects[Index]);
- Count += FileList->Count();
- }
- S += FORMAT(L" - in parallel, with %d total files", (Count));
- }
- if (OperationProgress->TotalSizeSet)
- {
- S += FORMAT(L" - total size: %s", (FormatSize(OperationProgress->TotalSize)));
- }
- LogEvent(S);
- LogEvent(0, CopyParam->LogStr);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LogTotalTransferDone(TFileOperationProgressType * OperationProgress)
- {
- LogEvent(L"Copying finished: " + OperationProgress->GetLogStr(true));
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CopyToRemote(
- TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
- TParallelOperation * ParallelOperation)
- {
- DebugAssert(FFileSystem);
- DebugAssert(FilesToCopy);
- bool Result = false;
- TOnceDoneOperation OnceDoneOperation = odoIdle;
- if ((CopyParam->OnTransferIn != NULL) && !FFileSystem->IsCapable(fcTransferIn))
- {
- throw Exception(LoadStr(NOTSUPPORTED));
- }
- try
- {
- __int64 Size;
- std::unique_ptr<TStringList> Files;
- bool ACanParallel =
- CanParallel(CopyParam, Params, ParallelOperation) &&
- !CopyParam->ClearArchive;
- if (ACanParallel)
- {
- Files.reset(new TStringList());
- Files->OwnsObjects = true;
- }
- bool CalculatedSize;
- if ((CopyParam->Size >= 0) &&
- DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
- {
- Size = CopyParam->Size;
- CalculatedSize = true;
- }
- else
- {
- bool CalculateSize = ACanParallel || CopyParam->CalculateSize;
- CalculatedSize = CalculateLocalFilesSize(FilesToCopy, Size, CopyParam, CalculateSize, Files.get(), NULL);
- }
- FLastProgressLogged = GetTickCount();
- TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
- OperationStart(
- OperationProgress, (Params & cpDelete ? foMove : foCopy), osLocal,
- FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
- bool CollectingUsage = false;
- try
- {
- if (CalculatedSize)
- {
- if (Configuration->Usage->Collect)
- {
- int CounterSize = TUsage::CalculateCounterSize(Size);
- Configuration->Usage->Inc(L"Uploads");
- Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
- Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
- CollectingUsage = true;
- }
- OperationProgress.SetTotalSize(Size);
- }
- UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
- BeginTransaction();
- try
- {
- bool Parallel = ACanParallel && CalculatedSize;
- LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
- if (Parallel)
- {
- // OnceDoneOperation is not supported
- ParallelOperation->Init(Files.release(), UnlockedTargetDir, CopyParam, Params, &OperationProgress, Log->Name);
- CopyParallel(ParallelOperation, &OperationProgress);
- }
- else
- {
- FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
- CopyParam, Params, &OperationProgress, OnceDoneOperation);
- }
- LogTotalTransferDone(&OperationProgress);
- }
- __finally
- {
- if (Active)
- {
- ReactOnCommand(fsCopyToRemote);
- }
- EndTransaction();
- }
- if (OperationProgress.Cancel == csContinue)
- {
- Result = true;
- }
- }
- __finally
- {
- if (CollectingUsage)
- {
- int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
- Configuration->Usage->Inc(L"UploadTime", CounterTime);
- Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
- }
- OperationStop(OperationProgress);
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
- OnceDoneOperation = odoIdle;
- }
- if (OnceDoneOperation != odoIdle)
- {
- CloseOnCompletion(OnceDoneOperation);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCopyToRemote(
- TStrings * FilesToCopy, const UnicodeString & ATargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
- {
- DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
- FFileSystem->TransferOnDirectory(ATargetDir, CopyParam, Params);
- UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
- UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
- int Index = 0;
- while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
- {
- bool Success = false;
- UnicodeString FileName = FilesToCopy->Strings[Index];
- TSearchRecSmart * SearchRec = NULL;
- if (FilesToCopy->Objects[Index] != NULL)
- {
- TLocalFile * LocalFile = dynamic_cast<TLocalFile *>(FilesToCopy->Objects[Index]);
- SearchRec = &LocalFile->SearchRec;
- }
- try
- {
- try
- {
- if (SessionData->CacheDirectories)
- {
- DirectoryModified(TargetDir, false);
- if (DirectoryExists(ApiPath(FileName)))
- {
- UnicodeString FileNameOnly = ExtractFileName(FileName);
- DirectoryModified(FullTargetDir + FileNameOnly, true);
- }
- }
- SourceRobust(FileName, SearchRec, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
- Success = true;
- }
- catch (ESkipFile & E)
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- if (!HandleException(&E))
- {
- throw;
- }
- }
- }
- __finally
- {
- OperationFinish(OperationProgress, FilesToCopy->Objects[Index], FileName, Success, OnceDoneOperation);
- }
- Index++;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SourceRobust(
- const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
- const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags)
- {
- TUploadSessionAction Action(ActionLog);
- bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
- bool CanRetry = (CopyParam->OnTransferIn == NULL);
- TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
- do
- {
- bool ChildError = false;
- try
- {
- Source(FileName, SearchRec, TargetDir, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
- }
- catch (Exception & E)
- {
- if (!RobustLoop.TryReopen(E))
- {
- if (!ChildError)
- {
- RollbackAction(Action, OperationProgress, &E);
- }
- throw;
- }
- }
- if (RobustLoop.ShouldRetry())
- {
- OperationProgress->RollbackTransfer();
- Action.Restart();
- // prevent overwrite and resume confirmations (should not be set for directories!)
- Params |= cpNoConfirmation;
- // enable resume even if we are uploading into new directory
- Flags &= ~tfNewDirectory;
- Flags |= tfAutoResume;
- }
- }
- while (RobustLoop.Retry());
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CreateTargetDirectory(
- const UnicodeString & DirectoryPath, int Attrs, const TCopyParamType * CopyParam)
- {
- TRemoteFile * File = NULL;
- bool DoCreate =
- !FileExists(DirectoryPath, &File) ||
- !File->IsDirectory; // just try to create and make it fail
- delete File;
- if (DoCreate)
- {
- TRemoteProperties Properties;
- if (CopyParam->PreserveRights)
- {
- Properties.Valid = Properties.Valid << vpRights;
- Properties.Rights = CopyParam->RemoteFileRights(Attrs);
- }
- Properties.Valid = Properties.Valid << vpEncrypt;
- Properties.Encrypt = CopyParam->EncryptNewFiles;
- CreateDirectory(DirectoryPath, &Properties);
- }
- return DoCreate;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DirectorySource(
- const UnicodeString & DirectoryName, const UnicodeString & TargetDir, const UnicodeString & DestDirectoryName,
- int Attrs, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags)
- {
- FFileSystem->TransferOnDirectory(TargetDir, CopyParam, Params);
- UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
- OperationProgress->SetFile(DirectoryName);
- bool PostCreateDir = FLAGCLEAR(Flags, tfPreCreateDir);
- // WebDAV, SFTP and S3
- if (!PostCreateDir)
- {
- // This is originally a code for WebDAV, SFTP used a slightly different logic,
- // but functionally it should be very similar.
- if (CreateTargetDirectory(DestFullName, Attrs, CopyParam))
- {
- Flags |= tfNewDirectory;
- }
- }
- bool DoRecurse = FLAGCLEAR(Params, cpNoRecurse);
- if (DoRecurse)
- {
- TSearchRecOwned SearchRec;
- bool FindOK = LocalFindFirstLoop(DirectoryName + L"*.*", SearchRec);
- while (FindOK && !OperationProgress->Cancel)
- {
- UnicodeString FileName = DirectoryName + SearchRec.Name;
- try
- {
- if (SearchRec.IsRealFile())
- {
- SourceRobust(FileName, &SearchRec, DestFullName, CopyParam, Params, OperationProgress, (Flags & ~(tfFirstLevel | tfAutoResume)));
- // FTP: if any file got uploaded (i.e. there were any file in the directory and at least one was not skipped),
- // do not try to create the directory, as it should be already created by FZAPI during upload
- PostCreateDir = false;
- }
- }
- catch (ESkipFile &E)
- {
- // If ESkipFile occurs, just log it and continue with next file
- TSuspendFileOperationProgress Suspend(OperationProgress);
- // here a message to user was displayed, which was not appropriate
- // when user refused to overwrite the file in subdirectory.
- // hopefully it won't be missing in other situations.
- if (!HandleException(&E))
- {
- throw;
- }
- }
- FindOK = LocalFindNextLoop(SearchRec);
- }
- SearchRec.Close();
- }
- // FTP
- if (PostCreateDir)
- {
- CreateTargetDirectory(DestFullName, Attrs, CopyParam);
- }
- // Paralell transfers (cpNoRecurse) won't be allowed if any of these are set anyway (see CanParallel).
- // Exception is ClearArchive, which is does not prevent parallel transfer, but is silently ignored for directories.
- if (DoRecurse && !OperationProgress->Cancel)
- {
- // TODO : Delete also read-only directories.
- // TODO : Show error message on failure.
- if (IsCapable[fcPreservingTimestampDirs] && CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
- {
- TRemoteProperties Properties;
- Properties.Valid << vpModification;
- OpenLocalFile(
- ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
- &Properties.Modification, &Properties.LastAccess, NULL);
- ChangeFileProperties(DestFullName, NULL, &Properties);
- }
- if (FLAGSET(Params, cpDelete))
- {
- DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
- RemoveDir(ApiPath(DirectoryName));
- }
- else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
- {
- FILE_OPERATION_LOOP_BEGIN
- {
- THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SelectTransferMode(
- const UnicodeString & BaseFileName, TOperationSide Side, const TCopyParamType * CopyParam,
- const TFileMasks::TParams & MaskParams)
- {
- bool AsciiTransfer = IsCapable[fcTextMode] && CopyParam->UseAsciiTransfer(BaseFileName, Side, MaskParams);
- OperationProgress->SetAsciiTransfer(AsciiTransfer);
- UnicodeString ModeName = (OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary");
- LogEvent(0, FORMAT(L"%s transfer mode selected.", (ModeName)));
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SelectSourceTransferMode(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam)
- {
- // Will we use ASCII or BINARY file transfer?
- TFileMasks::TParams MaskParams;
- MaskParams.Size = Handle.Size;
- MaskParams.Modification = Handle.Modification;
- UnicodeString BaseFileName = GetBaseFileName(Handle.FileName);
- SelectTransferMode(BaseFileName, osLocal, CopyParam, MaskParams);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::UpdateSource(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam, int Params)
- {
- // TODO: Delete also read-only files.
- if (FLAGSET(Params, cpDelete))
- {
- if (!Handle.Directory)
- {
- LogEvent(FORMAT(L"Deleting successfully uploaded source file \"%s\".", (Handle.FileName)));
- FILE_OPERATION_LOOP_BEGIN
- {
- THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(Handle.FileName)));
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (Handle.FileName)));
- }
- }
- else if (CopyParam->ClearArchive && FLAGSET(Handle.Attrs, faArchive))
- {
- FILE_OPERATION_LOOP_BEGIN
- {
- THROWOSIFFALSE(FileSetAttr(ApiPath(Handle.FileName), (Handle.Attrs & ~faArchive)) == 0);
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (Handle.FileName)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Source(
- const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
- const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags, TUploadSessionAction & Action, bool & ChildError)
- {
- UnicodeString ActionFileName = FileName;
- if (CopyParam->OnTransferIn == NULL)
- {
- ActionFileName = ExpandUNCFileName(ActionFileName);
- }
- Action.FileName(ActionFileName);
- OperationProgress->SetFile(FileName, false);
- if (!AllowLocalFileTransfer(FileName, SearchRec, CopyParam, OperationProgress))
- {
- throw ESkipFile();
- }
- TLocalFileHandle Handle;
- if (CopyParam->OnTransferIn == NULL)
- {
- OpenLocalFile(FileName, GENERIC_READ, Handle);
- }
- else
- {
- Handle.FileName = FileName;
- }
- OperationProgress->SetFileInProgress();
- UnicodeString DestFileName =
- ChangeFileName(CopyParam, ExtractFileName(FileName), osLocal, FLAGSET(Flags, tfFirstLevel));
- if (Handle.Directory)
- {
- Action.Cancel();
- DirectorySource(
- IncludeTrailingBackslash(FileName), TargetDir, DestFileName, Handle.Attrs,
- CopyParam, Params, OperationProgress, Flags);
- }
- else
- {
- if (CopyParam->OnTransferIn != NULL)
- {
- LogEvent(FORMAT(L"Streaming \"%s\" to remote directory started.", (FileName)));
- }
- else
- {
- LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
- OperationProgress->SetLocalSize(Handle.Size);
- // Suppose same data size to transfer as to read
- // (not true with ASCII transfer)
- OperationProgress->SetTransferSize(OperationProgress->LocalSize);
- }
- if (IsCapable[fcTextMode])
- {
- SelectSourceTransferMode(Handle, CopyParam);
- }
- FFileSystem->Source(
- Handle, TargetDir, DestFileName, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
- LogFileDone(OperationProgress, AbsolutePath(TargetDir + DestFileName, true));
- OperationProgress->Succeeded();
- }
- Handle.Release();
- UpdateSource(Handle, CopyParam, Params);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CopyToLocal(
- TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
- TParallelOperation * ParallelOperation)
- {
- DebugAssert(FFileSystem);
- // see scp.c: sink(), tolocal()
- bool Result = false;
- DebugAssert(FilesToCopy != NULL);
- TOnceDoneOperation OnceDoneOperation = odoIdle;
- if ((CopyParam->OnTransferOut != NULL) && !FFileSystem->IsCapable(fcTransferOut))
- {
- throw Exception(LoadStr(NOTSUPPORTED));
- }
- FDestFileName = L"";
- FMultipleDestinationFiles = false;
- BeginTransaction();
- try
- {
- __int64 TotalSize;
- bool TotalSizeKnown = false;
- FLastProgressLogged = GetTickCount();
- TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
- std::unique_ptr<TStringList> Files;
- bool ACanParallel = CanParallel(CopyParam, Params, ParallelOperation);
- if (ACanParallel)
- {
- Files.reset(new TStringList());
- Files->OwnsObjects = true;
- }
- if ((CopyParam->Size >= 0) &&
- DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
- {
- TotalSize = CopyParam->Size;
- TotalSizeKnown = true;
- }
- else
- {
- ExceptionOnFail = true;
- try
- {
- TCalculateSizeStats Stats;
- Stats.FoundFiles = Files.get();
- bool CalculateSize = ACanParallel || CopyParam->CalculateSize;
- if (CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors, CopyParam, CalculateSize, Stats))
- {
- TotalSizeKnown = true;
- }
- }
- __finally
- {
- ExceptionOnFail = false;
- }
- }
- OperationStart(OperationProgress, (Params & cpDelete ? foMove : foCopy), osRemote,
- FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
- bool CollectingUsage = false;
- try
- {
- if (TotalSizeKnown)
- {
- if (Configuration->Usage->Collect)
- {
- int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
- Configuration->Usage->Inc(L"Downloads");
- Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
- Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
- CollectingUsage = true;
- }
- OperationProgress.SetTotalSize(TotalSize);
- }
- try
- {
- try
- {
- bool Parallel = ACanParallel && TotalSizeKnown;
- LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
- if (Parallel)
- {
- // OnceDoneOperation is not supported
- ParallelOperation->Init(Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name);
- CopyParallel(ParallelOperation, &OperationProgress);
- }
- else
- {
- FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
- &OperationProgress, OnceDoneOperation);
- }
- LogTotalTransferDone(&OperationProgress);
- }
- __finally
- {
- if (Active)
- {
- ReactOnCommand(fsCopyToLocal);
- }
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
- OnceDoneOperation = odoIdle;
- }
- if (OperationProgress.Cancel == csContinue)
- {
- Result = true;
- }
- }
- __finally
- {
- if (CollectingUsage)
- {
- int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
- Configuration->Usage->Inc(L"DownloadTime", CounterTime);
- Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
- }
- OperationStop(OperationProgress);
- }
- }
- __finally
- {
- // If session is still active (no fatal error) we reload directory
- // by calling EndTransaction
- EndTransaction();
- }
- if (OnceDoneOperation != odoIdle)
- {
- UnicodeString DestFileName;
- if (!FMultipleDestinationFiles)
- {
- DestFileName = FDestFileName;
- }
- CloseOnCompletion(OnceDoneOperation, UnicodeString(), TargetDir, DestFileName);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCopyToLocal(
- TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
- {
- DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
- UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
- int Index = 0;
- while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
- {
- bool Success = false;
- UnicodeString FileName = FilesToCopy->Strings[Index];
- const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
- try
- {
- try
- {
- UnicodeString AbsoluteFileName = AbsolutePath(FileName, true);
- SinkRobust(AbsoluteFileName, File, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
- Success = true;
- }
- catch (ESkipFile & E)
- {
- TSuspendFileOperationProgress Suspend(OperationProgress);
- if (!HandleException(&E))
- {
- throw;
- }
- }
- }
- __finally
- {
- OperationFinish(OperationProgress, File, FileName, Success, OnceDoneOperation);
- }
- Index++;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SinkRobust(
- const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
- const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
- {
- TDownloadSessionAction Action(ActionLog);
- try
- {
- bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
- bool CanRetry = (CopyParam->OnTransferOut == NULL);
- TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
- bool Sunk = false;
- do
- {
- try
- {
- // If connection is lost while deleting the file, so not retry download on the next round.
- // The file may not exist anymore and the download attempt might overwrite the (only) local copy.
- if (!Sunk)
- {
- Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags, Action);
- Sunk = true;
- }
- if (FLAGSET(Params, cpDelete))
- {
- DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
- // If file is directory, do not delete it recursively, because it should be
- // empty already. If not, it should not be deleted (some files were
- // skipped or some new files were copied to it, while we were downloading)
- int Params = dfNoRecursive;
- DeleteFile(FileName, File, &Params);
- }
- }
- catch (Exception & E)
- {
- if (!RobustLoop.TryReopen(E))
- {
- if (!Sunk)
- {
- RollbackAction(Action, OperationProgress, &E);
- }
- throw;
- }
- }
- if (RobustLoop.ShouldRetry())
- {
- OperationProgress->RollbackTransfer();
- Action.Restart();
- DebugAssert(File != NULL);
- if (!File->IsDirectory)
- {
- // prevent overwrite and resume confirmations
- Params |= cpNoConfirmation;
- Flags |= tfAutoResume;
- }
- }
- }
- while (RobustLoop.Retry());
- }
- __finally
- {
- // Once we issue <download> we must terminate the data stream
- if (Action.IsValid() && (CopyParam->OnTransferOut != NULL) && DebugAlwaysTrue(IsCapable[fcTransferOut]))
- {
- CopyParam->OnTransferOut(this, NULL, 0);
- }
- }
- }
- //---------------------------------------------------------------------------
- struct TSinkFileParams
- {
- UnicodeString TargetDir;
- const TCopyParamType * CopyParam;
- int Params;
- TFileOperationProgressType * OperationProgress;
- bool Skipped;
- unsigned int Flags;
- };
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Sink(
- const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
- const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags,
- TDownloadSessionAction & Action)
- {
- Action.FileName(FileName);
- DebugAssert(File);
- if (!DoAllowRemoteFileTransfer(File, CopyParam, false))
- {
- LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
- throw ESkipFile();
- }
- if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
- {
- OperationProgress->AddSkippedFileSize(File->Resolve()->Size);
- throw ESkipFile();
- }
- LogFileDetails(FileName, File->Modification, File->Size, File->LinkedFile);
- OperationProgress->SetFile(FileName);
- UnicodeString OnlyFileName = UnixExtractFileName(FileName);
- UnicodeString DestFileName = ChangeFileName(CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
- UnicodeString DestFullName = TargetDir + DestFileName;
- if (File->IsDirectory)
- {
- Action.Cancel();
- if (CanRecurseToDirectory(File))
- {
- FILE_OPERATION_LOOP_BEGIN
- {
- int Attrs = FileGetAttrFix(ApiPath(DestFullName));
- if (FLAGCLEAR(Attrs, faDirectory))
- {
- EXCEPTION;
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
- FILE_OPERATION_LOOP_BEGIN
- {
- THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
- if (FLAGCLEAR(Params, cpNoRecurse))
- {
- TSinkFileParams SinkFileParams;
- SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
- SinkFileParams.CopyParam = CopyParam;
- SinkFileParams.Params = Params;
- SinkFileParams.OperationProgress = OperationProgress;
- SinkFileParams.Skipped = false;
- SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
- ProcessDirectory(FileName, SinkFile, &SinkFileParams);
- FFileSystem->DirectorySunk(DestFullName, File, CopyParam);
- // Do not delete directory if some of its files were skip.
- // Throw "skip file" for the directory to avoid attempt to deletion
- // of any parent directory
- if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
- {
- throw ESkipFile();
- }
- }
- }
- else
- {
- LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
- }
- }
- else
- {
- if (CopyParam->OnTransferOut != NULL)
- {
- LogEvent(FORMAT(L"Streaming \"%s\" to local machine started.", (FileName)));
- }
- else
- {
- LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
- }
- // Will we use ASCII or BINARY file transfer?
- UnicodeString BaseFileName = GetBaseFileName(FileName);
- const TRemoteFile * UltimateFile = File->Resolve();
- TFileMasks::TParams MaskParams;
- MaskParams.Size = UltimateFile->Size;
- MaskParams.Modification = File->Modification;
- SelectTransferMode(BaseFileName, osRemote, CopyParam, MaskParams);
- // Suppose same data size to transfer as to write
- // (not true with ASCII transfer)
- __int64 TransferSize = UltimateFile->Size;
- OperationProgress->SetLocalSize(TransferSize);
- if (IsFileEncrypted(FileName))
- {
- TransferSize += TEncryption::GetOverhead();
- }
- OperationProgress->SetTransferSize(TransferSize);
- int Attrs;
- UnicodeString LogFileName;
- if (CopyParam->OnTransferOut != NULL)
- {
- Attrs = -1;
- LogFileName = L"-";
- }
- else
- {
- FILE_OPERATION_LOOP_BEGIN
- {
- Attrs = FileGetAttrFix(ApiPath(DestFullName));
- if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
- {
- EXCEPTION;
- }
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
- LogFileName = ExpandUNCFileName(DestFullName);
- }
- FFileSystem->Sink(
- FileName, File, TargetDir, DestFileName, Attrs, CopyParam, Params, OperationProgress, Flags, Action);
- LogFileDone(OperationProgress, LogFileName);
- OperationProgress->Succeeded();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::UpdateTargetAttrs(
- const UnicodeString & DestFullName, const TRemoteFile * File, const TCopyParamType * CopyParam, int Attrs)
- {
- if (Attrs == -1)
- {
- Attrs = faArchive;
- }
- int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
- if ((NewAttrs & Attrs) != NewAttrs)
- {
- FILE_OPERATION_LOOP_BEGIN
- {
- THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
- }
- FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::UpdateTargetTime(HANDLE Handle, TDateTime Modification, TDSTMode DSTMode)
- {
- LogEvent(FORMAT(L"Preserving timestamp [%s]", (StandardTimestamp(Modification))));
- FILETIME WrTime = DateTimeToFileTime(Modification, DSTMode);
- if (!SetFileTime(Handle, NULL, NULL, &WrTime))
- {
- int Error = GetLastError();
- LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s", (SysErrorMessageForError(Error))));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SinkFile(UnicodeString FileName, const TRemoteFile * File, void * Param)
- {
- TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
- DebugAssert(Params->OperationProgress != NULL);
- try
- {
- SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
- Params->Params, Params->OperationProgress, Params->Flags);
- }
- catch (ESkipFile & E)
- {
- Params->Skipped = true;
- {
- TSuspendFileOperationProgress Suspend(Params->OperationProgress);
- if (!HandleException(&E))
- {
- throw;
- }
- }
- if (Params->OperationProgress->Cancel)
- {
- Abort();
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReflectSettings()
- {
- DebugAssert(FLog != NULL);
- FLog->ReflectSettings();
- DebugAssert(FActionLog != NULL);
- FActionLog->ReflectSettings();
- // also FTunnelLog ?
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CollectUsage()
- {
- switch (SessionData->FSProtocol)
- {
- case fsSCPonly:
- Configuration->Usage->Inc(L"OpenedSessionsSCP");
- break;
- case fsSFTP:
- case fsSFTPonly:
- Configuration->Usage->Inc(L"OpenedSessionsSFTP");
- break;
- case fsFTP:
- if (SessionData->Ftps == ftpsNone)
- {
- Configuration->Usage->Inc(L"OpenedSessionsFTP");
- }
- else
- {
- Configuration->Usage->Inc(L"OpenedSessionsFTPS");
- }
- break;
- case fsWebDAV:
- if (SessionData->Ftps == ftpsNone)
- {
- Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
- }
- else
- {
- Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
- }
- break;
- case fsS3:
- Configuration->Usage->Inc(L"OpenedSessionsS3");
- break;
- }
- if (Configuration->Logging && Configuration->LogToFile)
- {
- Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
- }
- if (Configuration->LogActions)
- {
- Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
- }
- std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
- if (!SessionData->IsSame(FactoryDefaults.get(), true))
- {
- Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
- }
- if (SessionData->ProxyMethod != ::pmNone)
- {
- Configuration->Usage->Inc(L"OpenedSessionsProxy");
- }
- if (SessionData->FtpProxyLogonType > 0)
- {
- Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
- }
- if (IsEncryptingFiles())
- {
- Configuration->Usage->Inc(L"OpenedSessionsEncrypted");
- }
- FCollectFileSystemUsage = true;
- }
- //---------------------------------------------------------------------------
- static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
- {
- return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::VerifyCertificate(
- const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
- const UnicodeString & FingerprintSHA1, const UnicodeString & FingerprintSHA256,
- const UnicodeString & CertificateSubject, int Failures)
- {
- bool Result = false;
- UnicodeString CertificateDataSHA1 = FormatCertificateData(FingerprintSHA1, Failures);
- UnicodeString CertificateDataSHA256 = FormatCertificateData(FingerprintSHA256, Failures);
- std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
- Storage->AccessMode = smRead;
- if (Storage->OpenSubKey(CertificateStorageKey, false))
- {
- if (Storage->ValueExists(SiteKey))
- {
- UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
- if (SameChecksum(CertificateDataSHA1, CachedCertificateData, false) ||
- SameChecksum(CertificateDataSHA256, CachedCertificateData, false))
- {
- LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
- Result = true;
- }
- }
- else if (Storage->ValueExists(FingerprintSHA1) || Storage->ValueExists(FingerprintSHA256))
- {
- LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
- Result = true;
- }
- }
- if (!Result)
- {
- UnicodeString Buf = SessionData->HostKey;
- while (!Result && !Buf.IsEmpty())
- {
- UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
- if (ExpectedKey == L"*")
- {
- UnicodeString Message = LoadStr(ANY_CERTIFICATE);
- Information(Message, true);
- Log->Add(llException, Message);
- Result = true;
- }
- else if (SameChecksum(ExpectedKey, FingerprintSHA1, false) ||
- SameChecksum(ExpectedKey, FingerprintSHA256, false))
- {
- LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
- Result = true;
- }
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::ConfirmCertificate(
- TSessionInfo & SessionInfo, int Failures, const UnicodeString & CertificateStorageKey, bool CanRemember)
- {
- TClipboardHandler ClipboardHandler;
- ClipboardHandler.Text =
- FORMAT(L"SHA-256: %s\nSHA-1: %s", (SessionInfo.CertificateFingerprintSHA256, SessionInfo.CertificateFingerprintSHA1));
- TQueryButtonAlias Aliases[1];
- Aliases[0].Button = qaRetry;
- Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
- Aliases[0].ActionAlias = LoadStr(COPY_CERTIFICATE_ACTION);
- Aliases[0].OnSubmit = &ClipboardHandler.Copy;
- TQueryParams Params(qpWaitInBatch);
- Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
- Params.NoBatchAnswers = qaYes | qaRetry;
- Params.Aliases = Aliases;
- Params.AliasesCount = LENOF(Aliases);
- unsigned int Answer =
- QueryUser(
- FMTLOAD(VERIFY_CERT_PROMPT3, (SessionInfo.Certificate)),
- NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
- bool Result;
- switch (Answer)
- {
- case qaYes:
- CacheCertificate(
- CertificateStorageKey, SessionData->SiteKey,
- SessionInfo.CertificateFingerprintSHA1, SessionInfo.CertificateFingerprintSHA256, Failures);
- Result = true;
- break;
- case qaNo:
- Result = true;
- break;
- case qaCancel:
- Configuration->Usage->Inc(L"HostNotVerified");
- Result = false;
- break;
- default:
- DebugFail();
- Result = false;
- break;
- }
- // Cache only if the certificate was accepted manually
- if (Result && CanRemember)
- {
- Configuration->RememberLastFingerprint(
- SessionData->SiteKey, TlsFingerprintType, SessionInfo.CertificateFingerprintSHA256);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CacheCertificate(
- const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
- const UnicodeString & DebugUsedArg(FingerprintSHA1), const UnicodeString & FingerprintSHA256, int Failures)
- {
- UnicodeString CertificateData = FormatCertificateData(FingerprintSHA256, Failures);
- std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
- Storage->AccessMode = smReadWrite;
- if (Storage->OpenSubKey(CertificateStorageKey, true))
- {
- Storage->WriteString(SiteKey, CertificateData);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
- {
- // see SSL_get_version() in OpenSSL ssl_lib.c
- if (TlsVersionStr == L"TLSv1.3")
- {
- Configuration->Usage->Inc(L"OpenedSessionsTLS13");
- }
- else if (TlsVersionStr == L"TLSv1.2")
- {
- Configuration->Usage->Inc(L"OpenedSessionsTLS12");
- }
- else if (TlsVersionStr == L"TLSv1.1")
- {
- Configuration->Usage->Inc(L"OpenedSessionsTLS11");
- }
- else if (TlsVersionStr == L"TLSv1")
- {
- Configuration->Usage->Inc(L"OpenedSessionsTLS10");
- }
- else if (TlsVersionStr == L"SSLv3")
- {
- Configuration->Usage->Inc(L"OpenedSessionsSSL30");
- }
- else if (TlsVersionStr == L"SSLv2")
- {
- Configuration->Usage->Inc(L"OpenedSessionsSSL20");
- }
- else
- {
- DebugFail();
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
- {
- bool Result = !SessionData->TlsCertificateFile.IsEmpty();
- if (Result)
- {
- UnicodeString Passphrase = SessionData->Passphrase;
- // Inspired by neon's ne_ssl_clicert_read
- bool Retry;
- do
- {
- Retry = false;
- bool WrongPassphrase;
- ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
- if (WrongPassphrase)
- {
- if (Passphrase.IsEmpty())
- {
- LogEvent(L"Certificate is encrypted, need passphrase");
- Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
- }
- else
- {
- Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
- }
- Passphrase = L"";
- if (PromptUser(
- SessionData, pkPassphrase,
- LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
- LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
- {
- Retry = true;
- }
- else
- {
- Result = false;
- }
- }
- }
- while (Retry);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
- {
- if (FSessionData->TrimVMSVersions)
- {
- int P = FileName.LastDelimiter(L";");
- if (P > 0)
- {
- FileName.SetLength(P - 1);
- }
- }
- return FileName;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
- UnicodeString FileName, TOperationSide Side, bool FirstLevel)
- {
- FileName = GetBaseFileName(FileName);
- FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
- return FileName;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
- {
- return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
- }
- //---------------------------------------------------------------------------
- TTerminal::TEncryptedFileNames::const_iterator __fastcall TTerminal::GetEncryptedFileName(const UnicodeString & Path)
- {
- UnicodeString FileDir = UnixExtractFileDir(Path);
- // If we haven't been in this folder yet, read it to collect mapping to encrypted file names.
- if (FFoldersScannedForEncryptedFiles.find(FileDir) == FFoldersScannedForEncryptedFiles.end())
- {
- try
- {
- delete DoReadDirectoryListing(FileDir, true);
- }
- catch (Exception & E)
- {
- if (!Active)
- {
- throw;
- }
- if (FEncryptedFileNames.find(Path) == FEncryptedFileNames.end())
- {
- FEncryptedFileNames.insert(std::make_pair(Path, UnixExtractFileName(Path)));
- LogEvent(2, FORMAT(L"Name of file '%s' assumed not to be encrypted", (Path)));
- }
- }
- FFoldersScannedForEncryptedFiles.insert(FileDir);
- }
- TEncryptedFileNames::const_iterator Result = FEncryptedFileNames.find(Path);
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::IsFileEncrypted(const UnicodeString & Path, bool EncryptNewFiles)
- {
- // can be optimized
- bool Result = (EncryptFileName(Path, EncryptNewFiles) != Path);
- return Result;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::EncryptFileName(const UnicodeString & Path, bool EncryptNewFiles)
- {
- UnicodeString Result = Path;
- if (IsEncryptingFiles() && !IsUnixRootPath(Path))
- {
- UnicodeString FileName = UnixExtractFileName(Path);
- UnicodeString FileDir = UnixExtractFileDir(Path);
- if (!FileName.IsEmpty() && IsRealFile(FileName))
- {
- TEncryptedFileNames::const_iterator I = GetEncryptedFileName(Path);
- if (I != FEncryptedFileNames.end())
- {
- FileName = I->second;
- }
- else if (EncryptNewFiles)
- {
- TEncryption Encryption(FEncryptKey);
- FileName = Encryption.EncryptFileName(FileName);
- FEncryptedFileNames.insert(std::make_pair(Path, FileName));
- LogEvent(2, FORMAT(L"Name of file '%s' encrypted as '%s'", (Path, FileName)));
- }
- }
- FileDir = EncryptFileName(FileDir, EncryptNewFiles);
- Result = UnixCombinePaths(FileDir, FileName);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall TTerminal::DecryptFileName(const UnicodeString & Path)
- {
- UnicodeString Result = Path;
- if (IsEncryptingFiles() && !IsUnixRootPath(Path))
- {
- UnicodeString FileName = UnixExtractFileName(Path);
- UnicodeString FileNameEncrypted = FileName;
- bool Encrypted = TEncryption::IsEncryptedFileName(FileName);
- if (Encrypted)
- {
- TEncryption Encryption(FEncryptKey);
- FileName = Encryption.DecryptFileName(FileName);
- UnicodeString FileDir = UnixExtractFileDir(Path);
- FileDir = DecryptFileName(FileDir);
- Result = UnixCombinePaths(FileDir, FileName);
- }
- TEncryptedFileNames::iterator Iter = FEncryptedFileNames.find(Result);
- bool NotCached = (Iter == FEncryptedFileNames.end());
- if (Encrypted || NotCached)
- {
- if (Encrypted && (NotCached || (Iter->second != FileNameEncrypted)))
- {
- LogEvent(2, FORMAT(L"Name of file '%s' decrypted from '%s'", (Result, FileNameEncrypted)));
- }
- // This may overwrite another variant of encryption
- FEncryptedFileNames[Result] = FileNameEncrypted;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
- TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
- TTerminal(ASessionData, Configuration),
- FMainTerminal(MainTerminal)
- {
- Log->SetParent(FMainTerminal->Log, Name);
- ActionLog->Enabled = false;
- SessionData->NonPersistant();
- DebugAssert(FMainTerminal != NULL);
- if (!FMainTerminal->UserName.IsEmpty())
- {
- SessionData->UserName = FMainTerminal->UserName;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSecondaryTerminal::UpdateFromMain()
- {
- if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
- {
- FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
- {
- FMainTerminal->DirectoryLoaded(FileList);
- DebugAssert(FileList != NULL);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
- bool SubDirs)
- {
- // clear cache of main terminal
- FMainTerminal->DirectoryModified(Path, SubDirs);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
- {
- return FMainTerminal;
- }
- //---------------------------------------------------------------------------
- __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
- TObjectList()
- {
- DebugAssert(AConfiguration);
- FConfiguration = AConfiguration;
- }
- //---------------------------------------------------------------------------
- __fastcall TTerminalList::~TTerminalList()
- {
- DebugAssert(Count == 0);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
- {
- return new TTerminal(Data, FConfiguration);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
- {
- TTerminal * Terminal = CreateTerminal(Data);
- Add(Terminal);
- return Terminal;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
- {
- DebugAssert(IndexOf(Terminal) >= 0);
- Remove(Terminal);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
- {
- TTerminal * T = Terminal;
- Terminal = NULL;
- FreeTerminal(T);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
- {
- return dynamic_cast<TTerminal *>(Items[Index]);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminalList::RecryptPasswords()
- {
- for (int Index = 0; Index < Count; Index++)
- {
- Terminals[Index]->RecryptPasswords();
- }
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- TLocalFileHandle::TLocalFileHandle()
- {
- Handle = 0;
- Attrs = 0;
- MTime = 0;
- ATime = 0;
- Size = 0;
- Directory = false;
- }
- //---------------------------------------------------------------------------
- TLocalFileHandle::~TLocalFileHandle()
- {
- Release();
- }
- //---------------------------------------------------------------------------
- void TLocalFileHandle::Release()
- {
- if (Handle != 0)
- {
- Close();
- }
- }
- //---------------------------------------------------------------------------
- void TLocalFileHandle::Dismiss()
- {
- if (DebugAlwaysTrue(Handle != 0))
- {
- Handle = 0;
- }
- }
- //---------------------------------------------------------------------------
- void TLocalFileHandle::Close()
- {
- if (DebugAlwaysTrue(Handle != 0))
- {
- CloseHandle(Handle);
- Dismiss();
- }
- }
|