Terminal.cpp 270 KB

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