Terminal.cpp 270 KB

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