PageRenderTime 73ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/DebugHelper.exe_src/synapse/blcksock.pas

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