Socket.cs 87 KB

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