IdStack.pas 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. {
  2. $Project$
  3. $Workfile$
  4. $Revision$
  5. $DateUTC$
  6. $Id$
  7. This file is part of the Indy (Internet Direct) project, and is offered
  8. under the dual-licensing agreement described on the Indy website.
  9. (http://www.indyproject.org/)
  10. Copyright:
  11. (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
  12. }
  13. {
  14. $Log$
  15. }
  16. {
  17. Rev 1.7 1/17/2005 7:25:48 PM JPMugaas
  18. Moved some stack management code here to so that we can reuse it in
  19. non-TIdComponent classes.
  20. Made HostToNetwork and NetworkToHost byte order overload functions for IPv6
  21. addresses.
  22. Rev 1.6 10/26/2004 8:12:30 PM JPMugaas
  23. Now uses TIdStrings and TIdStringList for portability.
  24. Rev 1.5 6/30/2004 12:41:14 PM BGooijen
  25. Added SetStackClass
  26. Rev 1.4 6/11/2004 8:28:50 AM DSiders
  27. Added "Do not Localize" comments.
  28. Rev 1.3 4/18/04 2:45:38 PM RLebeau
  29. Conversion support for Int64 values
  30. Rev 1.2 2004.03.07 11:45:22 AM czhower
  31. Flushbuffer fix + other minor ones found
  32. Rev 1.1 3/6/2004 5:16:20 PM JPMugaas
  33. Bug 67 fixes. Do not write to const values.
  34. Rev 1.0 2004.02.03 3:14:42 PM czhower
  35. Move and updates
  36. Rev 1.39 2/1/2004 6:10:50 PM JPMugaas
  37. GetSockOpt.
  38. Rev 1.38 2/1/2004 3:28:24 AM JPMugaas
  39. Changed WSGetLocalAddress to GetLocalAddress and moved into IdStack since
  40. that will work the same in the DotNET as elsewhere. This is required to
  41. reenable IPWatch.
  42. Rev 1.37 2/1/2004 1:54:56 AM JPMugaas
  43. Missapplied fix. IP 0.0.0.0 should now be accepted.
  44. Rev 1.36 1/31/2004 4:39:12 PM JPMugaas
  45. Removed empty methods.
  46. Rev 1.35 1/31/2004 1:13:04 PM JPMugaas
  47. Minor stack changes required as DotNET does support getting all IP addresses
  48. just like the other stacks.
  49. Rev 1.34 2004.01.22 5:59:10 PM czhower
  50. IdCriticalSection
  51. Rev 1.33 1/18/2004 11:15:52 AM JPMugaas
  52. IsIP was not handling "0" in an IP address. This caused the address
  53. "127.0.0.1" to be treated as a hostname.
  54. Rev 1.32 12/4/2003 3:14:50 PM BGooijen
  55. Added HostByAddress
  56. Rev 1.31 1/3/2004 12:21:44 AM BGooijen
  57. Added function SupportsIPv6
  58. Rev 1.30 12/31/2003 9:54:16 PM BGooijen
  59. Added IPv6 support
  60. Rev 1.29 2003.12.31 3:47:42 PM czhower
  61. Changed to use TextIsSame
  62. Rev 1.28 10/21/2003 9:24:32 PM BGooijen
  63. Started on SendTo, ReceiveFrom
  64. Rev 1.27 10/19/2003 5:21:28 PM BGooijen
  65. SetSocketOption
  66. Rev 1.26 10/15/2003 7:21:02 PM DSiders
  67. Added resource strings in TIdStack.Make.
  68. Rev 1.25 2003.10.11 5:51:02 PM czhower
  69. -VCL fixes for servers
  70. -Chain suport for servers (Super core)
  71. -Scheduler upgrades
  72. -Full yarn support
  73. Rev 1.24 10/5/2003 9:55:30 PM BGooijen
  74. TIdTCPServer works on D7 and DotNet now
  75. Rev 1.23 04/10/2003 22:31:56 HHariri
  76. moving of WSNXXX method to IdStack and renaming of the DotNet ones
  77. Rev 1.22 10/2/2003 7:31:18 PM BGooijen
  78. .net
  79. Rev 1.21 10/2/2003 6:05:16 PM GGrieve
  80. DontNet
  81. Rev 1.20 2003.10.02 10:16:30 AM czhower
  82. .Net
  83. Rev 1.19 2003.10.01 9:11:20 PM czhower
  84. .Net
  85. Rev 1.18 2003.10.01 5:05:16 PM czhower
  86. .Net
  87. Rev 1.17 2003.10.01 2:30:40 PM czhower
  88. .Net
  89. Rev 1.16 2003.10.01 12:30:08 PM czhower
  90. .Net
  91. Rev 1.14 2003.10.01 1:37:36 AM czhower
  92. .Net
  93. Rev 1.12 9/30/2003 7:15:46 PM BGooijen
  94. IdCompilerDefines.inc is included now
  95. Rev 1.11 2003.09.30 1:23:04 PM czhower
  96. Stack split for DotNet
  97. }
  98. unit IdStack;
  99. interface
  100. {$I IdCompilerDefines.inc}
  101. uses
  102. Classes,
  103. IdException, IdStackConsts, IdGlobal, SysUtils;
  104. type
  105. EIdSocketError = class(EIdException)
  106. protected
  107. FLastError: Integer;
  108. public
  109. // Params must be in this order to avoid conflict with CreateHelp
  110. // constructor in CBuilder as CB does not differentiate constructors
  111. // by name as Delphi does
  112. constructor CreateError(const AErr: Integer; const AMsg: string); virtual;
  113. //
  114. property LastError: Integer read FLastError;
  115. end;
  116. { resolving hostnames }
  117. EIdStackError = class (EIdException);
  118. EIdIPVersionUnsupported = class (EIdStackError);
  119. {$IFDEF UNIX}
  120. EIdResolveError = class(EIdSocketError);
  121. EIdReverseResolveError = class(EIdSocketError);
  122. EIdMaliciousPtrRecord = class(EIdReverseResolveError);
  123. {$ELSE}
  124. EIdMaliciousPtrRecord = class(EIdSocketError);
  125. {$ENDIF}
  126. EIdNotASocket = class(EIdSocketError);
  127. // TODO: move this to IdStackVCLPosix...
  128. {$IFDEF USE_VCL_POSIX}
  129. {$IFDEF ANDROID}
  130. EIdAndroidPermissionNeeded = class(EIdSocketError);
  131. EIdInternetPermissionNeeded = class(EIdAndroidPermissionNeeded);
  132. {$ENDIF}
  133. {$ENDIF}
  134. TIdServeFile = function(ASocket: TIdStackSocketHandle; const AFileName: string): Int64;
  135. TIdPacketInfo = class
  136. protected
  137. FSourceIP: String;
  138. FSourcePort : TIdPort;
  139. FSourceIF: UInt32;
  140. FSourceIPVersion: TIdIPVersion;
  141. FDestIP: String;
  142. FDestPort : TIdPort;
  143. FDestIF: UInt32;
  144. FDestIPVersion: TIdIPVersion;
  145. FTTL: Byte;
  146. public
  147. procedure Reset;
  148. property TTL : Byte read FTTL write FTTL;
  149. //The computer that sent it to you
  150. property SourceIP : String read FSourceIP write FSourceIP;
  151. property SourcePort : TIdPort read FSourcePort write FSourcePort;
  152. property SourceIF : UInt32 read FSourceIF write FSourceIF;
  153. property SourceIPVersion : TIdIPVersion read FSourceIPVersion write FSourceIPVersion;
  154. //you, the receiver - this is provided for multihomed machines
  155. property DestIP : String read FDestIP write FDestIP;
  156. property DestPort : TIdPort read FDestPort write FDestPort;
  157. property DestIF : UInt32 read FDestIF write FDestIF;
  158. property DestIPVersion : TIdIPVersion read FDestIPVersion write FDestIPVersion;
  159. end;
  160. TIdSocketListClass = class of TIdSocketList;
  161. // Descend from only TObject. This objects is created a lot and should be fast
  162. // and small
  163. TIdSocketList = class(TObject)
  164. protected
  165. FLock: TIdCriticalSection;
  166. //
  167. function GetItem(AIndex: Integer): TIdStackSocketHandle; virtual; abstract;
  168. public
  169. constructor Create; virtual;
  170. destructor Destroy; override;
  171. procedure Add(AHandle: TIdStackSocketHandle); virtual; abstract;
  172. function Clone: TIdSocketList; virtual; abstract;
  173. function Count: Integer; virtual; abstract;
  174. class function CreateSocketList: TIdSocketList;
  175. property Items[AIndex: Integer]: TIdStackSocketHandle read GetItem; default;
  176. procedure Remove(AHandle: TIdStackSocketHandle); virtual; abstract;
  177. procedure Clear; virtual; abstract;
  178. function ContainsSocket(AHandle: TIdStackSocketHandle): boolean; virtual; abstract;
  179. procedure Lock;
  180. class function Select(AReadList: TIdSocketList; AWriteList: TIdSocketList;
  181. AExceptList: TIdSocketList; const ATimeout: Integer = IdTimeoutInfinite): Boolean; virtual;
  182. function SelectRead(const ATimeout: Integer = IdTimeoutInfinite): Boolean; virtual; abstract;
  183. function SelectReadList(var VSocketList: TIdSocketList; const ATimeout: Integer = IdTimeoutInfinite): Boolean; virtual; abstract;
  184. procedure Unlock;
  185. end;
  186. TIdStackLocalAddress = class(TCollectionItem)
  187. protected
  188. FIPVersion: TIdIPVersion;
  189. FIPAddress: String;
  190. FInterfaceName: String;
  191. FInterfaceIndex: UInt32;
  192. FDescription: String;
  193. FFriendlyName: String;
  194. public
  195. constructor Create(ACollection: TCollection; const AIPVersion: TIdIPVersion; const AIPAddress: string); reintroduce;
  196. property IPVersion: TIdIPVersion read FIPVersion;
  197. property IPAddress: String read FIPAddress;
  198. property InterfaceName: String read FInterfaceName;
  199. property InterfaceIndex: UInt32 read FInterfaceIndex;
  200. property Description: String read FDescription;
  201. property FriendlyName: String read FFriendlyName;
  202. end;
  203. TIdStackLocalAddressIPv4 = class(TIdStackLocalAddress)
  204. protected
  205. FSubNetMask: String;
  206. public
  207. constructor Create(ACollection: TCollection; const AIPAddress, ASubNetMask: string); reintroduce;
  208. property SubNetMask: String read FSubNetMask;
  209. // TODO: add BroadcastIP
  210. end;
  211. TIdStackLocalAddressIPv6 = class(TIdStackLocalAddress)
  212. public
  213. constructor Create(ACollection: TCollection; const AIPAddress: string); reintroduce;
  214. end;
  215. TIdStackLocalAddressList = class(TCollection)
  216. protected
  217. function GetAddress(AIndex: Integer): TIdStackLocalAddress;
  218. public
  219. constructor Create; reintroduce;
  220. function IndexOfIP(const AIP: String): Integer; overload;
  221. function IndexOfIP(const AIP: String; AIPVersion: TIdIPVersion): Integer; overload;
  222. property Addresses[AIndex: Integer]: TIdStackLocalAddress read GetAddress; default;
  223. end;
  224. TIdStack = class(TObject)
  225. protected
  226. FLocalAddresses: TStrings;
  227. //
  228. procedure IPVersionUnsupported;
  229. function HostByName(const AHostName: string;
  230. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; virtual; abstract;
  231. function MakeCanonicalIPv6Address(const AAddr: string): string; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use IdGlobal.MakeCanonicalIPv6Address()'{$ENDIF};{$ENDIF}
  232. function ReadHostName: string; virtual; abstract;
  233. function GetLocalAddress: string;
  234. function GetLocalAddresses: TStrings;
  235. public
  236. function Accept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort): TIdStackSocketHandle; overload;
  237. function Accept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort;
  238. var VIPVersion: TIdIPVersion): TIdStackSocketHandle; overload; virtual; abstract;
  239. procedure Bind(ASocket: TIdStackSocketHandle; const AIP: string;
  240. const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ); virtual; abstract;
  241. procedure Connect(const ASocket: TIdStackSocketHandle; const AIP: string;
  242. const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract;
  243. constructor Create; virtual;
  244. destructor Destroy; override;
  245. procedure Disconnect(ASocket: TIdStackSocketHandle); virtual; abstract;
  246. function IOControl(const s: TIdStackSocketHandle; const cmd: UInt32;
  247. var arg: UInt32): Integer; virtual; abstract;
  248. class procedure IncUsage; //create stack if necessary and inc counter
  249. class procedure DecUsage; //decrement counter and free if it gets to zero
  250. procedure GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string;
  251. var VPort: TIdPort); overload;
  252. procedure GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string;
  253. var VPort: TIdPort; var VIPVersion: TIdIPVersion); overload; virtual; abstract;
  254. procedure GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string;
  255. var VPort: TIdPort); overload;
  256. procedure GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string;
  257. var VPort: TIdPort; var VIPVersion: TIdIPVersion); overload; virtual; abstract;
  258. function HostByAddress(const AAddress: string;
  259. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; virtual; abstract;
  260. function HostToNetwork(AValue: UInt16): UInt16; overload; virtual; abstract;
  261. function HostToNetwork(AValue: UInt32): UInt32; overload; virtual; abstract;
  262. function HostToNetwork(AValue: TIdUInt64): TIdUInt64; overload; virtual; abstract;
  263. function HostToNetwork(const AValue: TIdIPv6Address): TIdIPv6Address; overload; virtual;
  264. function IsIP(AIP: string): Boolean;
  265. procedure Listen(ASocket: TIdStackSocketHandle; ABackLog: Integer); virtual; abstract;
  266. function WSGetLastError: Integer; virtual; abstract;
  267. procedure WSSetLastError(const AErr : Integer); virtual; abstract;
  268. function WSTranslateSocketErrorMsg(const AErr: integer): string; virtual;
  269. function CheckForSocketError(const AResult: Integer): Integer; {$IFNDEF OVERLOADED_OPENARRAY_BUG}overload;{$ENDIF}
  270. function {$IFDEF OVERLOADED_OPENARRAY_BUG}CheckForSocketErrorArr{$ELSE}CheckForSocketError{$ENDIF}(
  271. const AResult: Integer; const AIgnore: array of Integer): Integer; {$IFNDEF OVERLOADED_OPENARRAY_BUG}overload;{$ENDIF}
  272. procedure RaiseLastSocketError;
  273. procedure RaiseSocketError(AErr: integer); virtual;
  274. function NewSocketHandle(const ASocketType: TIdSocketType; const AProtocol: TIdSocketProtocol;
  275. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const ANonBlocking: Boolean = False)
  276. : TIdStackSocketHandle; virtual; abstract;
  277. function NetworkToHost(AValue: UInt16): UInt16; overload; virtual; abstract;
  278. function NetworkToHost(AValue: UInt32): UInt32; overload; virtual; abstract;
  279. function NetworkToHost(AValue: TIdUInt64): TIdUInt64; overload; virtual; abstract;
  280. function NetworkToHost(const AValue: TIdIPv6Address): TIdIPv6Address; overload; virtual;
  281. procedure GetSocketOption(ASocket: TIdStackSocketHandle;
  282. ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption;
  283. out AOptVal: Integer); overload; virtual; abstract;
  284. procedure SetSocketOption(ASocket: TIdStackSocketHandle; ALevel: TIdSocketOptionLevel;
  285. AOptName: TIdSocketOption; AOptVal: Integer); overload; virtual; abstract;
  286. function ResolveHost(const AHost: string;
  287. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string;
  288. // Result:
  289. // > 0: Number of bytes received
  290. // 0: Connection closed gracefully
  291. // Will raise exceptions in other cases
  292. function Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes): Integer; virtual; abstract;
  293. function Send(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes;
  294. const AOffset: Integer = 0; const ASize: Integer = -1): Integer; virtual; abstract;
  295. function ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes;
  296. var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): Integer; virtual; abstract;
  297. function SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes;
  298. const AOffset: Integer; const AIP: string; const APort: TIdPort;
  299. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer; overload;
  300. function SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes;
  301. const AOffset: Integer; const ASize: Integer; const AIP: string;
  302. const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION)
  303. : Integer; overload; virtual; abstract;
  304. function ReceiveMsg(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes;
  305. APkt: TIdPacketInfo): UInt32; virtual; abstract;
  306. function SupportsIPv4: Boolean; virtual; abstract;
  307. function SupportsIPv6: Boolean; virtual; abstract;
  308. //multicast stuff Kudzu permitted me to add here.
  309. function IsValidIPv4MulticastGroup(const Value: string): Boolean;
  310. function IsValidIPv6MulticastGroup(const Value: string): Boolean;
  311. procedure SetKeepAliveValues(ASocket: TIdStackSocketHandle;
  312. const AEnabled: Boolean; const ATimeMS, AInterval: Integer); virtual;
  313. procedure SetMulticastTTL(AHandle: TIdStackSocketHandle;
  314. const AValue : Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract;
  315. procedure SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean;
  316. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract;
  317. procedure DropMulticastMembership(AHandle: TIdStackSocketHandle;
  318. const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract;
  319. procedure AddMulticastMembership(AHandle: TIdStackSocketHandle;
  320. const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract;
  321. //I know this looks like an odd place to put a function for calculating a
  322. //packet checksum. There is a reason for it though. The reason is that
  323. //you need it for ICMPv6 and in Windows, you do that with some other stuff
  324. //in the stack descendants
  325. function CalcCheckSum(const AData : TIdBytes): UInt16; virtual;
  326. //In Windows, this writes a checksum into a buffer. In Linux, it would probably
  327. //simply have the kernal write the checksum with something like this (RFC 2292):
  328. //
  329. // int offset = 2;
  330. // setsockopt(fd, IPPROTO_IPV6, IPV6_CHECKSUM, &offset, sizeof(offset));
  331. //
  332. // Note that this should be called
  333. //IMMEDIATELY before you do a SendTo because the Local IPv6 address might change
  334. procedure WriteChecksum(s : TIdStackSocketHandle;
  335. var VBuffer : TIdBytes; const AOffset : Integer; const AIP : String;
  336. const APort : TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract;
  337. //
  338. procedure AddLocalAddressesToList(AAddresses: TStrings); {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'use GetLocalAddressList()'{$ENDIF};{$ENDIF}
  339. procedure GetLocalAddressList(AAddresses: TIdStackLocalAddressList); virtual; abstract;
  340. //
  341. // Properties
  342. //
  343. property HostName: string read ReadHostName;
  344. property LocalAddress: string read GetLocalAddress; // {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'use GetLocalAddressList()'{$ENDIF};{$ENDIF}
  345. property LocalAddresses: TStrings read GetLocalAddresses; // {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'use GetLocalAddressList()'{$ENDIF};{$ENDIF}
  346. end;
  347. TIdStackClass = class of TIdStack;
  348. var
  349. GStack: TIdStack = nil;
  350. GServeFileProc: TIdServeFile = nil;
  351. GSocketListClass: TIdSocketListClass;
  352. // Procedures
  353. procedure SetStackClass( AStackClass: TIdStackClass );
  354. // TODO: move this to IdStackVCLPosix...
  355. {$IFDEF USE_VCL_POSIX}
  356. {$IFDEF ANDROID}
  357. function HasAndroidPermission(const Permission: string): Boolean;
  358. {$ENDIF}
  359. {$ENDIF}
  360. implementation
  361. {$O-}
  362. uses
  363. //done this way so we can have a separate stack for FPC under Unix systems
  364. {$IFDEF DOTNET}
  365. IdStackDotNet,
  366. {$ELSE}
  367. {$IFDEF WINDOWS}
  368. {$IFDEF USE_INLINE}
  369. Windows,
  370. {$ENDIF}
  371. IdStackWindows,
  372. {$ELSE}
  373. {$IFDEF USE_VCL_POSIX}
  374. IdStackVCLPosix,
  375. {$ELSE}
  376. {$IFDEF UNIX}
  377. {$IFDEF KYLIXCOMPAT}
  378. IdStackLibc,
  379. {$ELSE}
  380. {$IFDEF USE_BASEUNIX}
  381. IdStackUnix,
  382. {$ENDIF}
  383. {$ENDIF}
  384. {$ENDIF}
  385. {$ENDIF}
  386. {$ENDIF}
  387. {$ENDIF}
  388. // TODO: move this to IdStackVCLPosix...
  389. {$IFDEF USE_VCL_POSIX}
  390. {$IFDEF ANDROID}
  391. {$IFNDEF VCL_XE6_OR_ABOVE}
  392. // StringToJString() is here in XE5
  393. Androidapi.JNI.JavaTypes,
  394. {$ENDIF}
  395. {$IFNDEF VCL_XE7_OR_ABOVE}
  396. // SharedActivityContext() is here in XE5 and XE6
  397. FMX.Helpers.Android,
  398. {$ENDIF}
  399. {$IFDEF VCL_XE6_OR_ABOVE}
  400. {$IFDEF VCL_10_0_OR_ABOVE}
  401. // StringToJString() is inline in Seattle and later, so we need JavaTypes again...
  402. Androidapi.JNI.JavaTypes,
  403. {$ENDIF}
  404. // StringToJString() was moved here in XE6
  405. // SharedActivityContext() was moved here in XE7
  406. // TAndroidHelper was added here in Seattle
  407. Androidapi.Helpers,
  408. {$ENDIF}
  409. Androidapi.JNI.GraphicsContentViewText,
  410. {$ENDIF}
  411. {$ENDIF}
  412. IdResourceStrings;
  413. var
  414. GStackClass: TIdStackClass = nil;
  415. var
  416. {$IFNDEF USE_OBJECT_ARC}
  417. GInstanceCount: UInt32 = 0;
  418. {$ENDIF}
  419. GStackCriticalSection: TIdCriticalSection = nil;
  420. //for IPv4 Multicast address chacking
  421. const
  422. IPv4MCastLo = 224;
  423. IPv4MCastHi = 239;
  424. procedure SetStackClass(AStackClass: TIdStackClass);
  425. begin
  426. GStackClass := AStackClass;
  427. end;
  428. procedure TIdPacketInfo.Reset;
  429. begin
  430. FSourceIP := '';
  431. FSourcePort := 0;
  432. FSourceIF := 0;
  433. FSourceIPVersion := ID_DEFAULT_IP_VERSION;
  434. FDestIP := '';
  435. FDestPort:= 0;
  436. FDestIF := 0;
  437. FDestIPVersion := ID_DEFAULT_IP_VERSION;
  438. FTTL := 0;
  439. end;
  440. { TIdSocketList }
  441. constructor TIdSocketList.Create;
  442. begin
  443. inherited Create;
  444. FLock := TIdCriticalSection.Create;
  445. end;
  446. class function TIdSocketList.CreateSocketList: TIdSocketList;
  447. Begin
  448. Result := GSocketListClass.Create;
  449. End;
  450. destructor TIdSocketList.Destroy;
  451. begin
  452. FreeAndNil(FLock);
  453. inherited Destroy;
  454. end;
  455. procedure TIdSocketList.Lock;
  456. begin
  457. FLock.Acquire;
  458. end;
  459. class function TIdSocketList.Select(AReadList, AWriteList,
  460. AExceptList: TIdSocketList; const ATimeout: Integer): Boolean;
  461. begin
  462. // C++ Builder cannot have abstract class functions thus we need this base
  463. Result := False;
  464. end;
  465. procedure TIdSocketList.Unlock;
  466. begin
  467. FLock.Release;
  468. end;
  469. { EIdSocketError }
  470. constructor EIdSocketError.CreateError(const AErr: Integer; const AMsg: string);
  471. begin
  472. inherited Create(AMsg);
  473. FLastError := AErr;
  474. end;
  475. { TIdStackLocalAddressList }
  476. constructor TIdStackLocalAddress.Create(ACollection: TCollection; const AIPVersion: TIdIPVersion; const AIPAddress: string);
  477. begin
  478. inherited Create(ACollection);
  479. FIPVersion := AIPVersion;
  480. FIPAddress := AIPAddress;
  481. FInterfaceIndex := 0;
  482. end;
  483. constructor TIdStackLocalAddressIPv4.Create(ACollection: TCollection; const AIPAddress, ASubNetMask: string);
  484. begin
  485. inherited Create(ACollection, Id_IPv4, AIPAddress);
  486. FSubNetMask := ASubNetMask;
  487. end;
  488. constructor TIdStackLocalAddressIPv6.Create(ACollection: TCollection; const AIPAddress: string);
  489. begin
  490. inherited Create(ACollection, Id_IPv6, AIPAddress);
  491. end;
  492. constructor TIdStackLocalAddressList.Create;
  493. begin
  494. inherited Create(TIdStackLocalAddress);
  495. end;
  496. function TIdStackLocalAddressList.GetAddress(AIndex: Integer): TIdStackLocalAddress;
  497. begin
  498. Result := TIdStackLocalAddress(inherited Items[AIndex]);
  499. end;
  500. function TIdStackLocalAddressList.IndexOfIP(const AIP: String): Integer;
  501. var
  502. I: Integer;
  503. begin
  504. Result := -1;
  505. for I := 0 to Count-1 do begin
  506. if Addresses[I].IPAddress = AIP then begin
  507. Result := I;
  508. Exit;
  509. end;
  510. end;
  511. end;
  512. function TIdStackLocalAddressList.IndexOfIP(const AIP: String; AIPVersion: TIdIPVersion): Integer;
  513. var
  514. I: Integer;
  515. LAddr: TIdStackLocalAddress;
  516. begin
  517. Result := -1;
  518. for I := 0 to Count-1 do begin
  519. LAddr := Addresses[I];
  520. if (LAddr.IPVersion = AIPVersion) and (LAddr.IPAddress = AIP) then begin
  521. Result := I;
  522. Exit;
  523. end;
  524. end;
  525. end;
  526. { TIdStack }
  527. constructor TIdStack.Create;
  528. begin
  529. // Here for .net
  530. inherited Create;
  531. end;
  532. destructor TIdStack.Destroy;
  533. begin
  534. FreeAndNil(FLocalAddresses);
  535. inherited Destroy;
  536. end;
  537. procedure TIdStack.IPVersionUnsupported;
  538. begin
  539. raise EIdIPVersionUnsupported.Create(RSIPVersionUnsupported);
  540. end;
  541. function TIdStack.Accept(ASocket: TIdStackSocketHandle; var VIP: string;
  542. var VPort: TIdPort): TIdStackSocketHandle;
  543. var
  544. LIPVersion: TIdIPVersion;
  545. begin
  546. Result := Accept(ASocket, VIP, VPort, LIPVersion);
  547. end;
  548. procedure TIdStack.GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string;
  549. var VPort: TIdPort);
  550. var
  551. LIPVersion: TIdIPVersion;
  552. begin
  553. GetPeerName(ASocket, VIP, VPort, LIPVersion);
  554. end;
  555. procedure TIdStack.GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string;
  556. var VPort: TIdPort);
  557. var
  558. LIPVersion: TIdIPVersion;
  559. begin
  560. GetSocketName(ASocket, VIP, VPort, LIPVersion);
  561. end;
  562. {$I IdDeprecatedImplBugOff.inc}
  563. procedure TIdStack.AddLocalAddressesToList(AAddresses: TStrings);
  564. {$I IdDeprecatedImplBugOn.inc}
  565. var
  566. LList: TIdStackLocalAddressList;
  567. I: Integer;
  568. begin
  569. LList := TIdStackLocalAddressList.Create;
  570. try
  571. // for backwards compatibility, return only IPv4 addresses
  572. GetLocalAddressList(LList);
  573. if LList.Count > 0 then begin
  574. AAddresses.BeginUpdate;
  575. try
  576. for I := 0 to LList.Count-1 do begin
  577. if LList[I].IPVersion = Id_IPv4 then begin
  578. AAddresses.Add(LList[I].IPAddress);
  579. end;
  580. end;
  581. finally
  582. AAddresses.EndUpdate;
  583. end;
  584. end;
  585. finally
  586. LList.Free;
  587. end;
  588. end;
  589. function TIdStack.GetLocalAddresses: TStrings;
  590. var
  591. LList: TIdStackLocalAddressList;
  592. I: Integer;
  593. begin
  594. if FLocalAddresses = nil then begin
  595. FLocalAddresses := TStringList.Create;
  596. end;
  597. FLocalAddresses.BeginUpdate;
  598. try
  599. FLocalAddresses.Clear;
  600. LList := TIdStackLocalAddressList.Create;
  601. try
  602. // for backwards compatibility, return only IPv4 addresses
  603. GetLocalAddressList(LList);
  604. for I := 0 to LList.Count-1 do begin
  605. if LList[I].IPVersion = Id_IPv4 then begin
  606. FLocalAddresses.Add(LList[I].IPAddress);
  607. end;
  608. end;
  609. finally
  610. LList.Free;
  611. end;
  612. finally
  613. FLocalAddresses.EndUpdate;
  614. end;
  615. Result := FLocalAddresses;
  616. end;
  617. function TIdStack.GetLocalAddress: string;
  618. var
  619. LList: TIdStackLocalAddressList;
  620. I: Integer;
  621. begin
  622. // RLebeau: using a local list instead of the LocalAddresses
  623. // property so this method can be thread-safe...
  624. //
  625. // old code:
  626. // Result := LocalAddresses[0];
  627. Result := '';
  628. LList := TIdStackLocalAddressList.Create;
  629. try
  630. // for backwards compatibility, return only IPv4 addresses
  631. GetLocalAddressList(LList);
  632. for I := 0 to LList.Count-1 do begin
  633. if LList[I].IPVersion = Id_IPv4 then begin
  634. Result := LList[I].IPAddress;
  635. Exit;
  636. end;
  637. end;
  638. finally
  639. LList.Free;
  640. end;
  641. end;
  642. function TIdStack.IsIP(AIP: string): Boolean;
  643. var
  644. i: Integer;
  645. begin
  646. // TODO: support IPv6
  647. //
  648. //Result := Result and ((i > 0) and (i < 256));
  649. //
  650. i := IndyStrToInt(Fetch(AIP, '.'), -1); {Do not Localize}
  651. Result := (i > -1) and (i < 256);
  652. i := IndyStrToInt(Fetch(AIP, '.'), -1); {Do not Localize}
  653. Result := Result and ((i > -1) and (i < 256));
  654. i := IndyStrToInt(Fetch(AIP, '.'), -1); {Do not Localize}
  655. Result := Result and ((i > -1) and (i < 256));
  656. i := IndyStrToInt(Fetch(AIP, '.'), -1); {Do not Localize}
  657. Result := Result and ((i > -1) and (i < 256)) and (AIP = '');
  658. end;
  659. {$I IdDeprecatedImplBugOff.inc}
  660. function TIdStack.MakeCanonicalIPv6Address(const AAddr: string): string;
  661. {$I IdDeprecatedImplBugOn.inc}
  662. begin
  663. Result := IdGlobal.MakeCanonicalIPv6Address(AAddr);
  664. end;
  665. function TIdStack.ResolveHost(const AHost: string;
  666. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string;
  667. begin
  668. Result := '';
  669. case AIPVersion of
  670. Id_IPv4: begin
  671. // Sometimes 95 forgets who localhost is
  672. if TextIsSame(AHost, 'LOCALHOST') then begin {Do not Localize}
  673. Result := '127.0.0.1'; {Do not Localize}
  674. end else if IsIP(AHost) then begin
  675. Result := AHost;
  676. end else begin
  677. Result := HostByName(AHost, Id_IPv4);
  678. end;
  679. end;
  680. Id_IPv6: begin
  681. if TextIsSame(AHost, 'LOCALHOST') then begin {Do not Localize}
  682. Result := '::1'; {Do not Localize}
  683. end else begin
  684. Result := IdGlobal.MakeCanonicalIPv6Address(AHost);
  685. if Result = '' then begin
  686. Result := HostByName(AHost, Id_IPv6);
  687. end;
  688. end;
  689. end;
  690. else begin
  691. IPVersionUnsupported;
  692. end;
  693. end;
  694. end;
  695. function TIdStack.SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes;
  696. const AOffset: Integer; const AIP: string; const APort: TIdPort;
  697. const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer;
  698. begin
  699. Result := SendTo(ASocket, ABuffer, AOffset, -1, AIP, APort, AIPVersion);
  700. end;
  701. class procedure TIdStack.DecUsage;
  702. var
  703. // under ARC, increment the lock's reference count before working with it
  704. LLock: TIdCriticalSection;
  705. begin
  706. LLock := GStackCriticalSection;
  707. if not Assigned(LLock) then begin
  708. raise EIdStackError.Create('GStackCriticalSection is nil in TIdStack.DecUsage'); {do not localize}
  709. end;
  710. LLock.Acquire;
  711. try
  712. // This CS will guarantee that during the FreeAndNil nobody
  713. // will try to use or construct GStack
  714. {$IFDEF USE_OBJECT_ARC}
  715. if GStack <> nil then begin
  716. if GStack.__ObjRelease = 0 then begin
  717. Pointer(GStack) := nil;
  718. end;
  719. end;
  720. {$ELSE}
  721. if GInstanceCount > 0 then begin
  722. Dec(GInstanceCount);
  723. if GInstanceCount = 0 then begin
  724. FreeAndNil(GStack);
  725. end;
  726. end;
  727. {$ENDIF}
  728. finally
  729. LLock.Release;
  730. end;
  731. end;
  732. class procedure TIdStack.IncUsage;
  733. var
  734. // under ARC, increment the lock's reference count before working with it
  735. LLock: TIdCriticalSection;
  736. begin
  737. LLock := GStackCriticalSection;
  738. if not Assigned(LLock) then begin
  739. raise EIdStackError.Create('GStackCriticalSection is nil in TIdStack.IncUsage'); {do not localize}
  740. end;
  741. LLock.Acquire;
  742. try
  743. {$IFDEF USE_OBJECT_ARC}
  744. if GStack = nil then begin
  745. if GStackClass = nil then begin
  746. raise EIdStackError.Create(RSStackClassUndefined);
  747. end;
  748. GStack := GStackClass.Create;
  749. end else begin
  750. GStack.__ObjAddRef;
  751. end;
  752. {$ELSE}
  753. if GInstanceCount = 0 then begin
  754. if GStack <> nil then begin
  755. raise EIdStackError.Create(RSStackAlreadyCreated);
  756. end;
  757. if GStackClass = nil then begin
  758. raise EIdStackError.Create(RSStackClassUndefined);
  759. end;
  760. GStack := GStackClass.Create;
  761. end;
  762. Inc(GInstanceCount);
  763. {$ENDIF}
  764. finally
  765. LLock.Release;
  766. end;
  767. end;
  768. function TIdStack.CheckForSocketError(const AResult: Integer): Integer;
  769. begin
  770. if AResult = Integer(Id_SOCKET_ERROR) then begin
  771. RaiseLastSocketError;
  772. end;
  773. Result := AResult;
  774. end;
  775. function TIdStack.{$IFDEF OVERLOADED_OPENARRAY_BUG}CheckForSocketErrorArr{$ELSE}CheckForSocketError{$ENDIF}(
  776. const AResult: Integer; const AIgnore: array of integer): Integer;
  777. var
  778. i: Integer;
  779. LLastError: Integer;
  780. begin
  781. Result := AResult;
  782. if AResult = Integer(Id_SOCKET_ERROR) then begin
  783. LLastError := WSGetLastError;
  784. for i := Low(AIgnore) to High(AIgnore) do begin
  785. if LLastError = AIgnore[i] then begin
  786. Result := LLastError;
  787. Exit;
  788. end;
  789. end;
  790. RaiseSocketError(LLastError);
  791. end;
  792. end;
  793. procedure TIdStack.RaiseLastSocketError;
  794. begin
  795. RaiseSocketError(WSGetLastError);
  796. end;
  797. // TODO: move this to IdStackVCLPosix...
  798. {$IFDEF USE_VCL_POSIX}
  799. {$IFDEF ANDROID}
  800. function GetActivityContext: JContext; {$IFDEF USE_INLINE}inline;{$ENDIF}
  801. begin
  802. {$IFDEF HAS_TAndroidHelper}
  803. Result := TAndroidHelper.Context;
  804. {$ELSE}
  805. Result := SharedActivityContext;
  806. {$ENDIF}
  807. end;
  808. function HasAndroidPermission(const Permission: string): Boolean;
  809. begin
  810. Result := GetActivityContext.checkCallingOrSelfPermission(StringToJString(Permission)) = TJPackageManager.JavaClass.PERMISSION_GRANTED;
  811. end;
  812. {$ENDIF}
  813. {$ENDIF}
  814. procedure TIdStack.RaiseSocketError(AErr: integer);
  815. begin
  816. (*
  817. RRRRR EEEEEE AAAA DDDDD MM MM EEEEEE !! !! !!
  818. RR RR EE AA AA DD DD MMMM MMMM EE !! !! !!
  819. RRRRR EEEE AAAAAA DD DD MM MMM MM EEEE !! !! !!
  820. RR RR EE AA AA DD DD MM MM EE
  821. RR RR EEEEEE AA AA DDDDD MM MM EEEEEE .. .. ..
  822. Please read the note in the next comment.
  823. *)
  824. if AErr = Id_WSAENOTSOCK then begin
  825. // You can add this to your exception ignore list for easier debugging.
  826. // However please note that sometimes it is a true error. Your program
  827. // will still run correctly, but the debugger will not stop on it if you
  828. // list it in the ignore list. But for most times its fine to put it in
  829. // the ignore list, it only affects your debugging.
  830. raise EIdNotASocket.CreateError(AErr, WSTranslateSocketErrorMsg(AErr));
  831. end;
  832. // TODO: move this to IdStackVCLPosix...
  833. {$IFDEF USE_VCL_POSIX}
  834. {$IFDEF ANDROID}
  835. if (AErr = 9{EBADF}) or (AErr = 12{EBADR?}) or (AErr = 13{EACCES}) then begin
  836. if not HasAndroidPermission('android.permission.INTERNET') then begin {Do not Localize}
  837. raise EIdInternetPermissionNeeded.CreateError(AErr, WSTranslateSocketErrorMsg(AErr));
  838. end;
  839. end;
  840. {$ENDIF}
  841. {$ENDIF}
  842. (*
  843. It is normal to receive a 10038 exception (10038, NOT others!) here when
  844. *shutting down* (NOT at other times!) servers (NOT clients!).
  845. If you receive a 10038 exception here please see the FAQ at:
  846. http://www.IndyProject.org/
  847. If you insist upon requesting help via our email boxes on the 10038 error
  848. that is already answered in the FAQ and you are simply too slothful to
  849. search for your answer and ask your question in the public forums you may be
  850. publicly flogged, tarred and feathered and your name may be added to every
  851. chain letter / EMail in existence today."
  852. Otherwise, if you DID read the FAQ and have further questions, please feel
  853. free to ask using one of the methods (Carefullly note that these methods do
  854. not list email) listed on the Tech Support link at:
  855. http://www.IndyProject.org/
  856. RRRRR EEEEEE AAAA DDDDD MM MM EEEEEE !! !! !!
  857. RR RR EE AA AA DD DD MMMM MMMM EE !! !! !!
  858. RRRRR EEEE AAAAAA DD DD MM MMM MM EEEE !! !! !!
  859. RR RR EE AA AA DD DD MM MM EE
  860. RR RR EEEEEE AA AA DDDDD MM MM EEEEEE .. .. ..
  861. *)
  862. raise EIdSocketError.CreateError(AErr, WSTranslateSocketErrorMsg(AErr));
  863. end;
  864. function TIdStack.WSTranslateSocketErrorMsg(const AErr: integer): string;
  865. begin
  866. Result := ''; {Do not Localize}
  867. case AErr of
  868. Id_WSAEINTR: Result := RSStackEINTR;
  869. Id_WSAEBADF: Result := RSStackEBADF;
  870. Id_WSAEACCES: Result := RSStackEACCES;
  871. Id_WSAEFAULT: Result := RSStackEFAULT;
  872. Id_WSAEINVAL: Result := RSStackEINVAL;
  873. Id_WSAEMFILE: Result := RSStackEMFILE;
  874. Id_WSAEWOULDBLOCK: Result := RSStackEWOULDBLOCK;
  875. Id_WSAEINPROGRESS: Result := RSStackEINPROGRESS;
  876. Id_WSAEALREADY: Result := RSStackEALREADY;
  877. Id_WSAENOTSOCK: Result := RSStackENOTSOCK;
  878. Id_WSAEDESTADDRREQ: Result := RSStackEDESTADDRREQ;
  879. Id_WSAEMSGSIZE: Result := RSStackEMSGSIZE;
  880. Id_WSAEPROTOTYPE: Result := RSStackEPROTOTYPE;
  881. Id_WSAENOPROTOOPT: Result := RSStackENOPROTOOPT;
  882. Id_WSAEPROTONOSUPPORT: Result := RSStackEPROTONOSUPPORT;
  883. {$IFNDEF BEOS}
  884. Id_WSAESOCKTNOSUPPORT: Result := RSStackESOCKTNOSUPPORT;
  885. {$ENDIF}
  886. Id_WSAEOPNOTSUPP: Result := RSStackEOPNOTSUPP;
  887. Id_WSAEPFNOSUPPORT: Result := RSStackEPFNOSUPPORT;
  888. Id_WSAEAFNOSUPPORT: Result := RSStackEAFNOSUPPORT;
  889. Id_WSAEADDRINUSE: Result := RSStackEADDRINUSE;
  890. Id_WSAEADDRNOTAVAIL: Result := RSStackEADDRNOTAVAIL;
  891. Id_WSAENETDOWN: Result := RSStackENETDOWN;
  892. Id_WSAENETUNREACH: Result := RSStackENETUNREACH;
  893. Id_WSAENETRESET: Result := RSStackENETRESET;
  894. Id_WSAECONNABORTED: Result := RSStackECONNABORTED;
  895. Id_WSAECONNRESET: Result := RSStackECONNRESET;
  896. Id_WSAENOBUFS: Result := RSStackENOBUFS;
  897. Id_WSAEISCONN: Result := RSStackEISCONN;
  898. Id_WSAENOTCONN: Result := RSStackENOTCONN;
  899. Id_WSAESHUTDOWN: Result := RSStackESHUTDOWN;
  900. {$IFNDEF BEOS}
  901. Id_WSAETOOMANYREFS: Result := RSStackETOOMANYREFS;
  902. {$ENDIF}
  903. Id_WSAETIMEDOUT: Result := RSStackETIMEDOUT;
  904. Id_WSAECONNREFUSED: Result := RSStackECONNREFUSED;
  905. Id_WSAELOOP: Result := RSStackELOOP;
  906. Id_WSAENAMETOOLONG: Result := RSStackENAMETOOLONG;
  907. Id_WSAEHOSTDOWN: Result := RSStackEHOSTDOWN;
  908. Id_WSAEHOSTUNREACH: Result := RSStackEHOSTUNREACH;
  909. Id_WSAENOTEMPTY: Result := RSStackENOTEMPTY;
  910. end;
  911. Result := IndyFormat(RSStackError, [AErr, Result]);
  912. end;
  913. function TIdStack.HostToNetwork(const AValue: TIdIPv6Address): TIdIPv6Address;
  914. var
  915. i : Integer;
  916. begin
  917. for i := 0 to 7 do begin
  918. Result[i] := HostToNetwork(AValue[i]);
  919. end;
  920. end;
  921. function TIdStack.NetworkToHost(const AValue: TIdIPv6Address): TIdIPv6Address;
  922. var
  923. i : Integer;
  924. begin
  925. for i := 0 to 7 do begin
  926. Result[i] := NetworkToHost(AValue[i]);
  927. end;
  928. end;
  929. function TIdStack.IsValidIPv4MulticastGroup(const Value: string): Boolean;
  930. var
  931. LIP: string;
  932. LVal: Integer;
  933. begin
  934. Result := False;
  935. if IsIP(Value) then
  936. begin
  937. LIP := Value;
  938. LVal := IndyStrToInt(Fetch(LIP, '.')); {Do not Localize}
  939. Result := (LVal >= IPv4MCastLo) and (LVal <= IPv4MCastHi);
  940. end;
  941. end;
  942. { From "rfc 2373"
  943. 2.7 Multicast Addresses
  944. An IPv6 multicast address is an identifier for a group of nodes. A
  945. node may belong to any number of multicast groups. Multicast
  946. addresses have the following format:
  947. #
  948. | 8 | 4 | 4 | 112 bits |
  949. +------ -+----+----+---------------------------------------------+
  950. |11111111|flgs|scop| group ID |
  951. +--------+----+----+---------------------------------------------+
  952. 11111111 at the start of the address identifies the address as
  953. being a multicast address.
  954. +-+-+-+-+
  955. flgs is a set of 4 flags: |0|0|0|T|
  956. +-+-+-+-+
  957. The high-order 3 flags are reserved, and must be initialized to
  958. 0.
  959. T = 0 indicates a permanently-assigned ("well-known") multicast
  960. address, assigned by the global internet numbering authority.
  961. T = 1 indicates a non-permanently-assigned ("transient")
  962. multicast address.
  963. scop is a 4-bit multicast scope value used to limit the scope of
  964. the multicast group. The values are:
  965. 0 reserved
  966. 1 node-local scope
  967. 2 link-local scope
  968. 3 (unassigned)
  969. 4 (unassigned)
  970. 5 site-local scope
  971. 6 (unassigned)
  972. 7 (unassigned)
  973. 8 organization-local scope
  974. 9 (unassigned)
  975. A (unassigned)
  976. B (unassigned)
  977. C (unassigned)
  978. D (unassigned)
  979. E global scope
  980. F reserved
  981. group ID identifies the multicast group, either permanent or
  982. transient, within the given scope.
  983. The "meaning" of a permanently-assigned multicast address is
  984. independent of the scope value. For example, if the "NTP servers
  985. group" is assigned a permanent multicast address with a group ID of
  986. 101 (hex), then:
  987. FF01:0:0:0:0:0:0:101 means all NTP servers on the same node as the
  988. sender.
  989. FF02:0:0:0:0:0:0:101 means all NTP servers on the same link as the
  990. sender.
  991. FF05:0:0:0:0:0:0:101 means all NTP servers at the same site as the
  992. sender.
  993. FF0E:0:0:0:0:0:0:101 means all NTP servers in the internet.
  994. Non-permanently-assigned multicast addresses are meaningful only
  995. within a given scope. For example, a group identified by the non-
  996. permanent, site-local multicast address FF15:0:0:0:0:0:0:101 at one
  997. site bears no relationship to a group using the same address at a
  998. different site, nor to a non-permanent group using the same group ID
  999. with different scope, nor to a permanent group with the same group
  1000. ID.
  1001. Multicast addresses must not be used as source addresses in IPv6
  1002. packets or appear in any routing header.
  1003. }
  1004. function TIdStack.IsValidIPv6MulticastGroup(const Value: string): Boolean;
  1005. var
  1006. LTmp : String;
  1007. begin
  1008. LTmp := IdGlobal.MakeCanonicalIPv6Address(Value);
  1009. if LTmp <> '' then
  1010. begin
  1011. Result := TextStartsWith(LTmp, 'FF');
  1012. end else begin
  1013. Result := False;
  1014. end;
  1015. end;
  1016. function TIdStack.CalcCheckSum(const AData: TIdBytes): UInt16;
  1017. var
  1018. i : Integer;
  1019. LSize : Integer;
  1020. LCRC : UInt32;
  1021. begin
  1022. LCRC := 0;
  1023. i := 0;
  1024. LSize := Length(AData);
  1025. while LSize > 1 do
  1026. begin
  1027. LCRC := LCRC + BytesToUInt16(AData, i);
  1028. Dec(LSize, 2);
  1029. Inc(i, 2);
  1030. end;
  1031. if LSize > 0 then begin
  1032. LCRC := LCRC + AData[i];
  1033. end;
  1034. LCRC := (LCRC shr 16) + (LCRC and $ffff); //(LCRC >> 16)
  1035. LCRC := LCRC + (LCRC shr 16);
  1036. Result := not UInt16(LCRC);
  1037. end;
  1038. {$UNDEF HAS_TCP_KEEPIDLE_OR_KEEPINTVL}
  1039. {$IFDEF HAS_TCP_KEEPIDLE}
  1040. {$DEFINE HAS_TCP_KEEPIDLE_OR_KEEPINTVL}
  1041. {$ENDIF}
  1042. {$IFDEF HAS_TCP_KEEPINTVL}
  1043. {$DEFINE HAS_TCP_KEEPIDLE_OR_KEEPINTVL}
  1044. {$ENDIF}
  1045. procedure TIdStack.SetKeepAliveValues(ASocket: TIdStackSocketHandle;
  1046. const AEnabled: Boolean; const ATimeMS, AInterval: Integer);
  1047. begin
  1048. SetSocketOption(ASocket, Id_SOL_SOCKET, Id_SO_KEEPALIVE, iif(AEnabled, 1, 0));
  1049. {$IFDEF HAS_TCP_KEEPIDLE_OR_KEEPINTVL}
  1050. if AEnabled then
  1051. begin
  1052. // TODO: support TCP_KEEPCNT
  1053. {$IFDEF HAS_TCP_KEEPIDLE}
  1054. SetSocketOption(ASocket, Id_SOL_TCP, Id_TCP_KEEPIDLE, ATimeMS div MSecsPerSec);
  1055. {$ENDIF}
  1056. {$IFDEF HAS_TCP_KEEPINTVL}
  1057. SetSocketOption(ASocket, Id_SOL_TCP, Id_TCP_KEEPINTVL, AInterval div MSecsPerSec);
  1058. {$ENDIF}
  1059. end;
  1060. {$ENDIF}
  1061. end;
  1062. initialization
  1063. //done this way so we can have a separate stack just for FPC under Unix systems
  1064. GStackClass :=
  1065. {$IFDEF DOTNET}
  1066. TIdStackDotNet
  1067. {$ELSE}
  1068. {$IFDEF WINDOWS}
  1069. TIdStackWindows
  1070. {$ELSE}
  1071. {$IFDEF USE_VCL_POSIX}
  1072. TIdStackVCLPosix
  1073. {$ELSE}
  1074. {$IFDEF UNIX}
  1075. {$IFDEF KYLIXCOMPAT}
  1076. TIdStackLibc
  1077. {$ELSE}
  1078. {$IFDEF USE_BASEUNIX}
  1079. TIdStackUnix
  1080. {$ENDIF}
  1081. {$ENDIF}
  1082. {$ENDIF}
  1083. {$ENDIF}
  1084. {$ENDIF}
  1085. {$ENDIF}
  1086. ;
  1087. GStackCriticalSection := TIdCriticalSection.Create;
  1088. {$IFNDEF DOTNET}
  1089. {$IFDEF REGISTER_EXPECTED_MEMORY_LEAK}
  1090. IndyRegisterExpectedMemoryLeak(GStackCriticalSection);
  1091. {$ENDIF}
  1092. {$ENDIF}
  1093. finalization
  1094. // Dont Free. If shutdown is from another Init section, it can cause GPF when stack
  1095. // tries to access it. App will kill it off anyways, so just let it leak
  1096. {$IFDEF FREE_ON_FINAL}
  1097. FreeAndNil(GStackCriticalSection);
  1098. {$ENDIF}
  1099. end.