Socket.cs 85 KB

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