Socket.cs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786
  1. // System.Net.Sockets.Socket.cs
  2. //
  3. // Authors:
  4. // Phillip Pearson ([email protected])
  5. // Dick Porter <[email protected]>
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Sridhar Kulkarni ([email protected])
  8. // Brian Nickel ([email protected])
  9. // Ludovic Henry ([email protected])
  10. //
  11. // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
  12. // http://www.myelin.co.nz
  13. // (c) 2004-2011 Novell, Inc. (http://www.novell.com)
  14. //
  15. //
  16. // Permission is hereby granted, free of charge, to any person obtaining
  17. // a copy of this software and associated documentation files (the
  18. // "Software"), to deal in the Software without restriction, including
  19. // without limitation the rights to use, copy, modify, merge, publish,
  20. // distribute, sublicense, and/or sell copies of the Software, and to
  21. // permit persons to whom the Software is furnished to do so, subject to
  22. // the following conditions:
  23. //
  24. // The above copyright notice and this permission notice shall be
  25. // included in all copies or substantial portions of the Software.
  26. //
  27. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  28. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  30. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  31. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  32. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  33. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  34. //
  35. using System;
  36. using System.Net;
  37. using System.Collections;
  38. using System.Collections.Generic;
  39. using System.Runtime.CompilerServices;
  40. using System.Runtime.InteropServices;
  41. using System.Threading;
  42. using System.Reflection;
  43. using System.IO;
  44. using System.Net.Configuration;
  45. using System.Text;
  46. using System.Timers;
  47. using System.Net.NetworkInformation;
  48. namespace System.Net.Sockets
  49. {
  50. public partial class Socket : IDisposable
  51. {
  52. const int SOCKET_CLOSED_CODE = 10004;
  53. const string TIMEOUT_EXCEPTION_MSG = "A connection attempt failed because the connected party did not properly respond" +
  54. "after a period of time, or established connection failed because connected host has failed to respond";
  55. /* true if we called Close_internal */
  56. bool is_closed;
  57. bool is_listening;
  58. bool useOverlappedIO;
  59. int linger_timeout;
  60. AddressFamily addressFamily;
  61. SocketType socketType;
  62. ProtocolType protocolType;
  63. /* the field "m_Handle" is looked up by name by the runtime */
  64. internal SafeSocketHandle m_Handle;
  65. /*
  66. * This EndPoint is used when creating new endpoints. Because
  67. * there are many types of EndPoints possible,
  68. * seed_endpoint.Create(addr) is used for creating new ones.
  69. * As such, this value is set on Bind, SentTo, ReceiveFrom,
  70. * Connect, etc.
  71. */
  72. internal EndPoint seed_endpoint = null;
  73. internal SemaphoreSlim ReadSem = new SemaphoreSlim (1, 1);
  74. internal SemaphoreSlim WriteSem = new SemaphoreSlim (1, 1);
  75. internal bool is_blocking = true;
  76. internal bool is_bound;
  77. /* When true, the socket was connected at the time of the last IO operation */
  78. internal bool is_connected;
  79. int m_IntCleanedUp;
  80. internal bool connect_in_progress;
  81. #region Constructors
  82. public Socket (SocketInformation socketInformation)
  83. {
  84. this.is_listening = (socketInformation.Options & SocketInformationOptions.Listening) != 0;
  85. this.is_connected = (socketInformation.Options & SocketInformationOptions.Connected) != 0;
  86. this.is_blocking = (socketInformation.Options & SocketInformationOptions.NonBlocking) == 0;
  87. this.useOverlappedIO = (socketInformation.Options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;
  88. var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);
  89. this.addressFamily = (AddressFamily) (int) result [0];
  90. this.socketType = (SocketType) (int) result [1];
  91. this.protocolType = (ProtocolType) (int) result [2];
  92. this.is_bound = (ProtocolType) (int) result [3] != 0;
  93. this.m_Handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);
  94. InitializeSockets ();
  95. SocketDefaults ();
  96. }
  97. /* private constructor used by Accept, which already has a socket handle to use */
  98. internal Socket(AddressFamily family, SocketType type, ProtocolType proto, SafeSocketHandle safe_handle)
  99. {
  100. this.addressFamily = family;
  101. this.socketType = type;
  102. this.protocolType = proto;
  103. this.m_Handle = safe_handle;
  104. this.is_connected = true;
  105. InitializeSockets ();
  106. }
  107. void SocketDefaults ()
  108. {
  109. try {
  110. /* Need to test IPv6 further */
  111. if (addressFamily == AddressFamily.InterNetwork
  112. // || addressFamily == AddressFamily.InterNetworkV6
  113. ) {
  114. /* This is the default, but it probably has nasty side
  115. * effects on Linux, as the socket option is kludged by
  116. * turning on or off PMTU discovery... */
  117. this.DontFragment = false;
  118. if (protocolType == ProtocolType.Tcp)
  119. this.NoDelay = false;
  120. } else if (addressFamily == AddressFamily.InterNetworkV6) {
  121. this.DualMode = true;
  122. }
  123. /* Microsoft sets these to 8192, but we are going to keep them
  124. * both to the OS defaults as these have a big performance impact.
  125. * on WebClient performance. */
  126. // this.ReceiveBufferSize = 8192;
  127. // this.SendBufferSize = 8192;
  128. } catch (SocketException) {
  129. }
  130. }
  131. /* Creates a new system socket, returning the handle */
  132. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  133. extern IntPtr Socket_internal (AddressFamily family, SocketType type, ProtocolType proto, out int error);
  134. #endregion
  135. #region Properties
  136. public int Available {
  137. get {
  138. ThrowIfDisposedAndClosed ();
  139. int ret, error;
  140. ret = Available_internal (m_Handle, out error);
  141. if (error != 0)
  142. throw new SocketException (error);
  143. return ret;
  144. }
  145. }
  146. static int Available_internal (SafeSocketHandle safeHandle, out int error)
  147. {
  148. bool release = false;
  149. try {
  150. safeHandle.DangerousAddRef (ref release);
  151. return Available_internal (safeHandle.DangerousGetHandle (), out error);
  152. } finally {
  153. if (release)
  154. safeHandle.DangerousRelease ();
  155. }
  156. }
  157. /* Returns the amount of data waiting to be read on socket */
  158. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  159. extern static int Available_internal (IntPtr socket, out int error);
  160. // FIXME: import from referencesource
  161. public bool EnableBroadcast {
  162. get {
  163. ThrowIfDisposedAndClosed ();
  164. if (protocolType != ProtocolType.Udp)
  165. throw new SocketException ((int) SocketError.ProtocolOption);
  166. return ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0;
  167. }
  168. set {
  169. ThrowIfDisposedAndClosed ();
  170. if (protocolType != ProtocolType.Udp)
  171. throw new SocketException ((int) SocketError.ProtocolOption);
  172. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
  173. }
  174. }
  175. public bool IsBound {
  176. get {
  177. return is_bound;
  178. }
  179. }
  180. // FIXME: import from referencesource
  181. public bool MulticastLoopback {
  182. get {
  183. ThrowIfDisposedAndClosed ();
  184. /* Even though this option can be set for TCP sockets on Linux, throw
  185. * this exception anyway to be compatible (the MSDN docs say
  186. * "Setting this property on a Transmission Control Protocol (TCP)
  187. * socket will have no effect." but the MS runtime throws the
  188. * exception...) */
  189. if (protocolType == ProtocolType.Tcp)
  190. throw new SocketException ((int)SocketError.ProtocolOption);
  191. switch (addressFamily) {
  192. case AddressFamily.InterNetwork:
  193. return ((int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)) != 0;
  194. case AddressFamily.InterNetworkV6:
  195. return ((int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)) != 0;
  196. default:
  197. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  198. }
  199. }
  200. set {
  201. ThrowIfDisposedAndClosed ();
  202. /* Even though this option can be set for TCP sockets on Linux, throw
  203. * this exception anyway to be compatible (the MSDN docs say
  204. * "Setting this property on a Transmission Control Protocol (TCP)
  205. * socket will have no effect." but the MS runtime throws the
  206. * exception...) */
  207. if (protocolType == ProtocolType.Tcp)
  208. throw new SocketException ((int)SocketError.ProtocolOption);
  209. switch (addressFamily) {
  210. case AddressFamily.InterNetwork:
  211. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
  212. break;
  213. case AddressFamily.InterNetworkV6:
  214. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value ? 1 : 0);
  215. break;
  216. default:
  217. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  218. }
  219. }
  220. }
  221. // Wish: support non-IP endpoints.
  222. public EndPoint LocalEndPoint {
  223. get {
  224. ThrowIfDisposedAndClosed ();
  225. /* If the seed EndPoint is null, Connect, Bind, etc has not yet
  226. * been called. MS returns null in this case. */
  227. if (seed_endpoint == null)
  228. return null;
  229. int error;
  230. SocketAddress sa = LocalEndPoint_internal (m_Handle, (int) addressFamily, out error);
  231. if (error != 0)
  232. throw new SocketException (error);
  233. return seed_endpoint.Create (sa);
  234. }
  235. }
  236. static SocketAddress LocalEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
  237. {
  238. bool release = false;
  239. try {
  240. safeHandle.DangerousAddRef (ref release);
  241. return LocalEndPoint_internal (safeHandle.DangerousGetHandle (), family, out error);
  242. } finally {
  243. if (release)
  244. safeHandle.DangerousRelease ();
  245. }
  246. }
  247. /* Returns the local endpoint details in addr and port */
  248. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  249. extern static SocketAddress LocalEndPoint_internal (IntPtr socket, int family, out int error);
  250. public bool Blocking {
  251. get { return is_blocking; }
  252. set {
  253. ThrowIfDisposedAndClosed ();
  254. int error;
  255. Blocking_internal (m_Handle, value, out error);
  256. if (error != 0)
  257. throw new SocketException (error);
  258. is_blocking = value;
  259. }
  260. }
  261. static void Blocking_internal (SafeSocketHandle safeHandle, bool block, out int error)
  262. {
  263. bool release = false;
  264. try {
  265. safeHandle.DangerousAddRef (ref release);
  266. Blocking_internal (safeHandle.DangerousGetHandle (), block, out error);
  267. } finally {
  268. if (release)
  269. safeHandle.DangerousRelease ();
  270. }
  271. }
  272. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  273. internal extern static void Blocking_internal(IntPtr socket, bool block, out int error);
  274. public bool Connected {
  275. get { return is_connected; }
  276. internal set { is_connected = value; }
  277. }
  278. // FIXME: import from referencesource
  279. public bool NoDelay {
  280. get {
  281. ThrowIfDisposedAndClosed ();
  282. ThrowIfUdp ();
  283. return ((int) GetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay)) != 0;
  284. }
  285. set {
  286. ThrowIfDisposedAndClosed ();
  287. ThrowIfUdp ();
  288. SetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
  289. }
  290. }
  291. public EndPoint RemoteEndPoint {
  292. get {
  293. ThrowIfDisposedAndClosed ();
  294. /* If the seed EndPoint is null, Connect, Bind, etc has
  295. * not yet been called. MS returns null in this case. */
  296. if (!is_connected || seed_endpoint == null)
  297. return null;
  298. int error;
  299. SocketAddress sa = RemoteEndPoint_internal (m_Handle, (int) addressFamily, out error);
  300. if (error != 0)
  301. throw new SocketException (error);
  302. return seed_endpoint.Create (sa);
  303. }
  304. }
  305. static SocketAddress RemoteEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
  306. {
  307. bool release = false;
  308. try {
  309. safeHandle.DangerousAddRef (ref release);
  310. return RemoteEndPoint_internal (safeHandle.DangerousGetHandle (), family, out error);
  311. } finally {
  312. if (release)
  313. safeHandle.DangerousRelease ();
  314. }
  315. }
  316. /* Returns the remote endpoint details in addr and port */
  317. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  318. extern static SocketAddress RemoteEndPoint_internal (IntPtr socket, int family, out int error);
  319. #endregion
  320. #region Select
  321. public static void Select (IList checkRead, IList checkWrite, IList checkError, int microSeconds)
  322. {
  323. var list = new List<Socket> ();
  324. AddSockets (list, checkRead, "checkRead");
  325. AddSockets (list, checkWrite, "checkWrite");
  326. AddSockets (list, checkError, "checkError");
  327. if (list.Count == 3)
  328. throw new ArgumentNullException ("checkRead, checkWrite, checkError", "All the lists are null or empty.");
  329. /* The 'sockets' array contains:
  330. * - READ socket 0-n, null,
  331. * - WRITE socket 0-n, null,
  332. * - ERROR socket 0-n, null */
  333. Socket [] sockets = list.ToArray ();
  334. int error;
  335. Select_internal (ref sockets, microSeconds, out error);
  336. if (error != 0)
  337. throw new SocketException (error);
  338. if (sockets == null) {
  339. if (checkRead != null)
  340. checkRead.Clear ();
  341. if (checkWrite != null)
  342. checkWrite.Clear ();
  343. if (checkError != null)
  344. checkError.Clear ();
  345. return;
  346. }
  347. int mode = 0;
  348. int count = sockets.Length;
  349. IList currentList = checkRead;
  350. int currentIdx = 0;
  351. for (int i = 0; i < count; i++) {
  352. Socket sock = sockets [i];
  353. if (sock == null) { // separator
  354. if (currentList != null) {
  355. // Remove non-signaled sockets after the current one
  356. int to_remove = currentList.Count - currentIdx;
  357. for (int k = 0; k < to_remove; k++)
  358. currentList.RemoveAt (currentIdx);
  359. }
  360. currentList = (mode == 0) ? checkWrite : checkError;
  361. currentIdx = 0;
  362. mode++;
  363. continue;
  364. }
  365. if (mode == 1 && currentList == checkWrite && !sock.is_connected) {
  366. if ((int) sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0)
  367. sock.is_connected = true;
  368. }
  369. /* Remove non-signaled sockets before the current one */
  370. while (((Socket) currentList [currentIdx]) != sock)
  371. currentList.RemoveAt (currentIdx);
  372. currentIdx++;
  373. }
  374. }
  375. static void AddSockets (List<Socket> sockets, IList list, string name)
  376. {
  377. if (list != null) {
  378. foreach (Socket sock in list) {
  379. if (sock == null) // MS throws a NullRef
  380. throw new ArgumentNullException ("name", "Contains a null element");
  381. sockets.Add (sock);
  382. }
  383. }
  384. sockets.Add (null);
  385. }
  386. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  387. extern static void Select_internal (ref Socket [] sockets, int microSeconds, out int error);
  388. #endregion
  389. #region Poll
  390. public bool Poll (int microSeconds, SelectMode mode)
  391. {
  392. ThrowIfDisposedAndClosed ();
  393. if (mode != SelectMode.SelectRead && mode != SelectMode.SelectWrite && mode != SelectMode.SelectError)
  394. throw new NotSupportedException ("'mode' parameter is not valid.");
  395. int error;
  396. bool result = Poll_internal (m_Handle, mode, microSeconds, out error);
  397. if (error != 0)
  398. throw new SocketException (error);
  399. if (mode == SelectMode.SelectWrite && result && !is_connected) {
  400. /* Update the is_connected state; for non-blocking Connect()
  401. * this is when we can find out that the connect succeeded. */
  402. if ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0)
  403. is_connected = true;
  404. }
  405. return result;
  406. }
  407. static bool Poll_internal (SafeSocketHandle safeHandle, SelectMode mode, int timeout, out int error)
  408. {
  409. bool release = false;
  410. try {
  411. safeHandle.DangerousAddRef (ref release);
  412. return Poll_internal (safeHandle.DangerousGetHandle (), mode, timeout, out error);
  413. } finally {
  414. if (release)
  415. safeHandle.DangerousRelease ();
  416. }
  417. }
  418. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  419. extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
  420. #endregion
  421. #region Accept
  422. public Socket Accept()
  423. {
  424. ThrowIfDisposedAndClosed ();
  425. int error = 0;
  426. SafeSocketHandle safe_handle = Accept_internal (this.m_Handle, out error, is_blocking);
  427. if (error != 0) {
  428. if (is_closed)
  429. error = SOCKET_CLOSED_CODE;
  430. throw new SocketException(error);
  431. }
  432. Socket accepted = new Socket (this.AddressFamily, this.SocketType, this.ProtocolType, safe_handle) {
  433. seed_endpoint = this.seed_endpoint,
  434. Blocking = this.Blocking,
  435. };
  436. return accepted;
  437. }
  438. internal void Accept (Socket acceptSocket)
  439. {
  440. ThrowIfDisposedAndClosed ();
  441. int error = 0;
  442. SafeSocketHandle safe_handle = Accept_internal (this.m_Handle, out error, is_blocking);
  443. if (error != 0) {
  444. if (is_closed)
  445. error = SOCKET_CLOSED_CODE;
  446. throw new SocketException (error);
  447. }
  448. acceptSocket.addressFamily = this.AddressFamily;
  449. acceptSocket.socketType = this.SocketType;
  450. acceptSocket.protocolType = this.ProtocolType;
  451. acceptSocket.m_Handle = safe_handle;
  452. acceptSocket.is_connected = true;
  453. acceptSocket.seed_endpoint = this.seed_endpoint;
  454. acceptSocket.Blocking = this.Blocking;
  455. // FIXME: figure out what if anything else needs to be reset
  456. }
  457. public bool AcceptAsync (SocketAsyncEventArgs e)
  458. {
  459. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  460. ThrowIfDisposedAndClosed ();
  461. if (!is_bound)
  462. throw new InvalidOperationException ("You must call the Bind method before performing this operation.");
  463. if (!is_listening)
  464. throw new InvalidOperationException ("You must call the Listen method before performing this operation.");
  465. if (e.BufferList != null)
  466. throw new ArgumentException ("Multiple buffers cannot be used with this method.");
  467. if (e.Count < 0)
  468. throw new ArgumentOutOfRangeException ("e.Count");
  469. Socket acceptSocket = e.AcceptSocket;
  470. if (acceptSocket != null) {
  471. if (acceptSocket.is_bound || acceptSocket.is_connected)
  472. throw new InvalidOperationException ("AcceptSocket: The socket must not be bound or connected.");
  473. }
  474. InitSocketAsyncEventArgs (e, AcceptAsyncCallback, e, SocketOperation.Accept);
  475. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, e.socket_async_result));
  476. return true;
  477. }
  478. static AsyncCallback AcceptAsyncCallback = new AsyncCallback (ares => {
  479. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  480. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  481. throw new InvalidOperationException ("No operation in progress");
  482. try {
  483. e.AcceptSocket = e.current_socket.EndAccept (ares);
  484. } catch (SocketException ex) {
  485. e.SocketError = ex.SocketErrorCode;
  486. } catch (ObjectDisposedException) {
  487. e.SocketError = SocketError.OperationAborted;
  488. } finally {
  489. if (e.AcceptSocket == null)
  490. e.AcceptSocket = new Socket (e.current_socket.AddressFamily, e.current_socket.SocketType, e.current_socket.ProtocolType, null);
  491. e.Complete ();
  492. }
  493. });
  494. public IAsyncResult BeginAccept(AsyncCallback callback, object state)
  495. {
  496. ThrowIfDisposedAndClosed ();
  497. if (!is_bound || !is_listening)
  498. throw new InvalidOperationException ();
  499. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Accept);
  500. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, sockares));
  501. return sockares;
  502. }
  503. static IOAsyncCallback BeginAcceptCallback = new IOAsyncCallback (ares => {
  504. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  505. Socket acc_socket = null;
  506. try {
  507. if (sockares.AcceptSocket == null) {
  508. acc_socket = sockares.socket.Accept ();
  509. } else {
  510. acc_socket = sockares.AcceptSocket;
  511. sockares.socket.Accept (acc_socket);
  512. }
  513. } catch (Exception e) {
  514. sockares.Complete (e);
  515. return;
  516. }
  517. sockares.Complete (acc_socket);
  518. });
  519. public IAsyncResult BeginAccept (Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
  520. {
  521. ThrowIfDisposedAndClosed ();
  522. if (receiveSize < 0)
  523. throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
  524. if (acceptSocket != null) {
  525. ThrowIfDisposedAndClosed (acceptSocket);
  526. if (acceptSocket.IsBound)
  527. throw new InvalidOperationException ();
  528. /* For some reason the MS runtime
  529. * barfs if the new socket is not TCP,
  530. * even though it's just about to blow
  531. * away all those parameters
  532. */
  533. if (acceptSocket.ProtocolType != ProtocolType.Tcp)
  534. throw new SocketException ((int)SocketError.InvalidArgument);
  535. }
  536. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.AcceptReceive) {
  537. Buffer = new byte [receiveSize],
  538. Offset = 0,
  539. Size = receiveSize,
  540. SockFlags = SocketFlags.None,
  541. AcceptSocket = acceptSocket,
  542. };
  543. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));
  544. return sockares;
  545. }
  546. static IOAsyncCallback BeginAcceptReceiveCallback = new IOAsyncCallback (ares => {
  547. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  548. Socket acc_socket = null;
  549. try {
  550. if (sockares.AcceptSocket == null) {
  551. acc_socket = sockares.socket.Accept ();
  552. } else {
  553. acc_socket = sockares.AcceptSocket;
  554. sockares.socket.Accept (acc_socket);
  555. }
  556. } catch (Exception e) {
  557. sockares.Complete (e);
  558. return;
  559. }
  560. /* It seems the MS runtime special-cases 0-length requested receive data. See bug 464201. */
  561. int total = 0;
  562. if (sockares.Size > 0) {
  563. try {
  564. SocketError error;
  565. total = acc_socket.Receive (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out error);
  566. if (error != 0) {
  567. sockares.Complete (new SocketException ((int) error));
  568. return;
  569. }
  570. } catch (Exception e) {
  571. sockares.Complete (e);
  572. return;
  573. }
  574. }
  575. sockares.Complete (acc_socket, total);
  576. });
  577. public Socket EndAccept (IAsyncResult result)
  578. {
  579. int bytes;
  580. byte[] buffer;
  581. return EndAccept (out buffer, out bytes, result);
  582. }
  583. public Socket EndAccept (out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
  584. {
  585. ThrowIfDisposedAndClosed ();
  586. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndAccept", "asyncResult");
  587. if (!sockares.IsCompleted)
  588. sockares.AsyncWaitHandle.WaitOne ();
  589. sockares.CheckIfThrowDelayedException ();
  590. buffer = sockares.Buffer;
  591. bytesTransferred = sockares.Total;
  592. return sockares.AcceptedSocket;
  593. }
  594. static SafeSocketHandle Accept_internal (SafeSocketHandle safeHandle, out int error, bool blocking)
  595. {
  596. try {
  597. safeHandle.RegisterForBlockingSyscall ();
  598. var ret = Accept_internal (safeHandle.DangerousGetHandle (), out error, blocking);
  599. return new SafeSocketHandle (ret, true);
  600. } finally {
  601. safeHandle.UnRegisterForBlockingSyscall ();
  602. }
  603. }
  604. /* Creates a new system socket, returning the handle */
  605. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  606. extern static IntPtr Accept_internal (IntPtr sock, out int error, bool blocking);
  607. #endregion
  608. #region Bind
  609. public void Bind (EndPoint localEP)
  610. {
  611. #if FEATURE_NO_BSD_SOCKETS
  612. throw new PlatformNotSupportedException ("System.Net.Sockets.Socket:Bind is not supported on this platform.");
  613. #else
  614. ThrowIfDisposedAndClosed ();
  615. if (localEP == null)
  616. throw new ArgumentNullException("localEP");
  617. var ipEndPoint = localEP as IPEndPoint;
  618. if (ipEndPoint != null) {
  619. localEP = RemapIPEndPoint (ipEndPoint);
  620. }
  621. int error;
  622. Bind_internal (m_Handle, localEP.Serialize(), out error);
  623. if (error != 0)
  624. throw new SocketException (error);
  625. if (error == 0)
  626. is_bound = true;
  627. seed_endpoint = localEP;
  628. #endif // FEATURE_NO_BSD_SOCKETS
  629. }
  630. private static void Bind_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
  631. {
  632. bool release = false;
  633. try {
  634. safeHandle.DangerousAddRef (ref release);
  635. Bind_internal (safeHandle.DangerousGetHandle (), sa, out error);
  636. } finally {
  637. if (release)
  638. safeHandle.DangerousRelease ();
  639. }
  640. }
  641. // Creates a new system socket, returning the handle
  642. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  643. private extern static void Bind_internal(IntPtr sock, SocketAddress sa, out int error);
  644. #endregion
  645. #region Listen
  646. public void Listen (int backlog)
  647. {
  648. ThrowIfDisposedAndClosed ();
  649. if (!is_bound)
  650. throw new SocketException ((int) SocketError.InvalidArgument);
  651. int error;
  652. Listen_internal(m_Handle, backlog, out error);
  653. if (error != 0)
  654. throw new SocketException (error);
  655. is_listening = true;
  656. }
  657. static void Listen_internal (SafeSocketHandle safeHandle, int backlog, out int error)
  658. {
  659. bool release = false;
  660. try {
  661. safeHandle.DangerousAddRef (ref release);
  662. Listen_internal (safeHandle.DangerousGetHandle (), backlog, out error);
  663. } finally {
  664. if (release)
  665. safeHandle.DangerousRelease ();
  666. }
  667. }
  668. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  669. extern static void Listen_internal (IntPtr sock, int backlog, out int error);
  670. #endregion
  671. #region Connect
  672. public void Connect (IPAddress address, int port)
  673. {
  674. Connect (new IPEndPoint (address, port));
  675. }
  676. public void Connect (string host, int port)
  677. {
  678. Connect (Dns.GetHostAddresses (host), port);
  679. }
  680. public void Connect (EndPoint remoteEP)
  681. {
  682. ThrowIfDisposedAndClosed ();
  683. if (remoteEP == null)
  684. throw new ArgumentNullException ("remoteEP");
  685. IPEndPoint ep = remoteEP as IPEndPoint;
  686. /* Dgram uses Any to 'disconnect' */
  687. if (ep != null && socketType != SocketType.Dgram) {
  688. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
  689. throw new SocketException ((int) SocketError.AddressNotAvailable);
  690. }
  691. if (is_listening)
  692. throw new InvalidOperationException ();
  693. if (ep != null) {
  694. remoteEP = RemapIPEndPoint (ep);
  695. }
  696. SocketAddress serial = remoteEP.Serialize ();
  697. int error = 0;
  698. Connect_internal (m_Handle, serial, out error, is_blocking);
  699. if (error == 0 || error == 10035)
  700. seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
  701. if (error != 0) {
  702. if (is_closed)
  703. error = SOCKET_CLOSED_CODE;
  704. throw new SocketException (error);
  705. }
  706. is_connected = !(socketType == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
  707. is_bound = true;
  708. }
  709. public bool ConnectAsync (SocketAsyncEventArgs e)
  710. {
  711. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  712. ThrowIfDisposedAndClosed ();
  713. if (is_listening)
  714. throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
  715. if (e.RemoteEndPoint == null)
  716. throw new ArgumentNullException ("remoteEP");
  717. InitSocketAsyncEventArgs (e, null, e, SocketOperation.Connect);
  718. try {
  719. IPAddress [] addresses;
  720. SocketAsyncResult ares;
  721. if (!GetCheckedIPs (e, out addresses)) {
  722. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  723. ares = (SocketAsyncResult) BeginConnect (e.RemoteEndPoint, ConnectAsyncCallback, e);
  724. } else {
  725. DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
  726. e.socket_async_result.Addresses = addresses;
  727. e.socket_async_result.Port = dep.Port;
  728. ares = (SocketAsyncResult) BeginConnect (addresses, dep.Port, ConnectAsyncCallback, e);
  729. }
  730. if (ares.IsCompleted && ares.CompletedSynchronously) {
  731. ares.CheckIfThrowDelayedException ();
  732. return false;
  733. }
  734. } catch (Exception exc) {
  735. e.socket_async_result.Complete (exc, true);
  736. return false;
  737. }
  738. return true;
  739. }
  740. public static void CancelConnectAsync (SocketAsyncEventArgs e)
  741. {
  742. if (e == null)
  743. throw new ArgumentNullException("e");
  744. if (e.in_progress != 0 && e.LastOperation == SocketAsyncOperation.Connect)
  745. e.current_socket.Close();
  746. }
  747. static AsyncCallback ConnectAsyncCallback = new AsyncCallback (ares => {
  748. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  749. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  750. throw new InvalidOperationException ("No operation in progress");
  751. try {
  752. e.current_socket.EndConnect (ares);
  753. } catch (SocketException se) {
  754. e.SocketError = se.SocketErrorCode;
  755. } catch (ObjectDisposedException) {
  756. e.SocketError = SocketError.OperationAborted;
  757. } finally {
  758. e.Complete ();
  759. }
  760. });
  761. public IAsyncResult BeginConnect (string host, int port, AsyncCallback callback, object state)
  762. {
  763. ThrowIfDisposedAndClosed ();
  764. if (host == null)
  765. throw new ArgumentNullException ("host");
  766. if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
  767. throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
  768. if (port <= 0 || port > 65535)
  769. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  770. if (is_listening)
  771. throw new InvalidOperationException ();
  772. return BeginConnect (Dns.GetHostAddresses (host), port, callback, state);
  773. }
  774. public IAsyncResult BeginConnect (EndPoint end_point, AsyncCallback callback, object state)
  775. {
  776. ThrowIfDisposedAndClosed ();
  777. if (end_point == null)
  778. throw new ArgumentNullException ("end_point");
  779. if (is_listening)
  780. throw new InvalidOperationException ();
  781. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
  782. EndPoint = end_point,
  783. };
  784. // Bug #75154: Connect() should not succeed for .Any addresses.
  785. if (end_point is IPEndPoint) {
  786. IPEndPoint ep = (IPEndPoint) end_point;
  787. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  788. sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
  789. return sockares;
  790. }
  791. end_point = RemapIPEndPoint (ep);
  792. }
  793. int error = 0;
  794. if (connect_in_progress) {
  795. // This could happen when multiple IPs are used
  796. // Calling connect() again will reset the connection attempt and cause
  797. // an error. Better to just close the socket and move on.
  798. connect_in_progress = false;
  799. m_Handle.Dispose ();
  800. m_Handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
  801. if (error != 0)
  802. throw new SocketException (error);
  803. }
  804. bool blk = is_blocking;
  805. if (blk)
  806. Blocking = false;
  807. Connect_internal (m_Handle, end_point.Serialize (), out error, false);
  808. if (blk)
  809. Blocking = true;
  810. if (error == 0) {
  811. // succeeded synch
  812. is_connected = true;
  813. is_bound = true;
  814. sockares.Complete (true);
  815. return sockares;
  816. }
  817. if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
  818. // error synch
  819. is_connected = false;
  820. is_bound = false;
  821. sockares.Complete (new SocketException (error), true);
  822. return sockares;
  823. }
  824. // continue asynch
  825. is_connected = false;
  826. is_bound = false;
  827. connect_in_progress = true;
  828. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));
  829. return sockares;
  830. }
  831. public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
  832. {
  833. ThrowIfDisposedAndClosed ();
  834. if (addresses == null)
  835. throw new ArgumentNullException ("addresses");
  836. if (addresses.Length == 0)
  837. throw new ArgumentException ("Empty addresses list");
  838. if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
  839. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  840. if (port <= 0 || port > 65535)
  841. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  842. if (is_listening)
  843. throw new InvalidOperationException ();
  844. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
  845. Addresses = addresses,
  846. Port = port,
  847. };
  848. is_connected = false;
  849. return BeginMConnect (sockares);
  850. }
  851. internal IAsyncResult BeginMConnect (SocketAsyncResult sockares)
  852. {
  853. SocketAsyncResult ares = null;
  854. Exception exc = null;
  855. AsyncCallback callback;
  856. for (int i = sockares.CurrentAddress; i < sockares.Addresses.Length; i++) {
  857. try {
  858. sockares.CurrentAddress++;
  859. ares = (SocketAsyncResult) BeginConnect (new IPEndPoint (sockares.Addresses [i], sockares.Port), null, sockares);
  860. if (ares.IsCompleted && ares.CompletedSynchronously) {
  861. ares.CheckIfThrowDelayedException ();
  862. callback = ares.AsyncCallback;
  863. if (callback != null)
  864. ThreadPool.UnsafeQueueUserWorkItem (_ => callback (ares), null);
  865. }
  866. break;
  867. } catch (Exception e) {
  868. exc = e;
  869. ares = null;
  870. }
  871. }
  872. if (ares == null)
  873. throw exc;
  874. return sockares;
  875. }
  876. static IOAsyncCallback BeginConnectCallback = new IOAsyncCallback (ares => {
  877. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  878. if (sockares.EndPoint == null) {
  879. sockares.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
  880. return;
  881. }
  882. SocketAsyncResult mconnect = sockares.AsyncState as SocketAsyncResult;
  883. bool is_mconnect = mconnect != null && mconnect.Addresses != null;
  884. try {
  885. EndPoint ep = sockares.EndPoint;
  886. int error_code = (int) sockares.socket.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  887. if (error_code == 0) {
  888. if (is_mconnect)
  889. sockares = mconnect;
  890. sockares.socket.seed_endpoint = ep;
  891. sockares.socket.is_connected = true;
  892. sockares.socket.is_bound = true;
  893. sockares.socket.connect_in_progress = false;
  894. sockares.error = 0;
  895. sockares.Complete ();
  896. return;
  897. }
  898. if (!is_mconnect) {
  899. sockares.socket.connect_in_progress = false;
  900. sockares.Complete (new SocketException (error_code));
  901. return;
  902. }
  903. if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
  904. mconnect.Complete (new SocketException (error_code));
  905. return;
  906. }
  907. mconnect.socket.BeginMConnect (mconnect);
  908. } catch (Exception e) {
  909. sockares.socket.connect_in_progress = false;
  910. if (is_mconnect)
  911. sockares = mconnect;
  912. sockares.Complete (e);
  913. return;
  914. }
  915. });
  916. public void EndConnect (IAsyncResult result)
  917. {
  918. ThrowIfDisposedAndClosed ();
  919. SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndConnect", "result");
  920. if (!sockares.IsCompleted)
  921. sockares.AsyncWaitHandle.WaitOne();
  922. sockares.CheckIfThrowDelayedException();
  923. }
  924. static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error, bool blocking)
  925. {
  926. try {
  927. safeHandle.RegisterForBlockingSyscall ();
  928. Connect_internal (safeHandle.DangerousGetHandle (), sa, out error, blocking);
  929. } finally {
  930. safeHandle.UnRegisterForBlockingSyscall ();
  931. }
  932. }
  933. /* Connects to the remote address */
  934. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  935. extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error, bool blocking);
  936. /* Returns :
  937. * - false when it is ok to use RemoteEndPoint
  938. * - true when addresses must be used (and addresses could be null/empty) */
  939. bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
  940. {
  941. addresses = null;
  942. // Connect to the first address that match the host name, like:
  943. // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
  944. // while skipping entries that do not match the address family
  945. DnsEndPoint dep = e.RemoteEndPoint as DnsEndPoint;
  946. if (dep != null) {
  947. addresses = Dns.GetHostAddresses (dep.Host);
  948. return true;
  949. } else {
  950. e.ConnectByNameError = null;
  951. return false;
  952. }
  953. }
  954. #endregion
  955. #region Disconnect
  956. /* According to the docs, the MS runtime will throw PlatformNotSupportedException
  957. * if the platform is newer than w2k. We should be able to cope... */
  958. public void Disconnect (bool reuseSocket)
  959. {
  960. ThrowIfDisposedAndClosed ();
  961. int error = 0;
  962. Disconnect_internal (m_Handle, reuseSocket, out error);
  963. if (error != 0) {
  964. if (error == 50) {
  965. /* ERROR_NOT_SUPPORTED */
  966. throw new PlatformNotSupportedException ();
  967. } else {
  968. throw new SocketException (error);
  969. }
  970. }
  971. is_connected = false;
  972. if (reuseSocket) {
  973. /* Do managed housekeeping here... */
  974. }
  975. }
  976. public bool DisconnectAsync (SocketAsyncEventArgs e)
  977. {
  978. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  979. ThrowIfDisposedAndClosed ();
  980. InitSocketAsyncEventArgs (e, DisconnectAsyncCallback, e, SocketOperation.Disconnect);
  981. IOSelector.Add (e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, e.socket_async_result));
  982. return true;
  983. }
  984. static AsyncCallback DisconnectAsyncCallback = new AsyncCallback (ares => {
  985. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  986. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  987. throw new InvalidOperationException ("No operation in progress");
  988. try {
  989. e.current_socket.EndDisconnect (ares);
  990. } catch (SocketException ex) {
  991. e.SocketError = ex.SocketErrorCode;
  992. } catch (ObjectDisposedException) {
  993. e.SocketError = SocketError.OperationAborted;
  994. } finally {
  995. e.Complete ();
  996. }
  997. });
  998. public IAsyncResult BeginDisconnect (bool reuseSocket, AsyncCallback callback, object state)
  999. {
  1000. ThrowIfDisposedAndClosed ();
  1001. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Disconnect) {
  1002. ReuseSocket = reuseSocket,
  1003. };
  1004. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, sockares));
  1005. return sockares;
  1006. }
  1007. static IOAsyncCallback BeginDisconnectCallback = new IOAsyncCallback (ares => {
  1008. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1009. try {
  1010. sockares.socket.Disconnect (sockares.ReuseSocket);
  1011. } catch (Exception e) {
  1012. sockares.Complete (e);
  1013. return;
  1014. }
  1015. sockares.Complete ();
  1016. });
  1017. public void EndDisconnect (IAsyncResult asyncResult)
  1018. {
  1019. ThrowIfDisposedAndClosed ();
  1020. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndDisconnect", "asyncResult");
  1021. if (!sockares.IsCompleted)
  1022. sockares.AsyncWaitHandle.WaitOne ();
  1023. sockares.CheckIfThrowDelayedException ();
  1024. }
  1025. static void Disconnect_internal (SafeSocketHandle safeHandle, bool reuse, out int error)
  1026. {
  1027. bool release = false;
  1028. try {
  1029. safeHandle.DangerousAddRef (ref release);
  1030. Disconnect_internal (safeHandle.DangerousGetHandle (), reuse, out error);
  1031. } finally {
  1032. if (release)
  1033. safeHandle.DangerousRelease ();
  1034. }
  1035. }
  1036. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1037. extern static void Disconnect_internal (IntPtr sock, bool reuse, out int error);
  1038. #endregion
  1039. #region Receive
  1040. public int Receive (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
  1041. {
  1042. ThrowIfDisposedAndClosed ();
  1043. ThrowIfBufferNull (buffer);
  1044. ThrowIfBufferOutOfRange (buffer, offset, size);
  1045. int nativeError;
  1046. int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError, is_blocking);
  1047. errorCode = (SocketError) nativeError;
  1048. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
  1049. is_connected = false;
  1050. is_bound = false;
  1051. } else {
  1052. is_connected = true;
  1053. }
  1054. return ret;
  1055. }
  1056. [CLSCompliant (false)]
  1057. public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
  1058. {
  1059. ThrowIfDisposedAndClosed ();
  1060. if (buffers == null || buffers.Count == 0)
  1061. throw new ArgumentNullException ("buffers");
  1062. int numsegments = buffers.Count;
  1063. int nativeError;
  1064. int ret;
  1065. /* Only example I can find of sending a byte array reference directly into an internal
  1066. * call is in System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
  1067. * so taking a lead from that... */
  1068. WSABUF[] bufarray = new WSABUF[numsegments];
  1069. GCHandle[] gch = new GCHandle[numsegments];
  1070. for (int i = 0; i < numsegments; i++) {
  1071. ArraySegment<byte> segment = buffers[i];
  1072. if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
  1073. throw new ArgumentOutOfRangeException ("segment");
  1074. gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
  1075. bufarray[i].len = segment.Count;
  1076. bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
  1077. }
  1078. try {
  1079. ret = Receive_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
  1080. } finally {
  1081. for (int i = 0; i < numsegments; i++) {
  1082. if (gch[i].IsAllocated)
  1083. gch[i].Free ();
  1084. }
  1085. }
  1086. errorCode = (SocketError) nativeError;
  1087. return ret;
  1088. }
  1089. public bool ReceiveAsync (SocketAsyncEventArgs e)
  1090. {
  1091. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1092. ThrowIfDisposedAndClosed ();
  1093. // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
  1094. // thrown when e.Buffer and e.BufferList are null (works fine when one is
  1095. // set to a valid object)
  1096. if (e.Buffer == null && e.BufferList == null)
  1097. throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
  1098. if (e.Buffer == null) {
  1099. InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.ReceiveGeneric);
  1100. e.socket_async_result.Buffers = e.BufferList;
  1101. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
  1102. } else {
  1103. InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.Receive);
  1104. e.socket_async_result.Buffer = e.Buffer;
  1105. e.socket_async_result.Offset = e.Offset;
  1106. e.socket_async_result.Size = e.Count;
  1107. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
  1108. }
  1109. return true;
  1110. }
  1111. static AsyncCallback ReceiveAsyncCallback = new AsyncCallback (ares => {
  1112. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1113. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1114. throw new InvalidOperationException ("No operation in progress");
  1115. try {
  1116. e.BytesTransferred = e.current_socket.EndReceive (ares);
  1117. } catch (SocketException se){
  1118. e.SocketError = se.SocketErrorCode;
  1119. } catch (ObjectDisposedException) {
  1120. e.SocketError = SocketError.OperationAborted;
  1121. } finally {
  1122. e.Complete ();
  1123. }
  1124. });
  1125. public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1126. {
  1127. ThrowIfDisposedAndClosed ();
  1128. ThrowIfBufferNull (buffer);
  1129. ThrowIfBufferOutOfRange (buffer, offset, size);
  1130. /* As far as I can tell from the docs and from experimentation, a pointer to the
  1131. * SocketError parameter is not supposed to be saved for the async parts. And as we don't
  1132. * set any socket errors in the setup code, we just have to set it to Success. */
  1133. errorCode = SocketError.Success;
  1134. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Receive) {
  1135. Buffer = buffer,
  1136. Offset = offset,
  1137. Size = size,
  1138. SockFlags = socketFlags,
  1139. };
  1140. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));
  1141. return sockares;
  1142. }
  1143. static IOAsyncCallback BeginReceiveCallback = new IOAsyncCallback (ares => {
  1144. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1145. int total = 0;
  1146. try {
  1147. total = Receive_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, sockares.socket.is_blocking);
  1148. } catch (Exception e) {
  1149. sockares.Complete (e);
  1150. return;
  1151. }
  1152. sockares.Complete (total);
  1153. });
  1154. [CLSCompliant (false)]
  1155. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1156. {
  1157. ThrowIfDisposedAndClosed ();
  1158. if (buffers == null)
  1159. throw new ArgumentNullException ("buffers");
  1160. /* I assume the same SocketError semantics as above */
  1161. errorCode = SocketError.Success;
  1162. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveGeneric) {
  1163. Buffers = buffers,
  1164. SockFlags = socketFlags,
  1165. };
  1166. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));
  1167. return sockares;
  1168. }
  1169. static IOAsyncCallback BeginReceiveGenericCallback = new IOAsyncCallback (ares => {
  1170. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1171. int total = 0;
  1172. try {
  1173. total = sockares.socket.Receive (sockares.Buffers, sockares.SockFlags);
  1174. } catch (Exception e) {
  1175. sockares.Complete (e);
  1176. return;
  1177. }
  1178. sockares.Complete (total);
  1179. });
  1180. public int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
  1181. {
  1182. ThrowIfDisposedAndClosed ();
  1183. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceive", "asyncResult");
  1184. if (!sockares.IsCompleted)
  1185. sockares.AsyncWaitHandle.WaitOne ();
  1186. errorCode = sockares.ErrorCode;
  1187. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
  1188. is_connected = false;
  1189. // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
  1190. // kinds of exceptions that should be thrown.
  1191. if (errorCode == SocketError.Success)
  1192. sockares.CheckIfThrowDelayedException();
  1193. return sockares.Total;
  1194. }
  1195. static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
  1196. {
  1197. try {
  1198. safeHandle.RegisterForBlockingSyscall ();
  1199. return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
  1200. } finally {
  1201. safeHandle.UnRegisterForBlockingSyscall ();
  1202. }
  1203. }
  1204. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  1205. extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
  1206. static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking)
  1207. {
  1208. try {
  1209. safeHandle.RegisterForBlockingSyscall ();
  1210. return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error, blocking);
  1211. } finally {
  1212. safeHandle.UnRegisterForBlockingSyscall ();
  1213. }
  1214. }
  1215. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1216. extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking);
  1217. #endregion
  1218. #region ReceiveFrom
  1219. public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
  1220. {
  1221. ThrowIfDisposedAndClosed ();
  1222. ThrowIfBufferNull (buffer);
  1223. ThrowIfBufferOutOfRange (buffer, offset, size);
  1224. if (remoteEP == null)
  1225. throw new ArgumentNullException ("remoteEP");
  1226. SocketError errorCode;
  1227. int ret = ReceiveFrom (buffer, offset, size, socketFlags, ref remoteEP, out errorCode);
  1228. if (errorCode != SocketError.Success)
  1229. throw new SocketException (errorCode);
  1230. return ret;
  1231. }
  1232. internal int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode)
  1233. {
  1234. SocketAddress sockaddr = remoteEP.Serialize();
  1235. int nativeError;
  1236. int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking);
  1237. errorCode = (SocketError) nativeError;
  1238. if (errorCode != SocketError.Success) {
  1239. if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
  1240. is_connected = false;
  1241. } else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
  1242. errorCode = SocketError.TimedOut;
  1243. }
  1244. return 0;
  1245. }
  1246. is_connected = true;
  1247. is_bound = true;
  1248. /* If sockaddr is null then we're a connection oriented protocol and should ignore the
  1249. * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
  1250. if (sockaddr != null) {
  1251. /* Stupidly, EndPoint.Create() is an instance method */
  1252. remoteEP = remoteEP.Create (sockaddr);
  1253. }
  1254. seed_endpoint = remoteEP;
  1255. return cnt;
  1256. }
  1257. public bool ReceiveFromAsync (SocketAsyncEventArgs e)
  1258. {
  1259. ThrowIfDisposedAndClosed ();
  1260. // We do not support recv into multiple buffers yet
  1261. if (e.BufferList != null)
  1262. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  1263. if (e.RemoteEndPoint == null)
  1264. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  1265. InitSocketAsyncEventArgs (e, ReceiveFromAsyncCallback, e, SocketOperation.ReceiveFrom);
  1266. e.socket_async_result.Buffer = e.Buffer;
  1267. e.socket_async_result.Offset = e.Offset;
  1268. e.socket_async_result.Size = e.Count;
  1269. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  1270. e.socket_async_result.SockFlags = e.SocketFlags;
  1271. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));
  1272. return true;
  1273. }
  1274. static AsyncCallback ReceiveFromAsyncCallback = new AsyncCallback (ares => {
  1275. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1276. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1277. throw new InvalidOperationException ("No operation in progress");
  1278. try {
  1279. e.BytesTransferred = e.current_socket.EndReceiveFrom (ares, ref e.remote_ep);
  1280. } catch (SocketException ex) {
  1281. e.SocketError = ex.SocketErrorCode;
  1282. } catch (ObjectDisposedException) {
  1283. e.SocketError = SocketError.OperationAborted;
  1284. } finally {
  1285. e.Complete ();
  1286. }
  1287. });
  1288. public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, SocketFlags socket_flags, ref EndPoint remote_end, AsyncCallback callback, object state)
  1289. {
  1290. ThrowIfDisposedAndClosed ();
  1291. ThrowIfBufferNull (buffer);
  1292. ThrowIfBufferOutOfRange (buffer, offset, size);
  1293. if (remote_end == null)
  1294. throw new ArgumentNullException ("remote_end");
  1295. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveFrom) {
  1296. Buffer = buffer,
  1297. Offset = offset,
  1298. Size = size,
  1299. SockFlags = socket_flags,
  1300. EndPoint = remote_end,
  1301. };
  1302. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));
  1303. return sockares;
  1304. }
  1305. static IOAsyncCallback BeginReceiveFromCallback = new IOAsyncCallback (ares => {
  1306. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1307. int total = 0;
  1308. try {
  1309. SocketError errorCode;
  1310. total = sockares.socket.ReceiveFrom (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, out errorCode);
  1311. if (errorCode != SocketError.Success) {
  1312. sockares.Complete (new SocketException (errorCode));
  1313. return;
  1314. }
  1315. } catch (Exception e) {
  1316. sockares.Complete (e);
  1317. return;
  1318. }
  1319. sockares.Complete (total);
  1320. });
  1321. public int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
  1322. {
  1323. ThrowIfDisposedAndClosed ();
  1324. if (end_point == null)
  1325. throw new ArgumentNullException ("remote_end");
  1326. SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndReceiveFrom", "result");
  1327. if (!sockares.IsCompleted)
  1328. sockares.AsyncWaitHandle.WaitOne();
  1329. sockares.CheckIfThrowDelayedException();
  1330. end_point = sockares.EndPoint;
  1331. return sockares.Total;
  1332. }
  1333. static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking)
  1334. {
  1335. try {
  1336. safeHandle.RegisterForBlockingSyscall ();
  1337. return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error, blocking);
  1338. } finally {
  1339. safeHandle.UnRegisterForBlockingSyscall ();
  1340. }
  1341. }
  1342. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1343. extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking);
  1344. #endregion
  1345. #region ReceiveMessageFrom
  1346. [MonoTODO ("Not implemented")]
  1347. public int ReceiveMessageFrom (byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
  1348. {
  1349. ThrowIfDisposedAndClosed ();
  1350. ThrowIfBufferNull (buffer);
  1351. ThrowIfBufferOutOfRange (buffer, offset, size);
  1352. if (remoteEP == null)
  1353. throw new ArgumentNullException ("remoteEP");
  1354. // FIXME: figure out how we get hold of the IPPacketInformation
  1355. throw new NotImplementedException ();
  1356. }
  1357. [MonoTODO ("Not implemented")]
  1358. public bool ReceiveMessageFromAsync (SocketAsyncEventArgs e)
  1359. {
  1360. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1361. ThrowIfDisposedAndClosed ();
  1362. throw new NotImplementedException ();
  1363. }
  1364. [MonoTODO]
  1365. public IAsyncResult BeginReceiveMessageFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
  1366. {
  1367. ThrowIfDisposedAndClosed ();
  1368. ThrowIfBufferNull (buffer);
  1369. ThrowIfBufferOutOfRange (buffer, offset, size);
  1370. if (remoteEP == null)
  1371. throw new ArgumentNullException ("remoteEP");
  1372. throw new NotImplementedException ();
  1373. }
  1374. [MonoTODO]
  1375. public int EndReceiveMessageFrom (IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
  1376. {
  1377. ThrowIfDisposedAndClosed ();
  1378. if (endPoint == null)
  1379. throw new ArgumentNullException ("endPoint");
  1380. /*SocketAsyncResult sockares =*/ ValidateEndIAsyncResult (asyncResult, "EndReceiveMessageFrom", "asyncResult");
  1381. throw new NotImplementedException ();
  1382. }
  1383. #endregion
  1384. #region Send
  1385. public int Send (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
  1386. {
  1387. ThrowIfDisposedAndClosed ();
  1388. ThrowIfBufferNull (buffer);
  1389. ThrowIfBufferOutOfRange (buffer, offset, size);
  1390. if (size == 0) {
  1391. errorCode = SocketError.Success;
  1392. return 0;
  1393. }
  1394. int nativeError;
  1395. int sent = 0;
  1396. do {
  1397. sent += Send_internal (
  1398. m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError, is_blocking);
  1399. errorCode = (SocketError)nativeError;
  1400. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
  1401. is_connected = false;
  1402. is_bound = false;
  1403. break;
  1404. } else {
  1405. is_connected = true;
  1406. }
  1407. } while (sent < size);
  1408. return sent;
  1409. }
  1410. [CLSCompliant (false)]
  1411. public int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
  1412. {
  1413. ThrowIfDisposedAndClosed ();
  1414. if (buffers == null)
  1415. throw new ArgumentNullException ("buffers");
  1416. if (buffers.Count == 0)
  1417. throw new ArgumentException ("Buffer is empty", "buffers");
  1418. int numsegments = buffers.Count;
  1419. int nativeError;
  1420. int ret;
  1421. WSABUF[] bufarray = new WSABUF[numsegments];
  1422. GCHandle[] gch = new GCHandle[numsegments];
  1423. for(int i = 0; i < numsegments; i++) {
  1424. ArraySegment<byte> segment = buffers[i];
  1425. if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
  1426. throw new ArgumentOutOfRangeException ("segment");
  1427. gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
  1428. bufarray[i].len = segment.Count;
  1429. bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
  1430. }
  1431. try {
  1432. ret = Send_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
  1433. } finally {
  1434. for(int i = 0; i < numsegments; i++) {
  1435. if (gch[i].IsAllocated) {
  1436. gch[i].Free ();
  1437. }
  1438. }
  1439. }
  1440. errorCode = (SocketError)nativeError;
  1441. return ret;
  1442. }
  1443. public bool SendAsync (SocketAsyncEventArgs e)
  1444. {
  1445. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1446. ThrowIfDisposedAndClosed ();
  1447. if (e.Buffer == null && e.BufferList == null)
  1448. throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
  1449. if (e.Buffer == null) {
  1450. InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.SendGeneric);
  1451. e.socket_async_result.Buffers = e.BufferList;
  1452. QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
  1453. } else {
  1454. InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.Send);
  1455. e.socket_async_result.Buffer = e.Buffer;
  1456. e.socket_async_result.Offset = e.Offset;
  1457. e.socket_async_result.Size = e.Count;
  1458. QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
  1459. }
  1460. return true;
  1461. }
  1462. static AsyncCallback SendAsyncCallback = new AsyncCallback (ares => {
  1463. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1464. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1465. throw new InvalidOperationException ("No operation in progress");
  1466. try {
  1467. e.BytesTransferred = e.current_socket.EndSend (ares);
  1468. } catch (SocketException se){
  1469. e.SocketError = se.SocketErrorCode;
  1470. } catch (ObjectDisposedException) {
  1471. e.SocketError = SocketError.OperationAborted;
  1472. } finally {
  1473. e.Complete ();
  1474. }
  1475. });
  1476. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1477. {
  1478. ThrowIfDisposedAndClosed ();
  1479. ThrowIfBufferNull (buffer);
  1480. ThrowIfBufferOutOfRange (buffer, offset, size);
  1481. if (!is_connected) {
  1482. errorCode = SocketError.NotConnected;
  1483. return null;
  1484. }
  1485. errorCode = SocketError.Success;
  1486. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Send) {
  1487. Buffer = buffer,
  1488. Offset = offset,
  1489. Size = size,
  1490. SockFlags = socketFlags,
  1491. };
  1492. QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));
  1493. return sockares;
  1494. }
  1495. static void BeginSendCallback (SocketAsyncResult sockares, int sent_so_far)
  1496. {
  1497. int total = 0;
  1498. try {
  1499. total = Socket.Send_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, false);
  1500. } catch (Exception e) {
  1501. sockares.Complete (e);
  1502. return;
  1503. }
  1504. if (sockares.error == 0) {
  1505. sent_so_far += total;
  1506. sockares.Offset += total;
  1507. sockares.Size -= total;
  1508. if (sockares.socket.CleanedUp) {
  1509. sockares.Complete (total);
  1510. return;
  1511. }
  1512. if (sockares.Size > 0) {
  1513. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, sent_so_far), sockares));
  1514. return; // Have to finish writing everything. See bug #74475.
  1515. }
  1516. sockares.Total = sent_so_far;
  1517. }
  1518. sockares.Complete (total);
  1519. }
  1520. [CLSCompliant (false)]
  1521. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1522. {
  1523. ThrowIfDisposedAndClosed ();
  1524. if (buffers == null)
  1525. throw new ArgumentNullException ("buffers");
  1526. if (!is_connected) {
  1527. errorCode = SocketError.NotConnected;
  1528. return null;
  1529. }
  1530. errorCode = SocketError.Success;
  1531. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendGeneric) {
  1532. Buffers = buffers,
  1533. SockFlags = socketFlags,
  1534. };
  1535. QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));
  1536. return sockares;
  1537. }
  1538. static IOAsyncCallback BeginSendGenericCallback = new IOAsyncCallback (ares => {
  1539. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1540. int total = 0;
  1541. try {
  1542. total = sockares.socket.Send (sockares.Buffers, sockares.SockFlags);
  1543. } catch (Exception e) {
  1544. sockares.Complete (e);
  1545. return;
  1546. }
  1547. sockares.Complete (total);
  1548. });
  1549. public int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
  1550. {
  1551. ThrowIfDisposedAndClosed ();
  1552. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSend", "asyncResult");
  1553. if (!sockares.IsCompleted)
  1554. sockares.AsyncWaitHandle.WaitOne ();
  1555. errorCode = sockares.ErrorCode;
  1556. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
  1557. is_connected = false;
  1558. /* If no socket error occurred, call CheckIfThrowDelayedException in
  1559. * case there are other kinds of exceptions that should be thrown.*/
  1560. if (errorCode == SocketError.Success)
  1561. sockares.CheckIfThrowDelayedException ();
  1562. return sockares.Total;
  1563. }
  1564. static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
  1565. {
  1566. try {
  1567. safeHandle.RegisterForBlockingSyscall ();
  1568. return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
  1569. } finally {
  1570. safeHandle.UnRegisterForBlockingSyscall ();
  1571. }
  1572. }
  1573. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  1574. extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
  1575. static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking)
  1576. {
  1577. try {
  1578. safeHandle.RegisterForBlockingSyscall ();
  1579. return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error, blocking);
  1580. } finally {
  1581. safeHandle.UnRegisterForBlockingSyscall ();
  1582. }
  1583. }
  1584. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1585. extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking);
  1586. #endregion
  1587. #region SendTo
  1588. public int SendTo (byte [] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
  1589. {
  1590. ThrowIfDisposedAndClosed ();
  1591. ThrowIfBufferNull (buffer);
  1592. ThrowIfBufferOutOfRange (buffer, offset, size);
  1593. if (remoteEP == null)
  1594. throw new ArgumentNullException("remoteEP");
  1595. int error;
  1596. int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
  1597. SocketError err = (SocketError) error;
  1598. if (err != 0) {
  1599. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  1600. is_connected = false;
  1601. throw new SocketException (error);
  1602. }
  1603. is_connected = true;
  1604. is_bound = true;
  1605. seed_endpoint = remoteEP;
  1606. return ret;
  1607. }
  1608. public bool SendToAsync (SocketAsyncEventArgs e)
  1609. {
  1610. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1611. ThrowIfDisposedAndClosed ();
  1612. if (e.BufferList != null)
  1613. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  1614. if (e.RemoteEndPoint == null)
  1615. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  1616. InitSocketAsyncEventArgs (e, SendToAsyncCallback, e, SocketOperation.SendTo);
  1617. e.socket_async_result.Buffer = e.Buffer;
  1618. e.socket_async_result.Offset = e.Offset;
  1619. e.socket_async_result.Size = e.Count;
  1620. e.socket_async_result.SockFlags = e.SocketFlags;
  1621. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  1622. QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
  1623. return true;
  1624. }
  1625. static AsyncCallback SendToAsyncCallback = new AsyncCallback (ares => {
  1626. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1627. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1628. throw new InvalidOperationException ("No operation in progress");
  1629. try {
  1630. e.BytesTransferred = e.current_socket.EndSendTo (ares);
  1631. } catch (SocketException ex) {
  1632. e.SocketError = ex.SocketErrorCode;
  1633. } catch (ObjectDisposedException) {
  1634. e.SocketError = SocketError.OperationAborted;
  1635. } finally {
  1636. e.Complete ();
  1637. }
  1638. });
  1639. public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socket_flags, EndPoint remote_end, AsyncCallback callback, object state)
  1640. {
  1641. ThrowIfDisposedAndClosed ();
  1642. ThrowIfBufferNull (buffer);
  1643. ThrowIfBufferOutOfRange (buffer, offset, size);
  1644. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendTo) {
  1645. Buffer = buffer,
  1646. Offset = offset,
  1647. Size = size,
  1648. SockFlags = socket_flags,
  1649. EndPoint = remote_end,
  1650. };
  1651. QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));
  1652. return sockares;
  1653. }
  1654. static void BeginSendToCallback (SocketAsyncResult sockares, int sent_so_far)
  1655. {
  1656. int total = 0;
  1657. try {
  1658. total = sockares.socket.SendTo (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);
  1659. if (sockares.error == 0) {
  1660. sent_so_far += total;
  1661. sockares.Offset += total;
  1662. sockares.Size -= total;
  1663. }
  1664. if (sockares.Size > 0) {
  1665. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, sent_so_far), sockares));
  1666. return; // Have to finish writing everything. See bug #74475.
  1667. }
  1668. sockares.Total = sent_so_far;
  1669. } catch (Exception e) {
  1670. sockares.Complete (e);
  1671. return;
  1672. }
  1673. sockares.Complete ();
  1674. }
  1675. public int EndSendTo (IAsyncResult result)
  1676. {
  1677. ThrowIfDisposedAndClosed ();
  1678. SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndSendTo", "result");
  1679. if (!sockares.IsCompleted)
  1680. sockares.AsyncWaitHandle.WaitOne();
  1681. sockares.CheckIfThrowDelayedException();
  1682. return sockares.Total;
  1683. }
  1684. static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking)
  1685. {
  1686. try {
  1687. safeHandle.RegisterForBlockingSyscall ();
  1688. return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error, blocking);
  1689. } finally {
  1690. safeHandle.UnRegisterForBlockingSyscall ();
  1691. }
  1692. }
  1693. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1694. extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking);
  1695. #endregion
  1696. #region SendFile
  1697. public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
  1698. {
  1699. ThrowIfDisposedAndClosed ();
  1700. if (!is_connected)
  1701. throw new NotSupportedException ();
  1702. if (!is_blocking)
  1703. throw new InvalidOperationException ();
  1704. int error = 0;
  1705. if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags, out error, is_blocking) || error != 0) {
  1706. SocketException exc = new SocketException (error);
  1707. if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
  1708. throw new FileNotFoundException ();
  1709. throw exc;
  1710. }
  1711. }
  1712. public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
  1713. {
  1714. ThrowIfDisposedAndClosed ();
  1715. if (!is_connected)
  1716. throw new NotSupportedException ();
  1717. if (!File.Exists (fileName))
  1718. throw new FileNotFoundException ();
  1719. SendFileHandler handler = new SendFileHandler (SendFile);
  1720. return new SendFileAsyncResult (handler, handler.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => callback (new SendFileAsyncResult (handler, ar)), state));
  1721. }
  1722. public void EndSendFile (IAsyncResult asyncResult)
  1723. {
  1724. ThrowIfDisposedAndClosed ();
  1725. if (asyncResult == null)
  1726. throw new ArgumentNullException ("asyncResult");
  1727. SendFileAsyncResult ares = asyncResult as SendFileAsyncResult;
  1728. if (ares == null)
  1729. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1730. ares.Delegate.EndInvoke (ares.Original);
  1731. }
  1732. static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking)
  1733. {
  1734. try {
  1735. safeHandle.RegisterForBlockingSyscall ();
  1736. return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags, out error, blocking);
  1737. } finally {
  1738. safeHandle.UnRegisterForBlockingSyscall ();
  1739. }
  1740. }
  1741. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1742. extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking);
  1743. delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);
  1744. sealed class SendFileAsyncResult : IAsyncResult {
  1745. IAsyncResult ares;
  1746. SendFileHandler d;
  1747. public SendFileAsyncResult (SendFileHandler d, IAsyncResult ares)
  1748. {
  1749. this.d = d;
  1750. this.ares = ares;
  1751. }
  1752. public object AsyncState {
  1753. get { return ares.AsyncState; }
  1754. }
  1755. public WaitHandle AsyncWaitHandle {
  1756. get { return ares.AsyncWaitHandle; }
  1757. }
  1758. public bool CompletedSynchronously {
  1759. get { return ares.CompletedSynchronously; }
  1760. }
  1761. public bool IsCompleted {
  1762. get { return ares.IsCompleted; }
  1763. }
  1764. public SendFileHandler Delegate {
  1765. get { return d; }
  1766. }
  1767. public IAsyncResult Original {
  1768. get { return ares; }
  1769. }
  1770. }
  1771. #endregion
  1772. #region SendPackets
  1773. [MonoTODO ("Not implemented")]
  1774. public bool SendPacketsAsync (SocketAsyncEventArgs e)
  1775. {
  1776. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1777. ThrowIfDisposedAndClosed ();
  1778. throw new NotImplementedException ();
  1779. }
  1780. #endregion
  1781. #region DuplicateAndClose
  1782. [MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
  1783. public SocketInformation DuplicateAndClose (int targetProcessId)
  1784. {
  1785. var si = new SocketInformation ();
  1786. si.Options =
  1787. (is_listening ? SocketInformationOptions.Listening : 0) |
  1788. (is_connected ? SocketInformationOptions.Connected : 0) |
  1789. (is_blocking ? 0 : SocketInformationOptions.NonBlocking) |
  1790. (useOverlappedIO ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
  1791. MonoIOError error;
  1792. IntPtr duplicateHandle;
  1793. if (!MonoIO.DuplicateHandle (System.Diagnostics.Process.GetCurrentProcess ().Handle, Handle, new IntPtr (targetProcessId), out duplicateHandle, 0, 0, 0x00000002 /* DUPLICATE_SAME_ACCESS */, out error))
  1794. throw MonoIO.GetException (error);
  1795. si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)addressFamily, (int)socketType, (int)protocolType, is_bound ? 1 : 0, (long)duplicateHandle);
  1796. m_Handle = null;
  1797. return si;
  1798. }
  1799. #endregion
  1800. #region GetSocketOption
  1801. public void GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
  1802. {
  1803. ThrowIfDisposedAndClosed ();
  1804. if (optionValue == null)
  1805. throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
  1806. int error;
  1807. GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref optionValue, out error);
  1808. if (error != 0)
  1809. throw new SocketException (error);
  1810. }
  1811. public byte [] GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
  1812. {
  1813. ThrowIfDisposedAndClosed ();
  1814. int error;
  1815. byte[] byte_val = new byte [optionLength];
  1816. GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref byte_val, out error);
  1817. if (error != 0)
  1818. throw new SocketException (error);
  1819. return byte_val;
  1820. }
  1821. public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
  1822. {
  1823. ThrowIfDisposedAndClosed ();
  1824. int error;
  1825. object obj_val;
  1826. GetSocketOption_obj_internal (m_Handle, optionLevel, optionName, out obj_val, out error);
  1827. if (error != 0)
  1828. throw new SocketException (error);
  1829. if (optionName == SocketOptionName.Linger)
  1830. return (LingerOption) obj_val;
  1831. else if (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)
  1832. return (MulticastOption) obj_val;
  1833. else if (obj_val is int)
  1834. return (int) obj_val;
  1835. else
  1836. return obj_val;
  1837. }
  1838. static void GetSocketOption_arr_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error)
  1839. {
  1840. bool release = false;
  1841. try {
  1842. safeHandle.DangerousAddRef (ref release);
  1843. GetSocketOption_arr_internal (safeHandle.DangerousGetHandle (), level, name, ref byte_val, out error);
  1844. } finally {
  1845. if (release)
  1846. safeHandle.DangerousRelease ();
  1847. }
  1848. }
  1849. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1850. extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
  1851. static void GetSocketOption_obj_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error)
  1852. {
  1853. bool release = false;
  1854. try {
  1855. safeHandle.DangerousAddRef (ref release);
  1856. GetSocketOption_obj_internal (safeHandle.DangerousGetHandle (), level, name, out obj_val, out error);
  1857. } finally {
  1858. if (release)
  1859. safeHandle.DangerousRelease ();
  1860. }
  1861. }
  1862. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1863. extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
  1864. #endregion
  1865. #region SetSocketOption
  1866. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
  1867. {
  1868. ThrowIfDisposedAndClosed ();
  1869. // I'd throw an ArgumentNullException, but this is what MS does.
  1870. if (optionValue == null)
  1871. throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
  1872. int error;
  1873. SetSocketOption_internal (m_Handle, optionLevel, optionName, null, optionValue, 0, out error);
  1874. if (error != 0) {
  1875. if (error == (int) SocketError.InvalidArgument)
  1876. throw new ArgumentException ();
  1877. throw new SocketException (error);
  1878. }
  1879. }
  1880. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
  1881. {
  1882. ThrowIfDisposedAndClosed ();
  1883. // NOTE: if a null is passed, the byte[] overload is used instead...
  1884. if (optionValue == null)
  1885. throw new ArgumentNullException("optionValue");
  1886. int error;
  1887. if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger) {
  1888. LingerOption linger = optionValue as LingerOption;
  1889. if (linger == null)
  1890. throw new ArgumentException ("A 'LingerOption' value must be specified.", "optionValue");
  1891. SetSocketOption_internal (m_Handle, optionLevel, optionName, linger, null, 0, out error);
  1892. } else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
  1893. MulticastOption multicast = optionValue as MulticastOption;
  1894. if (multicast == null)
  1895. throw new ArgumentException ("A 'MulticastOption' value must be specified.", "optionValue");
  1896. SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
  1897. } else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
  1898. IPv6MulticastOption multicast = optionValue as IPv6MulticastOption;
  1899. if (multicast == null)
  1900. throw new ArgumentException ("A 'IPv6MulticastOption' value must be specified.", "optionValue");
  1901. SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
  1902. } else {
  1903. throw new ArgumentException ("Invalid value specified.", "optionValue");
  1904. }
  1905. if (error != 0) {
  1906. if (error == (int) SocketError.InvalidArgument)
  1907. throw new ArgumentException ();
  1908. throw new SocketException (error);
  1909. }
  1910. }
  1911. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
  1912. {
  1913. int int_val = optionValue ? 1 : 0;
  1914. SetSocketOption (optionLevel, optionName, int_val);
  1915. }
  1916. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
  1917. {
  1918. ThrowIfDisposedAndClosed ();
  1919. int error;
  1920. SetSocketOption_internal (m_Handle, optionLevel, optionName, null, null, optionValue, out error);
  1921. if (error != 0) {
  1922. if (error == (int) SocketError.InvalidArgument)
  1923. throw new ArgumentException ();
  1924. throw new SocketException (error);
  1925. }
  1926. }
  1927. static void SetSocketOption_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error)
  1928. {
  1929. bool release = false;
  1930. try {
  1931. safeHandle.DangerousAddRef (ref release);
  1932. SetSocketOption_internal (safeHandle.DangerousGetHandle (), level, name, obj_val, byte_val, int_val, out error);
  1933. } finally {
  1934. if (release)
  1935. safeHandle.DangerousRelease ();
  1936. }
  1937. }
  1938. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1939. extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error);
  1940. #endregion
  1941. #region IOControl
  1942. public int IOControl (int ioControlCode, byte [] optionInValue, byte [] optionOutValue)
  1943. {
  1944. if (CleanedUp)
  1945. throw new ObjectDisposedException (GetType ().ToString ());
  1946. int error;
  1947. int result = IOControl_internal (m_Handle, ioControlCode, optionInValue, optionOutValue, out error);
  1948. if (error != 0)
  1949. throw new SocketException (error);
  1950. if (result == -1)
  1951. throw new InvalidOperationException ("Must use Blocking property instead.");
  1952. return result;
  1953. }
  1954. static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
  1955. {
  1956. bool release = false;
  1957. try {
  1958. safeHandle.DangerousAddRef (ref release);
  1959. return IOControl_internal (safeHandle.DangerousGetHandle (), ioctl_code, input, output, out error);
  1960. } finally {
  1961. if (release)
  1962. safeHandle.DangerousRelease ();
  1963. }
  1964. }
  1965. /* See Socket.IOControl, WSAIoctl documentation in MSDN. The common options between UNIX
  1966. * and Winsock are FIONREAD, FIONBIO and SIOCATMARK. Anything else will depend on the system
  1967. * except SIO_KEEPALIVE_VALS which is properly handled on both windows and linux. */
  1968. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1969. extern static int IOControl_internal (IntPtr sock, int ioctl_code, byte [] input, byte [] output, out int error);
  1970. #endregion
  1971. #region Close
  1972. public void Close ()
  1973. {
  1974. linger_timeout = 0;
  1975. Dispose ();
  1976. }
  1977. public void Close (int timeout)
  1978. {
  1979. linger_timeout = timeout;
  1980. Dispose ();
  1981. }
  1982. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1983. internal extern static void Close_internal (IntPtr socket, out int error);
  1984. #endregion
  1985. #region Shutdown
  1986. public void Shutdown (SocketShutdown how)
  1987. {
  1988. ThrowIfDisposedAndClosed ();
  1989. if (!is_connected)
  1990. throw new SocketException (10057); // Not connected
  1991. int error;
  1992. Shutdown_internal (m_Handle, how, out error);
  1993. if (error != 0)
  1994. throw new SocketException (error);
  1995. }
  1996. static void Shutdown_internal (SafeSocketHandle safeHandle, SocketShutdown how, out int error)
  1997. {
  1998. bool release = false;
  1999. try {
  2000. safeHandle.DangerousAddRef (ref release);
  2001. Shutdown_internal (safeHandle.DangerousGetHandle (), how, out error);
  2002. } finally {
  2003. if (release)
  2004. safeHandle.DangerousRelease ();
  2005. }
  2006. }
  2007. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  2008. internal extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
  2009. #endregion
  2010. #region Dispose
  2011. protected virtual void Dispose (bool disposing)
  2012. {
  2013. if (CleanedUp)
  2014. return;
  2015. m_IntCleanedUp = 1;
  2016. bool was_connected = is_connected;
  2017. is_connected = false;
  2018. if (m_Handle != null) {
  2019. is_closed = true;
  2020. IntPtr x = Handle;
  2021. if (was_connected)
  2022. Linger (x);
  2023. m_Handle.Dispose ();
  2024. }
  2025. }
  2026. void Linger (IntPtr handle)
  2027. {
  2028. if (!is_connected || linger_timeout <= 0)
  2029. return;
  2030. /* We don't want to receive any more data */
  2031. int error;
  2032. Shutdown_internal (handle, SocketShutdown.Receive, out error);
  2033. if (error != 0)
  2034. return;
  2035. int seconds = linger_timeout / 1000;
  2036. int ms = linger_timeout % 1000;
  2037. if (ms > 0) {
  2038. /* If the other end closes, this will return 'true' with 'Available' == 0 */
  2039. Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
  2040. if (error != 0)
  2041. return;
  2042. }
  2043. if (seconds > 0) {
  2044. LingerOption linger = new LingerOption (true, seconds);
  2045. SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
  2046. /* Not needed, we're closing upon return */
  2047. //if (error != 0)
  2048. // return;
  2049. }
  2050. }
  2051. #endregion
  2052. void ThrowIfDisposedAndClosed (Socket socket)
  2053. {
  2054. if (socket.CleanedUp && socket.is_closed)
  2055. throw new ObjectDisposedException (socket.GetType ().ToString ());
  2056. }
  2057. void ThrowIfDisposedAndClosed ()
  2058. {
  2059. if (CleanedUp && is_closed)
  2060. throw new ObjectDisposedException (GetType ().ToString ());
  2061. }
  2062. void ThrowIfBufferNull (byte[] buffer)
  2063. {
  2064. if (buffer == null)
  2065. throw new ArgumentNullException ("buffer");
  2066. }
  2067. void ThrowIfBufferOutOfRange (byte[] buffer, int offset, int size)
  2068. {
  2069. if (offset < 0)
  2070. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  2071. if (offset > buffer.Length)
  2072. throw new ArgumentOutOfRangeException ("offset", "offset must be <= buffer.Length");
  2073. if (size < 0)
  2074. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  2075. if (size > buffer.Length - offset)
  2076. throw new ArgumentOutOfRangeException ("size", "size must be <= buffer.Length - offset");
  2077. }
  2078. void ThrowIfUdp ()
  2079. {
  2080. if (protocolType == ProtocolType.Udp)
  2081. throw new SocketException ((int)SocketError.ProtocolOption);
  2082. }
  2083. SocketAsyncResult ValidateEndIAsyncResult (IAsyncResult ares, string methodName, string argName)
  2084. {
  2085. if (ares == null)
  2086. throw new ArgumentNullException (argName);
  2087. SocketAsyncResult sockares = ares as SocketAsyncResult;
  2088. if (sockares == null)
  2089. throw new ArgumentException ("Invalid IAsyncResult", argName);
  2090. if (Interlocked.CompareExchange (ref sockares.EndCalled, 1, 0) == 1)
  2091. throw new InvalidOperationException (methodName + " can only be called once per asynchronous operation");
  2092. return sockares;
  2093. }
  2094. void QueueIOSelectorJob (SemaphoreSlim sem, IntPtr handle, IOSelectorJob job)
  2095. {
  2096. sem.WaitAsync ().ContinueWith (t => {
  2097. if (CleanedUp) {
  2098. job.MarkDisposed ();
  2099. return;
  2100. }
  2101. IOSelector.Add (handle, job);
  2102. });
  2103. }
  2104. void InitSocketAsyncEventArgs (SocketAsyncEventArgs e, AsyncCallback callback, object state, SocketOperation operation)
  2105. {
  2106. e.socket_async_result.Init (this, callback, state, operation);
  2107. if (e.AcceptSocket != null) {
  2108. e.socket_async_result.AcceptSocket = e.AcceptSocket;
  2109. }
  2110. e.current_socket = this;
  2111. e.SetLastOperation (SocketOperationToSocketAsyncOperation (operation));
  2112. e.SocketError = SocketError.Success;
  2113. e.BytesTransferred = 0;
  2114. }
  2115. SocketAsyncOperation SocketOperationToSocketAsyncOperation (SocketOperation op)
  2116. {
  2117. switch (op) {
  2118. case SocketOperation.Connect:
  2119. return SocketAsyncOperation.Connect;
  2120. case SocketOperation.Accept:
  2121. return SocketAsyncOperation.Accept;
  2122. case SocketOperation.Disconnect:
  2123. return SocketAsyncOperation.Disconnect;
  2124. case SocketOperation.Receive:
  2125. case SocketOperation.ReceiveGeneric:
  2126. return SocketAsyncOperation.Receive;
  2127. case SocketOperation.ReceiveFrom:
  2128. return SocketAsyncOperation.ReceiveFrom;
  2129. case SocketOperation.Send:
  2130. case SocketOperation.SendGeneric:
  2131. return SocketAsyncOperation.Send;
  2132. case SocketOperation.SendTo:
  2133. return SocketAsyncOperation.SendTo;
  2134. default:
  2135. throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
  2136. }
  2137. }
  2138. IPEndPoint RemapIPEndPoint (IPEndPoint input) {
  2139. // If socket is DualMode ensure we automatically handle mapping IPv4 addresses to IPv6.
  2140. if (IsDualMode && input.AddressFamily == AddressFamily.InterNetwork)
  2141. return new IPEndPoint (input.Address.MapToIPv6 (), input.Port);
  2142. return input;
  2143. }
  2144. [StructLayout (LayoutKind.Sequential)]
  2145. struct WSABUF {
  2146. public int len;
  2147. public IntPtr buf;
  2148. }
  2149. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2150. internal static extern void cancel_blocking_socket_operation (Thread thread);
  2151. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2152. internal static extern bool SupportsPortReuse (ProtocolType proto);
  2153. internal static int FamilyHint {
  2154. get {
  2155. // Returns one of
  2156. // MONO_HINT_UNSPECIFIED = 0,
  2157. // MONO_HINT_IPV4 = 1,
  2158. // MONO_HINT_IPV6 = 2,
  2159. int hint = 0;
  2160. if (OSSupportsIPv4) {
  2161. hint = 1;
  2162. }
  2163. if (OSSupportsIPv6) {
  2164. hint = hint == 0 ? 2 : 0;
  2165. }
  2166. return hint;
  2167. }
  2168. }
  2169. static bool IsProtocolSupported (NetworkInterfaceComponent networkInterface)
  2170. {
  2171. #if MOBILE
  2172. return true;
  2173. #else
  2174. var nics = NetworkInterface.GetAllNetworkInterfaces ();
  2175. foreach (var adapter in nics) {
  2176. if (adapter.Supports (networkInterface))
  2177. return true;
  2178. }
  2179. return false;
  2180. #endif
  2181. }
  2182. }
  2183. }