Socket.cs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777
  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 asyncResult)
  578. {
  579. int bytes;
  580. byte[] buffer;
  581. return EndAccept (out buffer, out bytes, asyncResult);
  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. //NOTE: DualMode may cause Socket's RemoteEndpoint to differ in AddressFamily from the
  723. // SocketAsyncEventArgs, but the SocketAsyncEventArgs itself is not changed
  724. ares = (SocketAsyncResult) BeginConnect (e.RemoteEndPoint, ConnectAsyncCallback, e);
  725. } else {
  726. DnsEndPoint dep = (DnsEndPoint)e.RemoteEndPoint;
  727. ares = (SocketAsyncResult) BeginConnect (addresses, dep.Port, ConnectAsyncCallback, e);
  728. }
  729. if (ares.IsCompleted && ares.CompletedSynchronously) {
  730. ares.CheckIfThrowDelayedException ();
  731. return false;
  732. }
  733. } catch (Exception exc) {
  734. e.socket_async_result.Complete (exc, true);
  735. return false;
  736. }
  737. return true;
  738. }
  739. public static void CancelConnectAsync (SocketAsyncEventArgs e)
  740. {
  741. if (e == null)
  742. throw new ArgumentNullException("e");
  743. if (e.in_progress != 0 && e.LastOperation == SocketAsyncOperation.Connect)
  744. e.current_socket.Close();
  745. }
  746. static AsyncCallback ConnectAsyncCallback = new AsyncCallback (ares => {
  747. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  748. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  749. throw new InvalidOperationException ("No operation in progress");
  750. try {
  751. e.current_socket.EndConnect (ares);
  752. } catch (SocketException se) {
  753. e.SocketError = se.SocketErrorCode;
  754. } catch (ObjectDisposedException) {
  755. e.SocketError = SocketError.OperationAborted;
  756. } finally {
  757. e.Complete ();
  758. }
  759. });
  760. public IAsyncResult BeginConnect (string host, int port, AsyncCallback requestCallback, object state)
  761. {
  762. ThrowIfDisposedAndClosed ();
  763. if (host == null)
  764. throw new ArgumentNullException ("host");
  765. if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
  766. throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
  767. if (port <= 0 || port > 65535)
  768. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  769. if (is_listening)
  770. throw new InvalidOperationException ();
  771. return BeginConnect (Dns.GetHostAddresses (host), port, requestCallback, state);
  772. }
  773. public IAsyncResult BeginConnect (EndPoint remoteEP, AsyncCallback callback, object state)
  774. {
  775. ThrowIfDisposedAndClosed ();
  776. if (remoteEP == null)
  777. throw new ArgumentNullException ("remoteEP");
  778. if (is_listening)
  779. throw new InvalidOperationException ();
  780. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
  781. EndPoint = remoteEP,
  782. };
  783. BeginSConnect (sockares);
  784. return sockares;
  785. }
  786. public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
  787. {
  788. ThrowIfDisposedAndClosed ();
  789. if (addresses == null)
  790. throw new ArgumentNullException ("addresses");
  791. if (addresses.Length == 0)
  792. throw new ArgumentException ("Empty addresses list");
  793. if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
  794. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  795. if (port <= 0 || port > 65535)
  796. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  797. if (is_listening)
  798. throw new InvalidOperationException ();
  799. SocketAsyncResult sockares = new SocketAsyncResult (this, requestCallback, state, SocketOperation.Connect) {
  800. Addresses = addresses,
  801. Port = port,
  802. };
  803. is_connected = false;
  804. BeginMConnect (sockares);
  805. return sockares;
  806. }
  807. static void BeginMConnect (SocketAsyncResult sockares)
  808. {
  809. Exception exc = null;
  810. for (int i = sockares.CurrentAddress; i < sockares.Addresses.Length; i++) {
  811. try {
  812. sockares.CurrentAddress++;
  813. sockares.EndPoint = new IPEndPoint (sockares.Addresses [i], sockares.Port);
  814. BeginSConnect (sockares);
  815. return;
  816. } catch (Exception e) {
  817. exc = e;
  818. }
  819. }
  820. throw exc;
  821. }
  822. static void BeginSConnect (SocketAsyncResult sockares)
  823. {
  824. EndPoint remoteEP = sockares.EndPoint;
  825. // Bug #75154: Connect() should not succeed for .Any addresses.
  826. if (remoteEP is IPEndPoint) {
  827. IPEndPoint ep = (IPEndPoint) remoteEP;
  828. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  829. sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
  830. return;
  831. }
  832. sockares.EndPoint = remoteEP = sockares.socket.RemapIPEndPoint (ep);
  833. }
  834. int error = 0;
  835. if (sockares.socket.connect_in_progress) {
  836. // This could happen when multiple IPs are used
  837. // Calling connect() again will reset the connection attempt and cause
  838. // an error. Better to just close the socket and move on.
  839. sockares.socket.connect_in_progress = false;
  840. sockares.socket.m_Handle.Dispose ();
  841. sockares.socket.m_Handle = new SafeSocketHandle (sockares.socket.Socket_internal (sockares.socket.addressFamily, sockares.socket.socketType, sockares.socket.protocolType, out error), true);
  842. if (error != 0)
  843. throw new SocketException (error);
  844. }
  845. bool blk = sockares.socket.is_blocking;
  846. if (blk)
  847. sockares.socket.Blocking = false;
  848. Connect_internal (sockares.socket.m_Handle, remoteEP.Serialize (), out error, false);
  849. if (blk)
  850. sockares.socket.Blocking = true;
  851. if (error == 0) {
  852. // succeeded synch
  853. sockares.socket.is_connected = true;
  854. sockares.socket.is_bound = true;
  855. sockares.Complete (true);
  856. return;
  857. }
  858. if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
  859. // error synch
  860. sockares.socket.is_connected = false;
  861. sockares.socket.is_bound = false;
  862. sockares.Complete (new SocketException (error), true);
  863. return;
  864. }
  865. // continue asynch
  866. sockares.socket.is_connected = false;
  867. sockares.socket.is_bound = false;
  868. sockares.socket.connect_in_progress = true;
  869. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));
  870. }
  871. static IOAsyncCallback BeginConnectCallback = new IOAsyncCallback (ares => {
  872. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  873. if (sockares.EndPoint == null) {
  874. sockares.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
  875. return;
  876. }
  877. try {
  878. int error = (int) sockares.socket.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  879. if (error == 0) {
  880. sockares.socket.seed_endpoint = sockares.EndPoint;
  881. sockares.socket.is_connected = true;
  882. sockares.socket.is_bound = true;
  883. sockares.socket.connect_in_progress = false;
  884. sockares.error = 0;
  885. sockares.Complete ();
  886. return;
  887. }
  888. if (sockares.Addresses == null) {
  889. sockares.socket.connect_in_progress = false;
  890. sockares.Complete (new SocketException (error));
  891. return;
  892. }
  893. if (sockares.CurrentAddress >= sockares.Addresses.Length) {
  894. sockares.Complete (new SocketException (error));
  895. return;
  896. }
  897. BeginMConnect (sockares);
  898. } catch (Exception e) {
  899. sockares.socket.connect_in_progress = false;
  900. sockares.Complete (e);
  901. }
  902. });
  903. public void EndConnect (IAsyncResult asyncResult)
  904. {
  905. ThrowIfDisposedAndClosed ();
  906. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndConnect", "asyncResult");
  907. if (!sockares.IsCompleted)
  908. sockares.AsyncWaitHandle.WaitOne();
  909. sockares.CheckIfThrowDelayedException();
  910. }
  911. static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error, bool blocking)
  912. {
  913. try {
  914. safeHandle.RegisterForBlockingSyscall ();
  915. Connect_internal (safeHandle.DangerousGetHandle (), sa, out error, blocking);
  916. } finally {
  917. safeHandle.UnRegisterForBlockingSyscall ();
  918. }
  919. }
  920. /* Connects to the remote address */
  921. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  922. extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error, bool blocking);
  923. /* Returns :
  924. * - false when it is ok to use RemoteEndPoint
  925. * - true when addresses must be used (and addresses could be null/empty) */
  926. bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
  927. {
  928. addresses = null;
  929. // Connect to the first address that match the host name, like:
  930. // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
  931. // while skipping entries that do not match the address family
  932. DnsEndPoint dep = e.RemoteEndPoint as DnsEndPoint;
  933. if (dep != null) {
  934. addresses = Dns.GetHostAddresses (dep.Host);
  935. return true;
  936. } else {
  937. e.ConnectByNameError = null;
  938. return false;
  939. }
  940. }
  941. #endregion
  942. #region Disconnect
  943. /* According to the docs, the MS runtime will throw PlatformNotSupportedException
  944. * if the platform is newer than w2k. We should be able to cope... */
  945. public void Disconnect (bool reuseSocket)
  946. {
  947. ThrowIfDisposedAndClosed ();
  948. int error = 0;
  949. Disconnect_internal (m_Handle, reuseSocket, out error);
  950. if (error != 0) {
  951. if (error == 50) {
  952. /* ERROR_NOT_SUPPORTED */
  953. throw new PlatformNotSupportedException ();
  954. } else {
  955. throw new SocketException (error);
  956. }
  957. }
  958. is_connected = false;
  959. if (reuseSocket) {
  960. /* Do managed housekeeping here... */
  961. }
  962. }
  963. public bool DisconnectAsync (SocketAsyncEventArgs e)
  964. {
  965. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  966. ThrowIfDisposedAndClosed ();
  967. InitSocketAsyncEventArgs (e, DisconnectAsyncCallback, e, SocketOperation.Disconnect);
  968. IOSelector.Add (e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, e.socket_async_result));
  969. return true;
  970. }
  971. static AsyncCallback DisconnectAsyncCallback = new AsyncCallback (ares => {
  972. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  973. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  974. throw new InvalidOperationException ("No operation in progress");
  975. try {
  976. e.current_socket.EndDisconnect (ares);
  977. } catch (SocketException ex) {
  978. e.SocketError = ex.SocketErrorCode;
  979. } catch (ObjectDisposedException) {
  980. e.SocketError = SocketError.OperationAborted;
  981. } finally {
  982. e.Complete ();
  983. }
  984. });
  985. public IAsyncResult BeginDisconnect (bool reuseSocket, AsyncCallback callback, object state)
  986. {
  987. ThrowIfDisposedAndClosed ();
  988. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Disconnect) {
  989. ReuseSocket = reuseSocket,
  990. };
  991. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, sockares));
  992. return sockares;
  993. }
  994. static IOAsyncCallback BeginDisconnectCallback = new IOAsyncCallback (ares => {
  995. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  996. try {
  997. sockares.socket.Disconnect (sockares.ReuseSocket);
  998. } catch (Exception e) {
  999. sockares.Complete (e);
  1000. return;
  1001. }
  1002. sockares.Complete ();
  1003. });
  1004. public void EndDisconnect (IAsyncResult asyncResult)
  1005. {
  1006. ThrowIfDisposedAndClosed ();
  1007. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndDisconnect", "asyncResult");
  1008. if (!sockares.IsCompleted)
  1009. sockares.AsyncWaitHandle.WaitOne ();
  1010. sockares.CheckIfThrowDelayedException ();
  1011. }
  1012. static void Disconnect_internal (SafeSocketHandle safeHandle, bool reuse, out int error)
  1013. {
  1014. bool release = false;
  1015. try {
  1016. safeHandle.DangerousAddRef (ref release);
  1017. Disconnect_internal (safeHandle.DangerousGetHandle (), reuse, out error);
  1018. } finally {
  1019. if (release)
  1020. safeHandle.DangerousRelease ();
  1021. }
  1022. }
  1023. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1024. extern static void Disconnect_internal (IntPtr sock, bool reuse, out int error);
  1025. #endregion
  1026. #region Receive
  1027. public int Receive (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
  1028. {
  1029. ThrowIfDisposedAndClosed ();
  1030. ThrowIfBufferNull (buffer);
  1031. ThrowIfBufferOutOfRange (buffer, offset, size);
  1032. int nativeError;
  1033. int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError, is_blocking);
  1034. errorCode = (SocketError) nativeError;
  1035. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
  1036. is_connected = false;
  1037. is_bound = false;
  1038. } else {
  1039. is_connected = true;
  1040. }
  1041. return ret;
  1042. }
  1043. [CLSCompliant (false)]
  1044. public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
  1045. {
  1046. ThrowIfDisposedAndClosed ();
  1047. if (buffers == null || buffers.Count == 0)
  1048. throw new ArgumentNullException ("buffers");
  1049. int numsegments = buffers.Count;
  1050. int nativeError;
  1051. int ret;
  1052. /* Only example I can find of sending a byte array reference directly into an internal
  1053. * call is in System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
  1054. * so taking a lead from that... */
  1055. WSABUF[] bufarray = new WSABUF[numsegments];
  1056. GCHandle[] gch = new GCHandle[numsegments];
  1057. for (int i = 0; i < numsegments; i++) {
  1058. ArraySegment<byte> segment = buffers[i];
  1059. if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
  1060. throw new ArgumentOutOfRangeException ("segment");
  1061. gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
  1062. bufarray[i].len = segment.Count;
  1063. bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
  1064. }
  1065. try {
  1066. ret = Receive_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
  1067. } finally {
  1068. for (int i = 0; i < numsegments; i++) {
  1069. if (gch[i].IsAllocated)
  1070. gch[i].Free ();
  1071. }
  1072. }
  1073. errorCode = (SocketError) nativeError;
  1074. return ret;
  1075. }
  1076. public bool ReceiveAsync (SocketAsyncEventArgs e)
  1077. {
  1078. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1079. ThrowIfDisposedAndClosed ();
  1080. // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
  1081. // thrown when e.Buffer and e.BufferList are null (works fine when one is
  1082. // set to a valid object)
  1083. if (e.Buffer == null && e.BufferList == null)
  1084. throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
  1085. if (e.Buffer == null) {
  1086. InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.ReceiveGeneric);
  1087. e.socket_async_result.Buffers = e.BufferList;
  1088. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
  1089. } else {
  1090. InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.Receive);
  1091. e.socket_async_result.Buffer = e.Buffer;
  1092. e.socket_async_result.Offset = e.Offset;
  1093. e.socket_async_result.Size = e.Count;
  1094. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
  1095. }
  1096. return true;
  1097. }
  1098. static AsyncCallback ReceiveAsyncCallback = new AsyncCallback (ares => {
  1099. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1100. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1101. throw new InvalidOperationException ("No operation in progress");
  1102. try {
  1103. e.BytesTransferred = e.current_socket.EndReceive (ares);
  1104. } catch (SocketException se){
  1105. e.SocketError = se.SocketErrorCode;
  1106. } catch (ObjectDisposedException) {
  1107. e.SocketError = SocketError.OperationAborted;
  1108. } finally {
  1109. e.Complete ();
  1110. }
  1111. });
  1112. public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1113. {
  1114. ThrowIfDisposedAndClosed ();
  1115. ThrowIfBufferNull (buffer);
  1116. ThrowIfBufferOutOfRange (buffer, offset, size);
  1117. /* As far as I can tell from the docs and from experimentation, a pointer to the
  1118. * SocketError parameter is not supposed to be saved for the async parts. And as we don't
  1119. * set any socket errors in the setup code, we just have to set it to Success. */
  1120. errorCode = SocketError.Success;
  1121. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Receive) {
  1122. Buffer = buffer,
  1123. Offset = offset,
  1124. Size = size,
  1125. SockFlags = socketFlags,
  1126. };
  1127. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));
  1128. return sockares;
  1129. }
  1130. static IOAsyncCallback BeginReceiveCallback = new IOAsyncCallback (ares => {
  1131. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1132. int total = 0;
  1133. try {
  1134. total = Receive_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, sockares.socket.is_blocking);
  1135. } catch (Exception e) {
  1136. sockares.Complete (e);
  1137. return;
  1138. }
  1139. sockares.Complete (total);
  1140. });
  1141. [CLSCompliant (false)]
  1142. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1143. {
  1144. ThrowIfDisposedAndClosed ();
  1145. if (buffers == null)
  1146. throw new ArgumentNullException ("buffers");
  1147. /* I assume the same SocketError semantics as above */
  1148. errorCode = SocketError.Success;
  1149. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveGeneric) {
  1150. Buffers = buffers,
  1151. SockFlags = socketFlags,
  1152. };
  1153. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));
  1154. return sockares;
  1155. }
  1156. static IOAsyncCallback BeginReceiveGenericCallback = new IOAsyncCallback (ares => {
  1157. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1158. int total = 0;
  1159. try {
  1160. total = sockares.socket.Receive (sockares.Buffers, sockares.SockFlags);
  1161. } catch (Exception e) {
  1162. sockares.Complete (e);
  1163. return;
  1164. }
  1165. sockares.Complete (total);
  1166. });
  1167. public int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
  1168. {
  1169. ThrowIfDisposedAndClosed ();
  1170. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceive", "asyncResult");
  1171. if (!sockares.IsCompleted)
  1172. sockares.AsyncWaitHandle.WaitOne ();
  1173. errorCode = sockares.ErrorCode;
  1174. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
  1175. is_connected = false;
  1176. // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
  1177. // kinds of exceptions that should be thrown.
  1178. if (errorCode == SocketError.Success)
  1179. sockares.CheckIfThrowDelayedException();
  1180. return sockares.Total;
  1181. }
  1182. static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
  1183. {
  1184. try {
  1185. safeHandle.RegisterForBlockingSyscall ();
  1186. return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
  1187. } finally {
  1188. safeHandle.UnRegisterForBlockingSyscall ();
  1189. }
  1190. }
  1191. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  1192. extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
  1193. static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking)
  1194. {
  1195. try {
  1196. safeHandle.RegisterForBlockingSyscall ();
  1197. return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error, blocking);
  1198. } finally {
  1199. safeHandle.UnRegisterForBlockingSyscall ();
  1200. }
  1201. }
  1202. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1203. extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking);
  1204. #endregion
  1205. #region ReceiveFrom
  1206. public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
  1207. {
  1208. ThrowIfDisposedAndClosed ();
  1209. ThrowIfBufferNull (buffer);
  1210. ThrowIfBufferOutOfRange (buffer, offset, size);
  1211. if (remoteEP == null)
  1212. throw new ArgumentNullException ("remoteEP");
  1213. SocketError errorCode;
  1214. int ret = ReceiveFrom (buffer, offset, size, socketFlags, ref remoteEP, out errorCode);
  1215. if (errorCode != SocketError.Success)
  1216. throw new SocketException (errorCode);
  1217. return ret;
  1218. }
  1219. internal int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode)
  1220. {
  1221. SocketAddress sockaddr = remoteEP.Serialize();
  1222. int nativeError;
  1223. int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking);
  1224. errorCode = (SocketError) nativeError;
  1225. if (errorCode != SocketError.Success) {
  1226. if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
  1227. is_connected = false;
  1228. } else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
  1229. errorCode = SocketError.TimedOut;
  1230. }
  1231. return 0;
  1232. }
  1233. is_connected = true;
  1234. is_bound = true;
  1235. /* If sockaddr is null then we're a connection oriented protocol and should ignore the
  1236. * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
  1237. if (sockaddr != null) {
  1238. /* Stupidly, EndPoint.Create() is an instance method */
  1239. remoteEP = remoteEP.Create (sockaddr);
  1240. }
  1241. seed_endpoint = remoteEP;
  1242. return cnt;
  1243. }
  1244. public bool ReceiveFromAsync (SocketAsyncEventArgs e)
  1245. {
  1246. ThrowIfDisposedAndClosed ();
  1247. // We do not support recv into multiple buffers yet
  1248. if (e.BufferList != null)
  1249. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  1250. if (e.RemoteEndPoint == null)
  1251. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  1252. InitSocketAsyncEventArgs (e, ReceiveFromAsyncCallback, e, SocketOperation.ReceiveFrom);
  1253. e.socket_async_result.Buffer = e.Buffer;
  1254. e.socket_async_result.Offset = e.Offset;
  1255. e.socket_async_result.Size = e.Count;
  1256. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  1257. e.socket_async_result.SockFlags = e.SocketFlags;
  1258. QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));
  1259. return true;
  1260. }
  1261. static AsyncCallback ReceiveFromAsyncCallback = new AsyncCallback (ares => {
  1262. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1263. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1264. throw new InvalidOperationException ("No operation in progress");
  1265. try {
  1266. e.BytesTransferred = e.current_socket.EndReceiveFrom (ares, ref e.remote_ep);
  1267. } catch (SocketException ex) {
  1268. e.SocketError = ex.SocketErrorCode;
  1269. } catch (ObjectDisposedException) {
  1270. e.SocketError = SocketError.OperationAborted;
  1271. } finally {
  1272. e.Complete ();
  1273. }
  1274. });
  1275. public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
  1276. {
  1277. ThrowIfDisposedAndClosed ();
  1278. ThrowIfBufferNull (buffer);
  1279. ThrowIfBufferOutOfRange (buffer, offset, size);
  1280. if (remoteEP == null)
  1281. throw new ArgumentNullException ("remoteEP");
  1282. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveFrom) {
  1283. Buffer = buffer,
  1284. Offset = offset,
  1285. Size = size,
  1286. SockFlags = socketFlags,
  1287. EndPoint = remoteEP,
  1288. };
  1289. QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));
  1290. return sockares;
  1291. }
  1292. static IOAsyncCallback BeginReceiveFromCallback = new IOAsyncCallback (ares => {
  1293. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1294. int total = 0;
  1295. try {
  1296. SocketError errorCode;
  1297. total = sockares.socket.ReceiveFrom (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, out errorCode);
  1298. if (errorCode != SocketError.Success) {
  1299. sockares.Complete (new SocketException (errorCode));
  1300. return;
  1301. }
  1302. } catch (Exception e) {
  1303. sockares.Complete (e);
  1304. return;
  1305. }
  1306. sockares.Complete (total);
  1307. });
  1308. public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
  1309. {
  1310. ThrowIfDisposedAndClosed ();
  1311. if (endPoint == null)
  1312. throw new ArgumentNullException ("endPoint");
  1313. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceiveFrom", "asyncResult");
  1314. if (!sockares.IsCompleted)
  1315. sockares.AsyncWaitHandle.WaitOne();
  1316. sockares.CheckIfThrowDelayedException();
  1317. endPoint = sockares.EndPoint;
  1318. return sockares.Total;
  1319. }
  1320. static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking)
  1321. {
  1322. try {
  1323. safeHandle.RegisterForBlockingSyscall ();
  1324. return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error, blocking);
  1325. } finally {
  1326. safeHandle.UnRegisterForBlockingSyscall ();
  1327. }
  1328. }
  1329. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1330. extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking);
  1331. #endregion
  1332. #region ReceiveMessageFrom
  1333. [MonoTODO ("Not implemented")]
  1334. public int ReceiveMessageFrom (byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
  1335. {
  1336. ThrowIfDisposedAndClosed ();
  1337. ThrowIfBufferNull (buffer);
  1338. ThrowIfBufferOutOfRange (buffer, offset, size);
  1339. if (remoteEP == null)
  1340. throw new ArgumentNullException ("remoteEP");
  1341. // FIXME: figure out how we get hold of the IPPacketInformation
  1342. throw new NotImplementedException ();
  1343. }
  1344. [MonoTODO ("Not implemented")]
  1345. public bool ReceiveMessageFromAsync (SocketAsyncEventArgs e)
  1346. {
  1347. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1348. ThrowIfDisposedAndClosed ();
  1349. throw new NotImplementedException ();
  1350. }
  1351. [MonoTODO]
  1352. public IAsyncResult BeginReceiveMessageFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
  1353. {
  1354. ThrowIfDisposedAndClosed ();
  1355. ThrowIfBufferNull (buffer);
  1356. ThrowIfBufferOutOfRange (buffer, offset, size);
  1357. if (remoteEP == null)
  1358. throw new ArgumentNullException ("remoteEP");
  1359. throw new NotImplementedException ();
  1360. }
  1361. [MonoTODO]
  1362. public int EndReceiveMessageFrom (IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
  1363. {
  1364. ThrowIfDisposedAndClosed ();
  1365. if (endPoint == null)
  1366. throw new ArgumentNullException ("endPoint");
  1367. /*SocketAsyncResult sockares =*/ ValidateEndIAsyncResult (asyncResult, "EndReceiveMessageFrom", "asyncResult");
  1368. throw new NotImplementedException ();
  1369. }
  1370. #endregion
  1371. #region Send
  1372. public int Send (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
  1373. {
  1374. ThrowIfDisposedAndClosed ();
  1375. ThrowIfBufferNull (buffer);
  1376. ThrowIfBufferOutOfRange (buffer, offset, size);
  1377. if (size == 0) {
  1378. errorCode = SocketError.Success;
  1379. return 0;
  1380. }
  1381. int nativeError;
  1382. int sent = 0;
  1383. do {
  1384. sent += Send_internal (
  1385. m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError, is_blocking);
  1386. errorCode = (SocketError)nativeError;
  1387. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
  1388. is_connected = false;
  1389. is_bound = false;
  1390. break;
  1391. } else {
  1392. is_connected = true;
  1393. }
  1394. } while (sent < size);
  1395. return sent;
  1396. }
  1397. [CLSCompliant (false)]
  1398. public int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
  1399. {
  1400. ThrowIfDisposedAndClosed ();
  1401. if (buffers == null)
  1402. throw new ArgumentNullException ("buffers");
  1403. if (buffers.Count == 0)
  1404. throw new ArgumentException ("Buffer is empty", "buffers");
  1405. int numsegments = buffers.Count;
  1406. int nativeError;
  1407. int ret;
  1408. WSABUF[] bufarray = new WSABUF[numsegments];
  1409. GCHandle[] gch = new GCHandle[numsegments];
  1410. for(int i = 0; i < numsegments; i++) {
  1411. ArraySegment<byte> segment = buffers[i];
  1412. if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
  1413. throw new ArgumentOutOfRangeException ("segment");
  1414. gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
  1415. bufarray[i].len = segment.Count;
  1416. bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
  1417. }
  1418. try {
  1419. ret = Send_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
  1420. } finally {
  1421. for(int i = 0; i < numsegments; i++) {
  1422. if (gch[i].IsAllocated) {
  1423. gch[i].Free ();
  1424. }
  1425. }
  1426. }
  1427. errorCode = (SocketError)nativeError;
  1428. return ret;
  1429. }
  1430. public bool SendAsync (SocketAsyncEventArgs e)
  1431. {
  1432. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1433. ThrowIfDisposedAndClosed ();
  1434. if (e.Buffer == null && e.BufferList == null)
  1435. throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
  1436. if (e.Buffer == null) {
  1437. InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.SendGeneric);
  1438. e.socket_async_result.Buffers = e.BufferList;
  1439. QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
  1440. } else {
  1441. InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.Send);
  1442. e.socket_async_result.Buffer = e.Buffer;
  1443. e.socket_async_result.Offset = e.Offset;
  1444. e.socket_async_result.Size = e.Count;
  1445. QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
  1446. }
  1447. return true;
  1448. }
  1449. static AsyncCallback SendAsyncCallback = new AsyncCallback (ares => {
  1450. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1451. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1452. throw new InvalidOperationException ("No operation in progress");
  1453. try {
  1454. e.BytesTransferred = e.current_socket.EndSend (ares);
  1455. } catch (SocketException se){
  1456. e.SocketError = se.SocketErrorCode;
  1457. } catch (ObjectDisposedException) {
  1458. e.SocketError = SocketError.OperationAborted;
  1459. } finally {
  1460. e.Complete ();
  1461. }
  1462. });
  1463. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1464. {
  1465. ThrowIfDisposedAndClosed ();
  1466. ThrowIfBufferNull (buffer);
  1467. ThrowIfBufferOutOfRange (buffer, offset, size);
  1468. if (!is_connected) {
  1469. errorCode = SocketError.NotConnected;
  1470. return null;
  1471. }
  1472. errorCode = SocketError.Success;
  1473. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Send) {
  1474. Buffer = buffer,
  1475. Offset = offset,
  1476. Size = size,
  1477. SockFlags = socketFlags,
  1478. };
  1479. QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));
  1480. return sockares;
  1481. }
  1482. static void BeginSendCallback (SocketAsyncResult sockares, int sent_so_far)
  1483. {
  1484. int total = 0;
  1485. try {
  1486. total = Socket.Send_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, false);
  1487. } catch (Exception e) {
  1488. sockares.Complete (e);
  1489. return;
  1490. }
  1491. if (sockares.error == 0) {
  1492. sent_so_far += total;
  1493. sockares.Offset += total;
  1494. sockares.Size -= total;
  1495. if (sockares.socket.CleanedUp) {
  1496. sockares.Complete (total);
  1497. return;
  1498. }
  1499. if (sockares.Size > 0) {
  1500. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, sent_so_far), sockares));
  1501. return; // Have to finish writing everything. See bug #74475.
  1502. }
  1503. sockares.Total = sent_so_far;
  1504. }
  1505. sockares.Complete (total);
  1506. }
  1507. [CLSCompliant (false)]
  1508. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1509. {
  1510. ThrowIfDisposedAndClosed ();
  1511. if (buffers == null)
  1512. throw new ArgumentNullException ("buffers");
  1513. if (!is_connected) {
  1514. errorCode = SocketError.NotConnected;
  1515. return null;
  1516. }
  1517. errorCode = SocketError.Success;
  1518. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendGeneric) {
  1519. Buffers = buffers,
  1520. SockFlags = socketFlags,
  1521. };
  1522. QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));
  1523. return sockares;
  1524. }
  1525. static IOAsyncCallback BeginSendGenericCallback = new IOAsyncCallback (ares => {
  1526. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1527. int total = 0;
  1528. try {
  1529. total = sockares.socket.Send (sockares.Buffers, sockares.SockFlags);
  1530. } catch (Exception e) {
  1531. sockares.Complete (e);
  1532. return;
  1533. }
  1534. sockares.Complete (total);
  1535. });
  1536. public int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
  1537. {
  1538. ThrowIfDisposedAndClosed ();
  1539. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSend", "asyncResult");
  1540. if (!sockares.IsCompleted)
  1541. sockares.AsyncWaitHandle.WaitOne ();
  1542. errorCode = sockares.ErrorCode;
  1543. if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
  1544. is_connected = false;
  1545. /* If no socket error occurred, call CheckIfThrowDelayedException in
  1546. * case there are other kinds of exceptions that should be thrown.*/
  1547. if (errorCode == SocketError.Success)
  1548. sockares.CheckIfThrowDelayedException ();
  1549. return sockares.Total;
  1550. }
  1551. static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
  1552. {
  1553. try {
  1554. safeHandle.RegisterForBlockingSyscall ();
  1555. return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
  1556. } finally {
  1557. safeHandle.UnRegisterForBlockingSyscall ();
  1558. }
  1559. }
  1560. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  1561. extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
  1562. static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking)
  1563. {
  1564. try {
  1565. safeHandle.RegisterForBlockingSyscall ();
  1566. return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error, blocking);
  1567. } finally {
  1568. safeHandle.UnRegisterForBlockingSyscall ();
  1569. }
  1570. }
  1571. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1572. extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking);
  1573. #endregion
  1574. #region SendTo
  1575. public int SendTo (byte [] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
  1576. {
  1577. ThrowIfDisposedAndClosed ();
  1578. ThrowIfBufferNull (buffer);
  1579. ThrowIfBufferOutOfRange (buffer, offset, size);
  1580. if (remoteEP == null)
  1581. throw new ArgumentNullException("remoteEP");
  1582. int error;
  1583. int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
  1584. SocketError err = (SocketError) error;
  1585. if (err != 0) {
  1586. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  1587. is_connected = false;
  1588. throw new SocketException (error);
  1589. }
  1590. is_connected = true;
  1591. is_bound = true;
  1592. seed_endpoint = remoteEP;
  1593. return ret;
  1594. }
  1595. public bool SendToAsync (SocketAsyncEventArgs e)
  1596. {
  1597. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1598. ThrowIfDisposedAndClosed ();
  1599. if (e.BufferList != null)
  1600. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  1601. if (e.RemoteEndPoint == null)
  1602. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  1603. InitSocketAsyncEventArgs (e, SendToAsyncCallback, e, SocketOperation.SendTo);
  1604. e.socket_async_result.Buffer = e.Buffer;
  1605. e.socket_async_result.Offset = e.Offset;
  1606. e.socket_async_result.Size = e.Count;
  1607. e.socket_async_result.SockFlags = e.SocketFlags;
  1608. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  1609. QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
  1610. return true;
  1611. }
  1612. static AsyncCallback SendToAsyncCallback = new AsyncCallback (ares => {
  1613. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1614. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1615. throw new InvalidOperationException ("No operation in progress");
  1616. try {
  1617. e.BytesTransferred = e.current_socket.EndSendTo (ares);
  1618. } catch (SocketException ex) {
  1619. e.SocketError = ex.SocketErrorCode;
  1620. } catch (ObjectDisposedException) {
  1621. e.SocketError = SocketError.OperationAborted;
  1622. } finally {
  1623. e.Complete ();
  1624. }
  1625. });
  1626. public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
  1627. {
  1628. ThrowIfDisposedAndClosed ();
  1629. ThrowIfBufferNull (buffer);
  1630. ThrowIfBufferOutOfRange (buffer, offset, size);
  1631. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendTo) {
  1632. Buffer = buffer,
  1633. Offset = offset,
  1634. Size = size,
  1635. SockFlags = socketFlags,
  1636. EndPoint = remoteEP,
  1637. };
  1638. QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));
  1639. return sockares;
  1640. }
  1641. static void BeginSendToCallback (SocketAsyncResult sockares, int sent_so_far)
  1642. {
  1643. int total = 0;
  1644. try {
  1645. total = sockares.socket.SendTo (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);
  1646. if (sockares.error == 0) {
  1647. sent_so_far += total;
  1648. sockares.Offset += total;
  1649. sockares.Size -= total;
  1650. }
  1651. if (sockares.Size > 0) {
  1652. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, sent_so_far), sockares));
  1653. return; // Have to finish writing everything. See bug #74475.
  1654. }
  1655. sockares.Total = sent_so_far;
  1656. } catch (Exception e) {
  1657. sockares.Complete (e);
  1658. return;
  1659. }
  1660. sockares.Complete ();
  1661. }
  1662. public int EndSendTo (IAsyncResult asyncResult)
  1663. {
  1664. ThrowIfDisposedAndClosed ();
  1665. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSendTo", "result");
  1666. if (!sockares.IsCompleted)
  1667. sockares.AsyncWaitHandle.WaitOne();
  1668. sockares.CheckIfThrowDelayedException();
  1669. return sockares.Total;
  1670. }
  1671. static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking)
  1672. {
  1673. try {
  1674. safeHandle.RegisterForBlockingSyscall ();
  1675. return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error, blocking);
  1676. } finally {
  1677. safeHandle.UnRegisterForBlockingSyscall ();
  1678. }
  1679. }
  1680. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1681. extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking);
  1682. #endregion
  1683. #region SendFile
  1684. public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
  1685. {
  1686. ThrowIfDisposedAndClosed ();
  1687. if (!is_connected)
  1688. throw new NotSupportedException ();
  1689. if (!is_blocking)
  1690. throw new InvalidOperationException ();
  1691. int error = 0;
  1692. if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags, out error, is_blocking) || error != 0) {
  1693. SocketException exc = new SocketException (error);
  1694. if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
  1695. throw new FileNotFoundException ();
  1696. throw exc;
  1697. }
  1698. }
  1699. public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
  1700. {
  1701. ThrowIfDisposedAndClosed ();
  1702. if (!is_connected)
  1703. throw new NotSupportedException ();
  1704. if (!File.Exists (fileName))
  1705. throw new FileNotFoundException ();
  1706. SendFileHandler handler = new SendFileHandler (SendFile);
  1707. return new SendFileAsyncResult (handler, handler.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => callback (new SendFileAsyncResult (handler, ar)), state));
  1708. }
  1709. public void EndSendFile (IAsyncResult asyncResult)
  1710. {
  1711. ThrowIfDisposedAndClosed ();
  1712. if (asyncResult == null)
  1713. throw new ArgumentNullException ("asyncResult");
  1714. SendFileAsyncResult ares = asyncResult as SendFileAsyncResult;
  1715. if (ares == null)
  1716. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1717. ares.Delegate.EndInvoke (ares.Original);
  1718. }
  1719. static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking)
  1720. {
  1721. try {
  1722. safeHandle.RegisterForBlockingSyscall ();
  1723. return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags, out error, blocking);
  1724. } finally {
  1725. safeHandle.UnRegisterForBlockingSyscall ();
  1726. }
  1727. }
  1728. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1729. extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking);
  1730. delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);
  1731. sealed class SendFileAsyncResult : IAsyncResult {
  1732. IAsyncResult ares;
  1733. SendFileHandler d;
  1734. public SendFileAsyncResult (SendFileHandler d, IAsyncResult ares)
  1735. {
  1736. this.d = d;
  1737. this.ares = ares;
  1738. }
  1739. public object AsyncState {
  1740. get { return ares.AsyncState; }
  1741. }
  1742. public WaitHandle AsyncWaitHandle {
  1743. get { return ares.AsyncWaitHandle; }
  1744. }
  1745. public bool CompletedSynchronously {
  1746. get { return ares.CompletedSynchronously; }
  1747. }
  1748. public bool IsCompleted {
  1749. get { return ares.IsCompleted; }
  1750. }
  1751. public SendFileHandler Delegate {
  1752. get { return d; }
  1753. }
  1754. public IAsyncResult Original {
  1755. get { return ares; }
  1756. }
  1757. }
  1758. #endregion
  1759. #region SendPackets
  1760. [MonoTODO ("Not implemented")]
  1761. public bool SendPacketsAsync (SocketAsyncEventArgs e)
  1762. {
  1763. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1764. ThrowIfDisposedAndClosed ();
  1765. throw new NotImplementedException ();
  1766. }
  1767. #endregion
  1768. #region DuplicateAndClose
  1769. [MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
  1770. public SocketInformation DuplicateAndClose (int targetProcessId)
  1771. {
  1772. var si = new SocketInformation ();
  1773. si.Options =
  1774. (is_listening ? SocketInformationOptions.Listening : 0) |
  1775. (is_connected ? SocketInformationOptions.Connected : 0) |
  1776. (is_blocking ? 0 : SocketInformationOptions.NonBlocking) |
  1777. (useOverlappedIO ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
  1778. MonoIOError error;
  1779. IntPtr duplicateHandle;
  1780. if (!MonoIO.DuplicateHandle (System.Diagnostics.Process.GetCurrentProcess ().Handle, Handle, new IntPtr (targetProcessId), out duplicateHandle, 0, 0, 0x00000002 /* DUPLICATE_SAME_ACCESS */, out error))
  1781. throw MonoIO.GetException (error);
  1782. si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)addressFamily, (int)socketType, (int)protocolType, is_bound ? 1 : 0, (long)duplicateHandle);
  1783. m_Handle = null;
  1784. return si;
  1785. }
  1786. #endregion
  1787. #region GetSocketOption
  1788. public void GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
  1789. {
  1790. ThrowIfDisposedAndClosed ();
  1791. if (optionValue == null)
  1792. throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
  1793. int error;
  1794. GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref optionValue, out error);
  1795. if (error != 0)
  1796. throw new SocketException (error);
  1797. }
  1798. public byte [] GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
  1799. {
  1800. ThrowIfDisposedAndClosed ();
  1801. int error;
  1802. byte[] byte_val = new byte [optionLength];
  1803. GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref byte_val, out error);
  1804. if (error != 0)
  1805. throw new SocketException (error);
  1806. return byte_val;
  1807. }
  1808. public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
  1809. {
  1810. ThrowIfDisposedAndClosed ();
  1811. int error;
  1812. object obj_val;
  1813. GetSocketOption_obj_internal (m_Handle, optionLevel, optionName, out obj_val, out error);
  1814. if (error != 0)
  1815. throw new SocketException (error);
  1816. if (optionName == SocketOptionName.Linger)
  1817. return (LingerOption) obj_val;
  1818. else if (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)
  1819. return (MulticastOption) obj_val;
  1820. else if (obj_val is int)
  1821. return (int) obj_val;
  1822. else
  1823. return obj_val;
  1824. }
  1825. static void GetSocketOption_arr_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error)
  1826. {
  1827. bool release = false;
  1828. try {
  1829. safeHandle.DangerousAddRef (ref release);
  1830. GetSocketOption_arr_internal (safeHandle.DangerousGetHandle (), level, name, ref byte_val, out error);
  1831. } finally {
  1832. if (release)
  1833. safeHandle.DangerousRelease ();
  1834. }
  1835. }
  1836. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1837. extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
  1838. static void GetSocketOption_obj_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error)
  1839. {
  1840. bool release = false;
  1841. try {
  1842. safeHandle.DangerousAddRef (ref release);
  1843. GetSocketOption_obj_internal (safeHandle.DangerousGetHandle (), level, name, out obj_val, out error);
  1844. } finally {
  1845. if (release)
  1846. safeHandle.DangerousRelease ();
  1847. }
  1848. }
  1849. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1850. extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
  1851. #endregion
  1852. #region SetSocketOption
  1853. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
  1854. {
  1855. ThrowIfDisposedAndClosed ();
  1856. // I'd throw an ArgumentNullException, but this is what MS does.
  1857. if (optionValue == null)
  1858. throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
  1859. int error;
  1860. SetSocketOption_internal (m_Handle, optionLevel, optionName, null, optionValue, 0, out error);
  1861. if (error != 0) {
  1862. if (error == (int) SocketError.InvalidArgument)
  1863. throw new ArgumentException ();
  1864. throw new SocketException (error);
  1865. }
  1866. }
  1867. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
  1868. {
  1869. ThrowIfDisposedAndClosed ();
  1870. // NOTE: if a null is passed, the byte[] overload is used instead...
  1871. if (optionValue == null)
  1872. throw new ArgumentNullException("optionValue");
  1873. int error;
  1874. if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger) {
  1875. LingerOption linger = optionValue as LingerOption;
  1876. if (linger == null)
  1877. throw new ArgumentException ("A 'LingerOption' value must be specified.", "optionValue");
  1878. SetSocketOption_internal (m_Handle, optionLevel, optionName, linger, null, 0, out error);
  1879. } else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
  1880. MulticastOption multicast = optionValue as MulticastOption;
  1881. if (multicast == null)
  1882. throw new ArgumentException ("A 'MulticastOption' value must be specified.", "optionValue");
  1883. SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
  1884. } else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
  1885. IPv6MulticastOption multicast = optionValue as IPv6MulticastOption;
  1886. if (multicast == null)
  1887. throw new ArgumentException ("A 'IPv6MulticastOption' value must be specified.", "optionValue");
  1888. SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
  1889. } else {
  1890. throw new ArgumentException ("Invalid value specified.", "optionValue");
  1891. }
  1892. if (error != 0) {
  1893. if (error == (int) SocketError.InvalidArgument)
  1894. throw new ArgumentException ();
  1895. throw new SocketException (error);
  1896. }
  1897. }
  1898. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
  1899. {
  1900. int int_val = optionValue ? 1 : 0;
  1901. SetSocketOption (optionLevel, optionName, int_val);
  1902. }
  1903. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
  1904. {
  1905. ThrowIfDisposedAndClosed ();
  1906. int error;
  1907. SetSocketOption_internal (m_Handle, optionLevel, optionName, null, null, optionValue, out error);
  1908. if (error != 0) {
  1909. if (error == (int) SocketError.InvalidArgument)
  1910. throw new ArgumentException ();
  1911. throw new SocketException (error);
  1912. }
  1913. }
  1914. static void SetSocketOption_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error)
  1915. {
  1916. bool release = false;
  1917. try {
  1918. safeHandle.DangerousAddRef (ref release);
  1919. SetSocketOption_internal (safeHandle.DangerousGetHandle (), level, name, obj_val, byte_val, int_val, out error);
  1920. } finally {
  1921. if (release)
  1922. safeHandle.DangerousRelease ();
  1923. }
  1924. }
  1925. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1926. extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error);
  1927. #endregion
  1928. #region IOControl
  1929. public int IOControl (int ioControlCode, byte [] optionInValue, byte [] optionOutValue)
  1930. {
  1931. if (CleanedUp)
  1932. throw new ObjectDisposedException (GetType ().ToString ());
  1933. int error;
  1934. int result = IOControl_internal (m_Handle, ioControlCode, optionInValue, optionOutValue, out error);
  1935. if (error != 0)
  1936. throw new SocketException (error);
  1937. if (result == -1)
  1938. throw new InvalidOperationException ("Must use Blocking property instead.");
  1939. return result;
  1940. }
  1941. static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
  1942. {
  1943. bool release = false;
  1944. try {
  1945. safeHandle.DangerousAddRef (ref release);
  1946. return IOControl_internal (safeHandle.DangerousGetHandle (), ioctl_code, input, output, out error);
  1947. } finally {
  1948. if (release)
  1949. safeHandle.DangerousRelease ();
  1950. }
  1951. }
  1952. /* See Socket.IOControl, WSAIoctl documentation in MSDN. The common options between UNIX
  1953. * and Winsock are FIONREAD, FIONBIO and SIOCATMARK. Anything else will depend on the system
  1954. * except SIO_KEEPALIVE_VALS which is properly handled on both windows and linux. */
  1955. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1956. extern static int IOControl_internal (IntPtr sock, int ioctl_code, byte [] input, byte [] output, out int error);
  1957. #endregion
  1958. #region Close
  1959. public void Close ()
  1960. {
  1961. linger_timeout = 0;
  1962. Dispose ();
  1963. }
  1964. public void Close (int timeout)
  1965. {
  1966. linger_timeout = timeout;
  1967. Dispose ();
  1968. }
  1969. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1970. internal extern static void Close_internal (IntPtr socket, out int error);
  1971. #endregion
  1972. #region Shutdown
  1973. public void Shutdown (SocketShutdown how)
  1974. {
  1975. ThrowIfDisposedAndClosed ();
  1976. if (!is_connected)
  1977. throw new SocketException (10057); // Not connected
  1978. int error;
  1979. Shutdown_internal (m_Handle, how, out error);
  1980. if (error != 0)
  1981. throw new SocketException (error);
  1982. }
  1983. static void Shutdown_internal (SafeSocketHandle safeHandle, SocketShutdown how, out int error)
  1984. {
  1985. bool release = false;
  1986. try {
  1987. safeHandle.DangerousAddRef (ref release);
  1988. Shutdown_internal (safeHandle.DangerousGetHandle (), how, out error);
  1989. } finally {
  1990. if (release)
  1991. safeHandle.DangerousRelease ();
  1992. }
  1993. }
  1994. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  1995. internal extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
  1996. #endregion
  1997. #region Dispose
  1998. protected virtual void Dispose (bool disposing)
  1999. {
  2000. if (CleanedUp)
  2001. return;
  2002. m_IntCleanedUp = 1;
  2003. bool was_connected = is_connected;
  2004. is_connected = false;
  2005. if (m_Handle != null) {
  2006. is_closed = true;
  2007. IntPtr x = Handle;
  2008. if (was_connected)
  2009. Linger (x);
  2010. m_Handle.Dispose ();
  2011. }
  2012. }
  2013. void Linger (IntPtr handle)
  2014. {
  2015. if (!is_connected || linger_timeout <= 0)
  2016. return;
  2017. /* We don't want to receive any more data */
  2018. int error;
  2019. Shutdown_internal (handle, SocketShutdown.Receive, out error);
  2020. if (error != 0)
  2021. return;
  2022. int seconds = linger_timeout / 1000;
  2023. int ms = linger_timeout % 1000;
  2024. if (ms > 0) {
  2025. /* If the other end closes, this will return 'true' with 'Available' == 0 */
  2026. Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
  2027. if (error != 0)
  2028. return;
  2029. }
  2030. if (seconds > 0) {
  2031. LingerOption linger = new LingerOption (true, seconds);
  2032. SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
  2033. /* Not needed, we're closing upon return */
  2034. //if (error != 0)
  2035. // return;
  2036. }
  2037. }
  2038. #endregion
  2039. void ThrowIfDisposedAndClosed (Socket socket)
  2040. {
  2041. if (socket.CleanedUp && socket.is_closed)
  2042. throw new ObjectDisposedException (socket.GetType ().ToString ());
  2043. }
  2044. void ThrowIfDisposedAndClosed ()
  2045. {
  2046. if (CleanedUp && is_closed)
  2047. throw new ObjectDisposedException (GetType ().ToString ());
  2048. }
  2049. void ThrowIfBufferNull (byte[] buffer)
  2050. {
  2051. if (buffer == null)
  2052. throw new ArgumentNullException ("buffer");
  2053. }
  2054. void ThrowIfBufferOutOfRange (byte[] buffer, int offset, int size)
  2055. {
  2056. if (offset < 0)
  2057. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  2058. if (offset > buffer.Length)
  2059. throw new ArgumentOutOfRangeException ("offset", "offset must be <= buffer.Length");
  2060. if (size < 0)
  2061. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  2062. if (size > buffer.Length - offset)
  2063. throw new ArgumentOutOfRangeException ("size", "size must be <= buffer.Length - offset");
  2064. }
  2065. void ThrowIfUdp ()
  2066. {
  2067. if (protocolType == ProtocolType.Udp)
  2068. throw new SocketException ((int)SocketError.ProtocolOption);
  2069. }
  2070. SocketAsyncResult ValidateEndIAsyncResult (IAsyncResult ares, string methodName, string argName)
  2071. {
  2072. if (ares == null)
  2073. throw new ArgumentNullException (argName);
  2074. SocketAsyncResult sockares = ares as SocketAsyncResult;
  2075. if (sockares == null)
  2076. throw new ArgumentException ("Invalid IAsyncResult", argName);
  2077. if (Interlocked.CompareExchange (ref sockares.EndCalled, 1, 0) == 1)
  2078. throw new InvalidOperationException (methodName + " can only be called once per asynchronous operation");
  2079. return sockares;
  2080. }
  2081. void QueueIOSelectorJob (SemaphoreSlim sem, IntPtr handle, IOSelectorJob job)
  2082. {
  2083. var task = sem.WaitAsync();
  2084. // fast path without Task<Action> allocation.
  2085. if (task.IsCompleted) {
  2086. if (CleanedUp) {
  2087. job.MarkDisposed ();
  2088. return;
  2089. }
  2090. IOSelector.Add (handle, job);
  2091. }
  2092. else
  2093. {
  2094. task.ContinueWith( t => {
  2095. if (CleanedUp) {
  2096. job.MarkDisposed ();
  2097. return;
  2098. }
  2099. IOSelector.Add(handle, job);
  2100. });
  2101. }
  2102. }
  2103. void InitSocketAsyncEventArgs (SocketAsyncEventArgs e, AsyncCallback callback, object state, SocketOperation operation)
  2104. {
  2105. e.socket_async_result.Init (this, callback, state, operation);
  2106. if (e.AcceptSocket != null) {
  2107. e.socket_async_result.AcceptSocket = e.AcceptSocket;
  2108. }
  2109. e.current_socket = this;
  2110. e.SetLastOperation (SocketOperationToSocketAsyncOperation (operation));
  2111. e.SocketError = SocketError.Success;
  2112. e.BytesTransferred = 0;
  2113. }
  2114. SocketAsyncOperation SocketOperationToSocketAsyncOperation (SocketOperation op)
  2115. {
  2116. switch (op) {
  2117. case SocketOperation.Connect:
  2118. return SocketAsyncOperation.Connect;
  2119. case SocketOperation.Accept:
  2120. return SocketAsyncOperation.Accept;
  2121. case SocketOperation.Disconnect:
  2122. return SocketAsyncOperation.Disconnect;
  2123. case SocketOperation.Receive:
  2124. case SocketOperation.ReceiveGeneric:
  2125. return SocketAsyncOperation.Receive;
  2126. case SocketOperation.ReceiveFrom:
  2127. return SocketAsyncOperation.ReceiveFrom;
  2128. case SocketOperation.Send:
  2129. case SocketOperation.SendGeneric:
  2130. return SocketAsyncOperation.Send;
  2131. case SocketOperation.SendTo:
  2132. return SocketAsyncOperation.SendTo;
  2133. default:
  2134. throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
  2135. }
  2136. }
  2137. IPEndPoint RemapIPEndPoint (IPEndPoint input) {
  2138. // If socket is DualMode ensure we automatically handle mapping IPv4 addresses to IPv6.
  2139. if (IsDualMode && input.AddressFamily == AddressFamily.InterNetwork)
  2140. return new IPEndPoint (input.Address.MapToIPv6 (), input.Port);
  2141. return input;
  2142. }
  2143. [StructLayout (LayoutKind.Sequential)]
  2144. struct WSABUF {
  2145. public int len;
  2146. public IntPtr buf;
  2147. }
  2148. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2149. internal static extern void cancel_blocking_socket_operation (Thread thread);
  2150. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2151. internal static extern bool SupportsPortReuse (ProtocolType proto);
  2152. internal static int FamilyHint {
  2153. get {
  2154. // Returns one of
  2155. // MONO_HINT_UNSPECIFIED = 0,
  2156. // MONO_HINT_IPV4 = 1,
  2157. // MONO_HINT_IPV6 = 2,
  2158. int hint = 0;
  2159. if (OSSupportsIPv4) {
  2160. hint = 1;
  2161. }
  2162. if (OSSupportsIPv6) {
  2163. hint = hint == 0 ? 2 : 0;
  2164. }
  2165. return hint;
  2166. }
  2167. }
  2168. static bool IsProtocolSupported (NetworkInterfaceComponent networkInterface)
  2169. {
  2170. #if MOBILE
  2171. return true;
  2172. #else
  2173. var nics = NetworkInterface.GetAllNetworkInterfaces ();
  2174. foreach (var adapter in nics) {
  2175. if (adapter.Supports (networkInterface))
  2176. return true;
  2177. }
  2178. return false;
  2179. #endif
  2180. }
  2181. }
  2182. }