Socket.cs 85 KB

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