Terminal.cpp 245 KB

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