Terminal.cpp 268 KB

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