Socket.cs 87 KB

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