1
0

Terminal.cpp 268 KB

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