Программа для прослушивания журнала АРК Томск http://blindage.org/?p=6627
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

blcksock.pas 130KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333
  1. {==============================================================================|
  2. | Project : Ararat Synapse | 009.008.005 |
  3. |==============================================================================|
  4. | Content: Library base |
  5. |==============================================================================|
  6. | Copyright (c)1999-2012, Lukas Gebauer |
  7. | All rights reserved. |
  8. | |
  9. | Redistribution and use in source and binary forms, with or without |
  10. | modification, are permitted provided that the following conditions are met: |
  11. | |
  12. | Redistributions of source code must retain the above copyright notice, this |
  13. | list of conditions and the following disclaimer. |
  14. | |
  15. | Redistributions in binary form must reproduce the above copyright notice, |
  16. | this list of conditions and the following disclaimer in the documentation |
  17. | and/or other materials provided with the distribution. |
  18. | |
  19. | Neither the name of Lukas Gebauer nor the names of its contributors may |
  20. | be used to endorse or promote products derived from this software without |
  21. | specific prior written permission. |
  22. | |
  23. | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
  24. | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
  25. | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
  26. | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
  27. | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
  28. | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
  29. | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
  30. | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  31. | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
  32. | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
  33. | DAMAGE. |
  34. |==============================================================================|
  35. | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
  36. | Portions created by Lukas Gebauer are Copyright (c)1999-2012. |
  37. | All Rights Reserved. |
  38. |==============================================================================|
  39. | Contributor(s): |
  40. |==============================================================================|
  41. | History: see HISTORY.HTM from distribution package |
  42. | (Found at URL: http://www.ararat.cz/synapse/) |
  43. |==============================================================================}
  44. {
  45. Special thanks to Gregor Ibic <gregor.ibic@intelicom.si>
  46. (Intelicom d.o.o., http://www.intelicom.si)
  47. for good inspiration about SSL programming.
  48. }
  49. {$DEFINE ONCEWINSOCK}
  50. {Note about define ONCEWINSOCK:
  51. If you remove this compiler directive, then socket interface is loaded and
  52. initialized on constructor of TBlockSocket class for each socket separately.
  53. Socket interface is used only if your need it.
  54. If you leave this directive here, then socket interface is loaded and
  55. initialized only once at start of your program! It boost performace on high
  56. count of created and destroyed sockets. It eliminate possible small resource
  57. leak on Windows systems too.
  58. }
  59. //{$DEFINE RAISEEXCEPT}
  60. {When you enable this define, then is Raiseexcept property is on by default
  61. }
  62. {:@abstract(Synapse's library core)
  63. Core with implementation basic socket classes.
  64. }
  65. {$IFDEF FPC}
  66. {$MODE DELPHI}
  67. {$ENDIF}
  68. {$IFDEF VER125}
  69. {$DEFINE BCB}
  70. {$ENDIF}
  71. {$IFDEF BCB}
  72. {$ObjExportAll On}
  73. {$ENDIF}
  74. {$Q-}
  75. {$H+}
  76. {$M+}
  77. {$TYPEDADDRESS OFF}
  78. //old Delphi does not have MSWINDOWS define.
  79. {$IFDEF WIN32}
  80. {$IFNDEF MSWINDOWS}
  81. {$DEFINE MSWINDOWS}
  82. {$ENDIF}
  83. {$ENDIF}
  84. {$IFDEF UNICODE}
  85. {$WARN IMPLICIT_STRING_CAST OFF}
  86. {$WARN IMPLICIT_STRING_CAST_LOSS OFF}
  87. {$ENDIF}
  88. unit blcksock;
  89. interface
  90. uses
  91. SysUtils, Classes,
  92. synafpc,
  93. synsock, synautil, synacode, synaip
  94. {$IFDEF CIL}
  95. ,System.Net
  96. ,System.Net.Sockets
  97. ,System.Text
  98. {$ENDIF}
  99. ;
  100. const
  101. SynapseRelease = '38';
  102. cLocalhost = '127.0.0.1';
  103. cAnyHost = '0.0.0.0';
  104. cBroadcast = '255.255.255.255';
  105. c6Localhost = '::1';
  106. c6AnyHost = '::0';
  107. c6Broadcast = 'ffff::1';
  108. cAnyPort = '0';
  109. CR = #$0d;
  110. LF = #$0a;
  111. CRLF = CR + LF;
  112. c64k = 65536;
  113. type
  114. {:@abstract(Exception clas used by Synapse)
  115. When you enable generating of exceptions, this exception is raised by
  116. Synapse's units.}
  117. ESynapseError = class(Exception)
  118. private
  119. FErrorCode: Integer;
  120. FErrorMessage: string;
  121. published
  122. {:Code of error. Value depending on used operating system}
  123. property ErrorCode: Integer read FErrorCode Write FErrorCode;
  124. {:Human readable description of error.}
  125. property ErrorMessage: string read FErrorMessage Write FErrorMessage;
  126. end;
  127. {:Types of OnStatus events}
  128. THookSocketReason = (
  129. {:Resolving is begin. Resolved IP and port is in parameter in format like:
  130. 'localhost.somewhere.com:25'.}
  131. HR_ResolvingBegin,
  132. {:Resolving is done. Resolved IP and port is in parameter in format like:
  133. 'localhost.somewhere.com:25'. It is always same as in HR_ResolvingBegin!}
  134. HR_ResolvingEnd,
  135. {:Socket created by CreateSocket method. It reporting Family of created
  136. socket too!}
  137. HR_SocketCreate,
  138. {:Socket closed by CloseSocket method.}
  139. HR_SocketClose,
  140. {:Socket binded to IP and Port. Binded IP and Port is in parameter in format
  141. like: 'localhost.somewhere.com:25'.}
  142. HR_Bind,
  143. {:Socket connected to IP and Port. Connected IP and Port is in parameter in
  144. format like: 'localhost.somewhere.com:25'.}
  145. HR_Connect,
  146. {:Called when CanRead method is used with @True result.}
  147. HR_CanRead,
  148. {:Called when CanWrite method is used with @True result.}
  149. HR_CanWrite,
  150. {:Socket is swithed to Listen mode. (TCP socket only)}
  151. HR_Listen,
  152. {:Socket Accepting client connection. (TCP socket only)}
  153. HR_Accept,
  154. {:report count of bytes readed from socket. Number is in parameter string.
  155. If you need is in integer, you must use StrToInt function!}
  156. HR_ReadCount,
  157. {:report count of bytes writed to socket. Number is in parameter string. If
  158. you need is in integer, you must use StrToInt function!}
  159. HR_WriteCount,
  160. {:If is limiting of bandwidth on, then this reason is called when sending or
  161. receiving is stopped for satisfy bandwidth limit. Parameter is count of
  162. waiting milliseconds.}
  163. HR_Wait,
  164. {:report situation where communication error occured. When raiseexcept is
  165. @true, then exception is called after this Hook reason.}
  166. HR_Error
  167. );
  168. {:Procedural type for OnStatus event. Sender is calling TBlockSocket object,
  169. Reason is one of set Status events and value is optional data.}
  170. THookSocketStatus = procedure(Sender: TObject; Reason: THookSocketReason;
  171. const Value: String) of object;
  172. {:This procedural type is used for DataFilter hooks.}
  173. THookDataFilter = procedure(Sender: TObject; var Value: AnsiString) of object;
  174. {:This procedural type is used for hook OnCreateSocket. By this hook you can
  175. insert your code after initialisation of socket. (you can set special socket
  176. options, etc.)}
  177. THookCreateSocket = procedure(Sender: TObject) of object;
  178. {:This procedural type is used for monitoring of communication.}
  179. THookMonitor = procedure(Sender: TObject; Writing: Boolean;
  180. const Buffer: TMemory; Len: Integer) of object;
  181. {:This procedural type is used for hook OnAfterConnect. By this hook you can
  182. insert your code after TCP socket has been sucessfully connected.}
  183. THookAfterConnect = procedure(Sender: TObject) of object;
  184. {:This procedural type is used for hook OnVerifyCert. By this hook you can
  185. insert your additional certificate verification code. Usefull to verify server
  186. CN against URL. }
  187. THookVerifyCert = function(Sender: TObject):boolean of object;
  188. {:This procedural type is used for hook OnHeartbeat. By this hook you can
  189. call your code repeately during long socket operations.
  190. You must enable heartbeats by @Link(HeartbeatRate) property!}
  191. THookHeartbeat = procedure(Sender: TObject) of object;
  192. {:Specify family of socket.}
  193. TSocketFamily = (
  194. {:Default mode. Socket family is defined by target address for connection.
  195. It allows instant access to IPv4 and IPv6 nodes. When you need IPv6 address
  196. as destination, then is used IPv6 mode. othervise is used IPv4 mode.
  197. However this mode not working properly with preliminary IPv6 supports!}
  198. SF_Any,
  199. {:Turn this class to pure IPv4 mode. This mode is totally compatible with
  200. previous Synapse releases.}
  201. SF_IP4,
  202. {:Turn to only IPv6 mode.}
  203. SF_IP6
  204. );
  205. {:specify possible values of SOCKS modes.}
  206. TSocksType = (
  207. ST_Socks5,
  208. ST_Socks4
  209. );
  210. {:Specify requested SSL/TLS version for secure connection.}
  211. TSSLType = (
  212. LT_all,
  213. LT_SSLv2,
  214. LT_SSLv3,
  215. LT_TLSv1,
  216. LT_TLSv1_1,
  217. LT_SSHv2
  218. );
  219. {:Specify type of socket delayed option.}
  220. TSynaOptionType = (
  221. SOT_Linger,
  222. SOT_RecvBuff,
  223. SOT_SendBuff,
  224. SOT_NonBlock,
  225. SOT_RecvTimeout,
  226. SOT_SendTimeout,
  227. SOT_Reuse,
  228. SOT_TTL,
  229. SOT_Broadcast,
  230. SOT_MulticastTTL,
  231. SOT_MulticastLoop
  232. );
  233. {:@abstract(this object is used for remember delayed socket option set.)}
  234. TSynaOption = class(TObject)
  235. public
  236. Option: TSynaOptionType;
  237. Enabled: Boolean;
  238. Value: Integer;
  239. end;
  240. TCustomSSL = class;
  241. TSSLClass = class of TCustomSSL;
  242. {:@abstract(Basic IP object.)
  243. This is parent class for other class with protocol implementations. Do not
  244. use this class directly! Use @link(TICMPBlockSocket), @link(TRAWBlockSocket),
  245. @link(TTCPBlockSocket) or @link(TUDPBlockSocket) instead.}
  246. TBlockSocket = class(TObject)
  247. private
  248. FOnStatus: THookSocketStatus;
  249. FOnReadFilter: THookDataFilter;
  250. FOnCreateSocket: THookCreateSocket;
  251. FOnMonitor: THookMonitor;
  252. FOnHeartbeat: THookHeartbeat;
  253. FLocalSin: TVarSin;
  254. FRemoteSin: TVarSin;
  255. FTag: integer;
  256. FBuffer: AnsiString;
  257. FRaiseExcept: Boolean;
  258. FNonBlockMode: Boolean;
  259. FMaxLineLength: Integer;
  260. FMaxSendBandwidth: Integer;
  261. FNextSend: LongWord;
  262. FMaxRecvBandwidth: Integer;
  263. FNextRecv: LongWord;
  264. FConvertLineEnd: Boolean;
  265. FLastCR: Boolean;
  266. FLastLF: Boolean;
  267. FBinded: Boolean;
  268. FFamily: TSocketFamily;
  269. FFamilySave: TSocketFamily;
  270. FIP6used: Boolean;
  271. FPreferIP4: Boolean;
  272. FDelayedOptions: TList;
  273. FInterPacketTimeout: Boolean;
  274. {$IFNDEF CIL}
  275. FFDSet: TFDSet;
  276. {$ENDIF}
  277. FRecvCounter: Integer;
  278. FSendCounter: Integer;
  279. FSendMaxChunk: Integer;
  280. FStopFlag: Boolean;
  281. FNonblockSendTimeout: Integer;
  282. FHeartbeatRate: integer;
  283. {$IFNDEF ONCEWINSOCK}
  284. FWsaDataOnce: TWSADATA;
  285. {$ENDIF}
  286. function GetSizeRecvBuffer: Integer;
  287. procedure SetSizeRecvBuffer(Size: Integer);
  288. function GetSizeSendBuffer: Integer;
  289. procedure SetSizeSendBuffer(Size: Integer);
  290. procedure SetNonBlockMode(Value: Boolean);
  291. procedure SetTTL(TTL: integer);
  292. function GetTTL:integer;
  293. procedure SetFamily(Value: TSocketFamily); virtual;
  294. procedure SetSocket(Value: TSocket); virtual;
  295. function GetWsaData: TWSAData;
  296. function FamilyToAF(f: TSocketFamily): TAddrFamily;
  297. protected
  298. FSocket: TSocket;
  299. FLastError: Integer;
  300. FLastErrorDesc: string;
  301. FOwner: TObject;
  302. procedure SetDelayedOption(const Value: TSynaOption);
  303. procedure DelayedOption(const Value: TSynaOption);
  304. procedure ProcessDelayedOptions;
  305. procedure InternalCreateSocket(Sin: TVarSin);
  306. procedure SetSin(var Sin: TVarSin; IP, Port: string);
  307. function GetSinIP(Sin: TVarSin): string;
  308. function GetSinPort(Sin: TVarSin): Integer;
  309. procedure DoStatus(Reason: THookSocketReason; const Value: string);
  310. procedure DoReadFilter(Buffer: TMemory; var Len: Integer);
  311. procedure DoMonitor(Writing: Boolean; const Buffer: TMemory; Len: Integer);
  312. procedure DoCreateSocket;
  313. procedure DoHeartbeat;
  314. procedure LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
  315. procedure SetBandwidth(Value: Integer);
  316. function TestStopFlag: Boolean;
  317. procedure InternalSendStream(const Stream: TStream; WithSize, Indy: boolean); virtual;
  318. function InternalCanRead(Timeout: Integer): Boolean; virtual;
  319. public
  320. constructor Create;
  321. {:Create object and load all necessary socket library. What library is
  322. loaded is described by STUB parameter. If STUB is empty string, then is
  323. loaded default libraries.}
  324. constructor CreateAlternate(Stub: string);
  325. destructor Destroy; override;
  326. {:If @link(family) is not SF_Any, then create socket with type defined in
  327. @link(Family) property. If family is SF_Any, then do nothing! (socket is
  328. created automaticly when you know what type of socket you need to create.
  329. (i.e. inside @link(Connect) or @link(Bind) call.) When socket is created,
  330. then is aplyed all stored delayed socket options.}
  331. procedure CreateSocket;
  332. {:It create socket. Address resolving of Value tells what type of socket is
  333. created. If Value is resolved as IPv4 IP, then is created IPv4 socket. If
  334. value is resolved as IPv6 address, then is created IPv6 socket.}
  335. procedure CreateSocketByName(const Value: String);
  336. {:Destroy socket in use. This method is also automatically called from
  337. object destructor.}
  338. procedure CloseSocket; virtual;
  339. {:Abort any work on Socket and destroy them.}
  340. procedure AbortSocket; virtual;
  341. {:Connects socket to local IP address and PORT. IP address may be numeric or
  342. symbolic ('192.168.74.50', 'cosi.nekde.cz', 'ff08::1'). The same for PORT
  343. - it may be number or mnemonic port ('23', 'telnet').
  344. If port value is '0', system chooses itself and conects unused port in the
  345. range 1024 to 4096 (this depending by operating system!). Structure
  346. LocalSin is filled after calling this method.
  347. Note: If you call this on non-created socket, then socket is created
  348. automaticly.
  349. Warning: when you call : Bind('0.0.0.0','0'); then is nothing done! In this
  350. case is used implicit system bind instead.}
  351. procedure Bind(IP, Port: string);
  352. {:Connects socket to remote IP address and PORT. The same rules as with
  353. @link(BIND) method are valid. The only exception is that PORT with 0 value
  354. will not be connected!
  355. Structures LocalSin and RemoteSin will be filled with valid values.
  356. When you call this on non-created socket, then socket is created
  357. automaticly. Type of created socket is by @link(Family) property. If is
  358. used SF_IP4, then is created socket for IPv4. If is used SF_IP6, then is
  359. created socket for IPv6. When you have family on SF_Any (default!), then
  360. type of created socket is determined by address resolving of destination
  361. address. (Not work properly on prilimitary winsock IPv6 support!)}
  362. procedure Connect(IP, Port: string); virtual;
  363. {:Sets socket to receive mode for new incoming connections. It is necessary
  364. to use @link(TBlockSocket.BIND) function call before this method to select
  365. receiving port!}
  366. procedure Listen; virtual;
  367. {:Waits until new incoming connection comes. After it comes a new socket is
  368. automatically created (socket handler is returned by this function as
  369. result).}
  370. function Accept: TSocket; virtual;
  371. {:Sends data of LENGTH from BUFFER address via connected socket. System
  372. automatically splits data to packets.}
  373. function SendBuffer(Buffer: Tmemory; Length: Integer): Integer; virtual;
  374. {:One data BYTE is sent via connected socket.}
  375. procedure SendByte(Data: Byte); virtual;
  376. {:Send data string via connected socket. Any terminator is not added! If you
  377. need send true string with CR-LF termination, you must add CR-LF characters
  378. to sended string! Because any termination is not added automaticly, you can
  379. use this function for sending any binary data in binary string.}
  380. procedure SendString(Data: AnsiString); virtual;
  381. {:Send integer as four bytes to socket.}
  382. procedure SendInteger(Data: integer); virtual;
  383. {:Send data as one block to socket. Each block begin with 4 bytes with
  384. length of data in block. This 4 bytes is added automaticly by this
  385. function.}
  386. procedure SendBlock(const Data: AnsiString); virtual;
  387. {:Send data from stream to socket.}
  388. procedure SendStreamRaw(const Stream: TStream); virtual;
  389. {:Send content of stream to socket. It using @link(SendBlock) method}
  390. procedure SendStream(const Stream: TStream); virtual;
  391. {:Send content of stream to socket. It using @link(SendBlock) method and
  392. this is compatible with streams in Indy library.}
  393. procedure SendStreamIndy(const Stream: TStream); virtual;
  394. {:Note: This is low-level receive function. You must be sure if data is
  395. waiting for read before call this function for avoid deadlock!
  396. Waits until allocated buffer is filled by received data. Returns number of
  397. data received, which equals to LENGTH value under normal operation. If it
  398. is not equal the communication channel is possibly broken.
  399. On stream oriented sockets if is received 0 bytes, it mean 'socket is
  400. closed!"
  401. On datagram socket is readed first waiting datagram.}
  402. function RecvBuffer(Buffer: TMemory; Length: Integer): Integer; virtual;
  403. {:Note: This is high-level receive function. It using internal
  404. @link(LineBuffer) and you can combine this function freely with other
  405. high-level functions!
  406. Method waits until data is received. If no data is received within TIMEOUT
  407. (in milliseconds) period, @link(LastError) is set to WSAETIMEDOUT. Methods
  408. serves for reading any size of data (i.e. one megabyte...). This method is
  409. preffered for reading from stream sockets (like TCP).}
  410. function RecvBufferEx(Buffer: Tmemory; Len: Integer;
  411. Timeout: Integer): Integer; virtual;
  412. {:Similar to @link(RecvBufferEx), but readed data is stored in binary
  413. string, not in memory buffer.}
  414. function RecvBufferStr(Len: Integer; Timeout: Integer): AnsiString; virtual;
  415. {:Note: This is high-level receive function. It using internal
  416. @link(LineBuffer) and you can combine this function freely with other
  417. high-level functions.
  418. Waits until one data byte is received which is also returned as function
  419. result. If no data is received within TIMEOUT (in milliseconds)period,
  420. @link(LastError) is set to WSAETIMEDOUT and result have value 0.}
  421. function RecvByte(Timeout: Integer): Byte; virtual;
  422. {:Note: This is high-level receive function. It using internal
  423. @link(LineBuffer) and you can combine this function freely with other
  424. high-level functions.
  425. Waits until one four bytes are received and return it as one Ineger Value.
  426. If no data is received within TIMEOUT (in milliseconds)period,
  427. @link(LastError) is set to WSAETIMEDOUT and result have value 0.}
  428. function RecvInteger(Timeout: Integer): Integer; virtual;
  429. {:Note: This is high-level receive function. It using internal
  430. @link(LineBuffer) and you can combine this function freely with other
  431. high-level functions.
  432. Method waits until data string is received. This string is terminated by
  433. CR-LF characters. The resulting string is returned without this termination
  434. (CR-LF)! If @link(ConvertLineEnd) is used, then CR-LF sequence may not be
  435. exactly CR-LF. See @link(ConvertLineEnd) description. If no data is
  436. received within TIMEOUT (in milliseconds) period, @link(LastError) is set
  437. to WSAETIMEDOUT. You may also specify maximum length of reading data by
  438. @link(MaxLineLength) property.}
  439. function RecvString(Timeout: Integer): AnsiString; virtual;
  440. {:Note: This is high-level receive function. It using internal
  441. @link(LineBuffer) and you can combine this function freely with other
  442. high-level functions.
  443. Method waits until data string is received. This string is terminated by
  444. Terminator string. The resulting string is returned without this
  445. termination. If no data is received within TIMEOUT (in milliseconds)
  446. period, @link(LastError) is set to WSAETIMEDOUT. You may also specify
  447. maximum length of reading data by @link(MaxLineLength) property.}
  448. function RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString; virtual;
  449. {:Note: This is high-level receive function. It using internal
  450. @link(LineBuffer) and you can combine this function freely with other
  451. high-level functions.
  452. Method reads all data waiting for read. If no data is received within
  453. TIMEOUT (in milliseconds) period, @link(LastError) is set to WSAETIMEDOUT.
  454. Methods serves for reading unknown size of data. Because before call this
  455. function you don't know size of received data, returned data is stored in
  456. dynamic size binary string. This method is preffered for reading from
  457. stream sockets (like TCP). It is very goot for receiving datagrams too!
  458. (UDP protocol)}
  459. function RecvPacket(Timeout: Integer): AnsiString; virtual;
  460. {:Read one block of data from socket. Each block begin with 4 bytes with
  461. length of data in block. This function read first 4 bytes for get lenght,
  462. then it wait for reported count of bytes.}
  463. function RecvBlock(Timeout: Integer): AnsiString; virtual;
  464. {:Read all data from socket to stream until socket is closed (or any error
  465. occured.)}
  466. procedure RecvStreamRaw(const Stream: TStream; Timeout: Integer); virtual;
  467. {:Read requested count of bytes from socket to stream.}
  468. procedure RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: Integer);
  469. {:Receive data to stream. It using @link(RecvBlock) method.}
  470. procedure RecvStream(const Stream: TStream; Timeout: Integer); virtual;
  471. {:Receive data to stream. This function is compatible with similar function
  472. in Indy library. It using @link(RecvBlock) method.}
  473. procedure RecvStreamIndy(const Stream: TStream; Timeout: Integer); virtual;
  474. {:Same as @link(RecvBuffer), but readed data stays in system input buffer.
  475. Warning: this function not respect data in @link(LineBuffer)! Is not
  476. recommended to use this function!}
  477. function PeekBuffer(Buffer: TMemory; Length: Integer): Integer; virtual;
  478. {:Same as @link(RecvByte), but readed data stays in input system buffer.
  479. Warning: this function not respect data in @link(LineBuffer)! Is not
  480. recommended to use this function!}
  481. function PeekByte(Timeout: Integer): Byte; virtual;
  482. {:On stream sockets it returns number of received bytes waiting for picking.
  483. 0 is returned when there is no such data. On datagram socket it returns
  484. length of the first waiting datagram. Returns 0 if no datagram is waiting.}
  485. function WaitingData: Integer; virtual;
  486. {:Same as @link(WaitingData), but if exists some of data in @link(Linebuffer),
  487. return their length instead.}
  488. function WaitingDataEx: Integer;
  489. {:Clear all waiting data for read from buffers.}
  490. procedure Purge;
  491. {:Sets linger. Enabled linger means that the system waits another LINGER
  492. (in milliseconds) time for delivery of sent data. This function is only for
  493. stream type of socket! (TCP)}
  494. procedure SetLinger(Enable: Boolean; Linger: Integer);
  495. {:Actualize values in @link(LocalSin).}
  496. procedure GetSinLocal;
  497. {:Actualize values in @link(RemoteSin).}
  498. procedure GetSinRemote;
  499. {:Actualize values in @link(LocalSin) and @link(RemoteSin).}
  500. procedure GetSins;
  501. {:Reset @link(LastError) and @link(LastErrorDesc) to non-error state.}
  502. procedure ResetLastError;
  503. {:If you "manually" call Socket API functions, forward their return code as
  504. parameter to this function, which evaluates it, eventually calls
  505. GetLastError and found error code returns and stores to @link(LastError).}
  506. function SockCheck(SockResult: Integer): Integer; virtual;
  507. {:If @link(LastError) contains some error code and @link(RaiseExcept)
  508. property is @true, raise adequate exception.}
  509. procedure ExceptCheck;
  510. {:Returns local computer name as numerical or symbolic value. It try get
  511. fully qualified domain name. Name is returned in the format acceptable by
  512. functions demanding IP as input parameter.}
  513. function LocalName: string;
  514. {:Try resolve name to all possible IP address. i.e. If you pass as name
  515. result of @link(LocalName) method, you get all IP addresses used by local
  516. system.}
  517. procedure ResolveNameToIP(Name: string; const IPList: TStrings);
  518. {:Try resolve name to primary IP address. i.e. If you pass as name result of
  519. @link(LocalName) method, you get primary IP addresses used by local system.}
  520. function ResolveName(Name: string): string;
  521. {:Try resolve IP to their primary domain name. If IP not have domain name,
  522. then is returned original IP.}
  523. function ResolveIPToName(IP: string): string;
  524. {:Try resolve symbolic port name to port number. (i.e. 'Echo' to 8)}
  525. function ResolvePort(Port: string): Word;
  526. {:Set information about remote side socket. It is good for seting remote
  527. side for sending UDP packet, etc.}
  528. procedure SetRemoteSin(IP, Port: string);
  529. {:Picks IP socket address from @link(LocalSin).}
  530. function GetLocalSinIP: string; virtual;
  531. {:Picks IP socket address from @link(RemoteSin).}
  532. function GetRemoteSinIP: string; virtual;
  533. {:Picks socket PORT number from @link(LocalSin).}
  534. function GetLocalSinPort: Integer; virtual;
  535. {:Picks socket PORT number from @link(RemoteSin).}
  536. function GetRemoteSinPort: Integer; virtual;
  537. {:Return @TRUE, if you can read any data from socket or is incoming
  538. connection on TCP based socket. Status is tested for time Timeout (in
  539. milliseconds). If value in Timeout is 0, status is only tested and
  540. continue. If value in Timeout is -1, run is breaked and waiting for read
  541. data maybe forever.
  542. This function is need only on special cases, when you need use
  543. @link(RecvBuffer) function directly! read functioms what have timeout as
  544. calling parameter, calling this function internally.}
  545. function CanRead(Timeout: Integer): Boolean; virtual;
  546. {:Same as @link(CanRead), but additionally return @TRUE if is some data in
  547. @link(LineBuffer).}
  548. function CanReadEx(Timeout: Integer): Boolean; virtual;
  549. {:Return @TRUE, if you can to socket write any data (not full sending
  550. buffer). Status is tested for time Timeout (in milliseconds). If value in
  551. Timeout is 0, status is only tested and continue. If value in Timeout is
  552. -1, run is breaked and waiting for write data maybe forever.
  553. This function is need only on special cases!}
  554. function CanWrite(Timeout: Integer): Boolean; virtual;
  555. {:Same as @link(SendBuffer), but send datagram to address from
  556. @link(RemoteSin). Usefull for sending reply to datagram received by
  557. function @link(RecvBufferFrom).}
  558. function SendBufferTo(Buffer: TMemory; Length: Integer): Integer; virtual;
  559. {:Note: This is low-lever receive function. You must be sure if data is
  560. waiting for read before call this function for avoid deadlock!
  561. Receives first waiting datagram to allocated buffer. If there is no waiting
  562. one, then waits until one comes. Returns length of datagram stored in
  563. BUFFER. If length exceeds buffer datagram is truncated. After this
  564. @link(RemoteSin) structure contains information about sender of UDP packet.}
  565. function RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer; virtual;
  566. {$IFNDEF CIL}
  567. {:This function is for check for incoming data on set of sockets. Whitch
  568. sockets is checked is decribed by SocketList Tlist with TBlockSocket
  569. objects. TList may have maximal number of objects defined by FD_SETSIZE
  570. constant. Return @TRUE, if you can from some socket read any data or is
  571. incoming connection on TCP based socket. Status is tested for time Timeout
  572. (in milliseconds). If value in Timeout is 0, status is only tested and
  573. continue. If value in Timeout is -1, run is breaked and waiting for read
  574. data maybe forever. If is returned @TRUE, CanReadList TList is filled by all
  575. TBlockSocket objects what waiting for read.}
  576. function GroupCanRead(const SocketList: TList; Timeout: Integer;
  577. const CanReadList: TList): Boolean;
  578. {$ENDIF}
  579. {:By this method you may turn address reuse mode for local @link(bind). It
  580. is good specially for UDP protocol. Using this with TCP protocol is
  581. hazardous!}
  582. procedure EnableReuse(Value: Boolean);
  583. {:Try set timeout for all sending and receiving operations, if socket
  584. provider can do it. (It not supported by all socket providers!)}
  585. procedure SetTimeout(Timeout: Integer);
  586. {:Try set timeout for all sending operations, if socket provider can do it.
  587. (It not supported by all socket providers!)}
  588. procedure SetSendTimeout(Timeout: Integer);
  589. {:Try set timeout for all receiving operations, if socket provider can do
  590. it. (It not supported by all socket providers!)}
  591. procedure SetRecvTimeout(Timeout: Integer);
  592. {:Return value of socket type.}
  593. function GetSocketType: integer; Virtual;
  594. {:Return value of protocol type for socket creation.}
  595. function GetSocketProtocol: integer; Virtual;
  596. {:WSA structure with information about socket provider. On non-windows
  597. platforms this structure is simulated!}
  598. property WSAData: TWSADATA read GetWsaData;
  599. {:FDset structure prepared for usage with this socket.}
  600. property FDset: TFDSet read FFDset;
  601. {:Structure describing local socket side.}
  602. property LocalSin: TVarSin read FLocalSin write FLocalSin;
  603. {:Structure describing remote socket side.}
  604. property RemoteSin: TVarSin read FRemoteSin write FRemoteSin;
  605. {:Socket handler. Suitable for "manual" calls to socket API or manual
  606. connection of socket to a previously created socket (i.e by Accept method
  607. on TCP socket)}
  608. property Socket: TSocket read FSocket write SetSocket;
  609. {:Last socket operation error code. Error codes are described in socket
  610. documentation. Human readable error description is stored in
  611. @link(LastErrorDesc) property.}
  612. property LastError: Integer read FLastError;
  613. {:Human readable error description of @link(LastError) code.}
  614. property LastErrorDesc: string read FLastErrorDesc;
  615. {:Buffer used by all high-level receiving functions. This buffer is used for
  616. optimized reading of data from socket. In normal cases you not need access
  617. to this buffer directly!}
  618. property LineBuffer: AnsiString read FBuffer write FBuffer;
  619. {:Size of Winsock receive buffer. If it is not supported by socket provider,
  620. it return as size one kilobyte.}
  621. property SizeRecvBuffer: Integer read GetSizeRecvBuffer write SetSizeRecvBuffer;
  622. {:Size of Winsock send buffer. If it is not supported by socket provider, it
  623. return as size one kilobyte.}
  624. property SizeSendBuffer: Integer read GetSizeSendBuffer write SetSizeSendBuffer;
  625. {:If @True, turn class to non-blocking mode. Not all functions are working
  626. properly in this mode, you must know exactly what you are doing! However
  627. when you have big experience with non-blocking programming, then you can
  628. optimise your program by non-block mode!}
  629. property NonBlockMode: Boolean read FNonBlockMode Write SetNonBlockMode;
  630. {:Set Time-to-live value. (if system supporting it!)}
  631. property TTL: Integer read GetTTL Write SetTTL;
  632. {:If is @true, then class in in IPv6 mode.}
  633. property IP6used: Boolean read FIP6used;
  634. {:Return count of received bytes on this socket from begin of current
  635. connection.}
  636. property RecvCounter: Integer read FRecvCounter;
  637. {:Return count of sended bytes on this socket from begin of current
  638. connection.}
  639. property SendCounter: Integer read FSendCounter;
  640. published
  641. {:Return descriptive string for given error code. This is class function.
  642. You may call it without created object!}
  643. class function GetErrorDesc(ErrorCode: Integer): string;
  644. {:Return descriptive string for @link(LastError).}
  645. function GetErrorDescEx: string; virtual;
  646. {:this value is for free use.}
  647. property Tag: Integer read FTag write FTag;
  648. {:If @true, winsock errors raises exception. Otherwise is setted
  649. @link(LastError) value only and you must check it from your program! Default
  650. value is @false.}
  651. property RaiseExcept: Boolean read FRaiseExcept write FRaiseExcept;
  652. {:Define maximum length in bytes of @link(LineBuffer) for high-level
  653. receiving functions. If this functions try to read more data then this
  654. limit, error is returned! If value is 0 (default), no limitation is used.
  655. This is very good protection for stupid attacks to your server by sending
  656. lot of data without proper terminator... until all your memory is allocated
  657. by LineBuffer!
  658. Note: This maximum length is checked only in functions, what read unknown
  659. number of bytes! (like @link(RecvString) or @link(RecvTerminated))}
  660. property MaxLineLength: Integer read FMaxLineLength Write FMaxLineLength;
  661. {:Define maximal bandwidth for all sending operations in bytes per second.
  662. If value is 0 (default), bandwidth limitation is not used.}
  663. property MaxSendBandwidth: Integer read FMaxSendBandwidth Write FMaxSendBandwidth;
  664. {:Define maximal bandwidth for all receiving operations in bytes per second.
  665. If value is 0 (default), bandwidth limitation is not used.}
  666. property MaxRecvBandwidth: Integer read FMaxRecvBandwidth Write FMaxRecvBandwidth;
  667. {:Define maximal bandwidth for all sending and receiving operations in bytes
  668. per second. If value is 0 (default), bandwidth limitation is not used.}
  669. property MaxBandwidth: Integer Write SetBandwidth;
  670. {:Do a conversion of non-standard line terminators to CRLF. (Off by default)
  671. If @True, then terminators like sigle CR, single LF or LFCR are converted
  672. to CRLF internally. This have effect only in @link(RecvString) method!}
  673. property ConvertLineEnd: Boolean read FConvertLineEnd Write FConvertLineEnd;
  674. {:Specified Family of this socket. When you are using Windows preliminary
  675. support for IPv6, then I recommend to set this property!}
  676. property Family: TSocketFamily read FFamily Write SetFamily;
  677. {:When resolving of domain name return both IPv4 and IPv6 addresses, then
  678. specify if is used IPv4 (dafault - @true) or IPv6.}
  679. property PreferIP4: Boolean read FPreferIP4 Write FPreferIP4;
  680. {:By default (@true) is all timeouts used as timeout between two packets in
  681. reading operations. If you set this to @false, then Timeouts is for overall
  682. reading operation!}
  683. property InterPacketTimeout: Boolean read FInterPacketTimeout Write FInterPacketTimeout;
  684. {:All sended datas was splitted by this value.}
  685. property SendMaxChunk: Integer read FSendMaxChunk Write FSendMaxChunk;
  686. {:By setting this property to @true you can stop any communication. You can
  687. use this property for soft abort of communication.}
  688. property StopFlag: Boolean read FStopFlag Write FStopFlag;
  689. {:Timeout for data sending by non-blocking socket mode.}
  690. property NonblockSendTimeout: Integer read FNonblockSendTimeout Write FNonblockSendTimeout;
  691. {:This event is called by various reasons. It is good for monitoring socket,
  692. create gauges for data transfers, etc.}
  693. property OnStatus: THookSocketStatus read FOnStatus write FOnStatus;
  694. {:this event is good for some internal thinks about filtering readed datas.
  695. It is used by telnet client by example.}
  696. property OnReadFilter: THookDataFilter read FOnReadFilter write FOnReadFilter;
  697. {:This event is called after real socket creation for setting special socket
  698. options, because you not know when socket is created. (it is depended on
  699. Ipv4, IPv6 or automatic mode)}
  700. property OnCreateSocket: THookCreateSocket read FOnCreateSocket write FOnCreateSocket;
  701. {:This event is good for monitoring content of readed or writed datas.}
  702. property OnMonitor: THookMonitor read FOnMonitor write FOnMonitor;
  703. {:This event is good for calling your code during long socket operations.
  704. (Example, for refresing UI if class in not called within the thread.)
  705. Rate of heartbeats can be modified by @link(HeartbeatRate) property.}
  706. property OnHeartbeat: THookHeartbeat read FOnHeartbeat write FOnHeartbeat;
  707. {:Specify typical rate of @link(OnHeartbeat) event and @link(StopFlag) testing.
  708. Default value 0 disabling heartbeats! Value is in milliseconds.
  709. Real rate can be higher or smaller then this value, because it depending
  710. on real socket operations too!
  711. Note: Each heartbeat slowing socket processing.}
  712. property HeartbeatRate: integer read FHeartbeatRate Write FHeartbeatRate;
  713. {:What class own this socket? Used by protocol implementation classes.}
  714. property Owner: TObject read FOwner Write FOwner;
  715. end;
  716. {:@abstract(Support for SOCKS4 and SOCKS5 proxy)
  717. Layer with definition all necessary properties and functions for
  718. implementation SOCKS proxy client. Do not use this class directly.}
  719. TSocksBlockSocket = class(TBlockSocket)
  720. protected
  721. FSocksIP: string;
  722. FSocksPort: string;
  723. FSocksTimeout: integer;
  724. FSocksUsername: string;
  725. FSocksPassword: string;
  726. FUsingSocks: Boolean;
  727. FSocksResolver: Boolean;
  728. FSocksLastError: integer;
  729. FSocksResponseIP: string;
  730. FSocksResponsePort: string;
  731. FSocksLocalIP: string;
  732. FSocksLocalPort: string;
  733. FSocksRemoteIP: string;
  734. FSocksRemotePort: string;
  735. FBypassFlag: Boolean;
  736. FSocksType: TSocksType;
  737. function SocksCode(IP, Port: string): Ansistring;
  738. function SocksDecode(Value: Ansistring): integer;
  739. public
  740. constructor Create;
  741. {:Open connection to SOCKS proxy and if @link(SocksUsername) is set, do
  742. authorisation to proxy. This is needed only in special cases! (it is called
  743. internally!)}
  744. function SocksOpen: Boolean;
  745. {:Send specified request to SOCKS proxy. This is needed only in special
  746. cases! (it is called internally!)}
  747. function SocksRequest(Cmd: Byte; const IP, Port: string): Boolean;
  748. {:Receive response to previosly sended request. This is needed only in
  749. special cases! (it is called internally!)}
  750. function SocksResponse: Boolean;
  751. {:Is @True when class is using SOCKS proxy.}
  752. property UsingSocks: Boolean read FUsingSocks;
  753. {:If SOCKS proxy failed, here is error code returned from SOCKS proxy.}
  754. property SocksLastError: integer read FSocksLastError;
  755. published
  756. {:Address of SOCKS server. If value is empty string, SOCKS support is
  757. disabled. Assingning any value to this property enable SOCKS mode.
  758. Warning: You cannot combine this mode with HTTP-tunneling mode!}
  759. property SocksIP: string read FSocksIP write FSocksIP;
  760. {:Port of SOCKS server. Default value is '1080'.}
  761. property SocksPort: string read FSocksPort write FSocksPort;
  762. {:If you need authorisation on SOCKS server, set username here.}
  763. property SocksUsername: string read FSocksUsername write FSocksUsername;
  764. {:If you need authorisation on SOCKS server, set password here.}
  765. property SocksPassword: string read FSocksPassword write FSocksPassword;
  766. {:Specify timeout for communicatin with SOCKS server. Default is one minute.}
  767. property SocksTimeout: integer read FSocksTimeout write FSocksTimeout;
  768. {:If @True, all symbolic names of target hosts is not translated to IP's
  769. locally, but resolving is by SOCKS proxy. Default is @True.}
  770. property SocksResolver: Boolean read FSocksResolver write FSocksResolver;
  771. {:Specify SOCKS type. By default is used SOCKS5, but you can use SOCKS4 too.
  772. When you select SOCKS4, then if @link(SOCKSResolver) is enabled, then is
  773. used SOCKS4a. Othervise is used pure SOCKS4.}
  774. property SocksType: TSocksType read FSocksType write FSocksType;
  775. end;
  776. {:@abstract(Implementation of TCP socket.)
  777. Supported features: IPv4, IPv6, SSL/TLS or SSH (depending on used plugin),
  778. SOCKS5 proxy (outgoing connections and limited incomming), SOCKS4/4a proxy
  779. (outgoing connections and limited incomming), TCP through HTTP proxy tunnel.}
  780. TTCPBlockSocket = class(TSocksBlockSocket)
  781. protected
  782. FOnAfterConnect: THookAfterConnect;
  783. FSSL: TCustomSSL;
  784. FHTTPTunnelIP: string;
  785. FHTTPTunnelPort: string;
  786. FHTTPTunnel: Boolean;
  787. FHTTPTunnelRemoteIP: string;
  788. FHTTPTunnelRemotePort: string;
  789. FHTTPTunnelUser: string;
  790. FHTTPTunnelPass: string;
  791. FHTTPTunnelTimeout: integer;
  792. procedure SocksDoConnect(IP, Port: string);
  793. procedure HTTPTunnelDoConnect(IP, Port: string);
  794. procedure DoAfterConnect;
  795. public
  796. {:Create TCP socket class with default plugin for SSL/TSL/SSH implementation
  797. (see @link(SSLImplementation))}
  798. constructor Create;
  799. {:Create TCP socket class with desired plugin for SSL/TSL/SSH implementation}
  800. constructor CreateWithSSL(SSLPlugin: TSSLClass);
  801. destructor Destroy; override;
  802. {:See @link(TBlockSocket.CloseSocket)}
  803. procedure CloseSocket; override;
  804. {:See @link(TBlockSocket.WaitingData)}
  805. function WaitingData: Integer; override;
  806. {:Sets socket to receive mode for new incoming connections. It is necessary
  807. to use @link(TBlockSocket.BIND) function call before this method to select
  808. receiving port!
  809. If you use SOCKS, activate incoming TCP connection by this proxy. (By BIND
  810. method of SOCKS.)}
  811. procedure Listen; override;
  812. {:Waits until new incoming connection comes. After it comes a new socket is
  813. automatically created (socket handler is returned by this function as
  814. result).
  815. If you use SOCKS, new socket is not created! In this case is used same
  816. socket as socket for listening! So, you can accept only one connection in
  817. SOCKS mode.}
  818. function Accept: TSocket; override;
  819. {:Connects socket to remote IP address and PORT. The same rules as with
  820. @link(TBlockSocket.BIND) method are valid. The only exception is that PORT
  821. with 0 value will not be connected. After call to this method
  822. a communication channel between local and remote socket is created. Local
  823. socket is assigned automatically if not controlled by previous call to
  824. @link(TBlockSocket.BIND) method. Structures @link(TBlockSocket.LocalSin)
  825. and @link(TBlockSocket.RemoteSin) will be filled with valid values.
  826. If you use SOCKS, activate outgoing TCP connection by SOCKS proxy specified
  827. in @link(TSocksBlockSocket.SocksIP). (By CONNECT method of SOCKS.)
  828. If you use HTTP-tunnel mode, activate outgoing TCP connection by HTTP
  829. tunnel specified in @link(HTTPTunnelIP). (By CONNECT method of HTTP
  830. protocol.)
  831. Note: If you call this on non-created socket, then socket is created
  832. automaticly.}
  833. procedure Connect(IP, Port: string); override;
  834. {:If you need upgrade existing TCP connection to SSL/TLS (or SSH2, if plugin
  835. allows it) mode, then call this method. This method switch this class to
  836. SSL mode and do SSL/TSL handshake.}
  837. procedure SSLDoConnect;
  838. {:By this method you can downgrade existing SSL/TLS connection to normal TCP
  839. connection.}
  840. procedure SSLDoShutdown;
  841. {:If you need use this component as SSL/TLS TCP server, then after accepting
  842. of inbound connection you need start SSL/TLS session by this method. Before
  843. call this function, you must have assigned all neeeded certificates and
  844. keys!}
  845. function SSLAcceptConnection: Boolean;
  846. {:See @link(TBlockSocket.GetLocalSinIP)}
  847. function GetLocalSinIP: string; override;
  848. {:See @link(TBlockSocket.GetRemoteSinIP)}
  849. function GetRemoteSinIP: string; override;
  850. {:See @link(TBlockSocket.GetLocalSinPort)}
  851. function GetLocalSinPort: Integer; override;
  852. {:See @link(TBlockSocket.GetRemoteSinPort)}
  853. function GetRemoteSinPort: Integer; override;
  854. {:See @link(TBlockSocket.SendBuffer)}
  855. function SendBuffer(Buffer: TMemory; Length: Integer): Integer; override;
  856. {:See @link(TBlockSocket.RecvBuffer)}
  857. function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; override;
  858. {:Return value of socket type. For TCP return SOCK_STREAM.}
  859. function GetSocketType: integer; override;
  860. {:Return value of protocol type for socket creation. For TCP return
  861. IPPROTO_TCP.}
  862. function GetSocketProtocol: integer; override;
  863. {:Class implementing SSL/TLS support. It is allways some descendant
  864. of @link(TCustomSSL) class. When programmer not select some SSL plugin
  865. class, then is used @link(TSSLNone)}
  866. property SSL: TCustomSSL read FSSL;
  867. {:@True if is used HTTP tunnel mode.}
  868. property HTTPTunnel: Boolean read FHTTPTunnel;
  869. published
  870. {:Return descriptive string for @link(LastError). On case of error
  871. in SSL/TLS subsystem, it returns right error description.}
  872. function GetErrorDescEx: string; override;
  873. {:Specify IP address of HTTP proxy. Assingning non-empty value to this
  874. property enable HTTP-tunnel mode. This mode is for tunnelling any outgoing
  875. TCP connection through HTTP proxy server. (If policy on HTTP proxy server
  876. allow this!) Warning: You cannot combine this mode with SOCK5 mode!}
  877. property HTTPTunnelIP: string read FHTTPTunnelIP Write FHTTPTunnelIP;
  878. {:Specify port of HTTP proxy for HTTP-tunneling.}
  879. property HTTPTunnelPort: string read FHTTPTunnelPort Write FHTTPTunnelPort;
  880. {:Specify authorisation username for access to HTTP proxy in HTTP-tunnel
  881. mode. If you not need authorisation, then let this property empty.}
  882. property HTTPTunnelUser: string read FHTTPTunnelUser Write FHTTPTunnelUser;
  883. {:Specify authorisation password for access to HTTP proxy in HTTP-tunnel
  884. mode.}
  885. property HTTPTunnelPass: string read FHTTPTunnelPass Write FHTTPTunnelPass;
  886. {:Specify timeout for communication with HTTP proxy in HTTPtunnel mode.}
  887. property HTTPTunnelTimeout: integer read FHTTPTunnelTimeout Write FHTTPTunnelTimeout;
  888. {:This event is called after sucessful TCP socket connection.}
  889. property OnAfterConnect: THookAfterConnect read FOnAfterConnect write FOnAfterConnect;
  890. end;
  891. {:@abstract(Datagram based communication)
  892. This class implementing datagram based communication instead default stream
  893. based communication style.}
  894. TDgramBlockSocket = class(TSocksBlockSocket)
  895. public
  896. {:Fill @link(TBlockSocket.RemoteSin) structure. This address is used for
  897. sending data.}
  898. procedure Connect(IP, Port: string); override;
  899. {:Silently redirected to @link(TBlockSocket.SendBufferTo).}
  900. function SendBuffer(Buffer: TMemory; Length: Integer): Integer; override;
  901. {:Silently redirected to @link(TBlockSocket.RecvBufferFrom).}
  902. function RecvBuffer(Buffer: TMemory; Length: Integer): Integer; override;
  903. end;
  904. {:@abstract(Implementation of UDP socket.)
  905. NOTE: in this class is all receiving redirected to RecvBufferFrom. You can
  906. use for reading any receive function. Preffered is RecvPacket! Similary all
  907. sending is redirected to SendbufferTo. You can use for sending UDP packet any
  908. sending function, like SendString.
  909. Supported features: IPv4, IPv6, unicasts, broadcasts, multicasts, SOCKS5
  910. proxy (only unicasts! Outgoing and incomming.)}
  911. TUDPBlockSocket = class(TDgramBlockSocket)
  912. protected
  913. FSocksControlSock: TTCPBlockSocket;
  914. function UdpAssociation: Boolean;
  915. procedure SetMulticastTTL(TTL: integer);
  916. function GetMulticastTTL:integer;
  917. public
  918. destructor Destroy; override;
  919. {:Enable or disable sending of broadcasts. If seting OK, result is @true.
  920. This method is not supported in SOCKS5 mode! IPv6 does not support
  921. broadcasts! In this case you must use Multicasts instead.}
  922. procedure EnableBroadcast(Value: Boolean);
  923. {:See @link(TBlockSocket.SendBufferTo)}
  924. function SendBufferTo(Buffer: TMemory; Length: Integer): Integer; override;
  925. {:See @link(TBlockSocket.RecvBufferFrom)}
  926. function RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer; override;
  927. {$IFNDEF CIL}
  928. {:Add this socket to given multicast group. You cannot use Multicasts in
  929. SOCKS mode!}
  930. procedure AddMulticast(MCastIP:string);
  931. {:Remove this socket from given multicast group.}
  932. procedure DropMulticast(MCastIP:string);
  933. {$ENDIF}
  934. {:All sended multicast datagrams is loopbacked to your interface too. (you
  935. can read your sended datas.) You can disable this feature by this function.
  936. This function not working on some Windows systems!}
  937. procedure EnableMulticastLoop(Value: Boolean);
  938. {:Return value of socket type. For UDP return SOCK_DGRAM.}
  939. function GetSocketType: integer; override;
  940. {:Return value of protocol type for socket creation. For UDP return
  941. IPPROTO_UDP.}
  942. function GetSocketProtocol: integer; override;
  943. {:Set Time-to-live value for multicasts packets. It define number of routers
  944. for transfer of datas. If you set this to 1 (dafault system value), then
  945. multicasts packet goes only to you local network. If you need transport
  946. multicast packet to worldwide, then increase this value, but be carefull,
  947. lot of routers on internet does not transport multicasts packets!}
  948. property MulticastTTL: Integer read GetMulticastTTL Write SetMulticastTTL;
  949. end;
  950. {:@abstract(Implementation of RAW ICMP socket.)
  951. For this object you must have rights for creating RAW sockets!}
  952. TICMPBlockSocket = class(TDgramBlockSocket)
  953. public
  954. {:Return value of socket type. For RAW and ICMP return SOCK_RAW.}
  955. function GetSocketType: integer; override;
  956. {:Return value of protocol type for socket creation. For ICMP returns
  957. IPPROTO_ICMP or IPPROTO_ICMPV6}
  958. function GetSocketProtocol: integer; override;
  959. end;
  960. {:@abstract(Implementation of RAW socket.)
  961. For this object you must have rights for creating RAW sockets!}
  962. TRAWBlockSocket = class(TBlockSocket)
  963. public
  964. {:Return value of socket type. For RAW and ICMP return SOCK_RAW.}
  965. function GetSocketType: integer; override;
  966. {:Return value of protocol type for socket creation. For RAW returns
  967. IPPROTO_RAW.}
  968. function GetSocketProtocol: integer; override;
  969. end;
  970. {:@abstract(Implementation of PGM-message socket.)
  971. Not all systems supports this protocol!}
  972. TPGMMessageBlockSocket = class(TBlockSocket)
  973. public
  974. {:Return value of socket type. For PGM-message return SOCK_RDM.}
  975. function GetSocketType: integer; override;
  976. {:Return value of protocol type for socket creation. For PGM-message returns
  977. IPPROTO_RM.}
  978. function GetSocketProtocol: integer; override;
  979. end;
  980. {:@abstract(Implementation of PGM-stream socket.)
  981. Not all systems supports this protocol!}
  982. TPGMStreamBlockSocket = class(TBlockSocket)
  983. public
  984. {:Return value of socket type. For PGM-stream return SOCK_STREAM.}
  985. function GetSocketType: integer; override;
  986. {:Return value of protocol type for socket creation. For PGM-stream returns
  987. IPPROTO_RM.}
  988. function GetSocketProtocol: integer; override;
  989. end;
  990. {:@abstract(Parent class for all SSL plugins.)
  991. This is abstract class defining interface for other SSL plugins.
  992. Instance of this class will be created for each @link(TTCPBlockSocket).
  993. Warning: not all methods and propertis can work in all existing SSL plugins!
  994. Please, read documentation of used SSL plugin.}
  995. TCustomSSL = class(TObject)
  996. private
  997. protected
  998. FOnVerifyCert: THookVerifyCert;
  999. FSocket: TTCPBlockSocket;
  1000. FSSLEnabled: Boolean;
  1001. FLastError: integer;
  1002. FLastErrorDesc: string;
  1003. FSSLType: TSSLType;
  1004. FKeyPassword: string;
  1005. FCiphers: string;
  1006. FCertificateFile: string;
  1007. FPrivateKeyFile: string;
  1008. FCertificate: Ansistring;
  1009. FPrivateKey: Ansistring;
  1010. FPFX: Ansistring;
  1011. FPFXfile: string;
  1012. FCertCA: Ansistring;
  1013. FCertCAFile: string;
  1014. FTrustCertificate: Ansistring;
  1015. FTrustCertificateFile: string;
  1016. FVerifyCert: Boolean;
  1017. FUsername: string;
  1018. FPassword: string;
  1019. FSSHChannelType: string;
  1020. FSSHChannelArg1: string;
  1021. FSSHChannelArg2: string;
  1022. FCertComplianceLevel: integer;
  1023. FSNIHost: string;
  1024. procedure ReturnError;
  1025. procedure SetCertCAFile(const Value: string); virtual;
  1026. function DoVerifyCert:boolean;
  1027. function CreateSelfSignedCert(Host: string): Boolean; virtual;
  1028. public
  1029. {: Create plugin class. it is called internally from @link(TTCPBlockSocket)}
  1030. constructor Create(const Value: TTCPBlockSocket); virtual;
  1031. {: Assign settings (certificates and configuration) from another SSL plugin
  1032. class.}
  1033. procedure Assign(const Value: TCustomSSL); virtual;
  1034. {: return description of used plugin. It usually return name and version
  1035. of used SSL library.}
  1036. function LibVersion: String; virtual;
  1037. {: return name of used plugin.}
  1038. function LibName: String; virtual;
  1039. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1040. Here is needed code for start SSL connection.}
  1041. function Connect: boolean; virtual;
  1042. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1043. Here is needed code for acept new SSL connection.}
  1044. function Accept: boolean; virtual;
  1045. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1046. Here is needed code for hard shutdown of SSL connection. (for example,
  1047. before socket is closed)}
  1048. function Shutdown: boolean; virtual;
  1049. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1050. Here is needed code for soft shutdown of SSL connection. (for example,
  1051. when you need to continue with unprotected connection.)}
  1052. function BiShutdown: boolean; virtual;
  1053. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1054. Here is needed code for sending some datas by SSL connection.}
  1055. function SendBuffer(Buffer: TMemory; Len: Integer): Integer; virtual;
  1056. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1057. Here is needed code for receiving some datas by SSL connection.}
  1058. function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; virtual;
  1059. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1060. Here is needed code for getting count of datas what waiting for read.
  1061. If SSL plugin not allows this, then it should return 0.}
  1062. function WaitingData: Integer; virtual;
  1063. {:Return string with identificator of SSL/TLS version of existing
  1064. connection.}
  1065. function GetSSLVersion: string; virtual;
  1066. {:Return subject of remote SSL peer.}
  1067. function GetPeerSubject: string; virtual;
  1068. {:Return Serial number if remote X509 certificate.}
  1069. function GetPeerSerialNo: integer; virtual;
  1070. {:Return issuer certificate of remote SSL peer.}
  1071. function GetPeerIssuer: string; virtual;
  1072. {:Return peer name from remote side certificate. This is good for verify,
  1073. if certificate is generated for remote side IP name.}
  1074. function GetPeerName: string; virtual;
  1075. {:Returns has of peer name from remote side certificate. This is good
  1076. for fast remote side authentication.}
  1077. function GetPeerNameHash: cardinal; virtual;
  1078. {:Return fingerprint of remote SSL peer.}
  1079. function GetPeerFingerprint: string; virtual;
  1080. {:Return all detailed information about certificate from remote side of
  1081. SSL/TLS connection. Result string can be multilined! Each plugin can return
  1082. this informations in different format!}
  1083. function GetCertInfo: string; virtual;
  1084. {:Return currently used Cipher.}
  1085. function GetCipherName: string; virtual;
  1086. {:Return currently used number of bits in current Cipher algorythm.}
  1087. function GetCipherBits: integer; virtual;
  1088. {:Return number of bits in current Cipher algorythm.}
  1089. function GetCipherAlgBits: integer; virtual;
  1090. {:Return result value of verify remote side certificate. Look to OpenSSL
  1091. documentation for possible values. For example 0 is successfuly verified
  1092. certificate, or 18 is self-signed certificate.}
  1093. function GetVerifyCert: integer; virtual;
  1094. {: Resurn @true if SSL mode is enabled on existing cvonnection.}
  1095. property SSLEnabled: Boolean read FSSLEnabled;
  1096. {:Return error code of last SSL operation. 0 is OK.}
  1097. property LastError: integer read FLastError;
  1098. {:Return error description of last SSL operation.}
  1099. property LastErrorDesc: string read FLastErrorDesc;
  1100. published
  1101. {:Here you can specify requested SSL/TLS mode. Default is autodetection, but
  1102. on some servers autodetection not working properly. In this case you must
  1103. specify requested SSL/TLS mode by your hand!}
  1104. property SSLType: TSSLType read FSSLType write FSSLType;
  1105. {:Password for decrypting of encoded certificate or key.}
  1106. property KeyPassword: string read FKeyPassword write FKeyPassword;
  1107. {:Username for possible credentials.}
  1108. property Username: string read FUsername write FUsername;
  1109. {:password for possible credentials.}
  1110. property Password: string read FPassword write FPassword;
  1111. {:By this property you can modify default set of SSL/TLS ciphers.}
  1112. property Ciphers: string read FCiphers write FCiphers;
  1113. {:Used for loading certificate from disk file. See to plugin documentation
  1114. if this method is supported and how!}
  1115. property CertificateFile: string read FCertificateFile write FCertificateFile;
  1116. {:Used for loading private key from disk file. See to plugin documentation
  1117. if this method is supported and how!}
  1118. property PrivateKeyFile: string read FPrivateKeyFile write FPrivateKeyFile;
  1119. {:Used for loading certificate from binary string. See to plugin documentation
  1120. if this method is supported and how!}
  1121. property Certificate: Ansistring read FCertificate write FCertificate;
  1122. {:Used for loading private key from binary string. See to plugin documentation
  1123. if this method is supported and how!}
  1124. property PrivateKey: Ansistring read FPrivateKey write FPrivateKey;
  1125. {:Used for loading PFX from binary string. See to plugin documentation
  1126. if this method is supported and how!}
  1127. property PFX: Ansistring read FPFX write FPFX;
  1128. {:Used for loading PFX from disk file. See to plugin documentation
  1129. if this method is supported and how!}
  1130. property PFXfile: string read FPFXfile write FPFXfile;
  1131. {:Used for loading trusted certificates from disk file. See to plugin documentation
  1132. if this method is supported and how!}
  1133. property TrustCertificateFile: string read FTrustCertificateFile write FTrustCertificateFile;
  1134. {:Used for loading trusted certificates from binary string. See to plugin documentation
  1135. if this method is supported and how!}
  1136. property TrustCertificate: Ansistring read FTrustCertificate write FTrustCertificate;
  1137. {:Used for loading CA certificates from binary string. See to plugin documentation
  1138. if this method is supported and how!}
  1139. property CertCA: Ansistring read FCertCA write FCertCA;
  1140. {:Used for loading CA certificates from disk file. See to plugin documentation
  1141. if this method is supported and how!}
  1142. property CertCAFile: string read FCertCAFile write SetCertCAFile;
  1143. {:If @true, then is verified client certificate. (it is good for writing
  1144. SSL/TLS servers.) When you are not server, but you are client, then if this
  1145. property is @true, verify servers certificate.}
  1146. property VerifyCert: Boolean read FVerifyCert write FVerifyCert;
  1147. {:channel type for possible SSH connections}
  1148. property SSHChannelType: string read FSSHChannelType write FSSHChannelType;
  1149. {:First argument of channel type for possible SSH connections}
  1150. property SSHChannelArg1: string read FSSHChannelArg1 write FSSHChannelArg1;
  1151. {:Second argument of channel type for possible SSH connections}
  1152. property SSHChannelArg2: string read FSSHChannelArg2 write FSSHChannelArg2;
  1153. {: Level of standards compliance level
  1154. (CryptLib: values in cryptlib.pas, -1: use default value ) }
  1155. property CertComplianceLevel:integer read FCertComplianceLevel write FCertComplianceLevel;
  1156. {:This event is called when verifying the server certificate immediatally after
  1157. a successfull verification in the ssl library.}
  1158. property OnVerifyCert: THookVerifyCert read FOnVerifyCert write FOnVerifyCert;
  1159. {: Server Name Identification. Host name to send to server. If empty the host name
  1160. found in URL will be used, which should be the normal use (http Header Host = SNI Host).
  1161. The value is cleared after the connection is established.
  1162. (SNI support requires OpenSSL 0.9.8k or later. Cryptlib not supported, yet ) }
  1163. property SNIHost:string read FSNIHost write FSNIHost;
  1164. end;
  1165. {:@abstract(Default SSL plugin with no SSL support.)
  1166. Dummy SSL plugin implementation for applications without SSL/TLS support.}
  1167. TSSLNone = class (TCustomSSL)
  1168. public
  1169. {:See @inherited}
  1170. function LibVersion: String; override;
  1171. {:See @inherited}
  1172. function LibName: String; override;
  1173. end;
  1174. {:@abstract(Record with definition of IP packet header.)
  1175. For reading data from ICMP or RAW sockets.}
  1176. TIPHeader = record
  1177. VerLen: Byte;
  1178. TOS: Byte;
  1179. TotalLen: Word;
  1180. Identifer: Word;
  1181. FragOffsets: Word;
  1182. TTL: Byte;
  1183. Protocol: Byte;
  1184. CheckSum: Word;
  1185. SourceIp: LongWord;
  1186. DestIp: LongWord;
  1187. Options: LongWord;
  1188. end;
  1189. {:@abstract(Parent class of application protocol implementations.)
  1190. By this class is defined common properties.}
  1191. TSynaClient = Class(TObject)
  1192. protected
  1193. FTargetHost: string;
  1194. FTargetPort: string;
  1195. FIPInterface: string;
  1196. FTimeout: integer;
  1197. FUserName: string;
  1198. FPassword: string;
  1199. public
  1200. constructor Create;
  1201. published
  1202. {:Specify terget server IP (or symbolic name). Default is 'localhost'.}
  1203. property TargetHost: string read FTargetHost Write FTargetHost;
  1204. {:Specify terget server port (or symbolic name).}
  1205. property TargetPort: string read FTargetPort Write FTargetPort;
  1206. {:Defined local socket address. (outgoing IP address). By default is used
  1207. '0.0.0.0' as wildcard for default IP.}
  1208. property IPInterface: string read FIPInterface Write FIPInterface;
  1209. {:Specify default timeout for socket operations.}
  1210. property Timeout: integer read FTimeout Write FTimeout;
  1211. {:If protocol need user authorization, then fill here username.}
  1212. property UserName: string read FUserName Write FUserName;
  1213. {:If protocol need user authorization, then fill here password.}
  1214. property Password: string read FPassword Write FPassword;
  1215. end;
  1216. var
  1217. {:Selected SSL plugin. Default is @link(TSSLNone).
  1218. Do not change this value directly!!!
  1219. Just add your plugin unit to your project uses instead. Each plugin unit have
  1220. initialization code what modify this variable.}
  1221. SSLImplementation: TSSLClass = TSSLNone;
  1222. implementation
  1223. {$IFDEF ONCEWINSOCK}
  1224. var
  1225. WsaDataOnce: TWSADATA;
  1226. e: ESynapseError;
  1227. {$ENDIF}
  1228. constructor TBlockSocket.Create;
  1229. begin
  1230. CreateAlternate('');
  1231. end;
  1232. constructor TBlockSocket.CreateAlternate(Stub: string);
  1233. {$IFNDEF ONCEWINSOCK}
  1234. var
  1235. e: ESynapseError;
  1236. {$ENDIF}
  1237. begin
  1238. inherited Create;
  1239. FDelayedOptions := TList.Create;
  1240. FRaiseExcept := False;
  1241. {$IFDEF RAISEEXCEPT}
  1242. FRaiseExcept := True;
  1243. {$ENDIF}
  1244. FSocket := INVALID_SOCKET;
  1245. FBuffer := '';
  1246. FLastCR := False;
  1247. FLastLF := False;
  1248. FBinded := False;
  1249. FNonBlockMode := False;
  1250. FMaxLineLength := 0;
  1251. FMaxSendBandwidth := 0;
  1252. FNextSend := 0;
  1253. FMaxRecvBandwidth := 0;
  1254. FNextRecv := 0;
  1255. FConvertLineEnd := False;
  1256. FFamily := SF_Any;
  1257. FFamilySave := SF_Any;
  1258. FIP6used := False;
  1259. FPreferIP4 := True;
  1260. FInterPacketTimeout := True;
  1261. FRecvCounter := 0;
  1262. FSendCounter := 0;
  1263. FSendMaxChunk := c64k;
  1264. FStopFlag := False;
  1265. FNonblockSendTimeout := 15000;
  1266. FHeartbeatRate := 0;
  1267. FOwner := nil;
  1268. {$IFNDEF ONCEWINSOCK}
  1269. if Stub = '' then
  1270. Stub := DLLStackName;
  1271. if not InitSocketInterface(Stub) then
  1272. begin
  1273. e := ESynapseError.Create('Error loading Socket interface (' + Stub + ')!');
  1274. e.ErrorCode := 0;
  1275. e.ErrorMessage := 'Error loading Socket interface (' + Stub + ')!';
  1276. raise e;
  1277. end;
  1278. SockCheck(synsock.WSAStartup(WinsockLevel, FWsaDataOnce));
  1279. ExceptCheck;
  1280. {$ENDIF}
  1281. end;
  1282. destructor TBlockSocket.Destroy;
  1283. var
  1284. n: integer;
  1285. p: TSynaOption;
  1286. begin
  1287. CloseSocket;
  1288. {$IFNDEF ONCEWINSOCK}
  1289. synsock.WSACleanup;
  1290. DestroySocketInterface;
  1291. {$ENDIF}
  1292. for n := FDelayedOptions.Count - 1 downto 0 do
  1293. begin
  1294. p := TSynaOption(FDelayedOptions[n]);
  1295. p.Free;
  1296. end;
  1297. FDelayedOptions.Free;
  1298. inherited Destroy;
  1299. end;
  1300. function TBlockSocket.FamilyToAF(f: TSocketFamily): TAddrFamily;
  1301. begin
  1302. case f of
  1303. SF_ip4:
  1304. Result := AF_INET;
  1305. SF_ip6:
  1306. Result := AF_INET6;
  1307. else
  1308. Result := AF_UNSPEC;
  1309. end;
  1310. end;
  1311. procedure TBlockSocket.SetDelayedOption(const Value: TSynaOption);
  1312. var
  1313. li: TLinger;
  1314. x: integer;
  1315. buf: TMemory;
  1316. {$IFNDEF MSWINDOWS}
  1317. timeval: TTimeval;
  1318. {$ENDIF}
  1319. begin
  1320. case value.Option of
  1321. SOT_Linger:
  1322. begin
  1323. {$IFDEF CIL}
  1324. li := TLinger.Create(Value.Enabled, Value.Value div 1000);
  1325. synsock.SetSockOptObj(FSocket, integer(SOL_SOCKET), integer(SO_LINGER), li);
  1326. {$ELSE}
  1327. li.l_onoff := Ord(Value.Enabled);
  1328. li.l_linger := Value.Value div 1000;
  1329. buf := @li;
  1330. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_LINGER), buf, SizeOf(li));
  1331. {$ENDIF}
  1332. end;
  1333. SOT_RecvBuff:
  1334. begin
  1335. {$IFDEF CIL}
  1336. buf := System.BitConverter.GetBytes(value.Value);
  1337. {$ELSE}
  1338. buf := @Value.Value;
  1339. {$ENDIF}
  1340. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVBUF),
  1341. buf, SizeOf(Value.Value));
  1342. end;
  1343. SOT_SendBuff:
  1344. begin
  1345. {$IFDEF CIL}
  1346. buf := System.BitConverter.GetBytes(value.Value);
  1347. {$ELSE}
  1348. buf := @Value.Value;
  1349. {$ENDIF}
  1350. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDBUF),
  1351. buf, SizeOf(Value.Value));
  1352. end;
  1353. SOT_NonBlock:
  1354. begin
  1355. FNonBlockMode := Value.Enabled;
  1356. x := Ord(FNonBlockMode);
  1357. synsock.IoctlSocket(FSocket, FIONBIO, x);
  1358. end;
  1359. SOT_RecvTimeout:
  1360. begin
  1361. {$IFDEF CIL}
  1362. buf := System.BitConverter.GetBytes(value.Value);
  1363. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
  1364. buf, SizeOf(Value.Value));
  1365. {$ELSE}
  1366. {$IFDEF MSWINDOWS}
  1367. buf := @Value.Value;
  1368. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
  1369. buf, SizeOf(Value.Value));
  1370. {$ELSE}
  1371. timeval.tv_sec:=Value.Value div 1000;
  1372. timeval.tv_usec:=(Value.Value mod 1000) * 1000;
  1373. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
  1374. @timeval, SizeOf(timeval));
  1375. {$ENDIF}
  1376. {$ENDIF}
  1377. end;
  1378. SOT_SendTimeout:
  1379. begin
  1380. {$IFDEF CIL}
  1381. buf := System.BitConverter.GetBytes(value.Value);
  1382. {$ELSE}
  1383. {$IFDEF MSWINDOWS}
  1384. buf := @Value.Value;
  1385. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDTIMEO),
  1386. buf, SizeOf(Value.Value));
  1387. {$ELSE}
  1388. timeval.tv_sec:=Value.Value div 1000;
  1389. timeval.tv_usec:=(Value.Value mod 1000) * 1000;
  1390. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDTIMEO),
  1391. @timeval, SizeOf(timeval));
  1392. {$ENDIF}
  1393. {$ENDIF}
  1394. end;
  1395. SOT_Reuse:
  1396. begin
  1397. x := Ord(Value.Enabled);
  1398. {$IFDEF CIL}
  1399. buf := System.BitConverter.GetBytes(x);
  1400. {$ELSE}
  1401. buf := @x;
  1402. {$ENDIF}
  1403. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_REUSEADDR), buf, SizeOf(x));
  1404. end;
  1405. SOT_TTL:
  1406. begin
  1407. {$IFDEF CIL}
  1408. buf := System.BitConverter.GetBytes(value.Value);
  1409. {$ELSE}
  1410. buf := @Value.Value;
  1411. {$ENDIF}
  1412. if FIP6Used then
  1413. synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_UNICAST_HOPS),
  1414. buf, SizeOf(Value.Value))
  1415. else
  1416. synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_TTL),
  1417. buf, SizeOf(Value.Value));
  1418. end;
  1419. SOT_Broadcast:
  1420. begin
  1421. //#todo1 broadcasty na IP6
  1422. x := Ord(Value.Enabled);
  1423. {$IFDEF CIL}
  1424. buf := System.BitConverter.GetBytes(x);
  1425. {$ELSE}
  1426. buf := @x;
  1427. {$ENDIF}
  1428. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_BROADCAST), buf, SizeOf(x));
  1429. end;
  1430. SOT_MulticastTTL:
  1431. begin
  1432. {$IFDEF CIL}
  1433. buf := System.BitConverter.GetBytes(value.Value);
  1434. {$ELSE}
  1435. buf := @Value.Value;
  1436. {$ENDIF}
  1437. if FIP6Used then
  1438. synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_MULTICAST_HOPS),
  1439. buf, SizeOf(Value.Value))
  1440. else
  1441. synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_MULTICAST_TTL),
  1442. buf, SizeOf(Value.Value));
  1443. end;
  1444. SOT_MulticastLoop:
  1445. begin
  1446. x := Ord(Value.Enabled);
  1447. {$IFDEF CIL}
  1448. buf := System.BitConverter.GetBytes(x);
  1449. {$ELSE}
  1450. buf := @x;
  1451. {$ENDIF}
  1452. if FIP6Used then
  1453. synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_MULTICAST_LOOP), buf, SizeOf(x))
  1454. else
  1455. synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_MULTICAST_LOOP), buf, SizeOf(x));
  1456. end;
  1457. end;
  1458. Value.free;
  1459. end;
  1460. procedure TBlockSocket.DelayedOption(const Value: TSynaOption);
  1461. begin
  1462. if FSocket = INVALID_SOCKET then
  1463. begin
  1464. FDelayedOptions.Insert(0, Value);
  1465. end
  1466. else
  1467. SetDelayedOption(Value);
  1468. end;
  1469. procedure TBlockSocket.ProcessDelayedOptions;
  1470. var
  1471. n: integer;
  1472. d: TSynaOption;
  1473. begin
  1474. for n := FDelayedOptions.Count - 1 downto 0 do
  1475. begin
  1476. d := TSynaOption(FDelayedOptions[n]);
  1477. SetDelayedOption(d);
  1478. end;
  1479. FDelayedOptions.Clear;
  1480. end;
  1481. procedure TBlockSocket.SetSin(var Sin: TVarSin; IP, Port: string);
  1482. var
  1483. f: TSocketFamily;
  1484. begin
  1485. DoStatus(HR_ResolvingBegin, IP + ':' + Port);
  1486. ResetLastError;
  1487. //if socket exists, then use their type, else use users selection
  1488. f := SF_Any;
  1489. if (FSocket = INVALID_SOCKET) and (FFamily = SF_any) then
  1490. begin
  1491. if IsIP(IP) then
  1492. f := SF_IP4
  1493. else
  1494. if IsIP6(IP) then
  1495. f := SF_IP6;
  1496. end
  1497. else
  1498. f := FFamily;
  1499. FLastError := synsock.SetVarSin(sin, ip, port, FamilyToAF(f),
  1500. GetSocketprotocol, GetSocketType, FPreferIP4);
  1501. DoStatus(HR_ResolvingEnd, GetSinIP(sin) + ':' + IntTostr(GetSinPort(sin)));
  1502. end;
  1503. function TBlockSocket.GetSinIP(Sin: TVarSin): string;
  1504. begin
  1505. Result := synsock.GetSinIP(sin);
  1506. end;
  1507. function TBlockSocket.GetSinPort(Sin: TVarSin): Integer;
  1508. begin
  1509. Result := synsock.GetSinPort(sin);
  1510. end;
  1511. procedure TBlockSocket.CreateSocket;
  1512. var
  1513. sin: TVarSin;
  1514. begin
  1515. //dummy for SF_Any Family mode
  1516. ResetLastError;
  1517. if (FFamily <> SF_Any) and (FSocket = INVALID_SOCKET) then
  1518. begin
  1519. {$IFDEF CIL}
  1520. if FFamily = SF_IP6 then
  1521. sin := TVarSin.Create(IPAddress.Parse('::0'), 0)
  1522. else
  1523. sin := TVarSin.Create(IPAddress.Parse('0.0.0.0'), 0);
  1524. {$ELSE}
  1525. FillChar(Sin, Sizeof(Sin), 0);
  1526. if FFamily = SF_IP6 then
  1527. sin.sin_family := AF_INET6
  1528. else
  1529. sin.sin_family := AF_INET;
  1530. {$ENDIF}
  1531. InternalCreateSocket(Sin);
  1532. end;
  1533. end;
  1534. procedure TBlockSocket.CreateSocketByName(const Value: String);
  1535. var
  1536. sin: TVarSin;
  1537. begin
  1538. ResetLastError;
  1539. if FSocket = INVALID_SOCKET then
  1540. begin
  1541. SetSin(sin, value, '0');
  1542. if FLastError = 0 then
  1543. InternalCreateSocket(Sin);
  1544. end;
  1545. end;
  1546. procedure TBlockSocket.InternalCreateSocket(Sin: TVarSin);
  1547. begin
  1548. FStopFlag := False;
  1549. FRecvCounter := 0;
  1550. FSendCounter := 0;
  1551. ResetLastError;
  1552. if FSocket = INVALID_SOCKET then
  1553. begin
  1554. FBuffer := '';
  1555. FBinded := False;
  1556. FIP6Used := Sin.AddressFamily = AF_INET6;
  1557. FSocket := synsock.Socket(integer(Sin.AddressFamily), GetSocketType, GetSocketProtocol);
  1558. if FSocket = INVALID_SOCKET then
  1559. FLastError := synsock.WSAGetLastError;
  1560. {$IFNDEF CIL}
  1561. FD_ZERO(FFDSet);
  1562. FD_SET(FSocket, FFDSet);
  1563. {$ENDIF}
  1564. ExceptCheck;
  1565. if FIP6used then
  1566. DoStatus(HR_SocketCreate, 'IPv6')
  1567. else
  1568. DoStatus(HR_SocketCreate, 'IPv4');
  1569. ProcessDelayedOptions;
  1570. DoCreateSocket;
  1571. end;
  1572. end;
  1573. procedure TBlockSocket.CloseSocket;
  1574. begin
  1575. AbortSocket;
  1576. end;
  1577. procedure TBlockSocket.AbortSocket;
  1578. var
  1579. n: integer;
  1580. p: TSynaOption;
  1581. begin
  1582. if FSocket <> INVALID_SOCKET then
  1583. synsock.CloseSocket(FSocket);
  1584. FSocket := INVALID_SOCKET;
  1585. for n := FDelayedOptions.Count - 1 downto 0 do
  1586. begin
  1587. p := TSynaOption(FDelayedOptions[n]);
  1588. p.Free;
  1589. end;
  1590. FDelayedOptions.Clear;
  1591. FFamily := FFamilySave;
  1592. DoStatus(HR_SocketClose, '');
  1593. end;
  1594. procedure TBlockSocket.Bind(IP, Port: string);
  1595. var
  1596. Sin: TVarSin;
  1597. begin
  1598. ResetLastError;
  1599. if (FSocket <> INVALID_SOCKET)
  1600. or not((FFamily = SF_ANY) and (IP = cAnyHost) and (Port = cAnyPort)) then
  1601. begin
  1602. SetSin(Sin, IP, Port);
  1603. if FLastError = 0 then
  1604. begin
  1605. if FSocket = INVALID_SOCKET then
  1606. InternalCreateSocket(Sin);
  1607. SockCheck(synsock.Bind(FSocket, Sin));
  1608. GetSinLocal;
  1609. FBuffer := '';
  1610. FBinded := True;
  1611. end;
  1612. ExceptCheck;
  1613. DoStatus(HR_Bind, IP + ':' + Port);
  1614. end;
  1615. end;
  1616. procedure TBlockSocket.Connect(IP, Port: string);
  1617. var
  1618. Sin: TVarSin;
  1619. begin
  1620. SetSin(Sin, IP, Port);
  1621. if FLastError = 0 then
  1622. begin
  1623. if FSocket = INVALID_SOCKET then
  1624. InternalCreateSocket(Sin);
  1625. SockCheck(synsock.Connect(FSocket, Sin));
  1626. if FLastError = 0 then
  1627. GetSins;
  1628. FBuffer := '';
  1629. FLastCR := False;
  1630. FLastLF := False;
  1631. end;
  1632. ExceptCheck;
  1633. DoStatus(HR_Connect, IP + ':' + Port);
  1634. end;
  1635. procedure TBlockSocket.Listen;
  1636. begin
  1637. SockCheck(synsock.Listen(FSocket, SOMAXCONN));
  1638. GetSins;
  1639. ExceptCheck;
  1640. DoStatus(HR_Listen, '');
  1641. end;
  1642. function TBlockSocket.Accept: TSocket;
  1643. begin
  1644. Result := synsock.Accept(FSocket, FRemoteSin);
  1645. /// SockCheck(Result);
  1646. ExceptCheck;
  1647. DoStatus(HR_Accept, '');
  1648. end;
  1649. procedure TBlockSocket.GetSinLocal;
  1650. begin
  1651. synsock.GetSockName(FSocket, FLocalSin);
  1652. end;
  1653. procedure TBlockSocket.GetSinRemote;
  1654. begin
  1655. synsock.GetPeerName(FSocket, FRemoteSin);
  1656. end;
  1657. procedure TBlockSocket.GetSins;
  1658. begin
  1659. GetSinLocal;
  1660. GetSinRemote;
  1661. end;
  1662. procedure TBlockSocket.SetBandwidth(Value: Integer);
  1663. begin
  1664. MaxSendBandwidth := Value;
  1665. MaxRecvBandwidth := Value;
  1666. end;
  1667. procedure TBlockSocket.LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
  1668. var
  1669. x: LongWord;
  1670. y: LongWord;
  1671. n: integer;
  1672. begin
  1673. if FStopFlag then
  1674. exit;
  1675. if MaxB > 0 then
  1676. begin
  1677. y := GetTick;
  1678. if Next > y then
  1679. begin
  1680. x := Next - y;
  1681. if x > 0 then
  1682. begin
  1683. DoStatus(HR_Wait, IntToStr(x));
  1684. sleep(x mod 250);
  1685. for n := 1 to x div 250 do
  1686. if FStopFlag then
  1687. Break
  1688. else
  1689. sleep(250);
  1690. end;
  1691. end;
  1692. Next := GetTick + Trunc((Length / MaxB) * 1000);
  1693. end;
  1694. end;
  1695. function TBlockSocket.TestStopFlag: Boolean;
  1696. begin
  1697. DoHeartbeat;
  1698. Result := FStopFlag;
  1699. if Result then
  1700. begin
  1701. FStopFlag := False;
  1702. FLastError := WSAECONNABORTED;
  1703. ExceptCheck;
  1704. end;
  1705. end;
  1706. function TBlockSocket.SendBuffer(Buffer: TMemory; Length: Integer): Integer;
  1707. {$IFNDEF CIL}
  1708. var
  1709. x, y: integer;
  1710. l, r: integer;
  1711. p: Pointer;
  1712. {$ENDIF}
  1713. begin
  1714. Result := 0;
  1715. if TestStopFlag then
  1716. Exit;
  1717. DoMonitor(True, Buffer, Length);
  1718. {$IFDEF CIL}
  1719. Result := synsock.Send(FSocket, Buffer, Length, 0);
  1720. {$ELSE}
  1721. l := Length;
  1722. x := 0;
  1723. while x < l do
  1724. begin
  1725. y := l - x;
  1726. if y > FSendMaxChunk then
  1727. y := FSendMaxChunk;
  1728. if y > 0 then
  1729. begin
  1730. LimitBandwidth(y, FMaxSendBandwidth, FNextsend);
  1731. p := IncPoint(Buffer, x);
  1732. r := synsock.Send(FSocket, p, y, MSG_NOSIGNAL);
  1733. SockCheck(r);
  1734. if FLastError = WSAEWOULDBLOCK then
  1735. begin
  1736. if CanWrite(FNonblockSendTimeout) then
  1737. begin
  1738. r := synsock.Send(FSocket, p, y, MSG_NOSIGNAL);
  1739. SockCheck(r);
  1740. end
  1741. else
  1742. FLastError := WSAETIMEDOUT;
  1743. end;
  1744. if FLastError <> 0 then
  1745. Break;
  1746. Inc(x, r);
  1747. Inc(Result, r);
  1748. Inc(FSendCounter, r);
  1749. DoStatus(HR_WriteCount, IntToStr(r));
  1750. end
  1751. else
  1752. break;
  1753. end;
  1754. {$ENDIF}
  1755. ExceptCheck;
  1756. end;
  1757. procedure TBlockSocket.SendByte(Data: Byte);
  1758. {$IFDEF CIL}
  1759. var
  1760. buf: TMemory;
  1761. {$ENDIF}
  1762. begin
  1763. {$IFDEF CIL}
  1764. setlength(buf, 1);
  1765. buf[0] := Data;
  1766. SendBuffer(buf, 1);
  1767. {$ELSE}
  1768. SendBuffer(@Data, 1);
  1769. {$ENDIF}
  1770. end;
  1771. procedure TBlockSocket.SendString(Data: AnsiString);
  1772. var
  1773. buf: TMemory;
  1774. begin
  1775. {$IFDEF CIL}
  1776. buf := BytesOf(Data);
  1777. {$ELSE}
  1778. buf := Pointer(data);
  1779. {$ENDIF}
  1780. SendBuffer(buf, Length(Data));
  1781. end;
  1782. procedure TBlockSocket.SendInteger(Data: integer);
  1783. var
  1784. buf: TMemory;
  1785. begin
  1786. {$IFDEF CIL}
  1787. buf := System.BitConverter.GetBytes(Data);
  1788. {$ELSE}
  1789. buf := @Data;
  1790. {$ENDIF}
  1791. SendBuffer(buf, SizeOf(Data));
  1792. end;
  1793. procedure TBlockSocket.SendBlock(const Data: AnsiString);
  1794. var
  1795. i: integer;
  1796. begin
  1797. i := SwapBytes(Length(data));
  1798. SendString(Codelongint(i) + Data);
  1799. end;
  1800. procedure TBlockSocket.InternalSendStream(const Stream: TStream; WithSize, Indy: boolean);
  1801. var
  1802. l: integer;
  1803. yr: integer;
  1804. s: AnsiString;
  1805. b: boolean;
  1806. {$IFDEF CIL}
  1807. buf: TMemory;
  1808. {$ENDIF}
  1809. begin
  1810. b := true;
  1811. l := 0;
  1812. if WithSize then
  1813. begin
  1814. l := Stream.Size - Stream.Position;;
  1815. if not Indy then
  1816. l := synsock.HToNL(l);
  1817. end;
  1818. repeat
  1819. {$IFDEF CIL}
  1820. Setlength(buf, FSendMaxChunk);
  1821. yr := Stream.read(buf, FSendMaxChunk);
  1822. if yr > 0 then
  1823. begin
  1824. if WithSize and b then
  1825. begin
  1826. b := false;
  1827. SendString(CodeLongInt(l));
  1828. end;
  1829. SendBuffer(buf, yr);
  1830. if FLastError <> 0 then
  1831. break;
  1832. end
  1833. {$ELSE}
  1834. Setlength(s, FSendMaxChunk);
  1835. yr := Stream.read(Pointer(s)^, FSendMaxChunk);
  1836. if yr > 0 then
  1837. begin
  1838. SetLength(s, yr);
  1839. if WithSize and b then
  1840. begin
  1841. b := false;
  1842. SendString(CodeLongInt(l) + s);
  1843. end
  1844. else
  1845. SendString(s);
  1846. if FLastError <> 0 then
  1847. break;
  1848. end
  1849. {$ENDIF}
  1850. until yr <= 0;
  1851. end;
  1852. procedure TBlockSocket.SendStreamRaw(const Stream: TStream);
  1853. begin
  1854. InternalSendStream(Stream, false, false);
  1855. end;
  1856. procedure TBlockSocket.SendStreamIndy(const Stream: TStream);
  1857. begin
  1858. InternalSendStream(Stream, true, true);
  1859. end;
  1860. procedure TBlockSocket.SendStream(const Stream: TStream);
  1861. begin
  1862. InternalSendStream(Stream, true, false);
  1863. end;
  1864. function TBlockSocket.RecvBuffer(Buffer: TMemory; Length: Integer): Integer;
  1865. begin
  1866. Result := 0;
  1867. if TestStopFlag then
  1868. Exit;
  1869. LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
  1870. // Result := synsock.Recv(FSocket, Buffer^, Length, MSG_NOSIGNAL);
  1871. Result := synsock.Recv(FSocket, Buffer, Length, MSG_NOSIGNAL);
  1872. if Result = 0 then
  1873. FLastError := WSAECONNRESET
  1874. else
  1875. SockCheck(Result);
  1876. ExceptCheck;
  1877. if Result > 0 then
  1878. begin
  1879. Inc(FRecvCounter, Result);
  1880. DoStatus(HR_ReadCount, IntToStr(Result));
  1881. DoMonitor(False, Buffer, Result);
  1882. DoReadFilter(Buffer, Result);
  1883. end;
  1884. end;
  1885. function TBlockSocket.RecvBufferEx(Buffer: TMemory; Len: Integer;
  1886. Timeout: Integer): Integer;
  1887. var
  1888. s: AnsiString;
  1889. rl, l: integer;
  1890. ti: LongWord;
  1891. {$IFDEF CIL}
  1892. n: integer;
  1893. b: TMemory;
  1894. {$ENDIF}
  1895. begin
  1896. ResetLastError;
  1897. Result := 0;
  1898. if Len > 0 then
  1899. begin
  1900. rl := 0;
  1901. repeat
  1902. ti := GetTick;
  1903. s := RecvPacket(Timeout);
  1904. l := Length(s);
  1905. if (rl + l) > Len then
  1906. l := Len - rl;
  1907. {$IFDEF CIL}
  1908. b := BytesOf(s);
  1909. for n := 0 to l do
  1910. Buffer[rl + n] := b[n];
  1911. {$ELSE}
  1912. Move(Pointer(s)^, IncPoint(Buffer, rl)^, l);
  1913. {$ENDIF}
  1914. rl := rl + l;
  1915. if FLastError <> 0 then
  1916. Break;
  1917. if rl >= Len then
  1918. Break;
  1919. if not FInterPacketTimeout then
  1920. begin
  1921. Timeout := Timeout - integer(TickDelta(ti, GetTick));
  1922. if Timeout <= 0 then
  1923. begin
  1924. FLastError := WSAETIMEDOUT;
  1925. Break;
  1926. end;
  1927. end;
  1928. until False;
  1929. delete(s, 1, l);
  1930. FBuffer := s;
  1931. Result := rl;
  1932. end;
  1933. end;
  1934. function TBlockSocket.RecvBufferStr(Len: Integer; Timeout: Integer): AnsiString;
  1935. var
  1936. x: integer;
  1937. {$IFDEF CIL}
  1938. buf: Tmemory;
  1939. {$ENDIF}
  1940. begin
  1941. Result := '';
  1942. if Len > 0 then
  1943. begin
  1944. {$IFDEF CIL}
  1945. Setlength(Buf, Len);
  1946. x := RecvBufferEx(buf, Len , Timeout);
  1947. if FLastError = 0 then
  1948. begin
  1949. SetLength(Buf, x);
  1950. Result := StringOf(buf);
  1951. end
  1952. else
  1953. Result := '';
  1954. {$ELSE}
  1955. Setlength(Result, Len);
  1956. x := RecvBufferEx(Pointer(Result), Len , Timeout);
  1957. if FLastError = 0 then
  1958. SetLength(Result, x)
  1959. else
  1960. Result := '';
  1961. {$ENDIF}
  1962. end;
  1963. end;
  1964. function TBlockSocket.RecvPacket(Timeout: Integer): AnsiString;
  1965. var
  1966. x: integer;
  1967. {$IFDEF CIL}
  1968. buf: TMemory;
  1969. {$ENDIF}
  1970. begin
  1971. Result := '';
  1972. ResetLastError;
  1973. if FBuffer <> '' then
  1974. begin
  1975. Result := FBuffer;
  1976. FBuffer := '';
  1977. end
  1978. else
  1979. begin
  1980. {$IFDEF MSWINDOWS}
  1981. //not drain CPU on large downloads...
  1982. Sleep(0);
  1983. {$ENDIF}
  1984. x := WaitingData;
  1985. if x > 0 then
  1986. begin
  1987. {$IFDEF CIL}
  1988. SetLength(Buf, x);
  1989. x := RecvBuffer(Buf, x);
  1990. if x >= 0 then
  1991. begin
  1992. SetLength(Buf, x);
  1993. Result := StringOf(Buf);
  1994. end;
  1995. {$ELSE}
  1996. SetLength(Result, x);
  1997. x := RecvBuffer(Pointer(Result), x);
  1998. if x >= 0 then
  1999. SetLength(Result, x);
  2000. {$ENDIF}
  2001. end
  2002. else
  2003. begin
  2004. if CanRead(Timeout) then
  2005. begin
  2006. x := WaitingData;
  2007. if x = 0 then
  2008. FLastError := WSAECONNRESET;
  2009. if x > 0 then
  2010. begin
  2011. {$IFDEF CIL}
  2012. SetLength(Buf, x);
  2013. x := RecvBuffer(Buf, x);
  2014. if x >= 0 then
  2015. begin
  2016. SetLength(Buf, x);
  2017. result := StringOf(Buf);
  2018. end;
  2019. {$ELSE}
  2020. SetLength(Result, x);
  2021. x := RecvBuffer(Pointer(Result), x);
  2022. if x >= 0 then
  2023. SetLength(Result, x);
  2024. {$ENDIF}
  2025. end;
  2026. end
  2027. else
  2028. FLastError := WSAETIMEDOUT;
  2029. end;
  2030. end;
  2031. if FConvertLineEnd and (Result <> '') then
  2032. begin
  2033. if FLastCR and (Result[1] = LF) then
  2034. Delete(Result, 1, 1);
  2035. if FLastLF and (Result[1] = CR) then
  2036. Delete(Result, 1, 1);
  2037. FLastCR := False;
  2038. FLastLF := False;
  2039. end;
  2040. ExceptCheck;
  2041. end;
  2042. function TBlockSocket.RecvByte(Timeout: Integer): Byte;
  2043. begin
  2044. Result := 0;
  2045. ResetLastError;
  2046. if FBuffer = '' then
  2047. FBuffer := RecvPacket(Timeout);
  2048. if (FLastError = 0) and (FBuffer <> '') then
  2049. begin
  2050. Result := Ord(FBuffer[1]);
  2051. Delete(FBuffer, 1, 1);
  2052. end;
  2053. ExceptCheck;
  2054. end;
  2055. function TBlockSocket.RecvInteger(Timeout: Integer): Integer;
  2056. var
  2057. s: AnsiString;
  2058. begin
  2059. Result := 0;
  2060. s := RecvBufferStr(4, Timeout);
  2061. if FLastError = 0 then
  2062. Result := (ord(s[1]) + ord(s[2]) * 256) + (ord(s[3]) + ord(s[4]) * 256) * 65536;
  2063. end;
  2064. function TBlockSocket.RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString;
  2065. var
  2066. x: Integer;
  2067. s: AnsiString;
  2068. l: Integer;
  2069. CorCRLF: Boolean;
  2070. t: AnsiString;
  2071. tl: integer;
  2072. ti: LongWord;
  2073. begin
  2074. ResetLastError;
  2075. Result := '';
  2076. l := Length(Terminator);
  2077. if l = 0 then
  2078. Exit;
  2079. tl := l;
  2080. CorCRLF := FConvertLineEnd and (Terminator = CRLF);
  2081. s := '';
  2082. x := 0;
  2083. repeat
  2084. //get rest of FBuffer or incomming new data...
  2085. ti := GetTick;
  2086. s := s + RecvPacket(Timeout);
  2087. if FLastError <> 0 then
  2088. Break;
  2089. x := 0;
  2090. if Length(s) > 0 then
  2091. if CorCRLF then
  2092. begin
  2093. t := '';
  2094. x := PosCRLF(s, t);
  2095. tl := Length(t);
  2096. if t = CR then
  2097. FLastCR := True;
  2098. if t = LF then
  2099. FLastLF := True;
  2100. end
  2101. else
  2102. begin
  2103. x := pos(Terminator, s);
  2104. tl := l;
  2105. end;
  2106. if (FMaxLineLength <> 0) and (Length(s) > FMaxLineLength) then
  2107. begin
  2108. FLastError := WSAENOBUFS;
  2109. Break;
  2110. end;
  2111. if x > 0 then
  2112. Break;
  2113. if not FInterPacketTimeout then
  2114. begin
  2115. Timeout := Timeout - integer(TickDelta(ti, GetTick));
  2116. if Timeout <= 0 then
  2117. begin
  2118. FLastError := WSAETIMEDOUT;
  2119. Break;
  2120. end;
  2121. end;
  2122. until False;
  2123. if x > 0 then
  2124. begin
  2125. Result := Copy(s, 1, x - 1);
  2126. Delete(s, 1, x + tl - 1);
  2127. end;
  2128. FBuffer := s;
  2129. ExceptCheck;
  2130. end;
  2131. function TBlockSocket.RecvString(Timeout: Integer): AnsiString;
  2132. var
  2133. s: AnsiString;
  2134. begin
  2135. Result := '';
  2136. s := RecvTerminated(Timeout, CRLF);
  2137. if FLastError = 0 then
  2138. Result := s;
  2139. end;
  2140. function TBlockSocket.RecvBlock(Timeout: Integer): AnsiString;
  2141. var
  2142. x: integer;
  2143. begin
  2144. Result := '';
  2145. x := RecvInteger(Timeout);
  2146. if FLastError = 0 then
  2147. Result := RecvBufferStr(x, Timeout);
  2148. end;
  2149. procedure TBlockSocket.RecvStreamRaw(const Stream: TStream; Timeout: Integer);
  2150. var
  2151. s: AnsiString;
  2152. begin
  2153. repeat
  2154. s := RecvPacket(Timeout);
  2155. if FLastError = 0 then
  2156. WriteStrToStream(Stream, s);
  2157. until FLastError <> 0;
  2158. end;
  2159. procedure TBlockSocket.RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: Integer);
  2160. var
  2161. s: AnsiString;
  2162. n: integer;
  2163. {$IFDEF CIL}
  2164. buf: TMemory;
  2165. {$ENDIF}
  2166. begin
  2167. for n := 1 to (Size div FSendMaxChunk) do
  2168. begin
  2169. {$IFDEF CIL}
  2170. SetLength(buf, FSendMaxChunk);
  2171. RecvBufferEx(buf, FSendMaxChunk, Timeout);
  2172. if FLastError <> 0 then
  2173. Exit;
  2174. Stream.Write(buf, FSendMaxChunk);
  2175. {$ELSE}
  2176. s := RecvBufferStr(FSendMaxChunk, Timeout);
  2177. if FLastError <> 0 then
  2178. Exit;
  2179. WriteStrToStream(Stream, s);
  2180. {$ENDIF}
  2181. end;
  2182. n := Size mod FSendMaxChunk;
  2183. if n > 0 then
  2184. begin
  2185. {$IFDEF CIL}
  2186. SetLength(buf, n);
  2187. RecvBufferEx(buf, n, Timeout);
  2188. if FLastError <> 0 then
  2189. Exit;
  2190. Stream.Write(buf, n);
  2191. {$ELSE}
  2192. s := RecvBufferStr(n, Timeout);
  2193. if FLastError <> 0 then
  2194. Exit;
  2195. WriteStrToStream(Stream, s);
  2196. {$ENDIF}
  2197. end;
  2198. end;
  2199. procedure TBlockSocket.RecvStreamIndy(const Stream: TStream; Timeout: Integer);
  2200. var
  2201. x: integer;
  2202. begin
  2203. x := RecvInteger(Timeout);
  2204. x := synsock.NToHL(x);
  2205. if FLastError = 0 then
  2206. RecvStreamSize(Stream, Timeout, x);
  2207. end;
  2208. procedure TBlockSocket.RecvStream(const Stream: TStream; Timeout: Integer);
  2209. var
  2210. x: integer;
  2211. begin
  2212. x := RecvInteger(Timeout);
  2213. if FLastError = 0 then
  2214. RecvStreamSize(Stream, Timeout, x);
  2215. end;
  2216. function TBlockSocket.PeekBuffer(Buffer: TMemory; Length: Integer): Integer;
  2217. begin
  2218. {$IFNDEF CIL}
  2219. // Result := synsock.Recv(FSocket, Buffer^, Length, MSG_PEEK + MSG_NOSIGNAL);
  2220. Result := synsock.Recv(FSocket, Buffer, Length, MSG_PEEK + MSG_NOSIGNAL);
  2221. SockCheck(Result);
  2222. ExceptCheck;
  2223. {$ENDIF}
  2224. end;
  2225. function TBlockSocket.PeekByte(Timeout: Integer): Byte;
  2226. var
  2227. s: string;
  2228. begin
  2229. {$IFNDEF CIL}
  2230. Result := 0;
  2231. if CanRead(Timeout) then
  2232. begin
  2233. SetLength(s, 1);
  2234. PeekBuffer(Pointer(s), 1);
  2235. if s <> '' then
  2236. Result := Ord(s[1]);
  2237. end
  2238. else
  2239. FLastError := WSAETIMEDOUT;
  2240. ExceptCheck;
  2241. {$ENDIF}
  2242. end;
  2243. procedure TBlockSocket.ResetLastError;
  2244. begin
  2245. FLastError := 0;
  2246. FLastErrorDesc := '';
  2247. end;
  2248. function TBlockSocket.SockCheck(SockResult: Integer): Integer;
  2249. begin
  2250. ResetLastError;
  2251. if SockResult = integer(SOCKET_ERROR) then
  2252. begin
  2253. FLastError := synsock.WSAGetLastError;
  2254. FLastErrorDesc := GetErrorDescEx;
  2255. end;
  2256. Result := FLastError;
  2257. end;
  2258. procedure TBlockSocket.ExceptCheck;
  2259. var
  2260. e: ESynapseError;
  2261. begin
  2262. FLastErrorDesc := GetErrorDescEx;
  2263. if (LastError <> 0) and (LastError <> WSAEINPROGRESS)
  2264. and (LastError <> WSAEWOULDBLOCK) then
  2265. begin
  2266. DoStatus(HR_Error, IntToStr(FLastError) + ',' + FLastErrorDesc);
  2267. if FRaiseExcept then
  2268. begin
  2269. e := ESynapseError.Create(Format('Synapse TCP/IP Socket error %d: %s',
  2270. [FLastError, FLastErrorDesc]));
  2271. e.ErrorCode := FLastError;
  2272. e.ErrorMessage := FLastErrorDesc;
  2273. raise e;
  2274. end;
  2275. end;
  2276. end;
  2277. function TBlockSocket.WaitingData: Integer;
  2278. var
  2279. x: Integer;
  2280. begin
  2281. Result := 0;
  2282. if synsock.IoctlSocket(FSocket, FIONREAD, x) = 0 then
  2283. Result := x;
  2284. if Result > c64k then
  2285. Result := c64k;
  2286. end;
  2287. function TBlockSocket.WaitingDataEx: Integer;
  2288. begin
  2289. if FBuffer <> '' then
  2290. Result := Length(FBuffer)
  2291. else
  2292. Result := WaitingData;
  2293. end;
  2294. procedure TBlockSocket.Purge;
  2295. begin
  2296. Sleep(1);
  2297. try
  2298. while (Length(FBuffer) > 0) or (WaitingData > 0) do
  2299. begin
  2300. RecvPacket(0);
  2301. if FLastError <> 0 then
  2302. break;
  2303. end;
  2304. except
  2305. on exception do;
  2306. end;
  2307. ResetLastError;
  2308. end;
  2309. procedure TBlockSocket.SetLinger(Enable: Boolean; Linger: Integer);
  2310. var
  2311. d: TSynaOption;
  2312. begin
  2313. d := TSynaOption.Create;
  2314. d.Option := SOT_Linger;
  2315. d.Enabled := Enable;
  2316. d.Value := Linger;
  2317. DelayedOption(d);
  2318. end;
  2319. function TBlockSocket.LocalName: string;
  2320. begin
  2321. Result := synsock.GetHostName;
  2322. if Result = '' then
  2323. Result := '127.0.0.1';
  2324. end;
  2325. procedure TBlockSocket.ResolveNameToIP(Name: string; const IPList: TStrings);
  2326. begin
  2327. IPList.Clear;
  2328. synsock.ResolveNameToIP(Name, FamilyToAF(FFamily), GetSocketprotocol, GetSocketType, IPList);
  2329. if IPList.Count = 0 then
  2330. IPList.Add(cAnyHost);
  2331. end;
  2332. function TBlockSocket.ResolveName(Name: string): string;
  2333. var
  2334. l: TStringList;
  2335. begin
  2336. l := TStringList.Create;
  2337. try
  2338. ResolveNameToIP(Name, l);
  2339. Result := l[0];
  2340. finally
  2341. l.Free;
  2342. end;
  2343. end;
  2344. function TBlockSocket.ResolvePort(Port: string): Word;
  2345. begin
  2346. Result := synsock.ResolvePort(Port, FamilyToAF(FFamily), GetSocketProtocol, GetSocketType);
  2347. end;
  2348. function TBlockSocket.ResolveIPToName(IP: string): string;
  2349. begin
  2350. if not IsIP(IP) and not IsIp6(IP) then
  2351. IP := ResolveName(IP);
  2352. Result := synsock.ResolveIPToName(IP, FamilyToAF(FFamily), GetSocketProtocol, GetSocketType);
  2353. end;
  2354. procedure TBlockSocket.SetRemoteSin(IP, Port: string);
  2355. begin
  2356. SetSin(FRemoteSin, IP, Port);
  2357. end;
  2358. function TBlockSocket.GetLocalSinIP: string;
  2359. begin
  2360. Result := GetSinIP(FLocalSin);
  2361. end;
  2362. function TBlockSocket.GetRemoteSinIP: string;
  2363. begin
  2364. Result := GetSinIP(FRemoteSin);
  2365. end;
  2366. function TBlockSocket.GetLocalSinPort: Integer;
  2367. begin
  2368. Result := GetSinPort(FLocalSin);
  2369. end;
  2370. function TBlockSocket.GetRemoteSinPort: Integer;
  2371. begin
  2372. Result := GetSinPort(FRemoteSin);
  2373. end;
  2374. function TBlockSocket.InternalCanRead(Timeout: Integer): Boolean;
  2375. {$IFDEF CIL}
  2376. begin
  2377. Result := FSocket.Poll(Timeout * 1000, SelectMode.SelectRead);
  2378. {$ELSE}
  2379. var
  2380. TimeVal: PTimeVal;
  2381. TimeV: TTimeVal;
  2382. x: Integer;
  2383. FDSet: TFDSet;
  2384. begin
  2385. TimeV.tv_usec := (Timeout mod 1000) * 1000;
  2386. TimeV.tv_sec := Timeout div 1000;
  2387. TimeVal := @TimeV;
  2388. if Timeout = -1 then
  2389. TimeVal := nil;
  2390. FDSet := FFdSet;
  2391. x := synsock.Select(FSocket + 1, @FDSet, nil, nil, TimeVal);
  2392. SockCheck(x);
  2393. if FLastError <> 0 then
  2394. x := 0;
  2395. Result := x > 0;
  2396. {$ENDIF}
  2397. end;
  2398. function TBlockSocket.CanRead(Timeout: Integer): Boolean;
  2399. var
  2400. ti, tr: Integer;
  2401. n: integer;
  2402. begin
  2403. if (FHeartbeatRate <> 0) and (Timeout <> -1) then
  2404. begin
  2405. ti := Timeout div FHeartbeatRate;
  2406. tr := Timeout mod FHeartbeatRate;
  2407. end
  2408. else
  2409. begin
  2410. ti := 0;
  2411. tr := Timeout;
  2412. end;
  2413. Result := InternalCanRead(tr);
  2414. if not Result then
  2415. for n := 0 to ti do
  2416. begin
  2417. DoHeartbeat;
  2418. if FStopFlag then
  2419. begin
  2420. Result := False;
  2421. FStopFlag := False;
  2422. Break;
  2423. end;
  2424. Result := InternalCanRead(FHeartbeatRate);
  2425. if Result then
  2426. break;
  2427. end;
  2428. ExceptCheck;
  2429. if Result then
  2430. DoStatus(HR_CanRead, '');
  2431. end;
  2432. function TBlockSocket.CanWrite(Timeout: Integer): Boolean;
  2433. {$IFDEF CIL}
  2434. begin
  2435. Result := FSocket.Poll(Timeout * 1000, SelectMode.SelectWrite);
  2436. {$ELSE}
  2437. var
  2438. TimeVal: PTimeVal;
  2439. TimeV: TTimeVal;
  2440. x: Integer;
  2441. FDSet: TFDSet;
  2442. begin
  2443. TimeV.tv_usec := (Timeout mod 1000) * 1000;
  2444. TimeV.tv_sec := Timeout div 1000;
  2445. TimeVal := @TimeV;
  2446. if Timeout = -1 then
  2447. TimeVal := nil;
  2448. FDSet := FFdSet;
  2449. x := synsock.Select(FSocket + 1, nil, @FDSet, nil, TimeVal);
  2450. SockCheck(x);
  2451. if FLastError <> 0 then
  2452. x := 0;
  2453. Result := x > 0;
  2454. {$ENDIF}
  2455. ExceptCheck;
  2456. if Result then
  2457. DoStatus(HR_CanWrite, '');
  2458. end;
  2459. function TBlockSocket.CanReadEx(Timeout: Integer): Boolean;
  2460. begin
  2461. if FBuffer <> '' then
  2462. Result := True
  2463. else
  2464. Result := CanRead(Timeout);
  2465. end;
  2466. function TBlockSocket.SendBufferTo(Buffer: TMemory; Length: Integer): Integer;
  2467. begin
  2468. Result := 0;
  2469. if TestStopFlag then
  2470. Exit;
  2471. DoMonitor(True, Buffer, Length);
  2472. LimitBandwidth(Length, FMaxSendBandwidth, FNextsend);
  2473. Result := synsock.SendTo(FSocket, Buffer, Length, MSG_NOSIGNAL, FRemoteSin);
  2474. SockCheck(Result);
  2475. ExceptCheck;
  2476. Inc(FSendCounter, Result);
  2477. DoStatus(HR_WriteCount, IntToStr(Result));
  2478. end;
  2479. function TBlockSocket.RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer;
  2480. begin
  2481. Result := 0;
  2482. if TestStopFlag then
  2483. Exit;
  2484. LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
  2485. Result := synsock.RecvFrom(FSocket, Buffer, Length, MSG_NOSIGNAL, FRemoteSin);
  2486. SockCheck(Result);
  2487. ExceptCheck;
  2488. Inc(FRecvCounter, Result);
  2489. DoStatus(HR_ReadCount, IntToStr(Result));
  2490. DoMonitor(False, Buffer, Result);
  2491. end;
  2492. function TBlockSocket.GetSizeRecvBuffer: Integer;
  2493. var
  2494. l: Integer;
  2495. {$IFDEF CIL}
  2496. buf: TMemory;
  2497. {$ENDIF}
  2498. begin
  2499. {$IFDEF CIL}
  2500. setlength(buf, 4);
  2501. SockCheck(synsock.GetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVBUF), buf, l));
  2502. Result := System.BitConverter.ToInt32(buf,0);
  2503. {$ELSE}
  2504. l := SizeOf(Result);
  2505. SockCheck(synsock.GetSockOpt(FSocket, SOL_SOCKET, SO_RCVBUF, @Result, l));
  2506. if FLastError <> 0 then
  2507. Result := 1024;
  2508. ExceptCheck;
  2509. {$ENDIF}
  2510. end;
  2511. procedure TBlockSocket.SetSizeRecvBuffer(Size: Integer);
  2512. var
  2513. d: TSynaOption;
  2514. begin
  2515. d := TSynaOption.Create;
  2516. d.Option := SOT_RecvBuff;
  2517. d.Value := Size;
  2518. DelayedOption(d);
  2519. end;
  2520. function TBlockSocket.GetSizeSendBuffer: Integer;
  2521. var
  2522. l: Integer;
  2523. {$IFDEF CIL}
  2524. buf: TMemory;
  2525. {$ENDIF}
  2526. begin
  2527. {$IFDEF CIL}
  2528. setlength(buf, 4);
  2529. SockCheck(synsock.GetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDBUF), buf, l));
  2530. Result := System.BitConverter.ToInt32(buf,0);
  2531. {$ELSE}
  2532. l := SizeOf(Result);
  2533. SockCheck(synsock.GetSockOpt(FSocket, SOL_SOCKET, SO_SNDBUF, @Result, l));
  2534. if FLastError <> 0 then
  2535. Result := 1024;
  2536. ExceptCheck;
  2537. {$ENDIF}
  2538. end;
  2539. procedure TBlockSocket.SetSizeSendBuffer(Size: Integer);
  2540. var
  2541. d: TSynaOption;
  2542. begin
  2543. d := TSynaOption.Create;
  2544. d.Option := SOT_SendBuff;
  2545. d.Value := Size;
  2546. DelayedOption(d);
  2547. end;
  2548. procedure TBlockSocket.SetNonBlockMode(Value: Boolean);
  2549. var
  2550. d: TSynaOption;
  2551. begin
  2552. d := TSynaOption.Create;
  2553. d.Option := SOT_nonblock;
  2554. d.Enabled := Value;
  2555. DelayedOption(d);
  2556. end;
  2557. procedure TBlockSocket.SetTimeout(Timeout: Integer);
  2558. begin
  2559. SetSendTimeout(Timeout);
  2560. SetRecvTimeout(Timeout);
  2561. end;
  2562. procedure TBlockSocket.SetSendTimeout(Timeout: Integer);
  2563. var
  2564. d: TSynaOption;
  2565. begin
  2566. d := TSynaOption.Create;
  2567. d.Option := SOT_sendtimeout;
  2568. d.Value := Timeout;
  2569. DelayedOption(d);
  2570. end;
  2571. procedure TBlockSocket.SetRecvTimeout(Timeout: Integer);
  2572. var
  2573. d: TSynaOption;
  2574. begin
  2575. d := TSynaOption.Create;
  2576. d.Option := SOT_recvtimeout;
  2577. d.Value := Timeout;
  2578. DelayedOption(d);
  2579. end;
  2580. {$IFNDEF CIL}
  2581. function TBlockSocket.GroupCanRead(const SocketList: TList; Timeout: Integer;
  2582. const CanReadList: TList): boolean;
  2583. var
  2584. FDSet: TFDSet;
  2585. TimeVal: PTimeVal;
  2586. TimeV: TTimeVal;
  2587. x, n: Integer;
  2588. Max: Integer;
  2589. begin
  2590. TimeV.tv_usec := (Timeout mod 1000) * 1000;
  2591. TimeV.tv_sec := Timeout div 1000;
  2592. TimeVal := @TimeV;
  2593. if Timeout = -1 then
  2594. TimeVal := nil;
  2595. FD_ZERO(FDSet);
  2596. Max := 0;
  2597. for n := 0 to SocketList.Count - 1 do
  2598. if TObject(SocketList.Items[n]) is TBlockSocket then
  2599. begin
  2600. if TBlockSocket(SocketList.Items[n]).Socket > Max then
  2601. Max := TBlockSocket(SocketList.Items[n]).Socket;
  2602. FD_SET(TBlockSocket(SocketList.Items[n]).Socket, FDSet);
  2603. end;
  2604. x := synsock.Select(Max + 1, @FDSet, nil, nil, TimeVal);
  2605. SockCheck(x);
  2606. ExceptCheck;
  2607. if FLastError <> 0 then
  2608. x := 0;
  2609. Result := x > 0;
  2610. CanReadList.Clear;
  2611. if Result then
  2612. for n := 0 to SocketList.Count - 1 do
  2613. if TObject(SocketList.Items[n]) is TBlockSocket then
  2614. if FD_ISSET(TBlockSocket(SocketList.Items[n]).Socket, FDSet) then
  2615. CanReadList.Add(TBlockSocket(SocketList.Items[n]));
  2616. end;
  2617. {$ENDIF}
  2618. procedure TBlockSocket.EnableReuse(Value: Boolean);
  2619. var
  2620. d: TSynaOption;
  2621. begin
  2622. d := TSynaOption.Create;
  2623. d.Option := SOT_reuse;
  2624. d.Enabled := Value;
  2625. DelayedOption(d);
  2626. end;
  2627. procedure TBlockSocket.SetTTL(TTL: integer);
  2628. var
  2629. d: TSynaOption;
  2630. begin
  2631. d := TSynaOption.Create;
  2632. d.Option := SOT_TTL;
  2633. d.Value := TTL;
  2634. DelayedOption(d);
  2635. end;
  2636. function TBlockSocket.GetTTL:integer;
  2637. var
  2638. l: Integer;
  2639. begin
  2640. {$IFNDEF CIL}
  2641. l := SizeOf(Result);
  2642. if FIP6Used then
  2643. synsock.GetSockOpt(FSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, @Result, l)
  2644. else
  2645. synsock.GetSockOpt(FSocket, IPPROTO_IP, IP_TTL, @Result, l);
  2646. {$ENDIF}
  2647. end;
  2648. procedure TBlockSocket.SetFamily(Value: TSocketFamily);
  2649. begin
  2650. FFamily := Value;
  2651. FFamilySave := Value;
  2652. end;
  2653. procedure TBlockSocket.SetSocket(Value: TSocket);
  2654. begin
  2655. FRecvCounter := 0;
  2656. FSendCounter := 0;
  2657. FSocket := Value;
  2658. {$IFNDEF CIL}
  2659. FD_ZERO(FFDSet);
  2660. FD_SET(FSocket, FFDSet);
  2661. {$ENDIF}
  2662. GetSins;
  2663. FIP6Used := FRemoteSin.AddressFamily = AF_INET6;
  2664. end;
  2665. function TBlockSocket.GetWsaData: TWSAData;
  2666. begin
  2667. {$IFDEF ONCEWINSOCK}
  2668. Result := WsaDataOnce;
  2669. {$ELSE}
  2670. Result := FWsaDataOnce;
  2671. {$ENDIF}
  2672. end;
  2673. function TBlockSocket.GetSocketType: integer;
  2674. begin
  2675. Result := 0;
  2676. end;
  2677. function TBlockSocket.GetSocketProtocol: integer;
  2678. begin
  2679. Result := integer(IPPROTO_IP);
  2680. end;
  2681. procedure TBlockSocket.DoStatus(Reason: THookSocketReason; const Value: string);
  2682. begin
  2683. if assigned(OnStatus) then
  2684. OnStatus(Self, Reason, Value);
  2685. end;
  2686. procedure TBlockSocket.DoReadFilter(Buffer: TMemory; var Len: Integer);
  2687. var
  2688. s: AnsiString;
  2689. begin
  2690. if assigned(OnReadFilter) then
  2691. if Len > 0 then
  2692. begin
  2693. {$IFDEF CIL}
  2694. s := StringOf(Buffer);
  2695. {$ELSE}
  2696. SetLength(s, Len);
  2697. Move(Buffer^, Pointer(s)^, Len);
  2698. {$ENDIF}
  2699. OnReadFilter(Self, s);
  2700. if Length(s) > Len then
  2701. SetLength(s, Len);
  2702. Len := Length(s);
  2703. {$IFDEF CIL}
  2704. Buffer := BytesOf(s);
  2705. {$ELSE}
  2706. Move(Pointer(s)^, Buffer^, Len);
  2707. {$ENDIF}
  2708. end;
  2709. end;
  2710. procedure TBlockSocket.DoCreateSocket;
  2711. begin
  2712. if assigned(OnCreateSocket) then
  2713. OnCreateSocket(Self);
  2714. end;
  2715. procedure TBlockSocket.DoMonitor(Writing: Boolean; const Buffer: TMemory; Len: Integer);
  2716. begin
  2717. if assigned(OnMonitor) then
  2718. begin
  2719. OnMonitor(Self, Writing, Buffer, Len);
  2720. end;
  2721. end;
  2722. procedure TBlockSocket.DoHeartbeat;
  2723. begin
  2724. if assigned(OnHeartbeat) and (FHeartbeatRate <> 0) then
  2725. begin
  2726. OnHeartbeat(Self);
  2727. end;
  2728. end;
  2729. function TBlockSocket.GetErrorDescEx: string;
  2730. begin
  2731. Result := GetErrorDesc(FLastError);
  2732. end;
  2733. class function TBlockSocket.GetErrorDesc(ErrorCode: Integer): string;
  2734. begin
  2735. {$IFDEF CIL}
  2736. if ErrorCode = 0 then
  2737. Result := ''
  2738. else
  2739. begin
  2740. Result := WSAGetLastErrorDesc;
  2741. if Result = '' then
  2742. Result := 'Other Winsock error (' + IntToStr(ErrorCode) + ')';
  2743. end;
  2744. {$ELSE}
  2745. case ErrorCode of
  2746. 0:
  2747. Result := '';
  2748. WSAEINTR: {10004}
  2749. Result := 'Interrupted system call';
  2750. WSAEBADF: {10009}
  2751. Result := 'Bad file number';
  2752. WSAEACCES: {10013}
  2753. Result := 'Permission denied';
  2754. WSAEFAULT: {10014}
  2755. Result := 'Bad address';
  2756. WSAEINVAL: {10022}
  2757. Result := 'Invalid argument';
  2758. WSAEMFILE: {10024}
  2759. Result := 'Too many open files';
  2760. WSAEWOULDBLOCK: {10035}
  2761. Result := 'Operation would block';
  2762. WSAEINPROGRESS: {10036}
  2763. Result := 'Operation now in progress';
  2764. WSAEALREADY: {10037}
  2765. Result := 'Operation already in progress';
  2766. WSAENOTSOCK: {10038}
  2767. Result := 'Socket operation on nonsocket';
  2768. WSAEDESTADDRREQ: {10039}
  2769. Result := 'Destination address required';
  2770. WSAEMSGSIZE: {10040}
  2771. Result := 'Message too long';
  2772. WSAEPROTOTYPE: {10041}
  2773. Result := 'Protocol wrong type for Socket';
  2774. WSAENOPROTOOPT: {10042}
  2775. Result := 'Protocol not available';
  2776. WSAEPROTONOSUPPORT: {10043}
  2777. Result := 'Protocol not supported';
  2778. WSAESOCKTNOSUPPORT: {10044}
  2779. Result := 'Socket not supported';
  2780. WSAEOPNOTSUPP: {10045}
  2781. Result := 'Operation not supported on Socket';
  2782. WSAEPFNOSUPPORT: {10046}
  2783. Result := 'Protocol family not supported';
  2784. WSAEAFNOSUPPORT: {10047}
  2785. Result := 'Address family not supported';
  2786. WSAEADDRINUSE: {10048}
  2787. Result := 'Address already in use';
  2788. WSAEADDRNOTAVAIL: {10049}
  2789. Result := 'Can''t assign requested address';
  2790. WSAENETDOWN: {10050}
  2791. Result := 'Network is down';
  2792. WSAENETUNREACH: {10051}
  2793. Result := 'Network is unreachable';
  2794. WSAENETRESET: {10052}
  2795. Result := 'Network dropped connection on reset';
  2796. WSAECONNABORTED: {10053}
  2797. Result := 'Software caused connection abort';
  2798. WSAECONNRESET: {10054}
  2799. Result := 'Connection reset by peer';
  2800. WSAENOBUFS: {10055}
  2801. Result := 'No Buffer space available';
  2802. WSAEISCONN: {10056}
  2803. Result := 'Socket is already connected';
  2804. WSAENOTCONN: {10057}
  2805. Result := 'Socket is not connected';
  2806. WSAESHUTDOWN: {10058}
  2807. Result := 'Can''t send after Socket shutdown';
  2808. WSAETOOMANYREFS: {10059}
  2809. Result := 'Too many references:can''t splice';
  2810. WSAETIMEDOUT: {10060}
  2811. Result := 'Connection timed out';
  2812. WSAECONNREFUSED: {10061}
  2813. Result := 'Connection refused';
  2814. WSAELOOP: {10062}
  2815. Result := 'Too many levels of symbolic links';
  2816. WSAENAMETOOLONG: {10063}
  2817. Result := 'File name is too long';
  2818. WSAEHOSTDOWN: {10064}
  2819. Result := 'Host is down';
  2820. WSAEHOSTUNREACH: {10065}
  2821. Result := 'No route to host';
  2822. WSAENOTEMPTY: {10066}
  2823. Result := 'Directory is not empty';
  2824. WSAEPROCLIM: {10067}
  2825. Result := 'Too many processes';
  2826. WSAEUSERS: {10068}
  2827. Result := 'Too many users';
  2828. WSAEDQUOT: {10069}
  2829. Result := 'Disk quota exceeded';
  2830. WSAESTALE: {10070}
  2831. Result := 'Stale NFS file handle';
  2832. WSAEREMOTE: {10071}
  2833. Result := 'Too many levels of remote in path';
  2834. WSASYSNOTREADY: {10091}
  2835. Result := 'Network subsystem is unusable';
  2836. WSAVERNOTSUPPORTED: {10092}
  2837. Result := 'Winsock DLL cannot support this application';
  2838. WSANOTINITIALISED: {10093}
  2839. Result := 'Winsock not initialized';
  2840. WSAEDISCON: {10101}
  2841. Result := 'Disconnect';
  2842. WSAHOST_NOT_FOUND: {11001}
  2843. Result := 'Host not found';
  2844. WSATRY_AGAIN: {11002}
  2845. Result := 'Non authoritative - host not found';
  2846. WSANO_RECOVERY: {11003}
  2847. Result := 'Non recoverable error';
  2848. WSANO_DATA: {11004}
  2849. Result := 'Valid name, no data record of requested type'
  2850. else
  2851. Result := 'Other Winsock error (' + IntToStr(ErrorCode) + ')';
  2852. end;
  2853. {$ENDIF}
  2854. end;
  2855. {======================================================================}
  2856. constructor TSocksBlockSocket.Create;
  2857. begin
  2858. inherited Create;
  2859. FSocksIP:= '';
  2860. FSocksPort:= '1080';
  2861. FSocksTimeout:= 60000;
  2862. FSocksUsername:= '';
  2863. FSocksPassword:= '';
  2864. FUsingSocks := False;
  2865. FSocksResolver := True;
  2866. FSocksLastError := 0;
  2867. FSocksResponseIP := '';
  2868. FSocksResponsePort := '';
  2869. FSocksLocalIP := '';
  2870. FSocksLocalPort := '';
  2871. FSocksRemoteIP := '';
  2872. FSocksRemotePort := '';
  2873. FBypassFlag := False;
  2874. FSocksType := ST_Socks5;
  2875. end;
  2876. function TSocksBlockSocket.SocksOpen: boolean;
  2877. var
  2878. Buf: AnsiString;
  2879. n: integer;
  2880. begin
  2881. Result := False;
  2882. FUsingSocks := False;
  2883. if FSocksType <> ST_Socks5 then
  2884. begin
  2885. FUsingSocks := True;
  2886. Result := True;
  2887. end
  2888. else
  2889. begin
  2890. FBypassFlag := True;
  2891. try
  2892. if FSocksUsername = '' then
  2893. Buf := #5 + #1 + #0
  2894. else
  2895. Buf := #5 + #2 + #2 +#0;
  2896. SendString(Buf);
  2897. Buf := RecvBufferStr(2, FSocksTimeout);
  2898. if Length(Buf) < 2 then
  2899. Exit;
  2900. if Buf[1] <> #5 then
  2901. Exit;
  2902. n := Ord(Buf[2]);
  2903. case n of
  2904. 0: //not need authorisation
  2905. ;
  2906. 2:
  2907. begin
  2908. Buf := #1 + AnsiChar(Length(FSocksUsername)) + FSocksUsername
  2909. + AnsiChar(Length(FSocksPassword)) + FSocksPassword;
  2910. SendString(Buf);
  2911. Buf := RecvBufferStr(2, FSocksTimeout);
  2912. if Length(Buf) < 2 then
  2913. Exit;
  2914. if Buf[2] <> #0 then
  2915. Exit;
  2916. end;
  2917. else
  2918. //other authorisation is not supported!
  2919. Exit;
  2920. end;
  2921. FUsingSocks := True;
  2922. Result := True;
  2923. finally
  2924. FBypassFlag := False;
  2925. end;
  2926. end;
  2927. end;
  2928. function TSocksBlockSocket.SocksRequest(Cmd: Byte;
  2929. const IP, Port: string): Boolean;
  2930. var
  2931. Buf: AnsiString;
  2932. begin
  2933. FBypassFlag := True;
  2934. try
  2935. if FSocksType <> ST_Socks5 then
  2936. Buf := #4 + AnsiChar(Cmd) + SocksCode(IP, Port)
  2937. else
  2938. Buf := #5 + AnsiChar(Cmd) + #0 + SocksCode(IP, Port);
  2939. SendString(Buf);
  2940. Result := FLastError = 0;
  2941. finally
  2942. FBypassFlag := False;
  2943. end;
  2944. end;
  2945. function TSocksBlockSocket.SocksResponse: Boolean;
  2946. var
  2947. Buf, s: AnsiString;
  2948. x: integer;
  2949. begin
  2950. Result := False;
  2951. FBypassFlag := True;
  2952. try
  2953. FSocksResponseIP := '';
  2954. FSocksResponsePort := '';
  2955. FSocksLastError := -1;
  2956. if FSocksType <> ST_Socks5 then
  2957. begin
  2958. Buf := RecvBufferStr(8, FSocksTimeout);
  2959. if FLastError <> 0 then
  2960. Exit;
  2961. if Buf[1] <> #0 then
  2962. Exit;
  2963. FSocksLastError := Ord(Buf[2]);
  2964. end
  2965. else
  2966. begin
  2967. Buf := RecvBufferStr(4, FSocksTimeout);
  2968. if FLastError <> 0 then
  2969. Exit;
  2970. if Buf[1] <> #5 then
  2971. Exit;
  2972. case Ord(Buf[4]) of
  2973. 1:
  2974. s := RecvBufferStr(4, FSocksTimeout);
  2975. 3:
  2976. begin
  2977. x := RecvByte(FSocksTimeout);
  2978. if FLastError <> 0 then
  2979. Exit;
  2980. s := AnsiChar(x) + RecvBufferStr(x, FSocksTimeout);
  2981. end;
  2982. 4:
  2983. s := RecvBufferStr(16, FSocksTimeout);
  2984. else
  2985. Exit;
  2986. end;
  2987. Buf := Buf + s + RecvBufferStr(2, FSocksTimeout);
  2988. if FLastError <> 0 then
  2989. Exit;
  2990. FSocksLastError := Ord(Buf[2]);
  2991. end;
  2992. if ((FSocksLastError <> 0) and (FSocksLastError <> 90)) then
  2993. Exit;
  2994. SocksDecode(Buf);
  2995. Result := True;
  2996. finally
  2997. FBypassFlag := False;
  2998. end;
  2999. end;
  3000. function TSocksBlockSocket.SocksCode(IP, Port: string): Ansistring;
  3001. var
  3002. ip6: TIp6Bytes;
  3003. n: integer;
  3004. begin
  3005. if FSocksType <> ST_Socks5 then
  3006. begin
  3007. Result := CodeInt(ResolvePort(Port));
  3008. if not FSocksResolver then
  3009. IP := ResolveName(IP);
  3010. if IsIP(IP) then
  3011. begin
  3012. Result := Result + IPToID(IP);
  3013. Result := Result + FSocksUsername + #0;
  3014. end
  3015. else
  3016. begin
  3017. Result := Result + IPToID('0.0.0.1');
  3018. Result := Result + FSocksUsername + #0;
  3019. Result := Result + IP + #0;
  3020. end;
  3021. end
  3022. else
  3023. begin
  3024. if not FSocksResolver then
  3025. IP := ResolveName(IP);
  3026. if IsIP(IP) then
  3027. Result := #1 + IPToID(IP)
  3028. else
  3029. if IsIP6(IP) then
  3030. begin
  3031. ip6 := StrToIP6(IP);
  3032. Result := #4;
  3033. for n := 0 to 15 do
  3034. Result := Result + AnsiChar(ip6[n]);
  3035. end
  3036. else
  3037. Result := #3 + AnsiChar(Length(IP)) + IP;
  3038. Result := Result + CodeInt(ResolvePort(Port));
  3039. end;
  3040. end;
  3041. function TSocksBlockSocket.SocksDecode(Value: Ansistring): integer;
  3042. var
  3043. Atyp: Byte;
  3044. y, n: integer;
  3045. w: Word;
  3046. ip6: TIp6Bytes;
  3047. begin
  3048. FSocksResponsePort := '0';
  3049. Result := 0;
  3050. if FSocksType <> ST_Socks5 then
  3051. begin
  3052. if Length(Value) < 8 then
  3053. Exit;
  3054. Result := 3;
  3055. w := DecodeInt(Value, Result);
  3056. FSocksResponsePort := IntToStr(w);
  3057. FSocksResponseIP := Format('%d.%d.%d.%d',
  3058. [Ord(Value[5]), Ord(Value[6]), Ord(Value[7]), Ord(Value[8])]);
  3059. Result := 9;
  3060. end
  3061. else
  3062. begin
  3063. if Length(Value) < 4 then
  3064. Exit;
  3065. Atyp := Ord(Value[4]);
  3066. Result := 5;
  3067. case Atyp of
  3068. 1:
  3069. begin
  3070. if Length(Value) < 10 then
  3071. Exit;
  3072. FSocksResponseIP := Format('%d.%d.%d.%d',
  3073. [Ord(Value[5]), Ord(Value[6]), Ord(Value[7]), Ord(Value[8])]);
  3074. Result := 9;
  3075. end;
  3076. 3:
  3077. begin
  3078. y := Ord(Value[5]);
  3079. if Length(Value) < (5 + y + 2) then
  3080. Exit;
  3081. for n := 6 to 6 + y - 1 do
  3082. FSocksResponseIP := FSocksResponseIP + Value[n];
  3083. Result := 5 + y + 1;
  3084. end;
  3085. 4:
  3086. begin
  3087. if Length(Value) < 22 then
  3088. Exit;
  3089. for n := 0 to 15 do
  3090. ip6[n] := ord(Value[n + 5]);
  3091. FSocksResponseIP := IP6ToStr(ip6);
  3092. Result := 21;
  3093. end;
  3094. else
  3095. Exit;
  3096. end;
  3097. w := DecodeInt(Value, Result);
  3098. FSocksResponsePort := IntToStr(w);
  3099. Result := Result + 2;
  3100. end;
  3101. end;
  3102. {======================================================================}
  3103. procedure TDgramBlockSocket.Connect(IP, Port: string);
  3104. begin
  3105. SetRemoteSin(IP, Port);
  3106. InternalCreateSocket(FRemoteSin);
  3107. FBuffer := '';
  3108. DoStatus(HR_Connect, IP + ':' + Port);
  3109. end;
  3110. function TDgramBlockSocket.RecvBuffer(Buffer: TMemory; Length: Integer): Integer;
  3111. begin
  3112. Result := RecvBufferFrom(Buffer, Length);
  3113. end;
  3114. function TDgramBlockSocket.SendBuffer(Buffer: TMemory; Length: Integer): Integer;
  3115. begin
  3116. Result := SendBufferTo(Buffer, Length);
  3117. end;
  3118. {======================================================================}
  3119. destructor TUDPBlockSocket.Destroy;
  3120. begin
  3121. if Assigned(FSocksControlSock) then
  3122. FSocksControlSock.Free;
  3123. inherited;
  3124. end;
  3125. procedure TUDPBlockSocket.EnableBroadcast(Value: Boolean);
  3126. var
  3127. d: TSynaOption;
  3128. begin
  3129. d := TSynaOption.Create;
  3130. d.Option := SOT_Broadcast;
  3131. d.Enabled := Value;
  3132. DelayedOption(d);
  3133. end;
  3134. function TUDPBlockSocket.UdpAssociation: Boolean;
  3135. var
  3136. b: Boolean;
  3137. begin
  3138. Result := True;
  3139. FUsingSocks := False;
  3140. if FSocksIP <> '' then
  3141. begin
  3142. Result := False;
  3143. if not Assigned(FSocksControlSock) then
  3144. FSocksControlSock := TTCPBlockSocket.Create;
  3145. FSocksControlSock.CloseSocket;
  3146. FSocksControlSock.CreateSocketByName(FSocksIP);
  3147. FSocksControlSock.Connect(FSocksIP, FSocksPort);
  3148. if FSocksControlSock.LastError <> 0 then
  3149. Exit;
  3150. // if not assigned local port, assign it!
  3151. if not FBinded then
  3152. Bind(cAnyHost, cAnyPort);
  3153. //open control TCP connection to SOCKS
  3154. FSocksControlSock.FSocksUsername := FSocksUsername;
  3155. FSocksControlSock.FSocksPassword := FSocksPassword;
  3156. b := FSocksControlSock.SocksOpen;
  3157. if b then
  3158. b := FSocksControlSock.SocksRequest(3, GetLocalSinIP, IntToStr(GetLocalSinPort));
  3159. if b then
  3160. b := FSocksControlSock.SocksResponse;
  3161. if not b and (FLastError = 0) then
  3162. FLastError := WSANO_RECOVERY;
  3163. FUsingSocks :=FSocksControlSock.UsingSocks;
  3164. FSocksRemoteIP := FSocksControlSock.FSocksResponseIP;
  3165. FSocksRemotePort := FSocksControlSock.FSocksResponsePort;
  3166. Result := b and (FLastError = 0);
  3167. end;
  3168. end;
  3169. function TUDPBlockSocket.SendBufferTo(Buffer: TMemory; Length: Integer): Integer;
  3170. var
  3171. SIp: string;
  3172. SPort: integer;
  3173. Buf: Ansistring;
  3174. begin
  3175. Result := 0;
  3176. FUsingSocks := False;
  3177. if (FSocksIP <> '') and (not UdpAssociation) then
  3178. FLastError := WSANO_RECOVERY
  3179. else
  3180. begin
  3181. if FUsingSocks then
  3182. begin
  3183. {$IFNDEF CIL}
  3184. Sip := GetRemoteSinIp;
  3185. SPort := GetRemoteSinPort;
  3186. SetRemoteSin(FSocksRemoteIP, FSocksRemotePort);
  3187. SetLength(Buf,Length);
  3188. Move(Buffer^, Pointer(Buf)^, Length);
  3189. Buf := #0 + #0 + #0 + SocksCode(Sip, IntToStr(SPort)) + Buf;
  3190. Result := inherited SendBufferTo(Pointer(Buf), System.Length(buf));
  3191. SetRemoteSin(Sip, IntToStr(SPort));
  3192. {$ENDIF}
  3193. end
  3194. else
  3195. Result := inherited SendBufferTo(Buffer, Length);
  3196. end;
  3197. end;
  3198. function TUDPBlockSocket.RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer;
  3199. var
  3200. Buf: Ansistring;
  3201. x: integer;
  3202. begin
  3203. Result := inherited RecvBufferFrom(Buffer, Length);
  3204. if FUsingSocks then
  3205. begin
  3206. {$IFNDEF CIL}
  3207. SetLength(Buf, Result);
  3208. Move(Buffer^, Pointer(Buf)^, Result);
  3209. x := SocksDecode(Buf);
  3210. Result := Result - x + 1;
  3211. Buf := Copy(Buf, x, Result);
  3212. Move(Pointer(Buf)^, Buffer^, Result);
  3213. SetRemoteSin(FSocksResponseIP, FSocksResponsePort);
  3214. {$ENDIF}
  3215. end;
  3216. end;
  3217. {$IFNDEF CIL}
  3218. procedure TUDPBlockSocket.AddMulticast(MCastIP: string);
  3219. var
  3220. Multicast: TIP_mreq;
  3221. Multicast6: TIPv6_mreq;
  3222. n: integer;
  3223. ip6: Tip6bytes;
  3224. begin
  3225. if FIP6Used then
  3226. begin
  3227. ip6 := StrToIp6(MCastIP);
  3228. for n := 0 to 15 do
  3229. Multicast6.ipv6mr_multiaddr.u6_addr8[n] := Ip6[n];
  3230. Multicast6.ipv6mr_interface := 0;
  3231. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  3232. PAnsiChar(@Multicast6), SizeOf(Multicast6)));
  3233. end
  3234. else
  3235. begin
  3236. Multicast.imr_multiaddr.S_addr := swapbytes(strtoip(MCastIP));
  3237. Multicast.imr_interface.S_addr := INADDR_ANY;
  3238. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  3239. PAnsiChar(@Multicast), SizeOf(Multicast)));
  3240. end;
  3241. ExceptCheck;
  3242. end;
  3243. procedure TUDPBlockSocket.DropMulticast(MCastIP: string);
  3244. var
  3245. Multicast: TIP_mreq;
  3246. Multicast6: TIPv6_mreq;
  3247. n: integer;
  3248. ip6: Tip6bytes;
  3249. begin
  3250. if FIP6Used then
  3251. begin
  3252. ip6 := StrToIp6(MCastIP);
  3253. for n := 0 to 15 do
  3254. Multicast6.ipv6mr_multiaddr.u6_addr8[n] := Ip6[n];
  3255. Multicast6.ipv6mr_interface := 0;
  3256. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
  3257. PAnsiChar(@Multicast6), SizeOf(Multicast6)));
  3258. end
  3259. else
  3260. begin
  3261. Multicast.imr_multiaddr.S_addr := swapbytes(strtoip(MCastIP));
  3262. Multicast.imr_interface.S_addr := INADDR_ANY;
  3263. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
  3264. PAnsiChar(@Multicast), SizeOf(Multicast)));
  3265. end;
  3266. ExceptCheck;
  3267. end;
  3268. {$ENDIF}
  3269. procedure TUDPBlockSocket.SetMulticastTTL(TTL: integer);
  3270. var
  3271. d: TSynaOption;
  3272. begin
  3273. d := TSynaOption.Create;
  3274. d.Option := SOT_MulticastTTL;
  3275. d.Value := TTL;
  3276. DelayedOption(d);
  3277. end;
  3278. function TUDPBlockSocket.GetMulticastTTL:integer;
  3279. var
  3280. l: Integer;
  3281. begin
  3282. {$IFNDEF CIL}
  3283. l := SizeOf(Result);
  3284. if FIP6Used then
  3285. synsock.GetSockOpt(FSocket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, @Result, l)
  3286. else
  3287. synsock.GetSockOpt(FSocket, IPPROTO_IP, IP_MULTICAST_TTL, @Result, l);
  3288. {$ENDIF}
  3289. end;
  3290. procedure TUDPBlockSocket.EnableMulticastLoop(Value: Boolean);
  3291. var
  3292. d: TSynaOption;
  3293. begin
  3294. d := TSynaOption.Create;
  3295. d.Option := SOT_MulticastLoop;
  3296. d.Enabled := Value;
  3297. DelayedOption(d);
  3298. end;
  3299. function TUDPBlockSocket.GetSocketType: integer;
  3300. begin
  3301. Result := integer(SOCK_DGRAM);
  3302. end;
  3303. function TUDPBlockSocket.GetSocketProtocol: integer;
  3304. begin
  3305. Result := integer(IPPROTO_UDP);
  3306. end;
  3307. {======================================================================}
  3308. constructor TTCPBlockSocket.CreateWithSSL(SSLPlugin: TSSLClass);
  3309. begin
  3310. inherited Create;
  3311. FSSL := SSLPlugin.Create(self);
  3312. FHTTPTunnelIP := '';
  3313. FHTTPTunnelPort := '';
  3314. FHTTPTunnel := False;
  3315. FHTTPTunnelRemoteIP := '';
  3316. FHTTPTunnelRemotePort := '';
  3317. FHTTPTunnelUser := '';
  3318. FHTTPTunnelPass := '';
  3319. FHTTPTunnelTimeout := 30000;
  3320. end;
  3321. constructor TTCPBlockSocket.Create;
  3322. begin
  3323. CreateWithSSL(SSLImplementation);
  3324. end;
  3325. destructor TTCPBlockSocket.Destroy;
  3326. begin
  3327. inherited Destroy;
  3328. FSSL.Free;
  3329. end;
  3330. function TTCPBlockSocket.GetErrorDescEx: string;
  3331. begin
  3332. Result := inherited GetErrorDescEx;
  3333. if (FLastError = WSASYSNOTREADY) and (self.SSL.LastError <> 0) then
  3334. begin
  3335. Result := self.SSL.LastErrorDesc;
  3336. end;
  3337. end;
  3338. procedure TTCPBlockSocket.CloseSocket;
  3339. begin
  3340. if FSSL.SSLEnabled then
  3341. FSSL.Shutdown;
  3342. if (FSocket <> INVALID_SOCKET) and (FLastError = 0) then
  3343. begin
  3344. Synsock.Shutdown(FSocket, 1);
  3345. Purge;
  3346. end;
  3347. inherited CloseSocket;
  3348. end;
  3349. procedure TTCPBlockSocket.DoAfterConnect;
  3350. begin
  3351. if assigned(OnAfterConnect) then
  3352. begin
  3353. OnAfterConnect(Self);
  3354. end;
  3355. end;
  3356. function TTCPBlockSocket.WaitingData: Integer;
  3357. begin
  3358. Result := 0;
  3359. if FSSL.SSLEnabled and (FSocket <> INVALID_SOCKET) then
  3360. Result := FSSL.WaitingData;
  3361. if Result = 0 then
  3362. Result := inherited WaitingData;
  3363. end;
  3364. procedure TTCPBlockSocket.Listen;
  3365. var
  3366. b: Boolean;
  3367. Sip,SPort: string;
  3368. begin
  3369. if FSocksIP = '' then
  3370. begin
  3371. inherited Listen;
  3372. end
  3373. else
  3374. begin
  3375. Sip := GetLocalSinIP;
  3376. if Sip = cAnyHost then
  3377. Sip := LocalName;
  3378. SPort := IntToStr(GetLocalSinPort);
  3379. inherited Connect(FSocksIP, FSocksPort);
  3380. b := SocksOpen;
  3381. if b then
  3382. b := SocksRequest(2, Sip, SPort);
  3383. if b then
  3384. b := SocksResponse;
  3385. if not b and (FLastError = 0) then
  3386. FLastError := WSANO_RECOVERY;
  3387. FSocksLocalIP := FSocksResponseIP;
  3388. if FSocksLocalIP = cAnyHost then
  3389. FSocksLocalIP := FSocksIP;
  3390. FSocksLocalPort := FSocksResponsePort;
  3391. FSocksRemoteIP := '';
  3392. FSocksRemotePort := '';
  3393. ExceptCheck;
  3394. DoStatus(HR_Listen, '');
  3395. end;
  3396. end;
  3397. function TTCPBlockSocket.Accept: TSocket;
  3398. begin
  3399. if FUsingSocks then
  3400. begin
  3401. if not SocksResponse and (FLastError = 0) then
  3402. FLastError := WSANO_RECOVERY;
  3403. FSocksRemoteIP := FSocksResponseIP;
  3404. FSocksRemotePort := FSocksResponsePort;
  3405. Result := FSocket;
  3406. ExceptCheck;
  3407. DoStatus(HR_Accept, '');
  3408. end
  3409. else
  3410. begin
  3411. result := inherited Accept;
  3412. end;
  3413. end;
  3414. procedure TTCPBlockSocket.Connect(IP, Port: string);
  3415. begin
  3416. if FSocksIP <> '' then
  3417. SocksDoConnect(IP, Port)
  3418. else
  3419. if FHTTPTunnelIP <> '' then
  3420. HTTPTunnelDoConnect(IP, Port)
  3421. else
  3422. inherited Connect(IP, Port);
  3423. if FLasterror = 0 then
  3424. DoAfterConnect;
  3425. end;
  3426. procedure TTCPBlockSocket.SocksDoConnect(IP, Port: string);
  3427. var
  3428. b: Boolean;
  3429. begin
  3430. inherited Connect(FSocksIP, FSocksPort);
  3431. if FLastError = 0 then
  3432. begin
  3433. b := SocksOpen;
  3434. if b then
  3435. b := SocksRequest(1, IP, Port);
  3436. if b then
  3437. b := SocksResponse;
  3438. if not b and (FLastError = 0) then
  3439. FLastError := WSASYSNOTREADY;
  3440. FSocksLocalIP := FSocksResponseIP;
  3441. FSocksLocalPort := FSocksResponsePort;
  3442. FSocksRemoteIP := IP;
  3443. FSocksRemotePort := Port;
  3444. end;
  3445. ExceptCheck;
  3446. DoStatus(HR_Connect, IP + ':' + Port);
  3447. end;
  3448. procedure TTCPBlockSocket.HTTPTunnelDoConnect(IP, Port: string);
  3449. //bugfixed by Mike Green (mgreen@emixode.com)
  3450. var
  3451. s: string;
  3452. begin
  3453. Port := IntToStr(ResolvePort(Port));
  3454. inherited Connect(FHTTPTunnelIP, FHTTPTunnelPort);
  3455. if FLastError <> 0 then
  3456. Exit;
  3457. FHTTPTunnel := False;
  3458. if IsIP6(IP) then
  3459. IP := '[' + IP + ']';
  3460. SendString('CONNECT ' + IP + ':' + Port + ' HTTP/1.0' + CRLF);
  3461. if FHTTPTunnelUser <> '' then
  3462. Sendstring('Proxy-Authorization: Basic ' +
  3463. EncodeBase64(FHTTPTunnelUser + ':' + FHTTPTunnelPass) + CRLF);
  3464. SendString(CRLF);
  3465. repeat
  3466. s := RecvTerminated(FHTTPTunnelTimeout, #$0a);
  3467. if FLastError <> 0 then
  3468. Break;
  3469. if (Pos('HTTP/', s) = 1) and (Length(s) > 11) then
  3470. FHTTPTunnel := s[10] = '2';
  3471. until (s = '') or (s = #$0d);
  3472. if (FLasterror = 0) and not FHTTPTunnel then
  3473. FLastError := WSASYSNOTREADY;
  3474. FHTTPTunnelRemoteIP := IP;
  3475. FHTTPTunnelRemotePort := Port;
  3476. ExceptCheck;
  3477. end;
  3478. procedure TTCPBlockSocket.SSLDoConnect;
  3479. begin
  3480. ResetLastError;
  3481. if not FSSL.Connect then
  3482. FLastError := WSASYSNOTREADY;
  3483. ExceptCheck;
  3484. end;
  3485. procedure TTCPBlockSocket.SSLDoShutdown;
  3486. begin
  3487. ResetLastError;
  3488. FSSL.BiShutdown;
  3489. end;
  3490. function TTCPBlockSocket.GetLocalSinIP: string;
  3491. begin
  3492. if FUsingSocks then
  3493. Result := FSocksLocalIP
  3494. else
  3495. Result := inherited GetLocalSinIP;
  3496. end;
  3497. function TTCPBlockSocket.GetRemoteSinIP: string;
  3498. begin
  3499. if FUsingSocks then
  3500. Result := FSocksRemoteIP
  3501. else
  3502. if FHTTPTunnel then
  3503. Result := FHTTPTunnelRemoteIP
  3504. else
  3505. Result := inherited GetRemoteSinIP;
  3506. end;
  3507. function TTCPBlockSocket.GetLocalSinPort: Integer;
  3508. begin
  3509. if FUsingSocks then
  3510. Result := StrToIntDef(FSocksLocalPort, 0)
  3511. else
  3512. Result := inherited GetLocalSinPort;
  3513. end;
  3514. function TTCPBlockSocket.GetRemoteSinPort: Integer;
  3515. begin
  3516. if FUsingSocks then
  3517. Result := ResolvePort(FSocksRemotePort)
  3518. else
  3519. if FHTTPTunnel then
  3520. Result := StrToIntDef(FHTTPTunnelRemotePort, 0)
  3521. else
  3522. Result := inherited GetRemoteSinPort;
  3523. end;
  3524. function TTCPBlockSocket.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
  3525. begin
  3526. if FSSL.SSLEnabled then
  3527. begin
  3528. Result := 0;
  3529. if TestStopFlag then
  3530. Exit;
  3531. ResetLastError;
  3532. LimitBandwidth(Len, FMaxRecvBandwidth, FNextRecv);
  3533. Result := FSSL.RecvBuffer(Buffer, Len);
  3534. if FSSL.LastError <> 0 then
  3535. FLastError := WSASYSNOTREADY;
  3536. ExceptCheck;
  3537. Inc(FRecvCounter, Result);
  3538. DoStatus(HR_ReadCount, IntToStr(Result));
  3539. DoMonitor(False, Buffer, Result);
  3540. DoReadFilter(Buffer, Result);
  3541. end
  3542. else
  3543. Result := inherited RecvBuffer(Buffer, Len);
  3544. end;
  3545. function TTCPBlockSocket.SendBuffer(Buffer: TMemory; Length: Integer): Integer;
  3546. var
  3547. x, y: integer;
  3548. l, r: integer;
  3549. {$IFNDEF CIL}
  3550. p: Pointer;
  3551. {$ENDIF}
  3552. begin
  3553. if FSSL.SSLEnabled then
  3554. begin
  3555. Result := 0;
  3556. if TestStopFlag then
  3557. Exit;
  3558. ResetLastError;
  3559. DoMonitor(True, Buffer, Length);
  3560. {$IFDEF CIL}
  3561. Result := FSSL.SendBuffer(Buffer, Length);
  3562. if FSSL.LastError <> 0 then
  3563. FLastError := WSASYSNOTREADY;
  3564. Inc(FSendCounter, Result);
  3565. DoStatus(HR_WriteCount, IntToStr(Result));
  3566. {$ELSE}
  3567. l := Length;
  3568. x := 0;
  3569. while x < l do
  3570. begin
  3571. y := l - x;
  3572. if y > FSendMaxChunk then
  3573. y := FSendMaxChunk;
  3574. if y > 0 then
  3575. begin
  3576. LimitBandwidth(y, FMaxSendBandwidth, FNextsend);
  3577. p := IncPoint(Buffer, x);
  3578. r := FSSL.SendBuffer(p, y);
  3579. if FSSL.LastError <> 0 then
  3580. FLastError := WSASYSNOTREADY;
  3581. if Flasterror <> 0 then
  3582. Break;
  3583. Inc(x, r);
  3584. Inc(Result, r);
  3585. Inc(FSendCounter, r);
  3586. DoStatus(HR_WriteCount, IntToStr(r));
  3587. end
  3588. else
  3589. break;
  3590. end;
  3591. {$ENDIF}
  3592. ExceptCheck;
  3593. end
  3594. else
  3595. Result := inherited SendBuffer(Buffer, Length);
  3596. end;
  3597. function TTCPBlockSocket.SSLAcceptConnection: Boolean;
  3598. begin
  3599. ResetLastError;
  3600. if not FSSL.Accept then
  3601. FLastError := WSASYSNOTREADY;
  3602. ExceptCheck;
  3603. Result := FLastError = 0;
  3604. end;
  3605. function TTCPBlockSocket.GetSocketType: integer;
  3606. begin
  3607. Result := integer(SOCK_STREAM);
  3608. end;
  3609. function TTCPBlockSocket.GetSocketProtocol: integer;
  3610. begin
  3611. Result := integer(IPPROTO_TCP);
  3612. end;
  3613. {======================================================================}
  3614. function TICMPBlockSocket.GetSocketType: integer;
  3615. begin
  3616. Result := integer(SOCK_RAW);
  3617. end;
  3618. function TICMPBlockSocket.GetSocketProtocol: integer;
  3619. begin
  3620. if FIP6Used then
  3621. Result := integer(IPPROTO_ICMPV6)
  3622. else
  3623. Result := integer(IPPROTO_ICMP);
  3624. end;
  3625. {======================================================================}
  3626. function TRAWBlockSocket.GetSocketType: integer;
  3627. begin
  3628. Result := integer(SOCK_RAW);
  3629. end;
  3630. function TRAWBlockSocket.GetSocketProtocol: integer;
  3631. begin
  3632. Result := integer(IPPROTO_RAW);
  3633. end;
  3634. {======================================================================}
  3635. function TPGMmessageBlockSocket.GetSocketType: integer;
  3636. begin
  3637. Result := integer(SOCK_RDM);
  3638. end;
  3639. function TPGMmessageBlockSocket.GetSocketProtocol: integer;
  3640. begin
  3641. Result := integer(IPPROTO_RM);
  3642. end;
  3643. {======================================================================}
  3644. function TPGMstreamBlockSocket.GetSocketType: integer;
  3645. begin
  3646. Result := integer(SOCK_STREAM);
  3647. end;
  3648. function TPGMstreamBlockSocket.GetSocketProtocol: integer;
  3649. begin
  3650. Result := integer(IPPROTO_RM);
  3651. end;
  3652. {======================================================================}
  3653. constructor TSynaClient.Create;
  3654. begin
  3655. inherited Create;
  3656. FIPInterface := cAnyHost;
  3657. FTargetHost := cLocalhost;
  3658. FTargetPort := cAnyPort;
  3659. FTimeout := 5000;
  3660. FUsername := '';
  3661. FPassword := '';
  3662. end;
  3663. {======================================================================}
  3664. constructor TCustomSSL.Create(const Value: TTCPBlockSocket);
  3665. begin
  3666. inherited Create;
  3667. FSocket := Value;
  3668. FSSLEnabled := False;
  3669. FUsername := '';
  3670. FPassword := '';
  3671. FLastError := 0;
  3672. FLastErrorDesc := '';
  3673. FVerifyCert := False;
  3674. FSSLType := LT_all;
  3675. FKeyPassword := '';
  3676. FCiphers := '';
  3677. FCertificateFile := '';
  3678. FPrivateKeyFile := '';
  3679. FCertCAFile := '';
  3680. FCertCA := '';
  3681. FTrustCertificate := '';
  3682. FTrustCertificateFile := '';
  3683. FCertificate := '';
  3684. FPrivateKey := '';
  3685. FPFX := '';
  3686. FPFXfile := '';
  3687. FSSHChannelType := '';
  3688. FSSHChannelArg1 := '';
  3689. FSSHChannelArg2 := '';
  3690. FCertComplianceLevel := -1; //default
  3691. FSNIHost := '';
  3692. end;
  3693. procedure TCustomSSL.Assign(const Value: TCustomSSL);
  3694. begin
  3695. FUsername := Value.Username;
  3696. FPassword := Value.Password;
  3697. FVerifyCert := Value.VerifyCert;
  3698. FSSLType := Value.SSLType;
  3699. FKeyPassword := Value.KeyPassword;
  3700. FCiphers := Value.Ciphers;
  3701. FCertificateFile := Value.CertificateFile;
  3702. FPrivateKeyFile := Value.PrivateKeyFile;
  3703. FCertCAFile := Value.CertCAFile;
  3704. FCertCA := Value.CertCA;
  3705. FTrustCertificate := Value.TrustCertificate;
  3706. FTrustCertificateFile := Value.TrustCertificateFile;
  3707. FCertificate := Value.Certificate;
  3708. FPrivateKey := Value.PrivateKey;
  3709. FPFX := Value.PFX;
  3710. FPFXfile := Value.PFXfile;
  3711. FCertComplianceLevel := Value.CertComplianceLevel;
  3712. FSNIHost := Value.FSNIHost;
  3713. end;
  3714. procedure TCustomSSL.ReturnError;
  3715. begin
  3716. FLastError := -1;
  3717. FLastErrorDesc := 'SSL/TLS support is not compiled!';
  3718. end;
  3719. function TCustomSSL.LibVersion: String;
  3720. begin
  3721. Result := '';
  3722. end;
  3723. function TCustomSSL.LibName: String;
  3724. begin
  3725. Result := '';
  3726. end;
  3727. function TCustomSSL.CreateSelfSignedCert(Host: string): Boolean;
  3728. begin
  3729. Result := False;
  3730. end;
  3731. function TCustomSSL.Connect: boolean;
  3732. begin
  3733. ReturnError;
  3734. Result := False;
  3735. end;
  3736. function TCustomSSL.Accept: boolean;
  3737. begin
  3738. ReturnError;
  3739. Result := False;
  3740. end;
  3741. function TCustomSSL.Shutdown: boolean;
  3742. begin
  3743. ReturnError;
  3744. Result := False;
  3745. end;
  3746. function TCustomSSL.BiShutdown: boolean;
  3747. begin
  3748. ReturnError;
  3749. Result := False;
  3750. end;
  3751. function TCustomSSL.SendBuffer(Buffer: TMemory; Len: Integer): Integer;
  3752. begin
  3753. ReturnError;
  3754. Result := integer(SOCKET_ERROR);
  3755. end;
  3756. procedure TCustomSSL.SetCertCAFile(const Value: string);
  3757. begin
  3758. FCertCAFile := Value;
  3759. end;
  3760. function TCustomSSL.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
  3761. begin
  3762. ReturnError;
  3763. Result := integer(SOCKET_ERROR);
  3764. end;
  3765. function TCustomSSL.WaitingData: Integer;
  3766. begin
  3767. ReturnError;
  3768. Result := 0;
  3769. end;
  3770. function TCustomSSL.GetSSLVersion: string;
  3771. begin
  3772. Result := '';
  3773. end;
  3774. function TCustomSSL.GetPeerSubject: string;
  3775. begin
  3776. Result := '';
  3777. end;
  3778. function TCustomSSL.GetPeerSerialNo: integer;
  3779. begin
  3780. Result := -1;
  3781. end;
  3782. function TCustomSSL.GetPeerName: string;
  3783. begin
  3784. Result := '';
  3785. end;
  3786. function TCustomSSL.GetPeerNameHash: cardinal;
  3787. begin
  3788. Result := 0;
  3789. end;
  3790. function TCustomSSL.GetPeerIssuer: string;
  3791. begin
  3792. Result := '';
  3793. end;
  3794. function TCustomSSL.GetPeerFingerprint: string;
  3795. begin
  3796. Result := '';
  3797. end;
  3798. function TCustomSSL.GetCertInfo: string;
  3799. begin
  3800. Result := '';
  3801. end;
  3802. function TCustomSSL.GetCipherName: string;
  3803. begin
  3804. Result := '';
  3805. end;
  3806. function TCustomSSL.GetCipherBits: integer;
  3807. begin
  3808. Result := 0;
  3809. end;
  3810. function TCustomSSL.GetCipherAlgBits: integer;
  3811. begin
  3812. Result := 0;
  3813. end;
  3814. function TCustomSSL.GetVerifyCert: integer;
  3815. begin
  3816. Result := 1;
  3817. end;
  3818. function TCustomSSL.DoVerifyCert:boolean;
  3819. begin
  3820. if assigned(OnVerifyCert) then
  3821. begin
  3822. result:=OnVerifyCert(Self);
  3823. end
  3824. else
  3825. result:=true;
  3826. end;
  3827. {======================================================================}
  3828. function TSSLNone.LibVersion: String;
  3829. begin
  3830. Result := 'Without SSL support';
  3831. end;
  3832. function TSSLNone.LibName: String;
  3833. begin
  3834. Result := 'ssl_none';
  3835. end;
  3836. {======================================================================}
  3837. initialization
  3838. begin
  3839. {$IFDEF ONCEWINSOCK}
  3840. if not InitSocketInterface(DLLStackName) then
  3841. begin
  3842. e := ESynapseError.Create('Error loading Socket interface (' + DLLStackName + ')!');
  3843. e.ErrorCode := 0;
  3844. e.ErrorMessage := 'Error loading Socket interface (' + DLLStackName + ')!';
  3845. raise e;
  3846. end;
  3847. synsock.WSAStartup(WinsockLevel, WsaDataOnce);
  3848. {$ENDIF}
  3849. end;
  3850. finalization
  3851. begin
  3852. {$IFDEF ONCEWINSOCK}
  3853. synsock.WSACleanup;
  3854. DestroySocketInterface;
  3855. {$ENDIF}
  3856. end;
  3857. end.