Socket.cs 85 KB

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