Terminal.cpp 179 KB

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