Terminal.cpp 177 KB

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