Terminal.cpp 266 KB

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