blcksock.pas 121 KB

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