Terminal.cpp 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "PuttyTools.h"
  9. #include "FileBuffer.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "SecureShell.h"
  13. #include "ScpFileSystem.h"
  14. #include "SftpFileSystem.h"
  15. #ifndef NO_FILEZILLA
  16. #include "FtpFileSystem.h"
  17. #endif
  18. #include "WebDAVFileSystem.h"
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "CoreMain.h"
  22. #include "Queue.h"
  23. #ifndef AUTO_WINSOCK
  24. #include <winsock2.h>
  25. #endif
  26. //---------------------------------------------------------------------------
  27. #pragma package(smart_init)
  28. //---------------------------------------------------------------------------
  29. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  30. { \
  31. unsigned int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  32. switch (Result) { \
  33. case qaRetry: { REPEAT; } break; \
  34. case qaAbort: Abort(); \
  35. } \
  36. }
  37. //---------------------------------------------------------------------------
  38. // Note that the action may already be canceled when RollbackAction is called
  39. #define COMMAND_ERROR_ARI_ACTION(MESSAGE, REPEAT, ACTION) \
  40. { \
  41. unsigned int Result; \
  42. try \
  43. { \
  44. Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  45. } \
  46. catch(Exception & E2) \
  47. { \
  48. RollbackAction(ACTION, NULL, &E2); \
  49. throw; \
  50. } \
  51. switch (Result) { \
  52. case qaRetry: ACTION.Cancel(); { REPEAT; } break; \
  53. case qaAbort: RollbackAction(ACTION, NULL, &E); Abort(); \
  54. case qaSkip: ACTION.Cancel(); break; \
  55. default: FAIL; \
  56. } \
  57. }
  58. #define FILE_OPERATION_LOOP_TERMINAL this
  59. //---------------------------------------------------------------------------
  60. //---------------------------------------------------------------------------
  61. class TLoopDetector
  62. {
  63. public:
  64. __fastcall TLoopDetector();
  65. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  66. bool __fastcall IsUnvisitedDirectory(const TRemoteFile * File);
  67. private:
  68. std::unique_ptr<TStringList> FVisitedDirectories;
  69. };
  70. //---------------------------------------------------------------------------
  71. __fastcall TLoopDetector::TLoopDetector()
  72. {
  73. FVisitedDirectories.reset(new TStringList());
  74. FVisitedDirectories->Sorted = true;
  75. }
  76. //---------------------------------------------------------------------------
  77. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  78. {
  79. UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
  80. FVisitedDirectories->Add(VisitedDirectory);
  81. }
  82. //---------------------------------------------------------------------------
  83. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const TRemoteFile * File)
  84. {
  85. assert(File->IsDirectory);
  86. UnicodeString Directory = UnixExcludeTrailingBackslash(File->FullFileName);
  87. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  88. if (Result)
  89. {
  90. if (File->IsSymLink)
  91. {
  92. UnicodeString BaseDirectory = UnixExtractFileDir(Directory);
  93. UnicodeString SymlinkDirectory =
  94. UnixExcludeTrailingBackslash(AbsolutePath(BaseDirectory, File->LinkTo));
  95. Result = (FVisitedDirectories->IndexOf(SymlinkDirectory) < 0);
  96. }
  97. }
  98. if (Result)
  99. {
  100. RecordVisitedDirectory(Directory);
  101. }
  102. return Result;
  103. }
  104. //---------------------------------------------------------------------------
  105. //---------------------------------------------------------------------------
  106. struct TMoveFileParams
  107. {
  108. UnicodeString Target;
  109. UnicodeString FileMask;
  110. };
  111. //---------------------------------------------------------------------------
  112. struct TFilesFindParams
  113. {
  114. TFileMasks FileMask;
  115. TFileFoundEvent OnFileFound;
  116. TFindingFileEvent OnFindingFile;
  117. bool Cancel;
  118. TLoopDetector LoopDetector;
  119. };
  120. //---------------------------------------------------------------------------
  121. TCalculateSizeStats::TCalculateSizeStats()
  122. {
  123. memset(this, 0, sizeof(*this));
  124. }
  125. //---------------------------------------------------------------------------
  126. TSynchronizeOptions::TSynchronizeOptions()
  127. {
  128. memset(this, 0, sizeof(*this));
  129. }
  130. //---------------------------------------------------------------------------
  131. TSynchronizeOptions::~TSynchronizeOptions()
  132. {
  133. delete Filter;
  134. }
  135. //---------------------------------------------------------------------------
  136. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  137. {
  138. int FoundIndex;
  139. bool Result;
  140. if (Filter == NULL)
  141. {
  142. Result = true;
  143. }
  144. else
  145. {
  146. Result = Filter->Find(FileName, FoundIndex);
  147. }
  148. return Result;
  149. }
  150. //---------------------------------------------------------------------------
  151. TSpaceAvailable::TSpaceAvailable()
  152. {
  153. memset(this, 0, sizeof(*this));
  154. }
  155. //---------------------------------------------------------------------------
  156. TOverwriteFileParams::TOverwriteFileParams()
  157. {
  158. SourceSize = 0;
  159. DestSize = 0;
  160. SourcePrecision = mfFull;
  161. DestPrecision = mfFull;
  162. }
  163. //---------------------------------------------------------------------------
  164. //---------------------------------------------------------------------------
  165. TSynchronizeChecklist::TItem::TItem() :
  166. Action(saNone), IsDirectory(false), RemoteFile(NULL), Checked(true), ImageIndex(-1)
  167. {
  168. Local.ModificationFmt = mfFull;
  169. Local.Modification = 0;
  170. Local.Size = 0;
  171. Remote.ModificationFmt = mfFull;
  172. Remote.Modification = 0;
  173. Remote.Size = 0;
  174. }
  175. //---------------------------------------------------------------------------
  176. TSynchronizeChecklist::TItem::~TItem()
  177. {
  178. delete RemoteFile;
  179. }
  180. //---------------------------------------------------------------------------
  181. const UnicodeString& TSynchronizeChecklist::TItem::GetFileName() const
  182. {
  183. if (!Remote.FileName.IsEmpty())
  184. {
  185. return Remote.FileName;
  186. }
  187. else
  188. {
  189. assert(!Local.FileName.IsEmpty());
  190. return Local.FileName;
  191. }
  192. }
  193. //---------------------------------------------------------------------------
  194. //---------------------------------------------------------------------------
  195. TSynchronizeChecklist::TSynchronizeChecklist() :
  196. FList(new TList())
  197. {
  198. }
  199. //---------------------------------------------------------------------------
  200. TSynchronizeChecklist::~TSynchronizeChecklist()
  201. {
  202. for (int Index = 0; Index < FList->Count; Index++)
  203. {
  204. delete static_cast<TItem *>(FList->Items[Index]);
  205. }
  206. delete FList;
  207. }
  208. //---------------------------------------------------------------------------
  209. void TSynchronizeChecklist::Add(TItem * Item)
  210. {
  211. FList->Add(Item);
  212. }
  213. //---------------------------------------------------------------------------
  214. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  215. {
  216. TItem * Item1 = static_cast<TItem *>(AItem1);
  217. TItem * Item2 = static_cast<TItem *>(AItem2);
  218. int Result;
  219. if (!Item1->Local.Directory.IsEmpty())
  220. {
  221. Result = AnsiCompareText(Item1->Local.Directory, Item2->Local.Directory);
  222. }
  223. else
  224. {
  225. assert(!Item1->Remote.Directory.IsEmpty());
  226. Result = AnsiCompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  227. }
  228. if (Result == 0)
  229. {
  230. Result = AnsiCompareText(Item1->GetFileName(), Item2->GetFileName());
  231. }
  232. return Result;
  233. }
  234. //---------------------------------------------------------------------------
  235. void TSynchronizeChecklist::Sort()
  236. {
  237. FList->Sort(Compare);
  238. }
  239. //---------------------------------------------------------------------------
  240. int TSynchronizeChecklist::GetCount() const
  241. {
  242. return FList->Count;
  243. }
  244. //---------------------------------------------------------------------------
  245. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  246. {
  247. return static_cast<TItem *>(FList->Items[Index]);
  248. }
  249. //---------------------------------------------------------------------------
  250. void __fastcall TSynchronizeChecklist::Update(const TItem * Item, bool Check, TAction Action)
  251. {
  252. // TSynchronizeChecklist owns non-const items so it can manipulate them freely,
  253. // const_cast here is just an optimization
  254. TItem * MutableItem = const_cast<TItem *>(Item);
  255. assert(FList->IndexOf(MutableItem) >= 0);
  256. MutableItem->Checked = Check;
  257. MutableItem->Action = Action;
  258. }
  259. //---------------------------------------------------------------------------
  260. TSynchronizeChecklist::TAction __fastcall TSynchronizeChecklist::Reverse(TSynchronizeChecklist::TAction Action)
  261. {
  262. switch (Action)
  263. {
  264. case saUploadNew:
  265. return saDeleteLocal;
  266. case saDownloadNew:
  267. return saDeleteRemote;
  268. case saUploadUpdate:
  269. return saDownloadUpdate;
  270. case saDownloadUpdate:
  271. return saUploadUpdate;
  272. case saDeleteRemote:
  273. return saDownloadNew;
  274. case saDeleteLocal:
  275. return saUploadNew;
  276. default:
  277. case saNone:
  278. FAIL;
  279. return saNone;
  280. }
  281. }
  282. //---------------------------------------------------------------------------
  283. //---------------------------------------------------------------------------
  284. class TTunnelThread : public TSimpleThread
  285. {
  286. public:
  287. __fastcall TTunnelThread(TSecureShell * SecureShell);
  288. virtual __fastcall ~TTunnelThread();
  289. virtual void __fastcall Terminate();
  290. protected:
  291. virtual void __fastcall Execute();
  292. private:
  293. TSecureShell * FSecureShell;
  294. bool FTerminated;
  295. };
  296. //---------------------------------------------------------------------------
  297. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  298. FSecureShell(SecureShell),
  299. FTerminated(false)
  300. {
  301. Start();
  302. }
  303. //---------------------------------------------------------------------------
  304. __fastcall TTunnelThread::~TTunnelThread()
  305. {
  306. // close before the class's virtual functions (Terminate particularly) are lost
  307. Close();
  308. }
  309. //---------------------------------------------------------------------------
  310. void __fastcall TTunnelThread::Terminate()
  311. {
  312. FTerminated = true;
  313. }
  314. //---------------------------------------------------------------------------
  315. void __fastcall TTunnelThread::Execute()
  316. {
  317. try
  318. {
  319. while (!FTerminated)
  320. {
  321. FSecureShell->Idle(250);
  322. }
  323. }
  324. catch(...)
  325. {
  326. if (FSecureShell->Active)
  327. {
  328. FSecureShell->Close();
  329. }
  330. // do not pass exception out of thread's proc
  331. }
  332. }
  333. //---------------------------------------------------------------------------
  334. //---------------------------------------------------------------------------
  335. class TTunnelUI : public TSessionUI
  336. {
  337. public:
  338. __fastcall TTunnelUI(TTerminal * Terminal);
  339. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  340. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  341. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  342. TQueryType QueryType);
  343. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  344. Exception * E, unsigned int Answers, const TQueryParams * Params,
  345. TQueryType QueryType);
  346. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  347. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  348. TStrings * Results);
  349. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  350. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  351. virtual void __fastcall HandleExtendedException(Exception * E);
  352. virtual void __fastcall Closed();
  353. private:
  354. TTerminal * FTerminal;
  355. unsigned int FTerminalThread;
  356. };
  357. //---------------------------------------------------------------------------
  358. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  359. {
  360. FTerminal = Terminal;
  361. FTerminalThread = GetCurrentThreadId();
  362. }
  363. //---------------------------------------------------------------------------
  364. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  365. {
  366. if (GetCurrentThreadId() == FTerminalThread)
  367. {
  368. FTerminal->Information(Str, Status);
  369. }
  370. }
  371. //---------------------------------------------------------------------------
  372. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  373. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  374. TQueryType QueryType)
  375. {
  376. unsigned int Result;
  377. if (GetCurrentThreadId() == FTerminalThread)
  378. {
  379. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  380. }
  381. else
  382. {
  383. Result = AbortAnswer(Answers);
  384. }
  385. return Result;
  386. }
  387. //---------------------------------------------------------------------------
  388. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  389. Exception * E, unsigned int Answers, const TQueryParams * Params,
  390. TQueryType QueryType)
  391. {
  392. unsigned int Result;
  393. if (GetCurrentThreadId() == FTerminalThread)
  394. {
  395. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  396. }
  397. else
  398. {
  399. Result = AbortAnswer(Answers);
  400. }
  401. return Result;
  402. }
  403. //---------------------------------------------------------------------------
  404. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  405. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  406. {
  407. bool Result;
  408. if (GetCurrentThreadId() == FTerminalThread)
  409. {
  410. if (IsAuthenticationPrompt(Kind))
  411. {
  412. Instructions = LoadStr(TUNNEL_INSTRUCTION) +
  413. (Instructions.IsEmpty() ? L"" : L"\n") +
  414. Instructions;
  415. }
  416. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  417. }
  418. else
  419. {
  420. Result = false;
  421. }
  422. return Result;
  423. }
  424. //---------------------------------------------------------------------------
  425. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  426. {
  427. if (GetCurrentThreadId() == FTerminalThread)
  428. {
  429. FTerminal->DisplayBanner(Banner);
  430. }
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  434. {
  435. throw ESshFatal(E, Msg, HelpKeyword);
  436. }
  437. //---------------------------------------------------------------------------
  438. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  439. {
  440. if (GetCurrentThreadId() == FTerminalThread)
  441. {
  442. FTerminal->HandleExtendedException(E);
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. void __fastcall TTunnelUI::Closed()
  447. {
  448. // noop
  449. }
  450. //---------------------------------------------------------------------------
  451. //---------------------------------------------------------------------------
  452. class TCallbackGuard
  453. {
  454. public:
  455. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  456. inline __fastcall ~TCallbackGuard();
  457. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  458. inline void __fastcall Verify();
  459. void __fastcall Dismiss();
  460. private:
  461. ExtException * FFatalError;
  462. TTerminal * FTerminal;
  463. bool FGuarding;
  464. };
  465. //---------------------------------------------------------------------------
  466. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  467. FTerminal(Terminal),
  468. FFatalError(NULL),
  469. FGuarding(FTerminal->FCallbackGuard == NULL)
  470. {
  471. if (FGuarding)
  472. {
  473. FTerminal->FCallbackGuard = this;
  474. }
  475. }
  476. //---------------------------------------------------------------------------
  477. __fastcall TCallbackGuard::~TCallbackGuard()
  478. {
  479. if (FGuarding)
  480. {
  481. assert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  482. FTerminal->FCallbackGuard = NULL;
  483. }
  484. delete FFatalError;
  485. }
  486. //---------------------------------------------------------------------------
  487. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  488. {
  489. assert(FGuarding);
  490. // make sure we do not bother about getting back the silent abort exception
  491. // we issued ourselves. this may happen when there is an exception handler
  492. // that converts any exception to fatal one (such as in TTerminal::Open).
  493. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  494. {
  495. delete FFatalError;
  496. FFatalError = new ExtException(E, Msg, HelpKeyword);
  497. }
  498. // silently abort what we are doing.
  499. // non-silent exception would be caught probably by default application
  500. // exception handler, which may not do an appropriate action
  501. // (particularly it will not resume broken transfer).
  502. throw ECallbackGuardAbort();
  503. }
  504. //---------------------------------------------------------------------------
  505. void __fastcall TCallbackGuard::Dismiss()
  506. {
  507. assert(FFatalError == NULL);
  508. FGuarding = false;
  509. }
  510. //---------------------------------------------------------------------------
  511. void __fastcall TCallbackGuard::Verify()
  512. {
  513. if (FGuarding)
  514. {
  515. FGuarding = false;
  516. assert(FTerminal->FCallbackGuard == this);
  517. FTerminal->FCallbackGuard = NULL;
  518. if (FFatalError != NULL)
  519. {
  520. throw ESshFatal(FFatalError, L"");
  521. }
  522. }
  523. }
  524. //---------------------------------------------------------------------------
  525. //---------------------------------------------------------------------------
  526. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  527. TConfiguration * Configuration)
  528. {
  529. FConfiguration = Configuration;
  530. FSessionData = new TSessionData(L"");
  531. FSessionData->Assign(SessionData);
  532. FLog = new TSessionLog(this, FSessionData, Configuration);
  533. FActionLog = new TActionLog(this, FSessionData, Configuration);
  534. FFiles = new TRemoteDirectory(this);
  535. FExceptionOnFail = 0;
  536. FInTransaction = 0;
  537. FReadCurrentDirectoryPending = false;
  538. FReadDirectoryPending = false;
  539. FUsersGroupsLookedup = False;
  540. FTunnelLocalPortNumber = 0;
  541. FFileSystem = NULL;
  542. FSecureShell = NULL;
  543. FOnProgress = NULL;
  544. FOnFinished = NULL;
  545. FOnDeleteLocalFile = NULL;
  546. FOnReadDirectoryProgress = NULL;
  547. FOnQueryUser = NULL;
  548. FOnPromptUser = NULL;
  549. FOnDisplayBanner = NULL;
  550. FOnShowExtendedException = NULL;
  551. FOnInformation = NULL;
  552. FOnClose = NULL;
  553. FOnFindingFile = NULL;
  554. FUseBusyCursor = True;
  555. FLockDirectory = L"";
  556. FDirectoryCache = new TRemoteDirectoryCache();
  557. FDirectoryChangesCache = NULL;
  558. FFSProtocol = cfsUnknown;
  559. FCommandSession = NULL;
  560. FAutoReadDirectory = true;
  561. FReadingCurrentDirectory = false;
  562. FStatus = ssClosed;
  563. FTunnelThread = NULL;
  564. FTunnel = NULL;
  565. FTunnelData = NULL;
  566. FTunnelLog = NULL;
  567. FTunnelUI = NULL;
  568. FTunnelOpening = false;
  569. FCallbackGuard = NULL;
  570. }
  571. //---------------------------------------------------------------------------
  572. __fastcall TTerminal::~TTerminal()
  573. {
  574. if (Active)
  575. {
  576. Close();
  577. }
  578. if (FCallbackGuard != NULL)
  579. {
  580. // see TTerminal::HandleExtendedException
  581. FCallbackGuard->Dismiss();
  582. }
  583. assert(FTunnel == NULL);
  584. SAFE_DESTROY(FCommandSession);
  585. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  586. (FDirectoryChangesCache != NULL))
  587. {
  588. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  589. FDirectoryChangesCache);
  590. }
  591. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  592. SAFE_DESTROY_EX(TSessionLog, FLog);
  593. SAFE_DESTROY_EX(TActionLog, FActionLog);
  594. delete FFiles;
  595. delete FDirectoryCache;
  596. delete FDirectoryChangesCache;
  597. SAFE_DESTROY(FSessionData);
  598. }
  599. //---------------------------------------------------------------------------
  600. void __fastcall TTerminal::Idle()
  601. {
  602. // once we disconnect, do nothing, until reconnect handler
  603. // "receives the information"
  604. if (Active)
  605. {
  606. if (Configuration->ActualLogProtocol >= 1)
  607. {
  608. LogEvent(L"Session upkeep");
  609. }
  610. assert(FFileSystem != NULL);
  611. FFileSystem->Idle();
  612. if (CommandSessionOpened)
  613. {
  614. try
  615. {
  616. FCommandSession->Idle();
  617. }
  618. catch(Exception & E)
  619. {
  620. // If the secondary session is dropped, ignore the error and let
  621. // it be reconnected when needed.
  622. // BTW, non-fatal error can hardly happen here, that's why
  623. // it is displayed, because it can be useful to know.
  624. if (FCommandSession->Active)
  625. {
  626. FCommandSession->HandleExtendedException(&E);
  627. }
  628. }
  629. }
  630. }
  631. }
  632. //---------------------------------------------------------------------
  633. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  634. {
  635. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  636. }
  637. //---------------------------------------------------------------------
  638. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  639. {
  640. UnicodeString Result;
  641. try
  642. {
  643. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  644. }
  645. catch(EAbort &)
  646. {
  647. // silently ignore aborted prompts for master password and return empty password
  648. }
  649. return Result;
  650. }
  651. //---------------------------------------------------------------------------
  652. void __fastcall TTerminal::RecryptPasswords()
  653. {
  654. FSessionData->RecryptPasswords();
  655. FRememberedPassword = EncryptPassword(DecryptPassword(FRememberedPassword));
  656. FRememberedTunnelPassword = EncryptPassword(DecryptPassword(FRememberedTunnelPassword));
  657. }
  658. //---------------------------------------------------------------------------
  659. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  660. const UnicodeString BasePath)
  661. {
  662. // replace this by AbsolutePath()
  663. Path = UnixExcludeTrailingBackslash(Path);
  664. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  665. {
  666. // TODO: Handle more complicated cases like "../../xxx"
  667. if (Path == L"..")
  668. {
  669. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  670. UnixExcludeTrailingBackslash(BasePath)));
  671. }
  672. else
  673. {
  674. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  675. }
  676. }
  677. return Path;
  678. }
  679. //---------------------------------------------------------------------------
  680. bool __fastcall TTerminal::GetActive()
  681. {
  682. return (FFileSystem != NULL) && FFileSystem->GetActive();
  683. }
  684. //---------------------------------------------------------------------------
  685. void __fastcall TTerminal::Close()
  686. {
  687. FFileSystem->Close();
  688. if (CommandSessionOpened)
  689. {
  690. FCommandSession->Close();
  691. }
  692. }
  693. //---------------------------------------------------------------------------
  694. void __fastcall TTerminal::ResetConnection()
  695. {
  696. // used to be called from Reopen(), why?
  697. FTunnelError = L"";
  698. FRememberedPasswordTried = false;
  699. FRememberedTunnelPasswordTried = false;
  700. if (FDirectoryChangesCache != NULL)
  701. {
  702. delete FDirectoryChangesCache;
  703. FDirectoryChangesCache = NULL;
  704. }
  705. FFiles->Directory = L"";
  706. // note that we cannot clear contained files
  707. // as they can still be referenced in the GUI atm
  708. }
  709. //---------------------------------------------------------------------------
  710. void __fastcall TTerminal::Open()
  711. {
  712. ReflectSettings();
  713. try
  714. {
  715. DoInformation(L"", true, 1);
  716. try
  717. {
  718. try
  719. {
  720. ResetConnection();
  721. FStatus = ssOpening;
  722. try
  723. {
  724. if (FFileSystem == NULL)
  725. {
  726. Log->AddSystemInfo();
  727. DoInitializeLog();
  728. Log->AddStartupInfo();
  729. }
  730. assert(FTunnel == NULL);
  731. if (FSessionData->Tunnel)
  732. {
  733. DoInformation(LoadStr(OPEN_TUNNEL), true);
  734. LogEvent(L"Opening tunnel.");
  735. OpenTunnel();
  736. Log->AddSeparator();
  737. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  738. DoInformation(LoadStr(USING_TUNNEL), false);
  739. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  740. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  741. }
  742. else
  743. {
  744. assert(FTunnelLocalPortNumber == 0);
  745. }
  746. if (FFileSystem == NULL)
  747. {
  748. if (SessionData->FSProtocol == fsFTP)
  749. {
  750. #ifdef NO_FILEZILLA
  751. LogEvent(L"FTP protocol is not supported by this build.");
  752. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  753. #else
  754. FFSProtocol = cfsFTP;
  755. FFileSystem = new TFTPFileSystem(this);
  756. FFileSystem->Open();
  757. Log->AddSeparator();
  758. LogEvent(L"Using FTP protocol.");
  759. #endif
  760. }
  761. else if (SessionData->FSProtocol == fsWebDAV)
  762. {
  763. FFSProtocol = cfsWebDAV;
  764. FFileSystem = new TWebDAVFileSystem(this);
  765. FFileSystem->Open();
  766. Log->AddSeparator();
  767. LogEvent(L"Using WebDAV protocol.");
  768. }
  769. else
  770. {
  771. assert(FSecureShell == NULL);
  772. try
  773. {
  774. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  775. try
  776. {
  777. // there will be only one channel in this session
  778. FSecureShell->Simple = true;
  779. FSecureShell->Open();
  780. }
  781. catch(Exception & E)
  782. {
  783. assert(!FSecureShell->Active);
  784. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  785. {
  786. // the only case where we expect this to happen
  787. assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  788. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  789. }
  790. else
  791. {
  792. throw;
  793. }
  794. }
  795. Log->AddSeparator();
  796. if ((SessionData->FSProtocol == fsSCPonly) ||
  797. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  798. {
  799. FFSProtocol = cfsSCP;
  800. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  801. FSecureShell = NULL; // ownership passed
  802. LogEvent(L"Using SCP protocol.");
  803. }
  804. else
  805. {
  806. FFSProtocol = cfsSFTP;
  807. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  808. FSecureShell = NULL; // ownership passed
  809. LogEvent(L"Using SFTP protocol.");
  810. }
  811. }
  812. __finally
  813. {
  814. delete FSecureShell;
  815. FSecureShell = NULL;
  816. }
  817. }
  818. }
  819. else
  820. {
  821. FFileSystem->Open();
  822. }
  823. }
  824. __finally
  825. {
  826. if (FSessionData->Tunnel)
  827. {
  828. FSessionData->RollbackTunnel();
  829. }
  830. }
  831. if (SessionData->CacheDirectoryChanges)
  832. {
  833. assert(FDirectoryChangesCache == NULL);
  834. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  835. Configuration->CacheDirectoryChangesMaxSize);
  836. if (SessionData->PreserveDirectoryChanges)
  837. {
  838. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  839. FDirectoryChangesCache);
  840. }
  841. }
  842. DoStartup();
  843. if (FCollectFileSystemUsage)
  844. {
  845. FFileSystem->CollectUsage();
  846. FCollectFileSystemUsage = false;
  847. }
  848. DoInformation(LoadStr(STATUS_READY), true);
  849. FStatus = ssOpened;
  850. }
  851. catch(...)
  852. {
  853. // rollback
  854. if (FDirectoryChangesCache != NULL)
  855. {
  856. delete FDirectoryChangesCache;
  857. FDirectoryChangesCache = NULL;
  858. }
  859. throw;
  860. }
  861. }
  862. __finally
  863. {
  864. DoInformation(L"", true, 0);
  865. }
  866. }
  867. catch(EFatal &)
  868. {
  869. throw;
  870. }
  871. catch(Exception & E)
  872. {
  873. // any exception while opening session is fatal
  874. FatalError(&E, L"");
  875. }
  876. }
  877. //---------------------------------------------------------------------------
  878. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  879. {
  880. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  881. bool Result = (Socket != INVALID_SOCKET);
  882. if (Result)
  883. {
  884. SOCKADDR_IN Address;
  885. memset(&Address, 0, sizeof(Address));
  886. Address.sin_family = AF_INET;
  887. Address.sin_port = htons(static_cast<short>(PortNumber));
  888. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  889. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  890. closesocket(Socket);
  891. }
  892. return Result;
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall TTerminal::OpenTunnel()
  896. {
  897. assert(FTunnelData == NULL);
  898. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  899. if (FTunnelLocalPortNumber == 0)
  900. {
  901. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  902. while (!IsListenerFree(FTunnelLocalPortNumber))
  903. {
  904. FTunnelLocalPortNumber++;
  905. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  906. {
  907. FTunnelLocalPortNumber = 0;
  908. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  909. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  910. }
  911. }
  912. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  913. }
  914. try
  915. {
  916. FTunnelData = new TSessionData(L"");
  917. FTunnelData->Assign(StoredSessions->DefaultSettings);
  918. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  919. FTunnelData->Tunnel = false;
  920. FTunnelData->HostName = FSessionData->TunnelHostName;
  921. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  922. FTunnelData->UserName = FSessionData->TunnelUserName;
  923. FTunnelData->Password = FSessionData->TunnelPassword;
  924. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  925. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  926. (FTunnelLocalPortNumber, FSessionData->HostNameExpanded, FSessionData->PortNumber));
  927. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  928. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  929. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  930. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  931. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  932. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  933. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  934. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  935. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  936. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  937. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  938. FTunnelLog->Parent = FLog;
  939. FTunnelLog->Name = L"Tunnel";
  940. FTunnelLog->ReflectSettings();
  941. FTunnelUI = new TTunnelUI(this);
  942. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  943. FTunnelOpening = true;
  944. try
  945. {
  946. FTunnel->Open();
  947. }
  948. __finally
  949. {
  950. FTunnelOpening = false;
  951. }
  952. FTunnelThread = new TTunnelThread(FTunnel);
  953. }
  954. catch(...)
  955. {
  956. CloseTunnel();
  957. throw;
  958. }
  959. }
  960. //---------------------------------------------------------------------------
  961. void __fastcall TTerminal::CloseTunnel()
  962. {
  963. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  964. FTunnelError = FTunnel->LastTunnelError;
  965. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  966. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  967. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  968. SAFE_DESTROY(FTunnelData);
  969. FTunnelLocalPortNumber = 0;
  970. }
  971. //---------------------------------------------------------------------------
  972. void __fastcall TTerminal::Closed()
  973. {
  974. if (FTunnel != NULL)
  975. {
  976. CloseTunnel();
  977. }
  978. if (OnClose)
  979. {
  980. TCallbackGuard Guard(this);
  981. OnClose(this);
  982. Guard.Verify();
  983. }
  984. FStatus = ssClosed;
  985. }
  986. //---------------------------------------------------------------------------
  987. void __fastcall TTerminal::Reopen(int Params)
  988. {
  989. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  990. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  991. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  992. bool PrevReadDirectoryPending = FReadDirectoryPending;
  993. assert(!FSuspendTransaction);
  994. bool PrevAutoReadDirectory = FAutoReadDirectory;
  995. // here used to be a check for FExceptionOnFail being 0
  996. // but it can happen, e.g. when we are downloading file to execute it.
  997. // however I'm not sure why we mind having excaption-on-fail enabled here
  998. int PrevExceptionOnFail = FExceptionOnFail;
  999. try
  1000. {
  1001. FReadCurrentDirectoryPending = false;
  1002. FReadDirectoryPending = false;
  1003. FSuspendTransaction = true;
  1004. FExceptionOnFail = 0;
  1005. // typically, we avoid reading directory, when there is operation ongoing,
  1006. // for file list which may reference files from current directory
  1007. if (FLAGSET(Params, ropNoReadDirectory))
  1008. {
  1009. AutoReadDirectory = false;
  1010. }
  1011. // only peek, we may not be connected at all atm,
  1012. // so make sure we do not try retrieving current directory from the server
  1013. // (particularly with FTP)
  1014. AnsiString ACurrentDirectory = PeekCurrentDirectory();
  1015. if (!ACurrentDirectory.IsEmpty())
  1016. {
  1017. SessionData->RemoteDirectory = ACurrentDirectory;
  1018. }
  1019. if (SessionData->FSProtocol == fsSFTP)
  1020. {
  1021. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1022. }
  1023. if (Active)
  1024. {
  1025. Close();
  1026. }
  1027. Open();
  1028. }
  1029. __finally
  1030. {
  1031. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1032. SessionData->FSProtocol = OrigFSProtocol;
  1033. FAutoReadDirectory = PrevAutoReadDirectory;
  1034. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1035. FReadDirectoryPending = PrevReadDirectoryPending;
  1036. FSuspendTransaction = false;
  1037. FExceptionOnFail = PrevExceptionOnFail;
  1038. }
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1042. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1043. {
  1044. bool AResult;
  1045. TStrings * Prompts = new TStringList;
  1046. TStrings * Results = new TStringList;
  1047. try
  1048. {
  1049. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1050. Results->AddObject(Result, (TObject *)MaxLen);
  1051. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1052. Result = Results->Strings[0];
  1053. }
  1054. __finally
  1055. {
  1056. delete Prompts;
  1057. delete Results;
  1058. }
  1059. return AResult;
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1063. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1064. {
  1065. // If PromptUser is overridden in descendant class, the overridden version
  1066. // is not called when accessed via TSessionIU interface.
  1067. // So this is workaround.
  1068. // Actually no longer needed as we do not uverride DoPromptUser
  1069. // anymore in TSecondaryTerminal.
  1070. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1071. }
  1072. //---------------------------------------------------------------------------
  1073. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1074. {
  1075. return this;
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1079. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1080. {
  1081. bool AResult = false;
  1082. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1083. if (PasswordOrPassphrasePrompt)
  1084. {
  1085. bool & PasswordTried =
  1086. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1087. if (!PasswordTried)
  1088. {
  1089. // let's expect that the main session is already authenticated and its password
  1090. // is not written after, so no locking is necessary
  1091. // (no longer true, once the main session can be reconnected)
  1092. UnicodeString APassword;
  1093. if (FTunnelOpening)
  1094. {
  1095. APassword = GetPasswordSource()->RememberedTunnelPassword;
  1096. }
  1097. else
  1098. {
  1099. APassword = GetPasswordSource()->RememberedPassword;
  1100. }
  1101. Results->Strings[0] = APassword;
  1102. if (!Results->Strings[0].IsEmpty())
  1103. {
  1104. LogEvent(L"Using remembered password.");
  1105. AResult = true;
  1106. }
  1107. PasswordTried = true;
  1108. }
  1109. }
  1110. if (!AResult)
  1111. {
  1112. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1113. {
  1114. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1115. }
  1116. if (OnPromptUser != NULL)
  1117. {
  1118. TCallbackGuard Guard(this);
  1119. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1120. Guard.Verify();
  1121. }
  1122. if (AResult && PasswordOrPassphrasePrompt &&
  1123. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1124. {
  1125. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1126. if (FTunnelOpening)
  1127. {
  1128. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1129. }
  1130. else
  1131. {
  1132. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1133. }
  1134. }
  1135. }
  1136. return AResult;
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1140. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1141. TQueryType QueryType)
  1142. {
  1143. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1144. unsigned int Answer = AbortAnswer(Answers);
  1145. if (FOnQueryUser)
  1146. {
  1147. TCallbackGuard Guard(this);
  1148. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1149. Guard.Verify();
  1150. }
  1151. return Answer;
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1155. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1156. TQueryType QueryType)
  1157. {
  1158. unsigned int Result;
  1159. UnicodeString ExMessage;
  1160. if (ALWAYS_TRUE(ExceptionMessage(E, ExMessage) || !Query.IsEmpty()))
  1161. {
  1162. TStrings * MoreMessages = new TStringList();
  1163. try
  1164. {
  1165. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1166. {
  1167. MoreMessages->Add(UnformatMessage(ExMessage));
  1168. }
  1169. ExtException * EE = dynamic_cast<ExtException*>(E);
  1170. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1171. {
  1172. MoreMessages->AddStrings(EE->MoreMessages);
  1173. }
  1174. // We know MoreMessages not to be NULL here,
  1175. // AppendExceptionStackTraceAndForget should never return true
  1176. // (indicating it had to create the string list)
  1177. ALWAYS_FALSE(AppendExceptionStackTraceAndForget(MoreMessages));
  1178. TQueryParams HelpKeywordOverrideParams;
  1179. if (Params != NULL)
  1180. {
  1181. HelpKeywordOverrideParams.Assign(*Params);
  1182. }
  1183. HelpKeywordOverrideParams.HelpKeyword =
  1184. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1185. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1186. MoreMessages->Count ? MoreMessages : NULL,
  1187. Answers, &HelpKeywordOverrideParams, QueryType);
  1188. }
  1189. __finally
  1190. {
  1191. delete MoreMessages;
  1192. }
  1193. }
  1194. return Result;
  1195. }
  1196. //---------------------------------------------------------------------------
  1197. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1198. {
  1199. if (OnDisplayBanner != NULL)
  1200. {
  1201. if (Configuration->ForceBanners ||
  1202. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1203. {
  1204. bool NeverShowAgain = false;
  1205. int Options =
  1206. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1207. TCallbackGuard Guard(this);
  1208. OnDisplayBanner(this, SessionData->SessionName, Banner,
  1209. NeverShowAgain, Options);
  1210. Guard.Verify();
  1211. if (!Configuration->ForceBanners && NeverShowAgain)
  1212. {
  1213. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1220. {
  1221. Log->AddException(E);
  1222. if (OnShowExtendedException != NULL)
  1223. {
  1224. TCallbackGuard Guard(this);
  1225. // the event handler may destroy 'this' ...
  1226. OnShowExtendedException(this, E, NULL);
  1227. // .. hence guard is dismissed from destructor, to make following call no-op
  1228. Guard.Verify();
  1229. }
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1233. {
  1234. Log->AddException(E);
  1235. if (OnShowExtendedException != NULL)
  1236. {
  1237. OnShowExtendedException(this, E, NULL);
  1238. }
  1239. }
  1240. //---------------------------------------------------------------------------
  1241. void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
  1242. int Phase)
  1243. {
  1244. if (OnInformation)
  1245. {
  1246. TCallbackGuard Guard(this);
  1247. OnInformation(this, Str, Status, Phase);
  1248. Guard.Verify();
  1249. }
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1253. {
  1254. DoInformation(Str, Status);
  1255. }
  1256. //---------------------------------------------------------------------------
  1257. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1258. {
  1259. if (OnProgress != NULL)
  1260. {
  1261. TCallbackGuard Guard(this);
  1262. OnProgress(ProgressData);
  1263. Guard.Verify();
  1264. }
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1268. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1269. {
  1270. if (OnFinished != NULL)
  1271. {
  1272. TCallbackGuard Guard(this);
  1273. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1274. Guard.Verify();
  1275. }
  1276. }
  1277. //---------------------------------------------------------------------------
  1278. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1279. {
  1280. for (int Index = 0; Index < fcCount; Index++)
  1281. {
  1282. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1283. }
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1287. {
  1288. assert(FFileSystem);
  1289. return FFileSystem->IsCapable(Capability);
  1290. }
  1291. //---------------------------------------------------------------------------
  1292. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1293. {
  1294. return FFileSystem->AbsolutePath(Path, Local);
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1298. {
  1299. bool ChangesDirectory = false;
  1300. bool ModifiesFiles = false;
  1301. switch ((TFSCommand)Cmd) {
  1302. case fsChangeDirectory:
  1303. case fsHomeDirectory:
  1304. ChangesDirectory = true;
  1305. break;
  1306. case fsCopyToRemote:
  1307. case fsDeleteFile:
  1308. case fsRenameFile:
  1309. case fsMoveFile:
  1310. case fsCopyFile:
  1311. case fsCreateDirectory:
  1312. case fsChangeMode:
  1313. case fsChangeGroup:
  1314. case fsChangeOwner:
  1315. case fsChangeProperties:
  1316. ModifiesFiles = true;
  1317. break;
  1318. case fsAnyCommand:
  1319. ChangesDirectory = true;
  1320. ModifiesFiles = true;
  1321. break;
  1322. }
  1323. if (ChangesDirectory)
  1324. {
  1325. if (!InTransaction())
  1326. {
  1327. ReadCurrentDirectory();
  1328. if (AutoReadDirectory)
  1329. {
  1330. ReadDirectory(false);
  1331. }
  1332. }
  1333. else
  1334. {
  1335. FReadCurrentDirectoryPending = true;
  1336. if (AutoReadDirectory)
  1337. {
  1338. FReadDirectoryPending = true;
  1339. }
  1340. }
  1341. }
  1342. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  1343. {
  1344. if (!InTransaction())
  1345. {
  1346. ReadDirectory(true);
  1347. }
  1348. else
  1349. {
  1350. FReadDirectoryPending = true;
  1351. }
  1352. }
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  1356. {
  1357. TerminalError(NULL, Msg);
  1358. }
  1359. //---------------------------------------------------------------------------
  1360. void __fastcall TTerminal::TerminalError(
  1361. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1362. {
  1363. throw ETerminal(E, Msg, HelpKeyword);
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  1367. {
  1368. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  1369. assert(Fatal != NULL);
  1370. bool Result;
  1371. if ((Fatal != NULL) && Fatal->ReopenQueried)
  1372. {
  1373. Result = false;
  1374. }
  1375. else
  1376. {
  1377. LogEvent(L"Connection was lost, asking what to do.");
  1378. TQueryParams Params(qpAllowContinueOnError);
  1379. Params.Timeout = Configuration->SessionReopenAuto;
  1380. Params.TimeoutAnswer = qaRetry;
  1381. TQueryButtonAlias Aliases[1];
  1382. Aliases[0].Button = qaRetry;
  1383. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  1384. Params.Aliases = Aliases;
  1385. Params.AliasesCount = LENOF(Aliases);
  1386. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  1387. if (Fatal != NULL)
  1388. {
  1389. Fatal->ReopenQueried = true;
  1390. }
  1391. }
  1392. return Result;
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  1396. TFileOperationProgressType * OperationProgress)
  1397. {
  1398. TSuspendFileOperationProgress Suspend(OperationProgress);
  1399. bool Result = DoQueryReopen(E);
  1400. if (Result)
  1401. {
  1402. TDateTime Start = Now();
  1403. do
  1404. {
  1405. try
  1406. {
  1407. Reopen(Params);
  1408. }
  1409. catch(Exception & E)
  1410. {
  1411. if (!Active)
  1412. {
  1413. Result =
  1414. ((Configuration->SessionReopenTimeout == 0) ||
  1415. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout)) &&
  1416. DoQueryReopen(&E);
  1417. }
  1418. else
  1419. {
  1420. throw;
  1421. }
  1422. }
  1423. }
  1424. while (!Active && Result);
  1425. }
  1426. return Result;
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  1430. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  1431. bool AllowSkip, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  1432. {
  1433. bool Result = false;
  1434. Log->AddException(&E);
  1435. unsigned int Answer;
  1436. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  1437. if (SkipToAllPossible && OperationProgress->SkipToAll)
  1438. {
  1439. Answer = qaSkip;
  1440. }
  1441. else
  1442. {
  1443. int Answers = qaRetry | qaAbort |
  1444. FLAGMASK(AllowSkip, qaSkip) |
  1445. FLAGMASK(SkipToAllPossible, qaAll) |
  1446. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  1447. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  1448. Params.HelpKeyword = HelpKeyword;
  1449. TQueryButtonAlias Aliases[2];
  1450. int AliasCount = 0;
  1451. if (FLAGSET(Answers, qaAll))
  1452. {
  1453. Aliases[AliasCount].Button = qaAll;
  1454. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  1455. AliasCount++;
  1456. }
  1457. if (FLAGSET(Answers, qaYes))
  1458. {
  1459. Aliases[AliasCount].Button = qaYes;
  1460. Aliases[AliasCount].Alias = SpecialRetry;
  1461. AliasCount++;
  1462. }
  1463. if (AliasCount > 0)
  1464. {
  1465. Params.Aliases = Aliases;
  1466. Params.AliasesCount = AliasCount;
  1467. }
  1468. {
  1469. TSuspendFileOperationProgress Suspend(OperationProgress);
  1470. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1471. }
  1472. if (Answer == qaAll)
  1473. {
  1474. assert(OperationProgress != NULL);
  1475. OperationProgress->SkipToAll = true;
  1476. Answer = qaSkip;
  1477. }
  1478. if (Answer == qaYes)
  1479. {
  1480. Result = true;
  1481. Answer = qaRetry;
  1482. }
  1483. }
  1484. if (Answer != qaRetry)
  1485. {
  1486. if ((Answer == qaAbort) && (OperationProgress != NULL))
  1487. {
  1488. OperationProgress->Cancel = csCancel;
  1489. }
  1490. if (AllowSkip)
  1491. {
  1492. THROW_SKIP_FILE(&E, Message);
  1493. }
  1494. else
  1495. {
  1496. // this can happen only during file transfer with SCP
  1497. throw ExtException(&E, Message);
  1498. }
  1499. }
  1500. return Result;
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1504. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1505. const UnicodeString Message, void * Param1, void * Param2)
  1506. {
  1507. assert(CallBackFunc);
  1508. int Result;
  1509. FILE_OPERATION_LOOP_BEGIN
  1510. {
  1511. Result = CallBackFunc(Param1, Param2);
  1512. }
  1513. FILE_OPERATION_LOOP_END_EX(Message, AllowSkip);
  1514. return Result;
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  1518. {
  1519. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  1520. {
  1521. if (Lock)
  1522. {
  1523. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1524. {
  1525. Path.Delete(1, FLockDirectory.Length());
  1526. if (Path.IsEmpty()) Path = L"/";
  1527. }
  1528. }
  1529. else
  1530. {
  1531. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1532. }
  1533. }
  1534. return Path;
  1535. }
  1536. //---------------------------------------------------------------------------
  1537. void __fastcall TTerminal::ClearCaches()
  1538. {
  1539. FDirectoryCache->Clear();
  1540. if (FDirectoryChangesCache != NULL)
  1541. {
  1542. FDirectoryChangesCache->Clear();
  1543. }
  1544. if (FCommandSession != NULL)
  1545. {
  1546. FCommandSession->ClearCaches();
  1547. }
  1548. }
  1549. //---------------------------------------------------------------------------
  1550. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  1551. bool SubDirs)
  1552. {
  1553. FDirectoryCache->ClearFileList(Path, SubDirs);
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1557. {
  1558. FDirectoryCache->AddFileList(FileList);
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. bool __fastcall TTerminal::DirectoryFileList(const UnicodeString Path,
  1562. TRemoteFileList *& FileList, bool CanLoad)
  1563. {
  1564. bool Result = false;
  1565. if (UnixSamePath(FFiles->Directory, Path))
  1566. {
  1567. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1568. if (Result)
  1569. {
  1570. if (FileList == NULL)
  1571. {
  1572. FileList = new TRemoteFileList();
  1573. }
  1574. FFiles->DuplicateTo(FileList);
  1575. }
  1576. }
  1577. else
  1578. {
  1579. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1580. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1581. {
  1582. bool Created = (FileList == NULL);
  1583. if (Created)
  1584. {
  1585. FileList = new TRemoteFileList();
  1586. }
  1587. Result = FDirectoryCache->GetFileList(Path, FileList);
  1588. if (!Result && Created)
  1589. {
  1590. SAFE_DESTROY(FileList);
  1591. }
  1592. }
  1593. // do not attempt to load file list if there is cached version,
  1594. // only absence of cached version indicates that we consider
  1595. // the directory content obsolete
  1596. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1597. {
  1598. bool Created = (FileList == NULL);
  1599. if (Created)
  1600. {
  1601. FileList = new TRemoteFileList();
  1602. }
  1603. FileList->Directory = Path;
  1604. try
  1605. {
  1606. ReadDirectory(FileList);
  1607. Result = true;
  1608. }
  1609. catch(...)
  1610. {
  1611. if (Created)
  1612. {
  1613. SAFE_DESTROY(FileList);
  1614. }
  1615. throw;
  1616. }
  1617. }
  1618. }
  1619. return Result;
  1620. }
  1621. //---------------------------------------------------------------------------
  1622. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  1623. {
  1624. assert(FFileSystem);
  1625. value = TranslateLockedPath(value, false);
  1626. if (value != FFileSystem->CurrentDirectory)
  1627. {
  1628. ChangeDirectory(value);
  1629. }
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  1633. {
  1634. if (FFileSystem != NULL)
  1635. {
  1636. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  1637. // to FCurrentDirectory, splitting the assignment to two statemets
  1638. // to locate the crash more closely
  1639. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  1640. FCurrentDirectory = CurrentDirectory;
  1641. if (FCurrentDirectory.IsEmpty())
  1642. {
  1643. ReadCurrentDirectory();
  1644. }
  1645. }
  1646. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1647. return Result;
  1648. }
  1649. //---------------------------------------------------------------------------
  1650. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  1651. {
  1652. if (FFileSystem)
  1653. {
  1654. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1655. }
  1656. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1657. return Result;
  1658. }
  1659. //---------------------------------------------------------------------------
  1660. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  1661. {
  1662. assert(FFileSystem);
  1663. LookupUsersGroups();
  1664. return &FGroups;
  1665. }
  1666. //---------------------------------------------------------------------------
  1667. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  1668. {
  1669. assert(FFileSystem);
  1670. LookupUsersGroups();
  1671. return &FUsers;
  1672. }
  1673. //---------------------------------------------------------------------------
  1674. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  1675. {
  1676. assert(FFileSystem);
  1677. LookupUsersGroups();
  1678. return &FMembership;
  1679. }
  1680. //---------------------------------------------------------------------------
  1681. UnicodeString __fastcall TTerminal::GetUserName() const
  1682. {
  1683. // in future might also be implemented to detect username similar to GetUserGroups
  1684. assert(FFileSystem != NULL);
  1685. UnicodeString Result = FFileSystem->GetUserName();
  1686. // Is empty also when stored username was used
  1687. if (Result.IsEmpty())
  1688. {
  1689. Result = SessionData->UserNameExpanded;
  1690. }
  1691. return Result;
  1692. }
  1693. //---------------------------------------------------------------------------
  1694. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1695. {
  1696. return FDirectoryCache->IsEmpty &&
  1697. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1698. }
  1699. //---------------------------------------------------------------------------
  1700. void __fastcall TTerminal::DoInitializeLog()
  1701. {
  1702. if (FOnInitializeLog)
  1703. {
  1704. TCallbackGuard Guard(this);
  1705. FOnInitializeLog(this);
  1706. Guard.Verify();
  1707. }
  1708. }
  1709. //---------------------------------------------------------------------------
  1710. void __fastcall TTerminal::DoChangeDirectory()
  1711. {
  1712. if (FOnChangeDirectory)
  1713. {
  1714. TCallbackGuard Guard(this);
  1715. FOnChangeDirectory(this);
  1716. Guard.Verify();
  1717. }
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1721. {
  1722. if (FOnReadDirectory)
  1723. {
  1724. TCallbackGuard Guard(this);
  1725. FOnReadDirectory(this, ReloadOnly);
  1726. Guard.Verify();
  1727. }
  1728. }
  1729. //---------------------------------------------------------------------------
  1730. void __fastcall TTerminal::DoStartReadDirectory()
  1731. {
  1732. if (FOnStartReadDirectory)
  1733. {
  1734. TCallbackGuard Guard(this);
  1735. FOnStartReadDirectory(this);
  1736. Guard.Verify();
  1737. }
  1738. }
  1739. //---------------------------------------------------------------------------
  1740. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  1741. {
  1742. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1743. {
  1744. TCallbackGuard Guard(this);
  1745. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  1746. Guard.Verify();
  1747. }
  1748. if (FOnFindingFile != NULL)
  1749. {
  1750. TCallbackGuard Guard(this);
  1751. FOnFindingFile(this, L"", Cancel);
  1752. Guard.Verify();
  1753. }
  1754. }
  1755. //---------------------------------------------------------------------------
  1756. bool __fastcall TTerminal::InTransaction()
  1757. {
  1758. return (FInTransaction > 0) && !FSuspendTransaction;
  1759. }
  1760. //---------------------------------------------------------------------------
  1761. void __fastcall TTerminal::BeginTransaction()
  1762. {
  1763. if (FInTransaction == 0)
  1764. {
  1765. FReadCurrentDirectoryPending = false;
  1766. FReadDirectoryPending = false;
  1767. }
  1768. FInTransaction++;
  1769. if (FCommandSession != NULL)
  1770. {
  1771. FCommandSession->BeginTransaction();
  1772. }
  1773. }
  1774. //---------------------------------------------------------------------------
  1775. void __fastcall TTerminal::EndTransaction()
  1776. {
  1777. DoEndTransaction(false);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  1781. {
  1782. if (FInTransaction == 0)
  1783. TerminalError(L"Can't end transaction, not in transaction");
  1784. assert(FInTransaction > 0);
  1785. FInTransaction--;
  1786. // it connection was closed due to fatal error during transaction, do nothing
  1787. if (Active)
  1788. {
  1789. if (FInTransaction == 0)
  1790. {
  1791. try
  1792. {
  1793. if (FReadCurrentDirectoryPending)
  1794. {
  1795. ReadCurrentDirectory();
  1796. }
  1797. if (FReadDirectoryPending)
  1798. {
  1799. if (Inform)
  1800. {
  1801. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1802. }
  1803. ReadDirectory(!FReadCurrentDirectoryPending);
  1804. }
  1805. }
  1806. __finally
  1807. {
  1808. FReadCurrentDirectoryPending = false;
  1809. FReadDirectoryPending = false;
  1810. }
  1811. }
  1812. }
  1813. if (FCommandSession != NULL)
  1814. {
  1815. FCommandSession->EndTransaction();
  1816. }
  1817. }
  1818. //---------------------------------------------------------------------------
  1819. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1820. {
  1821. if (value)
  1822. {
  1823. FExceptionOnFail++;
  1824. }
  1825. else
  1826. {
  1827. if (FExceptionOnFail == 0)
  1828. throw Exception(L"ExceptionOnFail is already zero.");
  1829. FExceptionOnFail--;
  1830. }
  1831. if (FCommandSession != NULL)
  1832. {
  1833. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  1834. }
  1835. }
  1836. //---------------------------------------------------------------------------
  1837. bool __fastcall TTerminal::GetExceptionOnFail() const
  1838. {
  1839. return (bool)(FExceptionOnFail > 0);
  1840. }
  1841. //---------------------------------------------------------------------------
  1842. void __fastcall TTerminal::FatalAbort()
  1843. {
  1844. FatalError(NULL, "");
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1848. {
  1849. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  1850. if (Active || SecureShellActive)
  1851. {
  1852. // We log this instead of exception handler, because Close() would
  1853. // probably cause exception handler to loose pointer to TShellLog()
  1854. LogEvent(L"Attempt to close connection due to fatal exception:");
  1855. Log->Add(llException, Msg);
  1856. Log->AddException(E);
  1857. if (Active)
  1858. {
  1859. Close();
  1860. }
  1861. // this may happen if failure of authentication of SSH, owned by terminal yet
  1862. // (because the protocol was not decided yet), is detected by us (not by putty).
  1863. // e.g. not verified host key
  1864. if (SecureShellActive)
  1865. {
  1866. FSecureShell->Close();
  1867. }
  1868. }
  1869. if (FCallbackGuard != NULL)
  1870. {
  1871. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  1872. }
  1873. else
  1874. {
  1875. throw ESshFatal(E, Msg, HelpKeyword);
  1876. }
  1877. }
  1878. //---------------------------------------------------------------------------
  1879. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  1880. {
  1881. CommandError(E, Msg, 0);
  1882. }
  1883. //---------------------------------------------------------------------------
  1884. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  1885. unsigned int Answers, const UnicodeString HelpKeyword)
  1886. {
  1887. // may not be, particularly when TTerminal::Reopen is being called
  1888. // from within OnShowExtendedException handler
  1889. assert(FCallbackGuard == NULL);
  1890. unsigned int Result = 0;
  1891. if (E && E->InheritsFrom(__classid(EFatal)))
  1892. {
  1893. FatalError(E, Msg, HelpKeyword);
  1894. }
  1895. else if (E && E->InheritsFrom(__classid(EAbort)))
  1896. {
  1897. // resent EAbort exception
  1898. Abort();
  1899. }
  1900. else if (ExceptionOnFail)
  1901. {
  1902. throw ECommand(E, Msg, HelpKeyword);
  1903. }
  1904. else if (!Answers)
  1905. {
  1906. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  1907. try
  1908. {
  1909. HandleExtendedException(ECmd);
  1910. }
  1911. __finally
  1912. {
  1913. delete ECmd;
  1914. }
  1915. }
  1916. else
  1917. {
  1918. // small hack to enable "skip to all" for COMMAND_ERROR_ARI
  1919. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  1920. if (CanSkip && OperationProgress->SkipToAll)
  1921. {
  1922. Result = qaSkip;
  1923. }
  1924. else
  1925. {
  1926. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  1927. TQueryButtonAlias Aliases[1];
  1928. if (CanSkip)
  1929. {
  1930. Aliases[0].Button = qaAll;
  1931. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  1932. Params.Aliases = Aliases;
  1933. Params.AliasesCount = LENOF(Aliases);
  1934. Answers |= qaAll;
  1935. }
  1936. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  1937. if (Result == qaAll)
  1938. {
  1939. assert(OperationProgress != NULL);
  1940. OperationProgress->SkipToAll = true;
  1941. Result = qaSkip;
  1942. }
  1943. }
  1944. }
  1945. return Result;
  1946. }
  1947. //---------------------------------------------------------------------------
  1948. bool __fastcall TTerminal::HandleException(Exception * E)
  1949. {
  1950. if (ExceptionOnFail)
  1951. {
  1952. return false;
  1953. }
  1954. else
  1955. {
  1956. Log->AddException(E);
  1957. return true;
  1958. }
  1959. }
  1960. //---------------------------------------------------------------------------
  1961. void __fastcall TTerminal::CloseOnCompletion(TOnceDoneOperation Operation, const UnicodeString Message)
  1962. {
  1963. Configuration->Usage->Inc(L"ClosesOnCompletion");
  1964. LogEvent(L"Closing session after completed operation (as requested by user)");
  1965. Close();
  1966. throw ESshTerminate(NULL,
  1967. Message.IsEmpty() ? UnicodeString(LoadStr(CLOSED_ON_COMPLETION)) : Message,
  1968. Operation);
  1969. }
  1970. //---------------------------------------------------------------------------
  1971. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  1972. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  1973. {
  1974. TBatchOverwrite Result;
  1975. if (Special &&
  1976. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(FileName)))
  1977. {
  1978. Result = boResume;
  1979. }
  1980. else if (FLAGSET(Params, cpAppend))
  1981. {
  1982. Result = boAppend;
  1983. }
  1984. else if (CopyParam->NewerOnly &&
  1985. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  1986. (OperationProgress->Side != osLocal)))
  1987. {
  1988. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  1989. Result = boOlder;
  1990. }
  1991. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  1992. {
  1993. // no way to change batch overwrite mode when overwrite confirmations are off
  1994. assert(OperationProgress->BatchOverwrite == boNo);
  1995. Result = boAll;
  1996. }
  1997. else
  1998. {
  1999. Result = OperationProgress->BatchOverwrite;
  2000. if (!Special &&
  2001. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2002. {
  2003. Result = boNo;
  2004. }
  2005. }
  2006. return Result;
  2007. }
  2008. //---------------------------------------------------------------------------
  2009. bool __fastcall TTerminal::CheckRemoteFile(
  2010. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2011. {
  2012. return (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2013. }
  2014. //---------------------------------------------------------------------------
  2015. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(const UnicodeString FileName,
  2016. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2017. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2018. UnicodeString Message)
  2019. {
  2020. unsigned int Result;
  2021. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2022. bool CanAlternateResume =
  2023. (FileParams != NULL) &&
  2024. (FileParams->DestSize < FileParams->SourceSize) &&
  2025. !OperationProgress->AsciiTransfer;
  2026. TBatchOverwrite BatchOverwrite = EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true);
  2027. bool Applicable = true;
  2028. switch (BatchOverwrite)
  2029. {
  2030. case boOlder:
  2031. Applicable = (FileParams != NULL);
  2032. break;
  2033. case boAlternateResume:
  2034. Applicable = CanAlternateResume;
  2035. break;
  2036. case boResume:
  2037. Applicable = CanAlternateResume;
  2038. break;
  2039. }
  2040. if (!Applicable)
  2041. {
  2042. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, false);
  2043. assert(BatchOverwrite != ABatchOverwrite);
  2044. BatchOverwrite = ABatchOverwrite;
  2045. }
  2046. if (BatchOverwrite == boNo)
  2047. {
  2048. if (Message.IsEmpty())
  2049. {
  2050. // Side refers to destination side here
  2051. UnicodeString FileNameOnly = (Side == osRemote) ? ExtractFileName(FileName) : UnixExtractFileName(FileName);
  2052. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2053. REMOTE_FILE_OVERWRITE2), (FileNameOnly, FileNameOnly));
  2054. }
  2055. if (FileParams != NULL)
  2056. {
  2057. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2058. FormatSize(FileParams->SourceSize),
  2059. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  2060. FormatSize(FileParams->DestSize),
  2061. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  2062. }
  2063. if (ALWAYS_TRUE(QueryParams->HelpKeyword.IsEmpty()))
  2064. {
  2065. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2066. }
  2067. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2068. switch (Result)
  2069. {
  2070. case qaNeverAskAgain:
  2071. Configuration->ConfirmOverwriting = false;
  2072. Result = qaYes;
  2073. break;
  2074. case qaYesToAll:
  2075. BatchOverwrite = boAll;
  2076. break;
  2077. case qaAll:
  2078. BatchOverwrite = boOlder;
  2079. break;
  2080. case qaNoToAll:
  2081. BatchOverwrite = boNone;
  2082. break;
  2083. }
  2084. // we user has not selected another batch overwrite mode,
  2085. // keep the current one. note that we may get here even
  2086. // when batch overwrite was selected already, but it could not be applied
  2087. // to current transfer (see condition above)
  2088. if (BatchOverwrite != boNo)
  2089. {
  2090. OperationProgress->BatchOverwrite = BatchOverwrite;
  2091. }
  2092. }
  2093. if (BatchOverwrite != boNo)
  2094. {
  2095. switch (BatchOverwrite)
  2096. {
  2097. case boAll:
  2098. Result = qaYes;
  2099. break;
  2100. case boNone:
  2101. Result = qaNo;
  2102. break;
  2103. case boOlder:
  2104. if (FileParams == NULL)
  2105. {
  2106. Result = qaNo;
  2107. }
  2108. else
  2109. {
  2110. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2111. TDateTime ReducedSourceTimestamp =
  2112. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2113. TDateTime ReducedDestTimestamp =
  2114. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2115. Result =
  2116. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2117. qaYes : qaNo;
  2118. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2119. (StandardTimestamp(ReducedSourceTimestamp),
  2120. StandardTimestamp(ReducedDestTimestamp),
  2121. ((Result == qaYes) ? L"" : L" not"))));
  2122. }
  2123. break;
  2124. case boAlternateResume:
  2125. assert(CanAlternateResume);
  2126. Result = qaSkip; // ugh
  2127. break;
  2128. case boAppend:
  2129. Result = qaRetry;
  2130. break;
  2131. case boResume:
  2132. Result = qaRetry;
  2133. break;
  2134. }
  2135. }
  2136. return Result;
  2137. }
  2138. //---------------------------------------------------------------------------
  2139. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2140. const UnicodeString FileName, bool ClearDirectoryChange)
  2141. {
  2142. UnicodeString ParentDirectory;
  2143. UnicodeString Directory;
  2144. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2145. {
  2146. if ((File != NULL) && (File->Directory != NULL))
  2147. {
  2148. if (File->IsDirectory)
  2149. {
  2150. Directory = File->Directory->FullDirectory + File->FileName;
  2151. }
  2152. ParentDirectory = File->Directory->Directory;
  2153. }
  2154. else if (!FileName.IsEmpty())
  2155. {
  2156. ParentDirectory = UnixExtractFilePath(FileName);
  2157. if (ParentDirectory.IsEmpty())
  2158. {
  2159. ParentDirectory = CurrentDirectory;
  2160. }
  2161. // this case for scripting
  2162. if ((File != NULL) && File->IsDirectory)
  2163. {
  2164. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2165. UnixExtractFileName(File->FileName);
  2166. }
  2167. }
  2168. }
  2169. if (SessionData->CacheDirectories)
  2170. {
  2171. if (!Directory.IsEmpty())
  2172. {
  2173. DirectoryModified(Directory, true);
  2174. }
  2175. if (!ParentDirectory.IsEmpty())
  2176. {
  2177. DirectoryModified(ParentDirectory, false);
  2178. }
  2179. }
  2180. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2181. {
  2182. if (!Directory.IsEmpty())
  2183. {
  2184. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2185. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2186. }
  2187. }
  2188. }
  2189. //---------------------------------------------------------------------------
  2190. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2191. {
  2192. if (Path.IsEmpty())
  2193. {
  2194. ClearCachedFileList(CurrentDirectory, SubDirs);
  2195. }
  2196. else
  2197. {
  2198. ClearCachedFileList(Path, SubDirs);
  2199. }
  2200. }
  2201. //---------------------------------------------------------------------------
  2202. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  2203. {
  2204. AddCachedFileList(FileList);
  2205. }
  2206. //---------------------------------------------------------------------------
  2207. void __fastcall TTerminal::ReloadDirectory()
  2208. {
  2209. if (SessionData->CacheDirectories)
  2210. {
  2211. DirectoryModified(CurrentDirectory, false);
  2212. }
  2213. if (SessionData->CacheDirectoryChanges)
  2214. {
  2215. assert(FDirectoryChangesCache != NULL);
  2216. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  2217. }
  2218. ReadCurrentDirectory();
  2219. FReadCurrentDirectoryPending = false;
  2220. ReadDirectory(true);
  2221. FReadDirectoryPending = false;
  2222. }
  2223. //---------------------------------------------------------------------------
  2224. void __fastcall TTerminal::RefreshDirectory()
  2225. {
  2226. if (!SessionData->CacheDirectories)
  2227. {
  2228. LogEvent(L"Not refreshing directory, caching is off.");
  2229. }
  2230. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  2231. {
  2232. // Second parameter was added to allow (rather force) using the cache.
  2233. // Before, the directory was reloaded always, it seems useless,
  2234. // has it any reason?
  2235. ReadDirectory(true, true);
  2236. FReadDirectoryPending = false;
  2237. }
  2238. }
  2239. //---------------------------------------------------------------------------
  2240. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  2241. {
  2242. // if filename doesn't contain path, we check for existence of file
  2243. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  2244. UnixSamePath(CurrentDirectory, FFiles->Directory))
  2245. {
  2246. TRemoteFile *File = FFiles->FindFile(FileName);
  2247. if (File)
  2248. {
  2249. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  2250. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  2251. }
  2252. }
  2253. }
  2254. //---------------------------------------------------------------------------
  2255. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  2256. {
  2257. if (Log->Logging)
  2258. {
  2259. Log->Add(llMessage, Str);
  2260. }
  2261. }
  2262. //---------------------------------------------------------------------------
  2263. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  2264. TFileOperationProgressType * OperationProgress, Exception * E)
  2265. {
  2266. // EScpSkipFile without "cancel" is file skip,
  2267. // and we do not want to record skipped actions.
  2268. // But EScpSkipFile with "cancel" is abort and we want to record that.
  2269. // Note that TSCPFileSystem modifies the logic of RollbackAction little bit.
  2270. if ((dynamic_cast<EScpSkipFile *>(E) != NULL) &&
  2271. ((OperationProgress == NULL) ||
  2272. (OperationProgress->Cancel == csContinue)))
  2273. {
  2274. Action.Cancel();
  2275. }
  2276. else
  2277. {
  2278. Action.Rollback(E);
  2279. }
  2280. }
  2281. //---------------------------------------------------------------------------
  2282. void __fastcall TTerminal::DoStartup()
  2283. {
  2284. LogEvent(L"Doing startup conversation with host.");
  2285. BeginTransaction();
  2286. try
  2287. {
  2288. DoInformation(LoadStr(STATUS_STARTUP), true);
  2289. // Make sure that directory would be loaded at last
  2290. FReadCurrentDirectoryPending = true;
  2291. FReadDirectoryPending = AutoReadDirectory;
  2292. FFileSystem->DoStartup();
  2293. LookupUsersGroups();
  2294. if (!SessionData->RemoteDirectory.IsEmpty())
  2295. {
  2296. ChangeDirectory(SessionData->RemoteDirectory);
  2297. }
  2298. }
  2299. __finally
  2300. {
  2301. DoEndTransaction(true);
  2302. }
  2303. LogEvent(L"Startup conversation with host finished.");
  2304. }
  2305. //---------------------------------------------------------------------------
  2306. void __fastcall TTerminal::ReadCurrentDirectory()
  2307. {
  2308. assert(FFileSystem);
  2309. try
  2310. {
  2311. // reset flag is case we are called externally (like from console dialog)
  2312. FReadCurrentDirectoryPending = false;
  2313. LogEvent(L"Getting current directory name.");
  2314. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  2315. FFileSystem->ReadCurrentDirectory();
  2316. ReactOnCommand(fsCurrentDirectory);
  2317. if (SessionData->CacheDirectoryChanges)
  2318. {
  2319. assert(FDirectoryChangesCache != NULL);
  2320. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  2321. {
  2322. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  2323. FLastDirectoryChange, CurrentDirectory);
  2324. }
  2325. // not to broke the cache, if the next directory change would not
  2326. // be initialized by ChangeDirectory(), which sets it
  2327. // (HomeDirectory() particularly)
  2328. FLastDirectoryChange = L"";
  2329. }
  2330. if (OldDirectory.IsEmpty())
  2331. {
  2332. FLockDirectory = (SessionData->LockInHome ?
  2333. FFileSystem->CurrentDirectory : UnicodeString(L""));
  2334. }
  2335. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  2336. }
  2337. catch (Exception &E)
  2338. {
  2339. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  2340. }
  2341. }
  2342. //---------------------------------------------------------------------------
  2343. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  2344. {
  2345. bool LoadedFromCache = false;
  2346. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  2347. {
  2348. if (ReloadOnly && !ForceCache)
  2349. {
  2350. LogEvent(L"Cached directory not reloaded.");
  2351. }
  2352. else
  2353. {
  2354. DoStartReadDirectory();
  2355. try
  2356. {
  2357. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  2358. }
  2359. __finally
  2360. {
  2361. DoReadDirectory(ReloadOnly);
  2362. }
  2363. if (LoadedFromCache)
  2364. {
  2365. LogEvent(L"Directory content loaded from cache.");
  2366. }
  2367. else
  2368. {
  2369. LogEvent(L"Cached Directory content has been removed.");
  2370. }
  2371. }
  2372. }
  2373. if (!LoadedFromCache)
  2374. {
  2375. DoStartReadDirectory();
  2376. FReadingCurrentDirectory = true;
  2377. bool Cancel = false; // dummy
  2378. DoReadDirectoryProgress(0, 0, Cancel);
  2379. try
  2380. {
  2381. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  2382. try
  2383. {
  2384. Files->Directory = CurrentDirectory;
  2385. CustomReadDirectory(Files);
  2386. }
  2387. __finally
  2388. {
  2389. DoReadDirectoryProgress(-1, 0, Cancel);
  2390. FReadingCurrentDirectory = false;
  2391. TRemoteDirectory * OldFiles = FFiles;
  2392. FFiles = Files;
  2393. try
  2394. {
  2395. DoReadDirectory(ReloadOnly);
  2396. }
  2397. __finally
  2398. {
  2399. // delete only after loading new files to dir view,
  2400. // not to destroy the file objects that the view holds
  2401. // (can be issue in multi threaded environment, such as when the
  2402. // terminal is reconnecting in the terminal thread)
  2403. delete OldFiles;
  2404. }
  2405. if (Active)
  2406. {
  2407. if (SessionData->CacheDirectories)
  2408. {
  2409. DirectoryLoaded(FFiles);
  2410. }
  2411. }
  2412. }
  2413. }
  2414. catch (Exception &E)
  2415. {
  2416. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  2417. }
  2418. }
  2419. }
  2420. //---------------------------------------------------------------------------
  2421. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  2422. {
  2423. // optimization
  2424. if (Log->Logging)
  2425. {
  2426. LogEvent(FORMAT(L"%s;%s;%d;%s;%s;%s;%s;%d",
  2427. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification),
  2428. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  2429. File->Attr)));
  2430. }
  2431. }
  2432. //---------------------------------------------------------------------------
  2433. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2434. {
  2435. UnicodeString Result;
  2436. // optimization
  2437. if (Log->Logging)
  2438. {
  2439. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  2440. }
  2441. return Result;
  2442. }
  2443. //---------------------------------------------------------------------------
  2444. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2445. {
  2446. // optimization
  2447. if (Log->Logging)
  2448. {
  2449. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size))));
  2450. }
  2451. }
  2452. //---------------------------------------------------------------------------
  2453. void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress)
  2454. {
  2455. // optimization
  2456. if (Log->Logging)
  2457. {
  2458. LogEvent(FORMAT("Transfer done: '%s' [%s]", (OperationProgress->FullFileName, IntToStr(OperationProgress->TransferedSize))));
  2459. }
  2460. }
  2461. //---------------------------------------------------------------------------
  2462. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2463. {
  2464. assert(FileList);
  2465. assert(FFileSystem);
  2466. FFileSystem->ReadDirectory(FileList);
  2467. if (Log->Logging)
  2468. {
  2469. for (int Index = 0; Index < FileList->Count; Index++)
  2470. {
  2471. LogRemoteFile(FileList->Files[Index]);
  2472. }
  2473. }
  2474. ReactOnCommand(fsListDirectory);
  2475. }
  2476. //---------------------------------------------------------------------------
  2477. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2478. {
  2479. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2480. TRemoteFileList * FileList = NULL;
  2481. try
  2482. {
  2483. FileList = DoReadDirectoryListing(Directory, false);
  2484. if (FileList != NULL)
  2485. {
  2486. int Index = 0;
  2487. while (Index < FileList->Count)
  2488. {
  2489. TRemoteFile * File = FileList->Files[Index];
  2490. TFileMasks::TParams Params;
  2491. Params.Size = File->Size;
  2492. Params.Modification = File->Modification;
  2493. // Have to use UnicodeString(), instead of L"", as with that
  2494. // overload with (UnicodeString, bool, bool, TParams*) wins
  2495. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  2496. {
  2497. FileList->Delete(Index);
  2498. }
  2499. else
  2500. {
  2501. Index++;
  2502. }
  2503. }
  2504. Action.FileList(FileList);
  2505. }
  2506. }
  2507. catch(Exception & E)
  2508. {
  2509. COMMAND_ERROR_ARI_ACTION
  2510. (
  2511. L"",
  2512. FileList = ReadDirectoryListing(Directory, Mask),
  2513. Action
  2514. );
  2515. }
  2516. return FileList;
  2517. }
  2518. //---------------------------------------------------------------------------
  2519. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2520. {
  2521. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2522. TRemoteFile * File = NULL;
  2523. try
  2524. {
  2525. // reset caches
  2526. AnnounceFileListOperation();
  2527. ReadFile(Path, File);
  2528. Action.File(File);
  2529. }
  2530. catch(Exception & E)
  2531. {
  2532. COMMAND_ERROR_ARI_ACTION
  2533. (
  2534. L"",
  2535. File = ReadFileListing(Path),
  2536. Action
  2537. );
  2538. }
  2539. return File;
  2540. }
  2541. //---------------------------------------------------------------------------
  2542. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2543. {
  2544. TRemoteFileList * FileList = NULL;
  2545. try
  2546. {
  2547. FileList = DoReadDirectoryListing(Directory, UseCache);
  2548. }
  2549. catch(Exception & E)
  2550. {
  2551. COMMAND_ERROR_ARI
  2552. (
  2553. L"",
  2554. FileList = CustomReadDirectoryListing(Directory, UseCache);
  2555. );
  2556. }
  2557. return FileList;
  2558. }
  2559. //---------------------------------------------------------------------------
  2560. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2561. {
  2562. TRemoteFileList * FileList = new TRemoteFileList();
  2563. try
  2564. {
  2565. bool Cache = UseCache && SessionData->CacheDirectories;
  2566. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2567. if (LoadedFromCache)
  2568. {
  2569. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2570. }
  2571. if (!LoadedFromCache)
  2572. {
  2573. FileList->Directory = Directory;
  2574. ExceptionOnFail = true;
  2575. try
  2576. {
  2577. ReadDirectory(FileList);
  2578. }
  2579. __finally
  2580. {
  2581. ExceptionOnFail = false;
  2582. }
  2583. if (Cache)
  2584. {
  2585. AddCachedFileList(FileList);
  2586. }
  2587. }
  2588. }
  2589. catch(...)
  2590. {
  2591. delete FileList;
  2592. throw;
  2593. }
  2594. return FileList;
  2595. }
  2596. //---------------------------------------------------------------------------
  2597. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2598. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2599. {
  2600. TRemoteFileList * FileList = NULL;
  2601. if (IgnoreErrors)
  2602. {
  2603. ExceptionOnFail = true;
  2604. try
  2605. {
  2606. try
  2607. {
  2608. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2609. }
  2610. catch(...)
  2611. {
  2612. if (!Active)
  2613. {
  2614. throw;
  2615. }
  2616. }
  2617. }
  2618. __finally
  2619. {
  2620. ExceptionOnFail = false;
  2621. }
  2622. }
  2623. else
  2624. {
  2625. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2626. }
  2627. // skip if directory listing fails and user selects "skip"
  2628. if (FileList)
  2629. {
  2630. try
  2631. {
  2632. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2633. TRemoteFile * File;
  2634. for (int Index = 0; Index < FileList->Count; Index++)
  2635. {
  2636. File = FileList->Files[Index];
  2637. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2638. {
  2639. CallBackFunc(Directory + File->FileName, File, Param);
  2640. // We should catch EScpSkipFile here as we do in ProcessFiles.
  2641. // Now we have to handle EScpSkipFile in every callback implementation.
  2642. }
  2643. }
  2644. }
  2645. __finally
  2646. {
  2647. delete FileList;
  2648. }
  2649. }
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2653. {
  2654. try
  2655. {
  2656. CustomReadDirectory(FileList);
  2657. }
  2658. catch (Exception &E)
  2659. {
  2660. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2661. }
  2662. }
  2663. //---------------------------------------------------------------------------
  2664. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2665. TRemoteFile *& File)
  2666. {
  2667. assert(FFileSystem);
  2668. try
  2669. {
  2670. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2671. FFileSystem->ReadSymlink(SymlinkFile, File);
  2672. ReactOnCommand(fsReadSymlink);
  2673. }
  2674. catch (Exception &E)
  2675. {
  2676. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2677. }
  2678. }
  2679. //---------------------------------------------------------------------------
  2680. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2681. TRemoteFile *& File)
  2682. {
  2683. assert(FFileSystem);
  2684. File = NULL;
  2685. try
  2686. {
  2687. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2688. FFileSystem->ReadFile(FileName, File);
  2689. ReactOnCommand(fsListFile);
  2690. LogRemoteFile(File);
  2691. }
  2692. catch (Exception &E)
  2693. {
  2694. if (File) delete File;
  2695. File = NULL;
  2696. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2697. }
  2698. }
  2699. //---------------------------------------------------------------------------
  2700. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2701. {
  2702. bool Result;
  2703. TRemoteFile * File = NULL;
  2704. try
  2705. {
  2706. ExceptionOnFail = true;
  2707. try
  2708. {
  2709. ReadFile(FileName, File);
  2710. }
  2711. __finally
  2712. {
  2713. ExceptionOnFail = false;
  2714. }
  2715. if (AFile != NULL)
  2716. {
  2717. *AFile = File;
  2718. }
  2719. else
  2720. {
  2721. delete File;
  2722. }
  2723. Result = true;
  2724. }
  2725. catch(...)
  2726. {
  2727. if (Active)
  2728. {
  2729. Result = false;
  2730. }
  2731. else
  2732. {
  2733. throw;
  2734. }
  2735. }
  2736. return Result;
  2737. }
  2738. //---------------------------------------------------------------------------
  2739. void __fastcall TTerminal::AnnounceFileListOperation()
  2740. {
  2741. FFileSystem->AnnounceFileListOperation();
  2742. }
  2743. //---------------------------------------------------------------------------
  2744. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2745. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2746. TOperationSide Side, bool Ex)
  2747. {
  2748. assert(FFileSystem);
  2749. assert(FileList);
  2750. bool Result = false;
  2751. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2752. try
  2753. {
  2754. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2755. Progress.Start(Operation, Side, FileList->Count);
  2756. FOperationProgress = &Progress;
  2757. try
  2758. {
  2759. if (Side == osRemote)
  2760. {
  2761. BeginTransaction();
  2762. }
  2763. try
  2764. {
  2765. int Index = 0;
  2766. UnicodeString FileName;
  2767. bool Success;
  2768. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  2769. {
  2770. FileName = FileList->Strings[Index];
  2771. try
  2772. {
  2773. try
  2774. {
  2775. Success = false;
  2776. if (!Ex)
  2777. {
  2778. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  2779. }
  2780. else
  2781. {
  2782. // not used anymore
  2783. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  2784. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  2785. }
  2786. Success = true;
  2787. }
  2788. __finally
  2789. {
  2790. Progress.Finish(FileName, Success, OnceDoneOperation);
  2791. }
  2792. }
  2793. catch(EScpSkipFile & E)
  2794. {
  2795. TSuspendFileOperationProgress Suspend(OperationProgress);
  2796. if (!HandleException(&E))
  2797. {
  2798. throw;
  2799. }
  2800. }
  2801. Index++;
  2802. }
  2803. }
  2804. __finally
  2805. {
  2806. if (Side == osRemote)
  2807. {
  2808. EndTransaction();
  2809. }
  2810. }
  2811. if (Progress.Cancel == csContinue)
  2812. {
  2813. Result = true;
  2814. }
  2815. }
  2816. __finally
  2817. {
  2818. FOperationProgress = NULL;
  2819. Progress.Stop();
  2820. }
  2821. }
  2822. catch (...)
  2823. {
  2824. OnceDoneOperation = odoIdle;
  2825. // this was missing here. was it by purpose?
  2826. // without it any error message is lost
  2827. throw;
  2828. }
  2829. if (OnceDoneOperation != odoIdle)
  2830. {
  2831. CloseOnCompletion(OnceDoneOperation);
  2832. }
  2833. return Result;
  2834. }
  2835. //---------------------------------------------------------------------------
  2836. // not used anymore
  2837. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  2838. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  2839. {
  2840. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  2841. Param, Side, true);
  2842. }
  2843. //---------------------------------------------------------------------------
  2844. TStrings * __fastcall TTerminal::GetFixedPaths()
  2845. {
  2846. assert(FFileSystem != NULL);
  2847. return FFileSystem->GetFixedPaths();
  2848. }
  2849. //---------------------------------------------------------------------------
  2850. bool __fastcall TTerminal::GetResolvingSymlinks()
  2851. {
  2852. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  2853. }
  2854. //---------------------------------------------------------------------------
  2855. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  2856. {
  2857. TUsableCopyParamAttrs Result;
  2858. Result.General =
  2859. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  2860. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  2861. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  2862. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  2863. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  2864. // the following three are never supported for download,
  2865. // so when they are not suppored for upload too,
  2866. // set them in General flags, so that they do not get enabled on
  2867. // Synchronize dialog.
  2868. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  2869. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  2870. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM);
  2871. Result.Download = Result.General | cpaNoClearArchive |
  2872. cpaNoIgnorePermErrors |
  2873. // May be already set in General flags, but it's unconditional here
  2874. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  2875. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  2876. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  2877. return Result;
  2878. }
  2879. //---------------------------------------------------------------------------
  2880. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  2881. {
  2882. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  2883. if (Result)
  2884. {
  2885. UnicodeString Path = UnixExtractFilePath(FileName);
  2886. if (Path.IsEmpty())
  2887. {
  2888. Path = CurrentDirectory;
  2889. }
  2890. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  2891. }
  2892. return Result;
  2893. }
  2894. //---------------------------------------------------------------------------
  2895. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  2896. const TRemoteFile * File)
  2897. {
  2898. if (FileName.IsEmpty())
  2899. {
  2900. assert(File != NULL);
  2901. FileName = File->FileName;
  2902. }
  2903. if (!IsRecycledFile(FileName))
  2904. {
  2905. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  2906. (FileName, SessionData->RecycleBinPath)));
  2907. TMoveFileParams Params;
  2908. Params.Target = SessionData->RecycleBinPath;
  2909. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  2910. MoveFile(FileName, File, &Params);
  2911. }
  2912. }
  2913. //---------------------------------------------------------------------------
  2914. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  2915. const TRemoteFile * File, void * AParams)
  2916. {
  2917. if (FileName.IsEmpty() && File)
  2918. {
  2919. FileName = File->FileName;
  2920. }
  2921. if (OperationProgress && OperationProgress->Operation == foDelete)
  2922. {
  2923. if (OperationProgress->Cancel != csContinue) Abort();
  2924. OperationProgress->SetFile(FileName);
  2925. }
  2926. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  2927. bool Recycle =
  2928. FLAGCLEAR(Params, dfForceDelete) &&
  2929. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  2930. !SessionData->RecycleBinPath.IsEmpty();
  2931. if (Recycle && !IsRecycledFile(FileName))
  2932. {
  2933. RecycleFile(FileName, File);
  2934. }
  2935. else
  2936. {
  2937. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  2938. if (File) FileModified(File, FileName, true);
  2939. DoDeleteFile(FileName, File, Params);
  2940. ReactOnCommand(fsDeleteFile);
  2941. }
  2942. }
  2943. //---------------------------------------------------------------------------
  2944. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  2945. const TRemoteFile * File, int Params)
  2946. {
  2947. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  2948. try
  2949. {
  2950. assert(FFileSystem);
  2951. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  2952. FFileSystem->DeleteFile(FileName, File, Params, Action);
  2953. }
  2954. catch(Exception & E)
  2955. {
  2956. COMMAND_ERROR_ARI_ACTION
  2957. (
  2958. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  2959. DoDeleteFile(FileName, File, Params),
  2960. Action
  2961. );
  2962. }
  2963. }
  2964. //---------------------------------------------------------------------------
  2965. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  2966. {
  2967. // TODO: avoid resolving symlinks while reading subdirectories.
  2968. // Resolving does not work anyway for relative symlinks in subdirectories
  2969. // (at least for SFTP).
  2970. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  2971. }
  2972. //---------------------------------------------------------------------------
  2973. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  2974. const TRemoteFile * /*File*/, void * Params)
  2975. {
  2976. if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  2977. {
  2978. OperationProgress->SetFile(FileName);
  2979. }
  2980. if (OnDeleteLocalFile == NULL)
  2981. {
  2982. if (!RecursiveDeleteFile(FileName, false))
  2983. {
  2984. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2985. }
  2986. }
  2987. else
  2988. {
  2989. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  2990. }
  2991. }
  2992. //---------------------------------------------------------------------------
  2993. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  2994. {
  2995. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  2996. }
  2997. //---------------------------------------------------------------------------
  2998. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  2999. const TRemoteFile * File, void * AParams)
  3000. {
  3001. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3002. if (FileName.IsEmpty() && File)
  3003. {
  3004. FileName = File->FileName;
  3005. }
  3006. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  3007. {
  3008. if (OperationProgress->Cancel != csContinue) Abort();
  3009. OperationProgress->SetFile(FileName);
  3010. }
  3011. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3012. (Params->Command, Params->Params, FileName)));
  3013. if (File) FileModified(File, FileName);
  3014. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3015. Params->OutputEvent);
  3016. ReactOnCommand(fsAnyCommand);
  3017. }
  3018. //---------------------------------------------------------------------------
  3019. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3020. const TRemoteFile * File, UnicodeString Command, int Params,
  3021. TCaptureOutputEvent OutputEvent)
  3022. {
  3023. try
  3024. {
  3025. if (IsCapable[fcAnyCommand])
  3026. {
  3027. assert(FFileSystem);
  3028. assert(fcShellAnyCommand);
  3029. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3030. }
  3031. else
  3032. {
  3033. assert(CommandSessionOpened);
  3034. assert(FCommandSession->FSProtocol == cfsSCP);
  3035. LogEvent(L"Executing custom command on command session.");
  3036. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3037. {
  3038. FCommandSession->CurrentDirectory = CurrentDirectory;
  3039. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3040. // until transaction ends. But we need to know CurrentDirectory to
  3041. // expand !/ pattern.
  3042. // Doing this only, when current directory of the main and secondary shell differs,
  3043. // what would be the case before the first file in transaction.
  3044. // Otherwise we would be reading pwd before every time as the
  3045. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3046. if (FCommandSession->FReadCurrentDirectoryPending)
  3047. {
  3048. FCommandSession->ReadCurrentDirectory();
  3049. }
  3050. }
  3051. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3052. Params, OutputEvent);
  3053. }
  3054. }
  3055. catch(Exception & E)
  3056. {
  3057. COMMAND_ERROR_ARI
  3058. (
  3059. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  3060. DoCustomCommandOnFile(FileName, File, Command, Params, OutputEvent)
  3061. );
  3062. }
  3063. }
  3064. //---------------------------------------------------------------------------
  3065. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3066. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3067. {
  3068. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3069. {
  3070. TCustomCommandParams AParams;
  3071. AParams.Command = Command;
  3072. AParams.Params = Params;
  3073. AParams.OutputEvent = OutputEvent;
  3074. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3075. }
  3076. else
  3077. {
  3078. UnicodeString FileList;
  3079. for (int i = 0; i < Files->Count; i++)
  3080. {
  3081. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3082. bool Dir = File->IsDirectory && !File->IsSymLink;
  3083. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3084. {
  3085. if (!FileList.IsEmpty())
  3086. {
  3087. FileList += L" ";
  3088. }
  3089. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3090. }
  3091. }
  3092. TCustomCommandData Data(this);
  3093. UnicodeString Cmd =
  3094. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3095. Complete(Command, true);
  3096. DoAnyCommand(Cmd, OutputEvent, NULL);
  3097. }
  3098. }
  3099. //---------------------------------------------------------------------------
  3100. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3101. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3102. {
  3103. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3104. assert(RProperties && !RProperties->Valid.Empty());
  3105. if (FileName.IsEmpty() && File)
  3106. {
  3107. FileName = File->FileName;
  3108. }
  3109. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  3110. {
  3111. if (OperationProgress->Cancel != csContinue) Abort();
  3112. OperationProgress->SetFile(FileName);
  3113. }
  3114. if (Log->Logging)
  3115. {
  3116. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3117. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3118. if (RProperties->Valid.Contains(vpRights))
  3119. {
  3120. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3121. }
  3122. if (RProperties->Valid.Contains(vpGroup))
  3123. {
  3124. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3125. }
  3126. if (RProperties->Valid.Contains(vpOwner))
  3127. {
  3128. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3129. }
  3130. if (RProperties->Valid.Contains(vpModification))
  3131. {
  3132. LogEvent(FORMAT(L" - modification: \"%s\"",
  3133. (FormatDateTime(L"dddddd tt",
  3134. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3135. }
  3136. if (RProperties->Valid.Contains(vpLastAccess))
  3137. {
  3138. LogEvent(FORMAT(L" - last access: \"%s\"",
  3139. (FormatDateTime(L"dddddd tt",
  3140. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3141. }
  3142. }
  3143. FileModified(File, FileName);
  3144. DoChangeFileProperties(FileName, File, RProperties);
  3145. ReactOnCommand(fsChangeProperties);
  3146. }
  3147. //---------------------------------------------------------------------------
  3148. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3149. const TRemoteFile * File, const TRemoteProperties * Properties)
  3150. {
  3151. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3152. try
  3153. {
  3154. assert(FFileSystem);
  3155. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3156. }
  3157. catch(Exception & E)
  3158. {
  3159. COMMAND_ERROR_ARI_ACTION
  3160. (
  3161. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  3162. DoChangeFileProperties(FileName, File, Properties),
  3163. Action
  3164. );
  3165. }
  3166. }
  3167. //---------------------------------------------------------------------------
  3168. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3169. const TRemoteProperties * Properties)
  3170. {
  3171. AnnounceFileListOperation();
  3172. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3173. }
  3174. //---------------------------------------------------------------------------
  3175. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3176. {
  3177. // see comment in TSFTPFileSystem::IsCapable
  3178. bool Result =
  3179. IsCapable[fcLoadingAdditionalProperties] &&
  3180. FFileSystem->LoadFilesProperties(FileList);
  3181. if (Result && SessionData->CacheDirectories &&
  3182. (FileList->Count > 0) &&
  3183. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3184. {
  3185. AddCachedFileList(FFiles);
  3186. }
  3187. return Result;
  3188. }
  3189. //---------------------------------------------------------------------------
  3190. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3191. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3192. {
  3193. assert(Param);
  3194. assert(File);
  3195. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3196. if (FileName.IsEmpty())
  3197. {
  3198. FileName = File->FileName;
  3199. }
  3200. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  3201. {
  3202. if (OperationProgress->Cancel != csContinue) Abort();
  3203. OperationProgress->SetFile(FileName);
  3204. }
  3205. bool AllowTransfer = (AParams->CopyParam == NULL);
  3206. if (!AllowTransfer)
  3207. {
  3208. TFileMasks::TParams MaskParams;
  3209. MaskParams.Size = File->Size;
  3210. MaskParams.Modification = File->Modification;
  3211. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3212. UnixExcludeTrailingBackslash(File->FullFileName), osRemote, File->IsDirectory,
  3213. MaskParams);
  3214. }
  3215. if (AllowTransfer)
  3216. {
  3217. if (File->IsDirectory)
  3218. {
  3219. if (!File->IsSymLink)
  3220. {
  3221. if (!AParams->AllowDirs)
  3222. {
  3223. AParams->Result = false;
  3224. }
  3225. else
  3226. {
  3227. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3228. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3229. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3230. }
  3231. }
  3232. else
  3233. {
  3234. AParams->Size += File->Size;
  3235. }
  3236. if (AParams->Stats != NULL)
  3237. {
  3238. AParams->Stats->Directories++;
  3239. }
  3240. }
  3241. else
  3242. {
  3243. AParams->Size += File->Size;
  3244. if (AParams->Stats != NULL)
  3245. {
  3246. AParams->Stats->Files++;
  3247. }
  3248. }
  3249. if ((AParams->Stats != NULL) && File->IsSymLink)
  3250. {
  3251. AParams->Stats->SymLinks++;
  3252. }
  3253. }
  3254. }
  3255. //---------------------------------------------------------------------------
  3256. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3257. const TRemoteFile * File, TCalculateSizeParams * Params)
  3258. {
  3259. try
  3260. {
  3261. ProcessDirectory(FileName, CalculateFileSize, Params);
  3262. }
  3263. catch(Exception & E)
  3264. {
  3265. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3266. {
  3267. COMMAND_ERROR_ARI
  3268. (
  3269. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  3270. DoCalculateDirectorySize(FileName, File, Params)
  3271. );
  3272. }
  3273. }
  3274. }
  3275. //---------------------------------------------------------------------------
  3276. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3277. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3278. bool AllowDirs, TCalculateSizeStats * Stats)
  3279. {
  3280. TCalculateSizeParams Param;
  3281. Param.Size = 0;
  3282. Param.Params = Params;
  3283. Param.CopyParam = CopyParam;
  3284. Param.Stats = Stats;
  3285. Param.AllowDirs = AllowDirs;
  3286. Param.Result = true;
  3287. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3288. Size = Param.Size;
  3289. return Param.Result;
  3290. }
  3291. //---------------------------------------------------------------------------
  3292. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3293. TStrings * FileList, TStrings * Checksums,
  3294. TCalculatedChecksumEvent OnCalculatedChecksum)
  3295. {
  3296. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3297. }
  3298. //---------------------------------------------------------------------------
  3299. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3300. const UnicodeString NewName)
  3301. {
  3302. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3303. DoRenameFile(FileName, NewName, false);
  3304. ReactOnCommand(fsRenameFile);
  3305. }
  3306. //---------------------------------------------------------------------------
  3307. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3308. const UnicodeString NewName, bool CheckExistence)
  3309. {
  3310. assert(File && File->Directory == FFiles);
  3311. bool Proceed = true;
  3312. // if filename doesn't contain path, we check for existence of file
  3313. if ((File->FileName != NewName) && CheckExistence &&
  3314. Configuration->ConfirmOverwriting &&
  3315. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3316. {
  3317. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3318. if (DuplicateFile)
  3319. {
  3320. UnicodeString QuestionFmt;
  3321. if (DuplicateFile->IsDirectory)
  3322. {
  3323. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3324. }
  3325. else
  3326. {
  3327. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3328. }
  3329. TQueryParams Params(qpNeverAskAgainCheck);
  3330. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3331. unsigned int Result = QueryUser(Question, NULL,
  3332. qaYes | qaNo, &Params);
  3333. if (Result == qaNeverAskAgain)
  3334. {
  3335. Proceed = true;
  3336. Configuration->ConfirmOverwriting = false;
  3337. }
  3338. else
  3339. {
  3340. Proceed = (Result == qaYes);
  3341. }
  3342. }
  3343. }
  3344. if (Proceed)
  3345. {
  3346. FileModified(File, File->FileName);
  3347. RenameFile(File->FileName, NewName);
  3348. }
  3349. }
  3350. //---------------------------------------------------------------------------
  3351. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3352. const UnicodeString NewName, bool Move)
  3353. {
  3354. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3355. try
  3356. {
  3357. assert(FFileSystem);
  3358. FFileSystem->RenameFile(FileName, NewName);
  3359. }
  3360. catch(Exception & E)
  3361. {
  3362. COMMAND_ERROR_ARI_ACTION
  3363. (
  3364. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  3365. DoRenameFile(FileName, NewName, Move),
  3366. Action
  3367. );
  3368. }
  3369. }
  3370. //---------------------------------------------------------------------------
  3371. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3372. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3373. {
  3374. if (OperationProgress &&
  3375. ((OperationProgress->Operation == foRemoteMove) ||
  3376. (OperationProgress->Operation == foDelete)))
  3377. {
  3378. if (OperationProgress->Cancel != csContinue) Abort();
  3379. OperationProgress->SetFile(FileName);
  3380. }
  3381. assert(Param != NULL);
  3382. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3383. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3384. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3385. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3386. FileModified(File, FileName);
  3387. DoRenameFile(FileName, NewName, true);
  3388. ReactOnCommand(fsMoveFile);
  3389. }
  3390. //---------------------------------------------------------------------------
  3391. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3392. const UnicodeString FileMask)
  3393. {
  3394. TMoveFileParams Params;
  3395. Params.Target = Target;
  3396. Params.FileMask = FileMask;
  3397. DirectoryModified(Target, true);
  3398. bool Result;
  3399. BeginTransaction();
  3400. try
  3401. {
  3402. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3403. }
  3404. __finally
  3405. {
  3406. if (Active)
  3407. {
  3408. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3409. bool PossiblyMoved = false;
  3410. // check if we was moving current directory.
  3411. // this is just optimization to avoid checking existence of current
  3412. // directory after each move operation.
  3413. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3414. {
  3415. const TRemoteFile * File =
  3416. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3417. // File can be NULL, and filename may not be full path,
  3418. // but currently this is the only way we can move (at least in GUI)
  3419. // current directory
  3420. if ((File != NULL) &&
  3421. File->IsDirectory &&
  3422. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3423. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3424. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3425. {
  3426. PossiblyMoved = true;
  3427. }
  3428. }
  3429. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3430. {
  3431. UnicodeString NearestExisting = CurrentDirectory;
  3432. do
  3433. {
  3434. NearestExisting = UnixExtractFileDir(NearestExisting);
  3435. }
  3436. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3437. ChangeDirectory(NearestExisting);
  3438. }
  3439. }
  3440. EndTransaction();
  3441. }
  3442. return Result;
  3443. }
  3444. //---------------------------------------------------------------------------
  3445. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3446. const UnicodeString NewName)
  3447. {
  3448. try
  3449. {
  3450. assert(FFileSystem);
  3451. if (IsCapable[fcRemoteCopy])
  3452. {
  3453. FFileSystem->CopyFile(FileName, NewName);
  3454. }
  3455. else
  3456. {
  3457. assert(CommandSessionOpened);
  3458. assert(FCommandSession->FSProtocol == cfsSCP);
  3459. LogEvent(L"Copying file on command session.");
  3460. FCommandSession->CurrentDirectory = CurrentDirectory;
  3461. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3462. }
  3463. }
  3464. catch(Exception & E)
  3465. {
  3466. COMMAND_ERROR_ARI
  3467. (
  3468. FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)),
  3469. DoCopyFile(FileName, NewName)
  3470. );
  3471. }
  3472. }
  3473. //---------------------------------------------------------------------------
  3474. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3475. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3476. {
  3477. if (OperationProgress && (OperationProgress->Operation == foRemoteCopy))
  3478. {
  3479. if (OperationProgress->Cancel != csContinue) Abort();
  3480. OperationProgress->SetFile(FileName);
  3481. }
  3482. assert(Param != NULL);
  3483. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3484. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3485. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3486. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3487. DoCopyFile(FileName, NewName);
  3488. ReactOnCommand(fsCopyFile);
  3489. }
  3490. //---------------------------------------------------------------------------
  3491. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3492. const UnicodeString FileMask)
  3493. {
  3494. TMoveFileParams Params;
  3495. Params.Target = Target;
  3496. Params.FileMask = FileMask;
  3497. DirectoryModified(Target, true);
  3498. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3499. }
  3500. //---------------------------------------------------------------------------
  3501. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3502. const TRemoteProperties * Properties)
  3503. {
  3504. assert(FFileSystem);
  3505. EnsureNonExistence(DirName);
  3506. FileModified(NULL, DirName);
  3507. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3508. DoCreateDirectory(DirName);
  3509. if ((Properties != NULL) && !Properties->Valid.Empty())
  3510. {
  3511. DoChangeFileProperties(DirName, NULL, Properties);
  3512. }
  3513. ReactOnCommand(fsCreateDirectory);
  3514. }
  3515. //---------------------------------------------------------------------------
  3516. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3517. {
  3518. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3519. try
  3520. {
  3521. assert(FFileSystem);
  3522. FFileSystem->CreateDirectory(DirName);
  3523. }
  3524. catch(Exception & E)
  3525. {
  3526. COMMAND_ERROR_ARI_ACTION
  3527. (
  3528. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  3529. DoCreateDirectory(DirName),
  3530. Action
  3531. );
  3532. }
  3533. }
  3534. //---------------------------------------------------------------------------
  3535. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3536. const UnicodeString PointTo, bool Symbolic)
  3537. {
  3538. assert(FFileSystem);
  3539. EnsureNonExistence(FileName);
  3540. if (SessionData->CacheDirectories)
  3541. {
  3542. DirectoryModified(CurrentDirectory, false);
  3543. }
  3544. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3545. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3546. DoCreateLink(FileName, PointTo, Symbolic);
  3547. ReactOnCommand(fsCreateDirectory);
  3548. }
  3549. //---------------------------------------------------------------------------
  3550. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3551. const UnicodeString PointTo, bool Symbolic)
  3552. {
  3553. try
  3554. {
  3555. assert(FFileSystem);
  3556. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3557. }
  3558. catch(Exception & E)
  3559. {
  3560. COMMAND_ERROR_ARI
  3561. (
  3562. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  3563. DoCreateLink(FileName, PointTo, Symbolic);
  3564. );
  3565. }
  3566. }
  3567. //---------------------------------------------------------------------------
  3568. void __fastcall TTerminal::HomeDirectory()
  3569. {
  3570. assert(FFileSystem);
  3571. try
  3572. {
  3573. LogEvent(L"Changing directory to home directory.");
  3574. FFileSystem->HomeDirectory();
  3575. ReactOnCommand(fsHomeDirectory);
  3576. }
  3577. catch (Exception &E)
  3578. {
  3579. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3580. }
  3581. }
  3582. //---------------------------------------------------------------------------
  3583. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3584. {
  3585. assert(FFileSystem);
  3586. try
  3587. {
  3588. UnicodeString CachedDirectory;
  3589. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3590. // never use directory change cache during startup, this ensures, we never
  3591. // end-up initially in non-existing directory
  3592. if ((Status == ssOpened) &&
  3593. SessionData->CacheDirectoryChanges &&
  3594. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3595. Directory, CachedDirectory))
  3596. {
  3597. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3598. (Directory, CachedDirectory)));
  3599. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3600. }
  3601. else
  3602. {
  3603. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3604. FFileSystem->ChangeDirectory(Directory);
  3605. }
  3606. FLastDirectoryChange = Directory;
  3607. ReactOnCommand(fsChangeDirectory);
  3608. }
  3609. catch (Exception &E)
  3610. {
  3611. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3612. }
  3613. }
  3614. //---------------------------------------------------------------------------
  3615. void __fastcall TTerminal::LookupUsersGroups()
  3616. {
  3617. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3618. IsCapable[fcUserGroupListing])
  3619. {
  3620. assert(FFileSystem);
  3621. try
  3622. {
  3623. FUsersGroupsLookedup = true;
  3624. LogEvent(L"Looking up groups and users.");
  3625. FFileSystem->LookupUsersGroups();
  3626. ReactOnCommand(fsLookupUsersGroups);
  3627. if (Log->Logging)
  3628. {
  3629. FGroups.Log(this, L"groups");
  3630. FMembership.Log(this, L"membership");
  3631. FUsers.Log(this, L"users");
  3632. }
  3633. }
  3634. catch (Exception &E)
  3635. {
  3636. if (!Active || (SessionData->LookupUserGroups == asOn))
  3637. {
  3638. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3639. }
  3640. }
  3641. }
  3642. }
  3643. //---------------------------------------------------------------------------
  3644. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3645. {
  3646. return !Command.Trim().IsEmpty();
  3647. }
  3648. //---------------------------------------------------------------------------
  3649. bool __fastcall TTerminal::GetCommandSessionOpened()
  3650. {
  3651. // consider secondary terminal open in "ready" state only
  3652. // so we never do keepalives on it until it is completely initialized
  3653. return (FCommandSession != NULL) &&
  3654. (FCommandSession->Status == ssOpened);
  3655. }
  3656. //---------------------------------------------------------------------------
  3657. TTerminal * __fastcall TTerminal::GetCommandSession()
  3658. {
  3659. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3660. {
  3661. SAFE_DESTROY(FCommandSession);
  3662. }
  3663. if (FCommandSession == NULL)
  3664. {
  3665. // transaction cannot be started yet to allow proper matching transaction
  3666. // levels between main and command session
  3667. assert(FInTransaction == 0);
  3668. try
  3669. {
  3670. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3671. Configuration, L"Shell");
  3672. FCommandSession->AutoReadDirectory = false;
  3673. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3674. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3675. CommandSessionData->FSProtocol = fsSCPonly;
  3676. CommandSessionData->ClearAliases = false;
  3677. CommandSessionData->UnsetNationalVars = false;
  3678. CommandSessionData->LookupUserGroups = asOff;
  3679. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3680. FCommandSession->OnQueryUser = OnQueryUser;
  3681. FCommandSession->OnPromptUser = OnPromptUser;
  3682. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3683. FCommandSession->OnProgress = OnProgress;
  3684. FCommandSession->OnFinished = OnFinished;
  3685. FCommandSession->OnInformation = OnInformation;
  3686. // do not copy OnDisplayBanner to avoid it being displayed
  3687. }
  3688. catch(...)
  3689. {
  3690. SAFE_DESTROY(FCommandSession);
  3691. throw;
  3692. }
  3693. }
  3694. return FCommandSession;
  3695. }
  3696. //---------------------------------------------------------------------------
  3697. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3698. TCaptureOutputEvent OutputEvent)
  3699. {
  3700. class TOutputProxy
  3701. {
  3702. public:
  3703. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3704. FAction(Action),
  3705. FOutputEvent(OutputEvent)
  3706. {
  3707. }
  3708. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  3709. {
  3710. switch (OutputType)
  3711. {
  3712. case cotOutput:
  3713. FAction.AddOutput(Str, false);
  3714. break;
  3715. case cotError:
  3716. FAction.AddOutput(Str, true);
  3717. break;
  3718. case cotExitCode:
  3719. FAction.AddExitCode(StrToInt(Str));
  3720. break;
  3721. }
  3722. if (FOutputEvent != NULL)
  3723. {
  3724. FOutputEvent(Str, OutputType);
  3725. }
  3726. }
  3727. private:
  3728. TCallSessionAction & FAction;
  3729. TCaptureOutputEvent FOutputEvent;
  3730. };
  3731. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3732. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3733. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3734. }
  3735. //---------------------------------------------------------------------------
  3736. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3737. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3738. {
  3739. assert(FFileSystem);
  3740. try
  3741. {
  3742. DirectoryModified(CurrentDirectory, false);
  3743. if (IsCapable[fcAnyCommand])
  3744. {
  3745. LogEvent(L"Executing user defined command.");
  3746. FFileSystem->AnyCommand(Command, OutputEvent);
  3747. }
  3748. else
  3749. {
  3750. assert(CommandSessionOpened);
  3751. assert(FCommandSession->FSProtocol == cfsSCP);
  3752. LogEvent(L"Executing user defined command on command session.");
  3753. FCommandSession->CurrentDirectory = CurrentDirectory;
  3754. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3755. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3756. // synchronize pwd (by purpose we lose transaction optimization here)
  3757. ChangeDirectory(FCommandSession->CurrentDirectory);
  3758. }
  3759. ReactOnCommand(fsAnyCommand);
  3760. }
  3761. catch (Exception &E)
  3762. {
  3763. if (Action != NULL)
  3764. {
  3765. RollbackAction(*Action, NULL, &E);
  3766. }
  3767. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3768. else HandleExtendedException(&E);
  3769. }
  3770. }
  3771. //---------------------------------------------------------------------------
  3772. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3773. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3774. bool NoConfirmation)
  3775. {
  3776. bool Result = true;
  3777. bool Done;
  3778. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  3779. do
  3780. {
  3781. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  3782. NULL, CREATE_ALWAYS, CreateAttr, 0);
  3783. Done = (*AHandle != INVALID_HANDLE_VALUE);
  3784. if (!Done)
  3785. {
  3786. // save the error, otherwise it gets overwritten by call to FileExists
  3787. int LastError = GetLastError();
  3788. int FileAttr;
  3789. if (::FileExists(ApiPath(FileName)) &&
  3790. (((FileAttr = FileGetAttr(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  3791. {
  3792. if (FLAGSET(FileAttr, faReadOnly))
  3793. {
  3794. if (OperationProgress->BatchOverwrite == boNone)
  3795. {
  3796. Result = false;
  3797. }
  3798. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  3799. {
  3800. unsigned int Answer;
  3801. {
  3802. TSuspendFileOperationProgress Suspend(OperationProgress);
  3803. Answer = QueryUser(
  3804. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  3805. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  3806. }
  3807. switch (Answer) {
  3808. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  3809. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  3810. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  3811. case qaNo: Result = false; break;
  3812. }
  3813. }
  3814. }
  3815. else
  3816. {
  3817. assert(FLAGSET(FileAttr, faHidden));
  3818. Result = true;
  3819. }
  3820. if (Result)
  3821. {
  3822. CreateAttr |=
  3823. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  3824. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  3825. FILE_OPERATION_LOOP_BEGIN
  3826. {
  3827. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  3828. {
  3829. RaiseLastOSError();
  3830. }
  3831. }
  3832. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  3833. }
  3834. else
  3835. {
  3836. Done = true;
  3837. }
  3838. }
  3839. else
  3840. {
  3841. RaiseLastOSError(LastError);
  3842. }
  3843. }
  3844. }
  3845. while (!Done);
  3846. return Result;
  3847. }
  3848. //---------------------------------------------------------------------------
  3849. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  3850. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3851. bool NoConfirmation)
  3852. {
  3853. assert(AHandle);
  3854. bool Result = true;
  3855. FILE_OPERATION_LOOP_BEGIN
  3856. {
  3857. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  3858. }
  3859. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  3860. return Result;
  3861. }
  3862. //---------------------------------------------------------------------------
  3863. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  3864. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  3865. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  3866. bool TryWriteReadOnly)
  3867. {
  3868. int Attrs = 0;
  3869. HANDLE Handle = 0;
  3870. FILE_OPERATION_LOOP_BEGIN
  3871. {
  3872. Attrs = FileGetAttr(ApiPath(FileName));
  3873. if (Attrs < 0) RaiseLastOSError();
  3874. }
  3875. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  3876. if ((Attrs & faDirectory) == 0)
  3877. {
  3878. bool NoHandle = false;
  3879. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  3880. ((Attrs & faReadOnly) != 0))
  3881. {
  3882. Access = GENERIC_READ;
  3883. NoHandle = true;
  3884. }
  3885. FILE_OPERATION_LOOP_BEGIN
  3886. {
  3887. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  3888. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  3889. NULL, OPEN_EXISTING, 0, 0);
  3890. if (Handle == INVALID_HANDLE_VALUE)
  3891. {
  3892. Handle = 0;
  3893. RaiseLastOSError();
  3894. }
  3895. }
  3896. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  3897. try
  3898. {
  3899. if (AATime || AMTime || ACTime)
  3900. {
  3901. FILETIME ATime;
  3902. FILETIME MTime;
  3903. FILETIME CTime;
  3904. // Get last file access and modification time
  3905. FILE_OPERATION_LOOP_BEGIN
  3906. {
  3907. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  3908. }
  3909. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3910. if (ACTime)
  3911. {
  3912. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  3913. }
  3914. if (AATime)
  3915. {
  3916. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  3917. }
  3918. if (AMTime)
  3919. {
  3920. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  3921. }
  3922. }
  3923. if (ASize)
  3924. {
  3925. // Get file size
  3926. FILE_OPERATION_LOOP_BEGIN
  3927. {
  3928. unsigned long LSize;
  3929. unsigned long HSize;
  3930. LSize = GetFileSize(Handle, &HSize);
  3931. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  3932. *ASize = (__int64(HSize) << 32) + LSize;
  3933. }
  3934. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3935. }
  3936. if ((AHandle == NULL) || NoHandle)
  3937. {
  3938. CloseHandle(Handle);
  3939. Handle = NULL;
  3940. }
  3941. }
  3942. catch(...)
  3943. {
  3944. CloseHandle(Handle);
  3945. throw;
  3946. }
  3947. }
  3948. if (AAttrs) *AAttrs = Attrs;
  3949. if (AHandle) *AHandle = Handle;
  3950. }
  3951. //---------------------------------------------------------------------------
  3952. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  3953. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  3954. {
  3955. bool Result = true;
  3956. // optimization
  3957. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  3958. {
  3959. WIN32_FIND_DATA FindData;
  3960. HANDLE Handle;
  3961. FILE_OPERATION_LOOP_BEGIN
  3962. {
  3963. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  3964. if (Handle == INVALID_HANDLE_VALUE)
  3965. {
  3966. RaiseLastOSError();
  3967. }
  3968. }
  3969. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  3970. ::FindClose(Handle);
  3971. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  3972. TFileMasks::TParams Params;
  3973. // SearchRec.Size in C++B2010 is __int64,
  3974. // so we should be able to use it instead of FindData.nFileSize*
  3975. Params.Size =
  3976. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  3977. FindData.nFileSizeLow;
  3978. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  3979. if (!CopyParam->AllowTransfer(FileName, osLocal, Directory, Params))
  3980. {
  3981. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  3982. Result = false;
  3983. }
  3984. else if (CopyParam->SkipTransfer(FileName, Directory))
  3985. {
  3986. OperationProgress->AddSkippedFileSize(Params.Size);
  3987. Result = false;
  3988. }
  3989. if (Result)
  3990. {
  3991. LogFileDetails(FileName, Params.Modification, Params.Size);
  3992. }
  3993. }
  3994. return Result;
  3995. }
  3996. //---------------------------------------------------------------------------
  3997. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  3998. const TSearchRec Rec, void * Param)
  3999. {
  4000. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4001. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4002. if (Directory && Params.Recursive)
  4003. {
  4004. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4005. }
  4006. if (!Directory || Params.IncludeDirs)
  4007. {
  4008. Params.FileList->Add(FileName);
  4009. if (Params.FileTimes != NULL)
  4010. {
  4011. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4012. }
  4013. }
  4014. }
  4015. //---------------------------------------------------------------------------
  4016. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4017. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4018. {
  4019. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4020. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4021. bool AllowTransfer = (AParams->CopyParam == NULL);
  4022. // SearchRec.Size in C++B2010 is __int64,
  4023. // so we should be able to use it instead of FindData.nFileSize*
  4024. __int64 Size =
  4025. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4026. Rec.FindData.nFileSizeLow;
  4027. if (!AllowTransfer)
  4028. {
  4029. TFileMasks::TParams MaskParams;
  4030. MaskParams.Size = Size;
  4031. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4032. AllowTransfer = AParams->CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams);
  4033. }
  4034. if (AllowTransfer)
  4035. {
  4036. if (!Dir)
  4037. {
  4038. AParams->Size += Size;
  4039. }
  4040. else
  4041. {
  4042. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4043. }
  4044. }
  4045. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  4046. {
  4047. if (OperationProgress->Cancel != csContinue) Abort();
  4048. OperationProgress->SetFile(FileName);
  4049. }
  4050. }
  4051. //---------------------------------------------------------------------------
  4052. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4053. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  4054. {
  4055. bool Result = true;
  4056. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4057. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4058. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4059. try
  4060. {
  4061. TCalculateSizeParams Params;
  4062. Params.Size = 0;
  4063. Params.Params = 0;
  4064. Params.CopyParam = CopyParam;
  4065. assert(!FOperationProgress);
  4066. FOperationProgress = &OperationProgress;
  4067. for (int Index = 0; Result && (Index < FileList->Count); Index++)
  4068. {
  4069. UnicodeString FileName = FileList->Strings[Index];
  4070. TSearchRec Rec;
  4071. if (FileSearchRec(FileName, Rec))
  4072. {
  4073. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4074. {
  4075. Result = false;
  4076. }
  4077. else
  4078. {
  4079. CalculateLocalFileSize(FileName, Rec, &Params);
  4080. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4081. }
  4082. }
  4083. }
  4084. Size = Params.Size;
  4085. }
  4086. __finally
  4087. {
  4088. FOperationProgress = NULL;
  4089. OperationProgress.Stop();
  4090. }
  4091. if (OnceDoneOperation != odoIdle)
  4092. {
  4093. CloseOnCompletion(OnceDoneOperation);
  4094. }
  4095. return Result;
  4096. }
  4097. //---------------------------------------------------------------------------
  4098. struct TSynchronizeFileData
  4099. {
  4100. bool Modified;
  4101. bool New;
  4102. bool IsDirectory;
  4103. TSynchronizeChecklist::TItem::TFileInfo Info;
  4104. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4105. TRemoteFile * MatchingRemoteFileFile;
  4106. int MatchingRemoteFileImageIndex;
  4107. FILETIME LocalLastWriteTime;
  4108. };
  4109. //---------------------------------------------------------------------------
  4110. const int sfFirstLevel = 0x01;
  4111. struct TSynchronizeData
  4112. {
  4113. UnicodeString LocalDirectory;
  4114. UnicodeString RemoteDirectory;
  4115. TTerminal::TSynchronizeMode Mode;
  4116. int Params;
  4117. TSynchronizeDirectory OnSynchronizeDirectory;
  4118. TSynchronizeOptions * Options;
  4119. int Flags;
  4120. TStringList * LocalFileList;
  4121. const TCopyParamType * CopyParam;
  4122. TSynchronizeChecklist * Checklist;
  4123. };
  4124. //---------------------------------------------------------------------------
  4125. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4126. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4127. const TCopyParamType * CopyParam, int Params,
  4128. TSynchronizeDirectory OnSynchronizeDirectory,
  4129. TSynchronizeOptions * Options)
  4130. {
  4131. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4132. try
  4133. {
  4134. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4135. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4136. Checklist);
  4137. Checklist->Sort();
  4138. }
  4139. catch(...)
  4140. {
  4141. delete Checklist;
  4142. throw;
  4143. }
  4144. return Checklist;
  4145. }
  4146. //---------------------------------------------------------------------------
  4147. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4148. {
  4149. if (FLAGSET(Params, Param))
  4150. {
  4151. AddToList(ParamsStr, Name, ", ");
  4152. }
  4153. Params &= ~Param;
  4154. }
  4155. //---------------------------------------------------------------------------
  4156. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4157. {
  4158. UnicodeString ModeStr;
  4159. switch (Mode)
  4160. {
  4161. case smRemote:
  4162. ModeStr = L"Remote";
  4163. break;
  4164. case smLocal:
  4165. ModeStr = L"Local";
  4166. break;
  4167. case smBoth:
  4168. ModeStr = L"Both";
  4169. break;
  4170. default:
  4171. ModeStr = L"Unknown";
  4172. break;
  4173. }
  4174. return ModeStr;
  4175. }
  4176. //---------------------------------------------------------------------------
  4177. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4178. {
  4179. UnicodeString ParamsStr;
  4180. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4181. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4182. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4183. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4184. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4185. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4186. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4187. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4188. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4189. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4190. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4191. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4192. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4193. if (Params > 0)
  4194. {
  4195. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4196. }
  4197. return ParamsStr;
  4198. }
  4199. //---------------------------------------------------------------------------
  4200. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4201. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4202. const TCopyParamType * CopyParam, int Params,
  4203. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4204. int Flags, TSynchronizeChecklist * Checklist)
  4205. {
  4206. TSynchronizeData Data;
  4207. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4208. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4209. Data.Mode = Mode;
  4210. Data.Params = Params;
  4211. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4212. Data.LocalFileList = NULL;
  4213. Data.CopyParam = CopyParam;
  4214. Data.Options = Options;
  4215. Data.Flags = Flags;
  4216. Data.Checklist = Checklist;
  4217. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4218. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4219. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4220. if (FLAGCLEAR(Params, spDelayProgress))
  4221. {
  4222. DoSynchronizeProgress(Data, true);
  4223. }
  4224. try
  4225. {
  4226. bool Found;
  4227. TSearchRecChecked SearchRec;
  4228. Data.LocalFileList = new TStringList();
  4229. Data.LocalFileList->Sorted = true;
  4230. Data.LocalFileList->CaseSensitive = false;
  4231. FILE_OPERATION_LOOP_BEGIN
  4232. {
  4233. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4234. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4235. }
  4236. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4237. if (Found)
  4238. {
  4239. try
  4240. {
  4241. UnicodeString FileName;
  4242. while (Found)
  4243. {
  4244. FileName = SearchRec.Name;
  4245. // add dirs for recursive mode or when we are interested in newly
  4246. // added subdirs
  4247. // SearchRec.Size in C++B2010 is __int64,
  4248. // so we should be able to use it instead of FindData.nFileSize*
  4249. __int64 Size =
  4250. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4251. SearchRec.FindData.nFileSizeLow;
  4252. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4253. TFileMasks::TParams MaskParams;
  4254. MaskParams.Size = Size;
  4255. MaskParams.Modification = Modification;
  4256. UnicodeString RemoteFileName =
  4257. CopyParam->ChangeFileName(FileName, osLocal, false);
  4258. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4259. if ((FileName != L".") && (FileName != L"..") &&
  4260. CopyParam->AllowTransfer(FullLocalFileName, osLocal,
  4261. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4262. !FFileSystem->TemporaryTransferFile(FileName) &&
  4263. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4264. (Options == NULL) ||
  4265. Options->MatchesFilter(FileName) ||
  4266. Options->MatchesFilter(RemoteFileName)))
  4267. {
  4268. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4269. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4270. FileData->Info.FileName = FileName;
  4271. FileData->Info.Directory = Data.LocalDirectory;
  4272. FileData->Info.Modification = Modification;
  4273. FileData->Info.ModificationFmt = mfFull;
  4274. FileData->Info.Size = Size;
  4275. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4276. FileData->New = true;
  4277. FileData->Modified = false;
  4278. Data.LocalFileList->AddObject(FileName,
  4279. reinterpret_cast<TObject*>(FileData));
  4280. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4281. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4282. }
  4283. else
  4284. {
  4285. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4286. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4287. }
  4288. FILE_OPERATION_LOOP_BEGIN
  4289. {
  4290. Found = (FindNextChecked(SearchRec) == 0);
  4291. }
  4292. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4293. }
  4294. }
  4295. __finally
  4296. {
  4297. FindClose(SearchRec);
  4298. }
  4299. // can we expect that ProcessDirectory would take so little time
  4300. // that we can postpone showing progress window until anything actually happens?
  4301. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4302. FDirectoryCache->HasFileList(RemoteDirectory);
  4303. if (!Cached && FLAGSET(Params, spDelayProgress))
  4304. {
  4305. DoSynchronizeProgress(Data, true);
  4306. }
  4307. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4308. FLAGSET(Params, spUseCache));
  4309. TSynchronizeFileData * FileData;
  4310. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4311. {
  4312. FileData = reinterpret_cast<TSynchronizeFileData *>
  4313. (Data.LocalFileList->Objects[Index]);
  4314. // add local file either if we are going to upload it
  4315. // (i.e. if it is updated or we want to upload even new files)
  4316. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4317. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4318. bool New = (FileData->New &&
  4319. ((Mode == smLocal) ||
  4320. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4321. if (New)
  4322. {
  4323. LogEvent(FORMAT(L"Local file %s is new",
  4324. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4325. FileData->Info.Modification, FileData->Info.Size))));
  4326. }
  4327. if (Modified || New)
  4328. {
  4329. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4330. try
  4331. {
  4332. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4333. ChecklistItem->Local = FileData->Info;
  4334. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4335. if (Modified)
  4336. {
  4337. assert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4338. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4339. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4340. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4341. }
  4342. else
  4343. {
  4344. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4345. }
  4346. if ((Mode == smBoth) || (Mode == smRemote))
  4347. {
  4348. ChecklistItem->Action =
  4349. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4350. ChecklistItem->Checked =
  4351. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4352. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4353. FLAGSET(Params, spSubDirs));
  4354. }
  4355. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4356. {
  4357. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4358. ChecklistItem->Checked =
  4359. FLAGSET(Params, spDelete) &&
  4360. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4361. FLAGSET(Params, spSubDirs));
  4362. }
  4363. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4364. {
  4365. Data.Checklist->Add(ChecklistItem);
  4366. ChecklistItem = NULL;
  4367. }
  4368. }
  4369. __finally
  4370. {
  4371. delete ChecklistItem;
  4372. }
  4373. }
  4374. else
  4375. {
  4376. if (FileData->Modified)
  4377. {
  4378. delete FileData->MatchingRemoteFileFile;
  4379. }
  4380. }
  4381. }
  4382. }
  4383. }
  4384. __finally
  4385. {
  4386. if (Data.LocalFileList != NULL)
  4387. {
  4388. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4389. {
  4390. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4391. (Data.LocalFileList->Objects[Index]);
  4392. delete FileData;
  4393. }
  4394. delete Data.LocalFileList;
  4395. }
  4396. }
  4397. }
  4398. //---------------------------------------------------------------------------
  4399. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4400. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4401. {
  4402. try
  4403. {
  4404. DoSynchronizeCollectFile(FileName, File, Param);
  4405. }
  4406. catch(EScpSkipFile & E)
  4407. {
  4408. TSuspendFileOperationProgress Suspend(OperationProgress);
  4409. if (!HandleException(&E))
  4410. {
  4411. throw;
  4412. }
  4413. }
  4414. }
  4415. //---------------------------------------------------------------------------
  4416. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4417. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4418. {
  4419. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4420. TFileMasks::TParams MaskParams;
  4421. MaskParams.Size = File->Size;
  4422. MaskParams.Modification = File->Modification;
  4423. UnicodeString LocalFileName =
  4424. Data->CopyParam->ChangeFileName(File->FileName, osRemote, false);
  4425. UnicodeString FullRemoteFileName =
  4426. UnixExcludeTrailingBackslash(File->FullFileName);
  4427. if (Data->CopyParam->AllowTransfer(
  4428. FullRemoteFileName, osRemote,
  4429. File->IsDirectory, MaskParams) &&
  4430. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4431. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4432. (Data->Options == NULL) ||
  4433. Data->Options->MatchesFilter(File->FileName) ||
  4434. Data->Options->MatchesFilter(LocalFileName)))
  4435. {
  4436. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4437. try
  4438. {
  4439. ChecklistItem->IsDirectory = File->IsDirectory;
  4440. ChecklistItem->ImageIndex = File->IconIndex;
  4441. ChecklistItem->Remote.FileName = File->FileName;
  4442. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4443. ChecklistItem->Remote.Modification = File->Modification;
  4444. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4445. ChecklistItem->Remote.Size = File->Size;
  4446. bool Modified = false;
  4447. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4448. bool New = (LocalIndex < 0);
  4449. if (!New)
  4450. {
  4451. TSynchronizeFileData * LocalData =
  4452. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4453. LocalData->New = false;
  4454. if (File->IsDirectory != LocalData->IsDirectory)
  4455. {
  4456. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4457. (File->FileName)));
  4458. }
  4459. else if (!File->IsDirectory)
  4460. {
  4461. ChecklistItem->Local = LocalData->Info;
  4462. ChecklistItem->Local.Modification =
  4463. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4464. bool LocalModified = false;
  4465. // for spTimestamp+spBySize require that the file sizes are the same
  4466. // before comparing file time
  4467. int TimeCompare;
  4468. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4469. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4470. FLAGCLEAR(Data->Params, spBySize) ||
  4471. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4472. {
  4473. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4474. ChecklistItem->Remote.Modification);
  4475. }
  4476. else
  4477. {
  4478. TimeCompare = 0;
  4479. }
  4480. if (TimeCompare < 0)
  4481. {
  4482. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4483. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4484. {
  4485. Modified = true;
  4486. }
  4487. else
  4488. {
  4489. LocalModified = true;
  4490. }
  4491. }
  4492. else if (TimeCompare > 0)
  4493. {
  4494. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4495. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4496. {
  4497. LocalModified = true;
  4498. }
  4499. else
  4500. {
  4501. Modified = true;
  4502. }
  4503. }
  4504. else if (FLAGSET(Data->Params, spBySize) &&
  4505. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4506. FLAGCLEAR(Data->Params, spTimestamp))
  4507. {
  4508. Modified = true;
  4509. LocalModified = true;
  4510. }
  4511. if (LocalModified)
  4512. {
  4513. LocalData->Modified = true;
  4514. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4515. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4516. // we need this for custom commands over checklist only,
  4517. // not for sync itself
  4518. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4519. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4520. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4521. LocalData->Info.Modification, LocalData->Info.Size),
  4522. FormatFileDetailsForLog(FullRemoteFileName,
  4523. File->Modification, File->Size))));
  4524. }
  4525. if (Modified)
  4526. {
  4527. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4528. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4529. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4530. LocalData->Info.Modification, LocalData->Info.Size))));
  4531. }
  4532. }
  4533. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4534. {
  4535. DoSynchronizeCollectDirectory(
  4536. Data->LocalDirectory + LocalData->Info.FileName,
  4537. Data->RemoteDirectory + File->FileName,
  4538. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4539. Data->Options, (Data->Flags & ~sfFirstLevel),
  4540. Data->Checklist);
  4541. }
  4542. }
  4543. else
  4544. {
  4545. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4546. LogEvent(FORMAT(L"Remote file %s is new",
  4547. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4548. }
  4549. if (New || Modified)
  4550. {
  4551. assert(!New || !Modified);
  4552. // download the file if it changed or is new and we want to have it locally
  4553. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4554. {
  4555. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4556. {
  4557. ChecklistItem->Action =
  4558. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4559. ChecklistItem->Checked =
  4560. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4561. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4562. FLAGSET(Data->Params, spSubDirs));
  4563. }
  4564. }
  4565. else if ((Data->Mode == smRemote) && New)
  4566. {
  4567. if (FLAGCLEAR(Data->Params, spTimestamp))
  4568. {
  4569. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4570. ChecklistItem->Checked =
  4571. FLAGSET(Data->Params, spDelete) &&
  4572. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4573. FLAGSET(Data->Params, spSubDirs));
  4574. }
  4575. }
  4576. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4577. {
  4578. ChecklistItem->RemoteFile = File->Duplicate();
  4579. Data->Checklist->Add(ChecklistItem);
  4580. ChecklistItem = NULL;
  4581. }
  4582. }
  4583. }
  4584. __finally
  4585. {
  4586. delete ChecklistItem;
  4587. }
  4588. }
  4589. else
  4590. {
  4591. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4592. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4593. }
  4594. }
  4595. //---------------------------------------------------------------------------
  4596. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4597. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4598. const TCopyParamType * CopyParam, int Params,
  4599. TSynchronizeDirectory OnSynchronizeDirectory)
  4600. {
  4601. TSynchronizeData Data;
  4602. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4603. int CopyParams =
  4604. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4605. TCopyParamType SyncCopyParam = *CopyParam;
  4606. // when synchronizing by time, we force preserving time,
  4607. // otherwise it does not make any sense
  4608. if (FLAGCLEAR(Params, spNotByTime))
  4609. {
  4610. SyncCopyParam.PreserveTime = true;
  4611. }
  4612. TStringList * DownloadList = new TStringList();
  4613. TStringList * DeleteRemoteList = new TStringList();
  4614. TStringList * UploadList = new TStringList();
  4615. TStringList * DeleteLocalList = new TStringList();
  4616. BeginTransaction();
  4617. try
  4618. {
  4619. int IIndex = 0;
  4620. while (IIndex < Checklist->Count)
  4621. {
  4622. const TSynchronizeChecklist::TItem * ChecklistItem;
  4623. DownloadList->Clear();
  4624. DeleteRemoteList->Clear();
  4625. UploadList->Clear();
  4626. DeleteLocalList->Clear();
  4627. ChecklistItem = Checklist->Item[IIndex];
  4628. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4629. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4630. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4631. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4632. int(Params), SynchronizeParamsStr(Params))));
  4633. int Count = 0;
  4634. while ((IIndex < Checklist->Count) &&
  4635. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4636. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4637. {
  4638. ChecklistItem = Checklist->Item[IIndex];
  4639. if (ChecklistItem->Checked)
  4640. {
  4641. Count++;
  4642. if (FLAGSET(Params, spTimestamp))
  4643. {
  4644. switch (ChecklistItem->Action)
  4645. {
  4646. case TSynchronizeChecklist::saDownloadUpdate:
  4647. DownloadList->AddObject(
  4648. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4649. ChecklistItem->Remote.FileName,
  4650. (TObject *)(ChecklistItem));
  4651. break;
  4652. case TSynchronizeChecklist::saUploadUpdate:
  4653. UploadList->AddObject(
  4654. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4655. ChecklistItem->Local.FileName,
  4656. (TObject *)(ChecklistItem));
  4657. break;
  4658. default:
  4659. FAIL;
  4660. break;
  4661. }
  4662. }
  4663. else
  4664. {
  4665. switch (ChecklistItem->Action)
  4666. {
  4667. case TSynchronizeChecklist::saDownloadNew:
  4668. case TSynchronizeChecklist::saDownloadUpdate:
  4669. DownloadList->AddObject(
  4670. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4671. ChecklistItem->Remote.FileName,
  4672. ChecklistItem->RemoteFile);
  4673. break;
  4674. case TSynchronizeChecklist::saDeleteRemote:
  4675. DeleteRemoteList->AddObject(
  4676. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4677. ChecklistItem->Remote.FileName,
  4678. ChecklistItem->RemoteFile);
  4679. break;
  4680. case TSynchronizeChecklist::saUploadNew:
  4681. case TSynchronizeChecklist::saUploadUpdate:
  4682. UploadList->Add(
  4683. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4684. ChecklistItem->Local.FileName);
  4685. break;
  4686. case TSynchronizeChecklist::saDeleteLocal:
  4687. DeleteLocalList->Add(
  4688. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4689. ChecklistItem->Local.FileName);
  4690. break;
  4691. default:
  4692. FAIL;
  4693. break;
  4694. }
  4695. }
  4696. }
  4697. IIndex++;
  4698. }
  4699. // prevent showing/updating of progress dialog if there's nothing to do
  4700. if (Count > 0)
  4701. {
  4702. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4703. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4704. DoSynchronizeProgress(Data, false);
  4705. if (FLAGSET(Params, spTimestamp))
  4706. {
  4707. if (DownloadList->Count > 0)
  4708. {
  4709. ProcessFiles(DownloadList, foSetProperties,
  4710. SynchronizeLocalTimestamp, NULL, osLocal);
  4711. }
  4712. if (UploadList->Count > 0)
  4713. {
  4714. ProcessFiles(UploadList, foSetProperties,
  4715. SynchronizeRemoteTimestamp);
  4716. }
  4717. }
  4718. else
  4719. {
  4720. if ((DownloadList->Count > 0) &&
  4721. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4722. {
  4723. Abort();
  4724. }
  4725. if ((DeleteRemoteList->Count > 0) &&
  4726. !DeleteFiles(DeleteRemoteList))
  4727. {
  4728. Abort();
  4729. }
  4730. if ((UploadList->Count > 0) &&
  4731. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4732. {
  4733. Abort();
  4734. }
  4735. if ((DeleteLocalList->Count > 0) &&
  4736. !DeleteLocalFiles(DeleteLocalList))
  4737. {
  4738. Abort();
  4739. }
  4740. }
  4741. }
  4742. }
  4743. }
  4744. __finally
  4745. {
  4746. delete DownloadList;
  4747. delete DeleteRemoteList;
  4748. delete UploadList;
  4749. delete DeleteLocalList;
  4750. EndTransaction();
  4751. }
  4752. }
  4753. //---------------------------------------------------------------------------
  4754. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4755. bool Collect)
  4756. {
  4757. if (Data.OnSynchronizeDirectory != NULL)
  4758. {
  4759. bool Continue = true;
  4760. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  4761. Continue, Collect);
  4762. if (!Continue)
  4763. {
  4764. Abort();
  4765. }
  4766. }
  4767. }
  4768. //---------------------------------------------------------------------------
  4769. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  4770. const TRemoteFile * File, void * /*Param*/)
  4771. {
  4772. const TSynchronizeChecklist::TItem * ChecklistItem =
  4773. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4774. UnicodeString LocalFile =
  4775. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4776. ChecklistItem->Local.FileName;
  4777. FILE_OPERATION_LOOP_BEGIN
  4778. {
  4779. HANDLE Handle;
  4780. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  4781. NULL, NULL, NULL, NULL);
  4782. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  4783. SessionData->DSTMode);
  4784. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  4785. int Error = GetLastError();
  4786. CloseHandle(Handle);
  4787. if (!Result)
  4788. {
  4789. RaiseLastOSError(Error);
  4790. }
  4791. }
  4792. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  4793. }
  4794. //---------------------------------------------------------------------------
  4795. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  4796. const TRemoteFile * File, void * /*Param*/)
  4797. {
  4798. const TSynchronizeChecklist::TItem * ChecklistItem =
  4799. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4800. TRemoteProperties Properties;
  4801. Properties.Valid << vpModification;
  4802. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  4803. SessionData->DSTMode);
  4804. ChangeFileProperties(
  4805. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  4806. NULL, &Properties);
  4807. }
  4808. //---------------------------------------------------------------------------
  4809. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  4810. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  4811. {
  4812. // see DoFilesFind
  4813. FOnFindingFile = NULL;
  4814. assert(Param);
  4815. assert(File);
  4816. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  4817. if (!AParams->Cancel)
  4818. {
  4819. if (FileName.IsEmpty())
  4820. {
  4821. FileName = File->FileName;
  4822. }
  4823. TFileMasks::TParams MaskParams;
  4824. MaskParams.Size = File->Size;
  4825. MaskParams.Modification = File->Modification;
  4826. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4827. bool ImplicitMatch;
  4828. if (AParams->FileMask.Matches(FullFileName, false,
  4829. File->IsDirectory, &MaskParams, ImplicitMatch))
  4830. {
  4831. if (!ImplicitMatch)
  4832. {
  4833. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  4834. }
  4835. if (File->IsDirectory)
  4836. {
  4837. if (!AParams->LoopDetector.IsUnvisitedDirectory(File))
  4838. {
  4839. LogEvent(FORMAT(L"Already searched \"%s\" directory, link loop detected", (FullFileName)));
  4840. }
  4841. else
  4842. {
  4843. DoFilesFind(FullFileName, *AParams);
  4844. }
  4845. }
  4846. }
  4847. }
  4848. }
  4849. //---------------------------------------------------------------------------
  4850. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params)
  4851. {
  4852. Params.OnFindingFile(this, Directory, Params.Cancel);
  4853. if (!Params.Cancel)
  4854. {
  4855. assert(FOnFindingFile == NULL);
  4856. // ideally we should set the handler only around actually reading
  4857. // of the directory listing, so we at least reset the handler in
  4858. // FileFind
  4859. FOnFindingFile = Params.OnFindingFile;
  4860. try
  4861. {
  4862. ProcessDirectory(Directory, FileFind, &Params, false, true);
  4863. }
  4864. __finally
  4865. {
  4866. FOnFindingFile = NULL;
  4867. }
  4868. }
  4869. }
  4870. //---------------------------------------------------------------------------
  4871. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  4872. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  4873. {
  4874. TFilesFindParams Params;
  4875. Params.FileMask = FileMask;
  4876. Params.OnFileFound = OnFileFound;
  4877. Params.OnFindingFile = OnFindingFile;
  4878. Params.Cancel = false;
  4879. Params.LoopDetector.RecordVisitedDirectory(Directory);
  4880. DoFilesFind(Directory, Params);
  4881. }
  4882. //---------------------------------------------------------------------------
  4883. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  4884. TSpaceAvailable & ASpaceAvailable)
  4885. {
  4886. assert(IsCapable[fcCheckingSpaceAvailable]);
  4887. try
  4888. {
  4889. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  4890. }
  4891. catch (Exception &E)
  4892. {
  4893. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  4894. }
  4895. }
  4896. //---------------------------------------------------------------------------
  4897. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  4898. {
  4899. return FFileSystem->GetSessionInfo();
  4900. }
  4901. //---------------------------------------------------------------------------
  4902. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  4903. {
  4904. return FFileSystem->GetFileSystemInfo(Retrieve);
  4905. }
  4906. //---------------------------------------------------------------------
  4907. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  4908. {
  4909. FFileSystem->GetSupportedChecksumAlgs(Algs);
  4910. }
  4911. //---------------------------------------------------------------------
  4912. UnicodeString __fastcall TTerminal::GetPassword()
  4913. {
  4914. UnicodeString Result;
  4915. // FRememberedPassword is empty also when stored password was used
  4916. if (FRememberedPassword.IsEmpty())
  4917. {
  4918. Result = SessionData->Password;
  4919. }
  4920. else
  4921. {
  4922. Result = RememberedPassword;
  4923. }
  4924. return Result;
  4925. }
  4926. //---------------------------------------------------------------------
  4927. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  4928. {
  4929. return DecryptPassword(FRememberedPassword);
  4930. }
  4931. //---------------------------------------------------------------------
  4932. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  4933. {
  4934. return DecryptPassword(FRememberedTunnelPassword);
  4935. }
  4936. //---------------------------------------------------------------------
  4937. bool __fastcall TTerminal::GetStoredCredentialsTried()
  4938. {
  4939. bool Result;
  4940. if (FFileSystem != NULL)
  4941. {
  4942. Result = FFileSystem->GetStoredCredentialsTried();
  4943. }
  4944. else if (FSecureShell != NULL)
  4945. {
  4946. Result = FSecureShell->GetStoredCredentialsTried();
  4947. }
  4948. else
  4949. {
  4950. assert(FTunnelOpening);
  4951. Result = false;
  4952. }
  4953. return Result;
  4954. }
  4955. //---------------------------------------------------------------------------
  4956. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  4957. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  4958. {
  4959. assert(FFileSystem);
  4960. assert(FilesToCopy);
  4961. bool Result = false;
  4962. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4963. try
  4964. {
  4965. __int64 Size;
  4966. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  4967. bool CalculatedSize =
  4968. CalculateLocalFilesSize(
  4969. FilesToCopy, Size,
  4970. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  4971. CopyParam->CalculateSize);
  4972. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4973. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  4974. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  4975. FOperationProgress = &OperationProgress;
  4976. bool CollectingUsage = false;
  4977. try
  4978. {
  4979. if (CalculatedSize)
  4980. {
  4981. if (Configuration->Usage->Collect)
  4982. {
  4983. int CounterSize = TUsage::CalculateCounterSize(Size);
  4984. Configuration->Usage->Inc(L"Uploads");
  4985. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  4986. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  4987. CollectingUsage = true;
  4988. }
  4989. OperationProgress.SetTotalSize(Size);
  4990. }
  4991. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  4992. BeginTransaction();
  4993. try
  4994. {
  4995. if (Log->Logging)
  4996. {
  4997. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  4998. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  4999. LogEvent(CopyParam->LogStr);
  5000. }
  5001. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  5002. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  5003. }
  5004. __finally
  5005. {
  5006. if (Active)
  5007. {
  5008. ReactOnCommand(fsCopyToRemote);
  5009. }
  5010. EndTransaction();
  5011. }
  5012. if (OperationProgress.Cancel == csContinue)
  5013. {
  5014. Result = true;
  5015. }
  5016. }
  5017. __finally
  5018. {
  5019. if (CollectingUsage)
  5020. {
  5021. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5022. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  5023. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  5024. }
  5025. OperationProgress.Stop();
  5026. FOperationProgress = NULL;
  5027. }
  5028. }
  5029. catch (Exception &E)
  5030. {
  5031. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  5032. OnceDoneOperation = odoIdle;
  5033. }
  5034. if (OnceDoneOperation != odoIdle)
  5035. {
  5036. CloseOnCompletion(OnceDoneOperation);
  5037. }
  5038. return Result;
  5039. }
  5040. //---------------------------------------------------------------------------
  5041. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  5042. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5043. {
  5044. assert(FFileSystem);
  5045. // see scp.c: sink(), tolocal()
  5046. bool Result = false;
  5047. bool OwnsFileList = (FilesToCopy == NULL);
  5048. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5049. try
  5050. {
  5051. if (OwnsFileList)
  5052. {
  5053. FilesToCopy = new TStringList();
  5054. FilesToCopy->Assign(Files->SelectedFiles);
  5055. }
  5056. BeginTransaction();
  5057. try
  5058. {
  5059. __int64 TotalSize;
  5060. bool TotalSizeKnown = false;
  5061. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5062. ExceptionOnFail = true;
  5063. try
  5064. {
  5065. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5066. if (CalculateFilesSize(
  5067. FilesToCopy, TotalSize, csIgnoreErrors,
  5068. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5069. CopyParam->CalculateSize, NULL))
  5070. {
  5071. TotalSizeKnown = true;
  5072. }
  5073. }
  5074. __finally
  5075. {
  5076. ExceptionOnFail = false;
  5077. }
  5078. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5079. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5080. FOperationProgress = &OperationProgress;
  5081. bool CollectingUsage = false;
  5082. try
  5083. {
  5084. if (TotalSizeKnown)
  5085. {
  5086. if (Configuration->Usage->Collect)
  5087. {
  5088. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5089. Configuration->Usage->Inc(L"Downloads");
  5090. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5091. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5092. CollectingUsage = true;
  5093. }
  5094. OperationProgress.SetTotalSize(TotalSize);
  5095. }
  5096. try
  5097. {
  5098. try
  5099. {
  5100. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5101. &OperationProgress, OnceDoneOperation);
  5102. }
  5103. __finally
  5104. {
  5105. if (Active)
  5106. {
  5107. ReactOnCommand(fsCopyToLocal);
  5108. }
  5109. }
  5110. }
  5111. catch (Exception &E)
  5112. {
  5113. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5114. OnceDoneOperation = odoIdle;
  5115. }
  5116. if (OperationProgress.Cancel == csContinue)
  5117. {
  5118. Result = true;
  5119. }
  5120. }
  5121. __finally
  5122. {
  5123. if (CollectingUsage)
  5124. {
  5125. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5126. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5127. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5128. }
  5129. FOperationProgress = NULL;
  5130. OperationProgress.Stop();
  5131. }
  5132. }
  5133. __finally
  5134. {
  5135. // If session is still active (no fatal error) we reload directory
  5136. // by calling EndTransaction
  5137. EndTransaction();
  5138. }
  5139. }
  5140. __finally
  5141. {
  5142. if (OwnsFileList) delete FilesToCopy;
  5143. }
  5144. if (OnceDoneOperation != odoIdle)
  5145. {
  5146. CloseOnCompletion(OnceDoneOperation);
  5147. }
  5148. return Result;
  5149. }
  5150. //---------------------------------------------------------------------------
  5151. void __fastcall TTerminal::ReflectSettings()
  5152. {
  5153. assert(FLog != NULL);
  5154. FLog->ReflectSettings();
  5155. assert(FActionLog != NULL);
  5156. FActionLog->ReflectSettings();
  5157. // also FTunnelLog ?
  5158. }
  5159. //---------------------------------------------------------------------------
  5160. void __fastcall TTerminal::CollectUsage()
  5161. {
  5162. switch (SessionData->FSProtocol)
  5163. {
  5164. case fsSCPonly:
  5165. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5166. break;
  5167. case fsSFTP:
  5168. case fsSFTPonly:
  5169. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5170. break;
  5171. case fsFTP:
  5172. if (SessionData->Ftps == ftpsNone)
  5173. {
  5174. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5175. }
  5176. else
  5177. {
  5178. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5179. }
  5180. break;
  5181. case fsWebDAV:
  5182. if (SessionData->Ftps == ftpsNone)
  5183. {
  5184. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5185. }
  5186. else
  5187. {
  5188. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5189. }
  5190. break;
  5191. }
  5192. if (Configuration->Logging && Configuration->LogToFile)
  5193. {
  5194. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5195. }
  5196. if (Configuration->LogActions)
  5197. {
  5198. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5199. }
  5200. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5201. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5202. {
  5203. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5204. }
  5205. if (SessionData->ProxyMethod != ::pmNone)
  5206. {
  5207. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5208. }
  5209. if (SessionData->FtpProxyLogonType > 0)
  5210. {
  5211. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5212. }
  5213. FCollectFileSystemUsage = true;
  5214. }
  5215. //---------------------------------------------------------------------------
  5216. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5217. {
  5218. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5219. }
  5220. //---------------------------------------------------------------------------
  5221. bool __fastcall TTerminal::VerifyCertificate(
  5222. const UnicodeString & CertificateStorageKey, const UnicodeString & Fingerprint,
  5223. const UnicodeString & CertificateSubject, int Failures)
  5224. {
  5225. bool Result = false;
  5226. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5227. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5228. Storage->AccessMode = smRead;
  5229. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5230. {
  5231. if (Storage->ValueExists(SessionData->SiteKey))
  5232. {
  5233. UnicodeString CachedCertificateData = Storage->ReadString(SessionData->SiteKey, L"");
  5234. if (CertificateData == CachedCertificateData)
  5235. {
  5236. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5237. Result = true;
  5238. }
  5239. }
  5240. else if (Storage->ValueExists(Fingerprint))
  5241. {
  5242. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5243. Result = true;
  5244. }
  5245. }
  5246. if (!Result)
  5247. {
  5248. UnicodeString Buf = SessionData->HostKey;
  5249. while (!Result && !Buf.IsEmpty())
  5250. {
  5251. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5252. if (ExpectedKey == L"*")
  5253. {
  5254. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5255. Information(Message, true);
  5256. Log->Add(llException, Message);
  5257. Result = true;
  5258. }
  5259. else if (ExpectedKey == Fingerprint)
  5260. {
  5261. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5262. Result = true;
  5263. }
  5264. }
  5265. }
  5266. return Result;
  5267. }
  5268. //---------------------------------------------------------------------------
  5269. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5270. const UnicodeString & Fingerprint, int Failures)
  5271. {
  5272. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5273. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5274. Storage->AccessMode = smReadWrite;
  5275. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5276. {
  5277. Storage->WriteString(SessionData->SiteKey, CertificateData);
  5278. }
  5279. }
  5280. //---------------------------------------------------------------------------
  5281. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  5282. {
  5283. // see SSL_get_version() in OpenSSL ssl_lib.c
  5284. if (TlsVersionStr == L"TLSv1.2")
  5285. {
  5286. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  5287. }
  5288. else if (TlsVersionStr == L"TLSv1.1")
  5289. {
  5290. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  5291. }
  5292. else if (TlsVersionStr == L"TLSv1")
  5293. {
  5294. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  5295. }
  5296. else if (TlsVersionStr == L"SSLv3")
  5297. {
  5298. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  5299. }
  5300. else if (TlsVersionStr == L"SSLv2")
  5301. {
  5302. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  5303. }
  5304. else
  5305. {
  5306. FAIL;
  5307. }
  5308. }
  5309. //---------------------------------------------------------------------------
  5310. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5311. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5312. TTerminal(ASessionData, Configuration),
  5313. FMainTerminal(MainTerminal)
  5314. {
  5315. Log->Parent = FMainTerminal->Log;
  5316. Log->Name = Name;
  5317. ActionLog->Enabled = false;
  5318. SessionData->NonPersistant();
  5319. assert(FMainTerminal != NULL);
  5320. if (!FMainTerminal->UserName.IsEmpty())
  5321. {
  5322. SessionData->UserName = FMainTerminal->UserName;
  5323. }
  5324. }
  5325. //---------------------------------------------------------------------------
  5326. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5327. {
  5328. FMainTerminal->DirectoryLoaded(FileList);
  5329. assert(FileList != NULL);
  5330. }
  5331. //---------------------------------------------------------------------------
  5332. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5333. bool SubDirs)
  5334. {
  5335. // clear cache of main terminal
  5336. FMainTerminal->DirectoryModified(Path, SubDirs);
  5337. }
  5338. //---------------------------------------------------------------------------
  5339. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5340. {
  5341. return FMainTerminal;
  5342. }
  5343. //---------------------------------------------------------------------------
  5344. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5345. TObjectList()
  5346. {
  5347. assert(AConfiguration);
  5348. FConfiguration = AConfiguration;
  5349. }
  5350. //---------------------------------------------------------------------------
  5351. __fastcall TTerminalList::~TTerminalList()
  5352. {
  5353. assert(Count == 0);
  5354. }
  5355. //---------------------------------------------------------------------------
  5356. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5357. {
  5358. return new TTerminal(Data, FConfiguration);
  5359. }
  5360. //---------------------------------------------------------------------------
  5361. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5362. {
  5363. TTerminal * Terminal = CreateTerminal(Data);
  5364. Add(Terminal);
  5365. return Terminal;
  5366. }
  5367. //---------------------------------------------------------------------------
  5368. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5369. {
  5370. assert(IndexOf(Terminal) >= 0);
  5371. Remove(Terminal);
  5372. }
  5373. //---------------------------------------------------------------------------
  5374. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5375. {
  5376. TTerminal * T = Terminal;
  5377. Terminal = NULL;
  5378. FreeTerminal(T);
  5379. }
  5380. //---------------------------------------------------------------------------
  5381. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5382. {
  5383. return dynamic_cast<TTerminal *>(Items[Index]);
  5384. }
  5385. //---------------------------------------------------------------------------
  5386. void __fastcall TTerminalList::Idle()
  5387. {
  5388. TTerminal * Terminal;
  5389. for (int i = 0; i < Count; i++)
  5390. {
  5391. Terminal = Terminals[i];
  5392. if (Terminal->Status == ssOpened)
  5393. {
  5394. Terminal->Idle();
  5395. }
  5396. }
  5397. }
  5398. //---------------------------------------------------------------------------
  5399. void __fastcall TTerminalList::RecryptPasswords()
  5400. {
  5401. for (int Index = 0; Index < Count; Index++)
  5402. {
  5403. Terminals[Index]->RecryptPasswords();
  5404. }
  5405. }