Terminal.cpp 257 KB

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