Terminal.cpp 178 KB

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