Terminal.cpp 288 KB

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