WebSocket.cs 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122
  1. #region License
  2. /*
  3. * WebSocket.cs
  4. *
  5. * This code is derived from WebSocket.java
  6. * (http://github.com/adamac/Java-WebSocket-client).
  7. *
  8. * The MIT License
  9. *
  10. * Copyright (c) 2009 Adam MacBeth
  11. * Copyright (c) 2010-2022 sta.blockhead
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in
  21. * all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29. * THE SOFTWARE.
  30. */
  31. #endregion
  32. #region Contributors
  33. /*
  34. * Contributors:
  35. * - Frank Razenberg <frank@zzattack.org>
  36. * - David Wood <dpwood@gmail.com>
  37. * - Liryna <liryna.stark@gmail.com>
  38. */
  39. #endregion
  40. using System;
  41. using System.Collections;
  42. using System.Collections.Generic;
  43. using System.Collections.Specialized;
  44. using System.Diagnostics;
  45. using System.IO;
  46. using System.Net.Security;
  47. using System.Net.Sockets;
  48. using System.Security.Cryptography;
  49. using System.Text;
  50. using System.Threading;
  51. using WebSocketSharp.Net;
  52. using WebSocketSharp.Net.WebSockets;
  53. namespace WebSocketSharp
  54. {
  55. /// <summary>
  56. /// Implements the WebSocket interface.
  57. /// </summary>
  58. /// <remarks>
  59. /// <para>
  60. /// This class provides a set of methods and properties for two-way
  61. /// communication using the WebSocket protocol.
  62. /// </para>
  63. /// <para>
  64. /// The WebSocket protocol is defined in
  65. /// <see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>.
  66. /// </para>
  67. /// </remarks>
  68. public class WebSocket : IDisposable
  69. {
  70. #region Private Fields
  71. private AuthenticationChallenge _authChallenge;
  72. private string _base64Key;
  73. private bool _client;
  74. private Action _closeContext;
  75. private CompressionMethod _compression;
  76. private WebSocketContext _context;
  77. private CookieCollection _cookies;
  78. private NetworkCredential _credentials;
  79. private bool _emitOnPing;
  80. private bool _enableRedirection;
  81. private string _extensions;
  82. private bool _extensionsRequested;
  83. private object _forMessageEventQueue;
  84. private object _forPing;
  85. private object _forSend;
  86. private object _forState;
  87. private MemoryStream _fragmentsBuffer;
  88. private bool _fragmentsCompressed;
  89. private Opcode _fragmentsOpcode;
  90. private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  91. private Func<WebSocketContext, string> _handshakeRequestChecker;
  92. private bool _ignoreExtensions;
  93. private bool _inContinuation;
  94. private volatile bool _inMessage;
  95. private volatile Logger _log;
  96. private static readonly int _maxRetryCountForConnect;
  97. private Action<MessageEventArgs> _message;
  98. private Queue<MessageEventArgs> _messageEventQueue;
  99. private uint _nonceCount;
  100. private string _origin;
  101. private ManualResetEvent _pongReceived;
  102. private bool _preAuth;
  103. private string _protocol;
  104. private string[] _protocols;
  105. private bool _protocolsRequested;
  106. private NetworkCredential _proxyCredentials;
  107. private Uri _proxyUri;
  108. private volatile WebSocketState _readyState;
  109. private ManualResetEvent _receivingExited;
  110. private int _retryCountForConnect;
  111. private bool _secure;
  112. private ClientSslConfiguration _sslConfig;
  113. private Stream _stream;
  114. private TcpClient _tcpClient;
  115. private Uri _uri;
  116. private const string _version = "13";
  117. private TimeSpan _waitTime;
  118. #endregion
  119. #region Internal Fields
  120. /// <summary>
  121. /// Represents the empty array of <see cref="byte"/> used internally.
  122. /// </summary>
  123. internal static readonly byte[] EmptyBytes;
  124. /// <summary>
  125. /// Represents the length used to determine whether the data should
  126. /// be fragmented in sending.
  127. /// </summary>
  128. /// <remarks>
  129. /// <para>
  130. /// The data will be fragmented if its length is greater than
  131. /// the value of this field.
  132. /// </para>
  133. /// <para>
  134. /// If you would like to change the value, you must set it to
  135. /// a value between 125 and <c>Int32.MaxValue - 14</c> inclusive.
  136. /// </para>
  137. /// </remarks>
  138. internal static readonly int FragmentLength;
  139. /// <summary>
  140. /// Represents the random number generator used internally.
  141. /// </summary>
  142. internal static readonly RandomNumberGenerator RandomNumber;
  143. #endregion
  144. #region Static Constructor
  145. static WebSocket ()
  146. {
  147. _maxRetryCountForConnect = 10;
  148. EmptyBytes = new byte[0];
  149. FragmentLength = 1016;
  150. RandomNumber = new RNGCryptoServiceProvider ();
  151. }
  152. #endregion
  153. #region Internal Constructors
  154. // As server
  155. internal WebSocket (HttpListenerWebSocketContext context, string protocol)
  156. {
  157. _context = context;
  158. _protocol = protocol;
  159. _closeContext = context.Close;
  160. _log = context.Log;
  161. _message = messages;
  162. _secure = context.IsSecureConnection;
  163. _stream = context.Stream;
  164. _waitTime = TimeSpan.FromSeconds (1);
  165. init ();
  166. }
  167. // As server
  168. internal WebSocket (TcpListenerWebSocketContext context, string protocol)
  169. {
  170. _context = context;
  171. _protocol = protocol;
  172. _closeContext = context.Close;
  173. _log = context.Log;
  174. _message = messages;
  175. _secure = context.IsSecureConnection;
  176. _stream = context.Stream;
  177. _waitTime = TimeSpan.FromSeconds (1);
  178. init ();
  179. }
  180. #endregion
  181. #region Public Constructors
  182. /// <summary>
  183. /// Initializes a new instance of the <see cref="WebSocket"/> class with
  184. /// the specified URL and optionally subprotocols.
  185. /// </summary>
  186. /// <param name="url">
  187. /// <para>
  188. /// A <see cref="string"/> that specifies the URL to which to connect.
  189. /// </para>
  190. /// <para>
  191. /// The scheme of the URL must be ws or wss.
  192. /// </para>
  193. /// <para>
  194. /// The new instance uses a secure connection if the scheme is wss.
  195. /// </para>
  196. /// </param>
  197. /// <param name="protocols">
  198. /// <para>
  199. /// An array of <see cref="string"/> that specifies the names of
  200. /// the subprotocols if necessary.
  201. /// </para>
  202. /// <para>
  203. /// Each value of the array must be a token defined in
  204. /// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">
  205. /// RFC 2616</see>.
  206. /// </para>
  207. /// </param>
  208. /// <exception cref="ArgumentNullException">
  209. /// <paramref name="url"/> is <see langword="null"/>.
  210. /// </exception>
  211. /// <exception cref="ArgumentException">
  212. /// <para>
  213. /// <paramref name="url"/> is an empty string.
  214. /// </para>
  215. /// <para>
  216. /// -or-
  217. /// </para>
  218. /// <para>
  219. /// <paramref name="url"/> is an invalid WebSocket URL string.
  220. /// </para>
  221. /// <para>
  222. /// -or-
  223. /// </para>
  224. /// <para>
  225. /// <paramref name="protocols"/> contains a value that is not a token.
  226. /// </para>
  227. /// <para>
  228. /// -or-
  229. /// </para>
  230. /// <para>
  231. /// <paramref name="protocols"/> contains a value twice.
  232. /// </para>
  233. /// </exception>
  234. public WebSocket (string url, params string[] protocols)
  235. {
  236. if (url == null)
  237. throw new ArgumentNullException ("url");
  238. if (url.Length == 0)
  239. throw new ArgumentException ("An empty string.", "url");
  240. string msg;
  241. if (!url.TryCreateWebSocketUri (out _uri, out msg))
  242. throw new ArgumentException (msg, "url");
  243. if (protocols != null && protocols.Length > 0) {
  244. if (!checkProtocols (protocols, out msg))
  245. throw new ArgumentException (msg, "protocols");
  246. _protocols = protocols;
  247. }
  248. _base64Key = CreateBase64Key ();
  249. _client = true;
  250. _log = new Logger ();
  251. _message = messagec;
  252. _retryCountForConnect = -1;
  253. _secure = _uri.Scheme == "wss";
  254. _waitTime = TimeSpan.FromSeconds (5);
  255. init ();
  256. }
  257. #endregion
  258. #region Internal Properties
  259. internal CookieCollection CookieCollection {
  260. get {
  261. return _cookies;
  262. }
  263. }
  264. // As server
  265. internal Func<WebSocketContext, string> CustomHandshakeRequestChecker {
  266. get {
  267. return _handshakeRequestChecker;
  268. }
  269. set {
  270. _handshakeRequestChecker = value;
  271. }
  272. }
  273. // As server
  274. internal bool IgnoreExtensions {
  275. get {
  276. return _ignoreExtensions;
  277. }
  278. set {
  279. _ignoreExtensions = value;
  280. }
  281. }
  282. #endregion
  283. #region Public Properties
  284. /// <summary>
  285. /// Gets or sets the compression method used to compress a message.
  286. /// </summary>
  287. /// <remarks>
  288. /// The set operation works if the current state of the interface is
  289. /// New or Closed.
  290. /// </remarks>
  291. /// <value>
  292. /// <para>
  293. /// One of the <see cref="CompressionMethod"/> enum values.
  294. /// </para>
  295. /// <para>
  296. /// It indicates the compression method used to compress a message.
  297. /// </para>
  298. /// <para>
  299. /// The default value is <see cref="CompressionMethod.None"/>.
  300. /// </para>
  301. /// </value>
  302. /// <exception cref="InvalidOperationException">
  303. /// The set operation is not available if the interface is not for
  304. /// the client.
  305. /// </exception>
  306. public CompressionMethod Compression {
  307. get {
  308. return _compression;
  309. }
  310. set {
  311. if (!_client) {
  312. var msg = "The interface is not for the client.";
  313. throw new InvalidOperationException (msg);
  314. }
  315. lock (_forState) {
  316. if (!canSet ())
  317. return;
  318. _compression = value;
  319. }
  320. }
  321. }
  322. /// <summary>
  323. /// Gets the HTTP cookies included in the handshake request/response.
  324. /// </summary>
  325. /// <value>
  326. /// <para>
  327. /// An <see cref="T:System.Collections.Generic.IEnumerable{WebSocketSharp.Net.Cookie}"/>
  328. /// instance.
  329. /// </para>
  330. /// <para>
  331. /// It provides an enumerator which supports the iteration over
  332. /// the collection of the cookies.
  333. /// </para>
  334. /// </value>
  335. public IEnumerable<Cookie> Cookies {
  336. get {
  337. lock (_cookies.SyncRoot) {
  338. foreach (var cookie in _cookies)
  339. yield return cookie;
  340. }
  341. }
  342. }
  343. /// <summary>
  344. /// Gets the credentials for the HTTP authentication (Basic/Digest).
  345. /// </summary>
  346. /// <value>
  347. /// <para>
  348. /// A <see cref="NetworkCredential"/> that represents the credentials
  349. /// used to authenticate the client.
  350. /// </para>
  351. /// <para>
  352. /// The default value is <see langword="null"/>.
  353. /// </para>
  354. /// </value>
  355. public NetworkCredential Credentials {
  356. get {
  357. return _credentials;
  358. }
  359. }
  360. /// <summary>
  361. /// Gets or sets a value indicating whether the message event is
  362. /// emitted when the interface receives a ping.
  363. /// </summary>
  364. /// <value>
  365. /// <para>
  366. /// <c>true</c> if the interface emits the message event when
  367. /// receives a ping; otherwise, <c>false</c>.
  368. /// </para>
  369. /// <para>
  370. /// The default value is <c>false</c>.
  371. /// </para>
  372. /// </value>
  373. public bool EmitOnPing {
  374. get {
  375. return _emitOnPing;
  376. }
  377. set {
  378. _emitOnPing = value;
  379. }
  380. }
  381. /// <summary>
  382. /// Gets or sets a value indicating whether the URL redirection for
  383. /// the handshake request is allowed.
  384. /// </summary>
  385. /// <remarks>
  386. /// The set operation works if the current state of the interface is
  387. /// New or Closed.
  388. /// </remarks>
  389. /// <value>
  390. /// <para>
  391. /// <c>true</c> if the interface allows the URL redirection for
  392. /// the handshake request; otherwise, <c>false</c>.
  393. /// </para>
  394. /// <para>
  395. /// The default value is <c>false</c>.
  396. /// </para>
  397. /// </value>
  398. /// <exception cref="InvalidOperationException">
  399. /// The set operation is not available if the interface is not for
  400. /// the client.
  401. /// </exception>
  402. public bool EnableRedirection {
  403. get {
  404. return _enableRedirection;
  405. }
  406. set {
  407. if (!_client) {
  408. var msg = "The interface is not for the client.";
  409. throw new InvalidOperationException (msg);
  410. }
  411. lock (_forState) {
  412. if (!canSet ())
  413. return;
  414. _enableRedirection = value;
  415. }
  416. }
  417. }
  418. /// <summary>
  419. /// Gets the extensions selected by the server.
  420. /// </summary>
  421. /// <value>
  422. /// <para>
  423. /// A <see cref="string"/> that represents a list of the extensions
  424. /// negotiated between the client and server.
  425. /// </para>
  426. /// <para>
  427. /// An empty string if not specified or selected.
  428. /// </para>
  429. /// </value>
  430. public string Extensions {
  431. get {
  432. return _extensions ?? String.Empty;
  433. }
  434. }
  435. /// <summary>
  436. /// Gets a value indicating whether the communication is possible.
  437. /// </summary>
  438. /// <value>
  439. /// <c>true</c> if the communication is possible; otherwise, <c>false</c>.
  440. /// </value>
  441. public bool IsAlive {
  442. get {
  443. return ping (EmptyBytes);
  444. }
  445. }
  446. /// <summary>
  447. /// Gets a value indicating whether the connection is secure.
  448. /// </summary>
  449. /// <value>
  450. /// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
  451. /// </value>
  452. public bool IsSecure {
  453. get {
  454. return _secure;
  455. }
  456. }
  457. /// <summary>
  458. /// Gets the logging function.
  459. /// </summary>
  460. /// <remarks>
  461. /// The default logging level is <see cref="LogLevel.Error"/>.
  462. /// </remarks>
  463. /// <value>
  464. /// A <see cref="Logger"/> that provides the logging function.
  465. /// </value>
  466. public Logger Log {
  467. get {
  468. return _log;
  469. }
  470. internal set {
  471. _log = value;
  472. }
  473. }
  474. /// <summary>
  475. /// Gets or sets the value of the HTTP Origin header to send with
  476. /// the handshake request.
  477. /// </summary>
  478. /// <remarks>
  479. /// <para>
  480. /// The HTTP Origin header is defined in
  481. /// <see href="http://tools.ietf.org/html/rfc6454#section-7">
  482. /// Section 7 of RFC 6454</see>.
  483. /// </para>
  484. /// <para>
  485. /// The interface sends the Origin header if this property has any.
  486. /// </para>
  487. /// <para>
  488. /// The set operation works if the current state of the interface is
  489. /// New or Closed.
  490. /// </para>
  491. /// </remarks>
  492. /// <value>
  493. /// <para>
  494. /// A <see cref="string"/> that represents the value of the Origin
  495. /// header to send.
  496. /// </para>
  497. /// <para>
  498. /// The syntax is &lt;scheme&gt;://&lt;host&gt;[:&lt;port&gt;].
  499. /// </para>
  500. /// <para>
  501. /// The default value is <see langword="null"/>.
  502. /// </para>
  503. /// </value>
  504. /// <exception cref="InvalidOperationException">
  505. /// The set operation is not available if the interface is not for
  506. /// the client.
  507. /// </exception>
  508. /// <exception cref="ArgumentException">
  509. /// <para>
  510. /// The value specified for a set operation is not an absolute URI string.
  511. /// </para>
  512. /// <para>
  513. /// -or-
  514. /// </para>
  515. /// <para>
  516. /// The value specified for a set operation includes the path segments.
  517. /// </para>
  518. /// </exception>
  519. public string Origin {
  520. get {
  521. return _origin;
  522. }
  523. set {
  524. if (!_client) {
  525. var msg = "The interface is not for the client.";
  526. throw new InvalidOperationException (msg);
  527. }
  528. if (!value.IsNullOrEmpty ()) {
  529. Uri uri;
  530. if (!Uri.TryCreate (value, UriKind.Absolute, out uri)) {
  531. var msg = "Not an absolute URI string.";
  532. throw new ArgumentException (msg, "value");
  533. }
  534. if (uri.Segments.Length > 1) {
  535. var msg = "It includes the path segments.";
  536. throw new ArgumentException (msg, "value");
  537. }
  538. }
  539. lock (_forState) {
  540. if (!canSet ())
  541. return;
  542. _origin = !value.IsNullOrEmpty () ? value.TrimEnd ('/') : value;
  543. }
  544. }
  545. }
  546. /// <summary>
  547. /// Gets the name of subprotocol selected by the server.
  548. /// </summary>
  549. /// <value>
  550. /// <para>
  551. /// A <see cref="string"/> that will be one of the names of
  552. /// subprotocols specified by client.
  553. /// </para>
  554. /// <para>
  555. /// An empty string if not specified or selected.
  556. /// </para>
  557. /// </value>
  558. public string Protocol {
  559. get {
  560. return _protocol ?? String.Empty;
  561. }
  562. internal set {
  563. _protocol = value;
  564. }
  565. }
  566. /// <summary>
  567. /// Gets the current state of the interface.
  568. /// </summary>
  569. /// <value>
  570. /// <para>
  571. /// One of the <see cref="WebSocketState"/> enum values.
  572. /// </para>
  573. /// <para>
  574. /// It indicates the current state of the interface.
  575. /// </para>
  576. /// <para>
  577. /// The default value is <see cref="WebSocketState.New"/>.
  578. /// </para>
  579. /// </value>
  580. public WebSocketState ReadyState {
  581. get {
  582. return _readyState;
  583. }
  584. }
  585. /// <summary>
  586. /// Gets the configuration for secure connection.
  587. /// </summary>
  588. /// <remarks>
  589. /// The configuration is used when the interface attempts to connect,
  590. /// so it must be configured before any connect method is called.
  591. /// </remarks>
  592. /// <value>
  593. /// A <see cref="ClientSslConfiguration"/> that represents the
  594. /// configuration used to establish a secure connection.
  595. /// </value>
  596. /// <exception cref="InvalidOperationException">
  597. /// <para>
  598. /// The interface is not for the client.
  599. /// </para>
  600. /// <para>
  601. /// -or-
  602. /// </para>
  603. /// <para>
  604. /// The interface does not use a secure connection.
  605. /// </para>
  606. /// </exception>
  607. public ClientSslConfiguration SslConfiguration {
  608. get {
  609. if (!_client) {
  610. var msg = "The interface is not for the client.";
  611. throw new InvalidOperationException (msg);
  612. }
  613. if (!_secure) {
  614. var msg = "The interface does not use a secure connection.";
  615. throw new InvalidOperationException (msg);
  616. }
  617. return getSslConfiguration ();
  618. }
  619. }
  620. /// <summary>
  621. /// Gets the URL to which to connect.
  622. /// </summary>
  623. /// <value>
  624. /// <para>
  625. /// A <see cref="Uri"/> that represents the URL to which to connect.
  626. /// </para>
  627. /// <para>
  628. /// Also it represents the URL requested by the client if the interface
  629. /// is for the server.
  630. /// </para>
  631. /// </value>
  632. public Uri Url {
  633. get {
  634. return _client ? _uri : _context.RequestUri;
  635. }
  636. }
  637. /// <summary>
  638. /// Gets or sets the time to wait for the response to the ping or close.
  639. /// </summary>
  640. /// <remarks>
  641. /// The set operation works if the current state of the interface is
  642. /// New or Closed.
  643. /// </remarks>
  644. /// <value>
  645. /// <para>
  646. /// A <see cref="TimeSpan"/> that represents the time to wait for
  647. /// the response.
  648. /// </para>
  649. /// <para>
  650. /// The default value is the same as 5 seconds if the interface is
  651. /// for the client.
  652. /// </para>
  653. /// </value>
  654. /// <exception cref="ArgumentOutOfRangeException">
  655. /// The value specified for a set operation is zero or less.
  656. /// </exception>
  657. public TimeSpan WaitTime {
  658. get {
  659. return _waitTime;
  660. }
  661. set {
  662. if (value <= TimeSpan.Zero) {
  663. var msg = "Zero or less.";
  664. throw new ArgumentOutOfRangeException ("value", msg);
  665. }
  666. lock (_forState) {
  667. if (!canSet ())
  668. return;
  669. _waitTime = value;
  670. }
  671. }
  672. }
  673. #endregion
  674. #region Public Events
  675. /// <summary>
  676. /// Occurs when the connection has been closed.
  677. /// </summary>
  678. public event EventHandler<CloseEventArgs> OnClose;
  679. /// <summary>
  680. /// Occurs when the interface gets an error.
  681. /// </summary>
  682. public event EventHandler<ErrorEventArgs> OnError;
  683. /// <summary>
  684. /// Occurs when the interface receives a message.
  685. /// </summary>
  686. public event EventHandler<MessageEventArgs> OnMessage;
  687. /// <summary>
  688. /// Occurs when the connection has been established.
  689. /// </summary>
  690. public event EventHandler OnOpen;
  691. #endregion
  692. #region Private Methods
  693. private void abort (string reason, Exception exception)
  694. {
  695. var code = exception is WebSocketException
  696. ? ((WebSocketException) exception).Code
  697. : (ushort) 1006;
  698. abort (code, reason);
  699. }
  700. private void abort (ushort code, string reason)
  701. {
  702. var data = new PayloadData (code, reason);
  703. close (data, false, false);
  704. }
  705. // As server
  706. private bool accept ()
  707. {
  708. lock (_forState) {
  709. if (_readyState == WebSocketState.Open) {
  710. _log.Trace ("The connection has already been established.");
  711. return false;
  712. }
  713. if (_readyState == WebSocketState.Closing) {
  714. _log.Error ("The close process is in progress.");
  715. error ("An error has occurred before accepting.", null);
  716. return false;
  717. }
  718. if (_readyState == WebSocketState.Closed) {
  719. _log.Error ("The connection has been closed.");
  720. error ("An error has occurred before accepting.", null);
  721. return false;
  722. }
  723. _readyState = WebSocketState.Connecting;
  724. var accepted = false;
  725. try {
  726. accepted = acceptHandshake ();
  727. }
  728. catch (Exception ex) {
  729. _log.Fatal (ex.Message);
  730. _log.Debug (ex.ToString ());
  731. abort (1011, "An exception has occurred while accepting.");
  732. }
  733. if (!accepted)
  734. return false;
  735. _readyState = WebSocketState.Open;
  736. return true;
  737. }
  738. }
  739. // As server
  740. private bool acceptHandshake ()
  741. {
  742. string msg;
  743. if (!checkHandshakeRequest (_context, out msg)) {
  744. _log.Error (msg);
  745. _log.Debug (_context.ToString ());
  746. refuseHandshake (1002, "A handshake error has occurred.");
  747. return false;
  748. }
  749. if (!customCheckHandshakeRequest (_context, out msg)) {
  750. _log.Error (msg);
  751. _log.Debug (_context.ToString ());
  752. refuseHandshake (1002, "A handshake error has occurred.");
  753. return false;
  754. }
  755. _base64Key = _context.Headers["Sec-WebSocket-Key"];
  756. if (_protocol != null) {
  757. var matched = _context
  758. .SecWebSocketProtocols
  759. .Contains (p => p == _protocol);
  760. if (!matched)
  761. _protocol = null;
  762. }
  763. if (!_ignoreExtensions) {
  764. var val = _context.Headers["Sec-WebSocket-Extensions"];
  765. processSecWebSocketExtensionsClientHeader (val);
  766. }
  767. createHandshakeResponse ().WriteTo (_stream);
  768. return true;
  769. }
  770. private bool canSet ()
  771. {
  772. return _readyState == WebSocketState.New
  773. || _readyState == WebSocketState.Closed;
  774. }
  775. // As server
  776. private bool checkHandshakeRequest (
  777. WebSocketContext context, out string message
  778. )
  779. {
  780. message = null;
  781. if (!context.IsWebSocketRequest) {
  782. message = "Not a WebSocket handshake request.";
  783. return false;
  784. }
  785. var headers = context.Headers;
  786. var key = headers["Sec-WebSocket-Key"];
  787. if (key == null) {
  788. message = "The Sec-WebSocket-Key header is non-existent.";
  789. return false;
  790. }
  791. if (key.Length == 0) {
  792. message = "The Sec-WebSocket-Key header is invalid.";
  793. return false;
  794. }
  795. var ver = headers["Sec-WebSocket-Version"];
  796. if (ver == null) {
  797. message = "The Sec-WebSocket-Version header is non-existent.";
  798. return false;
  799. }
  800. if (ver != _version) {
  801. message = "The Sec-WebSocket-Version header is invalid.";
  802. return false;
  803. }
  804. var subps = headers["Sec-WebSocket-Protocol"];
  805. if (subps != null) {
  806. if (subps.Length == 0) {
  807. message = "The Sec-WebSocket-Protocol header is invalid.";
  808. return false;
  809. }
  810. }
  811. if (!_ignoreExtensions) {
  812. var exts = headers["Sec-WebSocket-Extensions"];
  813. if (exts != null) {
  814. if (exts.Length == 0) {
  815. message = "The Sec-WebSocket-Extensions header is invalid.";
  816. return false;
  817. }
  818. }
  819. }
  820. return true;
  821. }
  822. // As client
  823. private bool checkHandshakeResponse (
  824. HttpResponse response, out string message
  825. )
  826. {
  827. message = null;
  828. if (response.IsRedirect) {
  829. message = "The redirection is indicated.";
  830. return false;
  831. }
  832. if (response.IsUnauthorized) {
  833. message = "The authentication is required.";
  834. return false;
  835. }
  836. if (!response.IsWebSocketResponse) {
  837. message = "Not a WebSocket handshake response.";
  838. return false;
  839. }
  840. var headers = response.Headers;
  841. var key = headers["Sec-WebSocket-Accept"];
  842. if (key == null) {
  843. message = "The Sec-WebSocket-Accept header is non-existent.";
  844. return false;
  845. }
  846. if (key != CreateResponseKey (_base64Key)) {
  847. message = "The Sec-WebSocket-Accept header is invalid.";
  848. return false;
  849. }
  850. var ver = headers["Sec-WebSocket-Version"];
  851. if (ver != null) {
  852. if (ver != _version) {
  853. message = "The Sec-WebSocket-Version header is invalid.";
  854. return false;
  855. }
  856. }
  857. var subp = headers["Sec-WebSocket-Protocol"];
  858. if (subp == null) {
  859. if (_protocolsRequested) {
  860. message = "The Sec-WebSocket-Protocol header is non-existent.";
  861. return false;
  862. }
  863. }
  864. else {
  865. var valid = _protocolsRequested
  866. && subp.Length > 0
  867. && _protocols.Contains (p => p == subp);
  868. if (!valid) {
  869. message = "The Sec-WebSocket-Protocol header is invalid.";
  870. return false;
  871. }
  872. }
  873. var exts = headers["Sec-WebSocket-Extensions"];
  874. if (exts != null) {
  875. if (!validateSecWebSocketExtensionsServerHeader (exts)) {
  876. message = "The Sec-WebSocket-Extensions header is invalid.";
  877. return false;
  878. }
  879. }
  880. return true;
  881. }
  882. private static bool checkProtocols (string[] protocols, out string message)
  883. {
  884. message = null;
  885. Func<string, bool> cond = p => p.IsNullOrEmpty () || !p.IsToken ();
  886. if (protocols.Contains (cond)) {
  887. message = "It contains a value that is not a token.";
  888. return false;
  889. }
  890. if (protocols.ContainsTwice ()) {
  891. message = "It contains a value twice.";
  892. return false;
  893. }
  894. return true;
  895. }
  896. // As client
  897. private bool checkProxyConnectResponse (
  898. HttpResponse response, out string message
  899. )
  900. {
  901. message = null;
  902. if (response.IsProxyAuthenticationRequired) {
  903. message = "The proxy authentication is required.";
  904. return false;
  905. }
  906. if (!response.IsSuccess) {
  907. message = "The proxy has failed a connection to the requested URL.";
  908. return false;
  909. }
  910. return true;
  911. }
  912. private bool checkReceivedFrame (WebSocketFrame frame, out string message)
  913. {
  914. message = null;
  915. if (frame.IsMasked) {
  916. if (_client) {
  917. message = "A frame from the server is masked.";
  918. return false;
  919. }
  920. }
  921. else {
  922. if (!_client) {
  923. message = "A frame from a client is not masked.";
  924. return false;
  925. }
  926. }
  927. if (frame.IsCompressed) {
  928. if (_compression == CompressionMethod.None) {
  929. message = "A frame is compressed without any agreement for it.";
  930. return false;
  931. }
  932. if (!frame.IsData) {
  933. message = "A non data frame is compressed.";
  934. return false;
  935. }
  936. }
  937. if (frame.IsData) {
  938. if (_inContinuation) {
  939. message = "A data frame was received while receiving continuation frames.";
  940. return false;
  941. }
  942. }
  943. if (frame.IsControl) {
  944. if (frame.Fin == Fin.More) {
  945. message = "A control frame is fragmented.";
  946. return false;
  947. }
  948. if (frame.PayloadLength > 125) {
  949. message = "The payload length of a control frame is greater than 125.";
  950. return false;
  951. }
  952. }
  953. if (frame.Rsv2 == Rsv.On) {
  954. message = "The RSV2 of a frame is non-zero without any negotiation for it.";
  955. return false;
  956. }
  957. if (frame.Rsv3 == Rsv.On) {
  958. message = "The RSV3 of a frame is non-zero without any negotiation for it.";
  959. return false;
  960. }
  961. return true;
  962. }
  963. private void close (ushort code, string reason)
  964. {
  965. if (_readyState == WebSocketState.Closing) {
  966. _log.Trace ("The close process is already in progress.");
  967. return;
  968. }
  969. if (_readyState == WebSocketState.Closed) {
  970. _log.Trace ("The connection has already been closed.");
  971. return;
  972. }
  973. if (code == 1005) {
  974. close (PayloadData.Empty, true, false);
  975. return;
  976. }
  977. var data = new PayloadData (code, reason);
  978. var send = !code.IsReservedStatusCode ();
  979. close (data, send, false);
  980. }
  981. private void close (PayloadData payloadData, bool send, bool received)
  982. {
  983. lock (_forState) {
  984. if (_readyState == WebSocketState.Closing) {
  985. _log.Trace ("The close process is already in progress.");
  986. return;
  987. }
  988. if (_readyState == WebSocketState.Closed) {
  989. _log.Trace ("The connection has already been closed.");
  990. return;
  991. }
  992. send = send && _readyState == WebSocketState.Open;
  993. _readyState = WebSocketState.Closing;
  994. }
  995. _log.Trace ("Begin closing the connection.");
  996. var res = closeHandshake (payloadData, send, received);
  997. releaseResources ();
  998. _log.Trace ("End closing the connection.");
  999. _readyState = WebSocketState.Closed;
  1000. var e = new CloseEventArgs (payloadData, res);
  1001. try {
  1002. OnClose.Emit (this, e);
  1003. }
  1004. catch (Exception ex) {
  1005. _log.Error (ex.Message);
  1006. _log.Debug (ex.ToString ());
  1007. }
  1008. }
  1009. private void closeAsync (ushort code, string reason)
  1010. {
  1011. if (_readyState == WebSocketState.Closing) {
  1012. _log.Trace ("The close process is already in progress.");
  1013. return;
  1014. }
  1015. if (_readyState == WebSocketState.Closed) {
  1016. _log.Trace ("The connection has already been closed.");
  1017. return;
  1018. }
  1019. if (code == 1005) {
  1020. closeAsync (PayloadData.Empty, true, false);
  1021. return;
  1022. }
  1023. var data = new PayloadData (code, reason);
  1024. var send = !code.IsReservedStatusCode ();
  1025. closeAsync (data, send, false);
  1026. }
  1027. private void closeAsync (PayloadData payloadData, bool send, bool received)
  1028. {
  1029. Action<PayloadData, bool, bool> closer = close;
  1030. closer.BeginInvoke (
  1031. payloadData, send, received, ar => closer.EndInvoke (ar), null
  1032. );
  1033. }
  1034. private bool closeHandshake (
  1035. PayloadData payloadData, bool send, bool received
  1036. )
  1037. {
  1038. var sent = false;
  1039. if (send) {
  1040. var frame = WebSocketFrame.CreateCloseFrame (payloadData, _client);
  1041. var bytes = frame.ToArray ();
  1042. sent = sendBytes (bytes);
  1043. if (_client)
  1044. frame.Unmask ();
  1045. }
  1046. var wait = !received && sent && _receivingExited != null;
  1047. if (wait)
  1048. received = _receivingExited.WaitOne (_waitTime);
  1049. var ret = sent && received;
  1050. var msg = String.Format (
  1051. "The closing was clean? {0} (sent: {1} received: {2})",
  1052. ret,
  1053. sent,
  1054. received
  1055. );
  1056. _log.Debug (msg);
  1057. return ret;
  1058. }
  1059. // As client
  1060. private bool connect ()
  1061. {
  1062. if (_readyState == WebSocketState.Connecting) {
  1063. _log.Trace ("The connect process is in progress.");
  1064. return false;
  1065. }
  1066. lock (_forState) {
  1067. if (_readyState == WebSocketState.Open) {
  1068. _log.Trace ("The connection has already been established.");
  1069. return false;
  1070. }
  1071. if (_readyState == WebSocketState.Closing) {
  1072. _log.Error ("The close process is in progress.");
  1073. error ("An error has occurred before connecting.", null);
  1074. return false;
  1075. }
  1076. if (_retryCountForConnect >= _maxRetryCountForConnect) {
  1077. _log.Error ("An opportunity for reconnecting has been lost.");
  1078. error ("An error has occurred before connecting.", null);
  1079. return false;
  1080. }
  1081. _retryCountForConnect++;
  1082. _readyState = WebSocketState.Connecting;
  1083. var done = false;
  1084. try {
  1085. done = doHandshake ();
  1086. }
  1087. catch (Exception ex) {
  1088. _log.Fatal (ex.Message);
  1089. _log.Debug (ex.ToString ());
  1090. abort ("An exception has occurred while connecting.", ex);
  1091. }
  1092. if (!done)
  1093. return false;
  1094. _retryCountForConnect = -1;
  1095. _readyState = WebSocketState.Open;
  1096. return true;
  1097. }
  1098. }
  1099. // As client
  1100. private AuthenticationResponse createAuthenticationResponse ()
  1101. {
  1102. if (_credentials == null)
  1103. return null;
  1104. if (_authChallenge != null) {
  1105. var ret = new AuthenticationResponse (
  1106. _authChallenge, _credentials, _nonceCount
  1107. );
  1108. _nonceCount = ret.NonceCount;
  1109. return ret;
  1110. }
  1111. return _preAuth ? new AuthenticationResponse (_credentials) : null;
  1112. }
  1113. // As client
  1114. private string createExtensions ()
  1115. {
  1116. var buff = new StringBuilder (80);
  1117. if (_compression != CompressionMethod.None) {
  1118. var str = _compression.ToExtensionString (
  1119. "server_no_context_takeover", "client_no_context_takeover"
  1120. );
  1121. buff.AppendFormat ("{0}, ", str);
  1122. }
  1123. var len = buff.Length;
  1124. if (len <= 2)
  1125. return null;
  1126. buff.Length = len - 2;
  1127. return buff.ToString ();
  1128. }
  1129. // As server
  1130. private HttpResponse createHandshakeFailureResponse ()
  1131. {
  1132. var ret = HttpResponse.CreateCloseResponse (HttpStatusCode.BadRequest);
  1133. ret.Headers["Sec-WebSocket-Version"] = _version;
  1134. return ret;
  1135. }
  1136. // As client
  1137. private HttpRequest createHandshakeRequest ()
  1138. {
  1139. var ret = HttpRequest.CreateWebSocketHandshakeRequest (_uri);
  1140. var headers = ret.Headers;
  1141. headers["Sec-WebSocket-Key"] = _base64Key;
  1142. headers["Sec-WebSocket-Version"] = _version;
  1143. if (!_origin.IsNullOrEmpty ())
  1144. headers["Origin"] = _origin;
  1145. if (_protocols != null) {
  1146. headers["Sec-WebSocket-Protocol"] = _protocols.ToString (", ");
  1147. _protocolsRequested = true;
  1148. }
  1149. var exts = createExtensions ();
  1150. if (exts != null) {
  1151. headers["Sec-WebSocket-Extensions"] = exts;
  1152. _extensionsRequested = true;
  1153. }
  1154. var ares = createAuthenticationResponse ();
  1155. if (ares != null)
  1156. headers["Authorization"] = ares.ToString ();
  1157. if (_cookies.Count > 0)
  1158. ret.SetCookies (_cookies);
  1159. return ret;
  1160. }
  1161. // As server
  1162. private HttpResponse createHandshakeResponse ()
  1163. {
  1164. var ret = HttpResponse.CreateWebSocketHandshakeResponse ();
  1165. var headers = ret.Headers;
  1166. headers["Sec-WebSocket-Accept"] = CreateResponseKey (_base64Key);
  1167. if (_protocol != null)
  1168. headers["Sec-WebSocket-Protocol"] = _protocol;
  1169. if (_extensions != null)
  1170. headers["Sec-WebSocket-Extensions"] = _extensions;
  1171. if (_cookies.Count > 0)
  1172. ret.SetCookies (_cookies);
  1173. return ret;
  1174. }
  1175. // As server
  1176. private bool customCheckHandshakeRequest (
  1177. WebSocketContext context, out string message
  1178. )
  1179. {
  1180. message = null;
  1181. if (_handshakeRequestChecker == null)
  1182. return true;
  1183. message = _handshakeRequestChecker (context);
  1184. return message == null;
  1185. }
  1186. private MessageEventArgs dequeueFromMessageEventQueue ()
  1187. {
  1188. lock (_forMessageEventQueue) {
  1189. return _messageEventQueue.Count > 0
  1190. ? _messageEventQueue.Dequeue ()
  1191. : null;
  1192. }
  1193. }
  1194. // As client
  1195. private bool doHandshake ()
  1196. {
  1197. setClientStream ();
  1198. var res = sendHandshakeRequest ();
  1199. string msg;
  1200. if (!checkHandshakeResponse (res, out msg)) {
  1201. _log.Error (msg);
  1202. _log.Debug (res.ToString ());
  1203. abort (1002, "A handshake error has occurred.");
  1204. return false;
  1205. }
  1206. if (_protocolsRequested)
  1207. _protocol = res.Headers["Sec-WebSocket-Protocol"];
  1208. if (_extensionsRequested) {
  1209. var exts = res.Headers["Sec-WebSocket-Extensions"];
  1210. if (exts == null)
  1211. _compression = CompressionMethod.None;
  1212. else
  1213. _extensions = exts;
  1214. }
  1215. var cookies = res.Cookies;
  1216. if (cookies.Count > 0)
  1217. _cookies.SetOrRemove (cookies);
  1218. return true;
  1219. }
  1220. private void enqueueToMessageEventQueue (MessageEventArgs e)
  1221. {
  1222. lock (_forMessageEventQueue)
  1223. _messageEventQueue.Enqueue (e);
  1224. }
  1225. private void error (string message, Exception exception)
  1226. {
  1227. var e = new ErrorEventArgs (message, exception);
  1228. try {
  1229. OnError.Emit (this, e);
  1230. }
  1231. catch (Exception ex) {
  1232. _log.Error (ex.Message);
  1233. _log.Debug (ex.ToString ());
  1234. }
  1235. }
  1236. private ClientSslConfiguration getSslConfiguration ()
  1237. {
  1238. if (_sslConfig == null)
  1239. _sslConfig = new ClientSslConfiguration (_uri.DnsSafeHost);
  1240. return _sslConfig;
  1241. }
  1242. private void init ()
  1243. {
  1244. _compression = CompressionMethod.None;
  1245. _cookies = new CookieCollection ();
  1246. _forPing = new object ();
  1247. _forSend = new object ();
  1248. _forState = new object ();
  1249. _messageEventQueue = new Queue<MessageEventArgs> ();
  1250. _forMessageEventQueue = ((ICollection) _messageEventQueue).SyncRoot;
  1251. _readyState = WebSocketState.New;
  1252. }
  1253. private void message ()
  1254. {
  1255. MessageEventArgs e = null;
  1256. lock (_forMessageEventQueue) {
  1257. if (_inMessage)
  1258. return;
  1259. if (_messageEventQueue.Count == 0)
  1260. return;
  1261. if (_readyState != WebSocketState.Open)
  1262. return;
  1263. e = _messageEventQueue.Dequeue ();
  1264. _inMessage = true;
  1265. }
  1266. _message (e);
  1267. }
  1268. private void messagec (MessageEventArgs e)
  1269. {
  1270. do {
  1271. try {
  1272. OnMessage.Emit (this, e);
  1273. }
  1274. catch (Exception ex) {
  1275. _log.Error (ex.Message);
  1276. _log.Debug (ex.ToString ());
  1277. error ("An exception has occurred during an OnMessage event.", ex);
  1278. }
  1279. lock (_forMessageEventQueue) {
  1280. if (_messageEventQueue.Count == 0) {
  1281. _inMessage = false;
  1282. break;
  1283. }
  1284. if (_readyState != WebSocketState.Open) {
  1285. _inMessage = false;
  1286. break;
  1287. }
  1288. e = _messageEventQueue.Dequeue ();
  1289. }
  1290. }
  1291. while (true);
  1292. }
  1293. private void messages (MessageEventArgs e)
  1294. {
  1295. try {
  1296. OnMessage.Emit (this, e);
  1297. }
  1298. catch (Exception ex) {
  1299. _log.Error (ex.Message);
  1300. _log.Debug (ex.ToString ());
  1301. error ("An exception has occurred during an OnMessage event.", ex);
  1302. }
  1303. lock (_forMessageEventQueue) {
  1304. if (_messageEventQueue.Count == 0) {
  1305. _inMessage = false;
  1306. return;
  1307. }
  1308. if (_readyState != WebSocketState.Open) {
  1309. _inMessage = false;
  1310. return;
  1311. }
  1312. e = _messageEventQueue.Dequeue ();
  1313. }
  1314. ThreadPool.QueueUserWorkItem (state => messages (e));
  1315. }
  1316. private void open ()
  1317. {
  1318. _inMessage = true;
  1319. startReceiving ();
  1320. try {
  1321. OnOpen.Emit (this, EventArgs.Empty);
  1322. }
  1323. catch (Exception ex) {
  1324. _log.Error (ex.Message);
  1325. _log.Debug (ex.ToString ());
  1326. error ("An exception has occurred during the OnOpen event.", ex);
  1327. }
  1328. MessageEventArgs e = null;
  1329. lock (_forMessageEventQueue) {
  1330. if (_messageEventQueue.Count == 0) {
  1331. _inMessage = false;
  1332. return;
  1333. }
  1334. if (_readyState != WebSocketState.Open) {
  1335. _inMessage = false;
  1336. return;
  1337. }
  1338. e = _messageEventQueue.Dequeue ();
  1339. }
  1340. _message.BeginInvoke (e, ar => _message.EndInvoke (ar), null);
  1341. }
  1342. private bool ping (byte[] data)
  1343. {
  1344. if (_readyState != WebSocketState.Open)
  1345. return false;
  1346. var received = _pongReceived;
  1347. if (received == null)
  1348. return false;
  1349. lock (_forPing) {
  1350. try {
  1351. received.Reset ();
  1352. var sent = send (Fin.Final, Opcode.Ping, data, false);
  1353. if (!sent)
  1354. return false;
  1355. return received.WaitOne (_waitTime);
  1356. }
  1357. catch (ObjectDisposedException) {
  1358. return false;
  1359. }
  1360. }
  1361. }
  1362. private bool processCloseFrame (WebSocketFrame frame)
  1363. {
  1364. var data = frame.PayloadData;
  1365. var send = !data.HasReservedCode;
  1366. close (data, send, true);
  1367. return false;
  1368. }
  1369. private bool processDataFrame (WebSocketFrame frame)
  1370. {
  1371. var e = frame.IsCompressed
  1372. ? new MessageEventArgs (
  1373. frame.Opcode,
  1374. frame.PayloadData.ApplicationData.Decompress (_compression)
  1375. )
  1376. : new MessageEventArgs (frame);
  1377. enqueueToMessageEventQueue (e);
  1378. return true;
  1379. }
  1380. private bool processFragmentFrame (WebSocketFrame frame)
  1381. {
  1382. if (!_inContinuation) {
  1383. if (frame.IsContinuation)
  1384. return true;
  1385. _fragmentsOpcode = frame.Opcode;
  1386. _fragmentsCompressed = frame.IsCompressed;
  1387. _fragmentsBuffer = new MemoryStream ();
  1388. _inContinuation = true;
  1389. }
  1390. _fragmentsBuffer.WriteBytes (frame.PayloadData.ApplicationData, 1024);
  1391. if (frame.IsFinal) {
  1392. using (_fragmentsBuffer) {
  1393. var data = _fragmentsCompressed
  1394. ? _fragmentsBuffer.DecompressToArray (_compression)
  1395. : _fragmentsBuffer.ToArray ();
  1396. var e = new MessageEventArgs (_fragmentsOpcode, data);
  1397. enqueueToMessageEventQueue (e);
  1398. }
  1399. _fragmentsBuffer = null;
  1400. _inContinuation = false;
  1401. }
  1402. return true;
  1403. }
  1404. private bool processPingFrame (WebSocketFrame frame)
  1405. {
  1406. _log.Trace ("A ping was received.");
  1407. var pong = WebSocketFrame.CreatePongFrame (frame.PayloadData, _client);
  1408. lock (_forState) {
  1409. if (_readyState != WebSocketState.Open) {
  1410. _log.Trace ("A pong to this ping cannot be sent.");
  1411. return true;
  1412. }
  1413. var bytes = pong.ToArray ();
  1414. var sent = sendBytes (bytes);
  1415. if (!sent)
  1416. return false;
  1417. }
  1418. _log.Trace ("A pong to this ping has been sent.");
  1419. if (_emitOnPing) {
  1420. if (_client)
  1421. pong.Unmask ();
  1422. var e = new MessageEventArgs (frame);
  1423. enqueueToMessageEventQueue (e);
  1424. }
  1425. return true;
  1426. }
  1427. private bool processPongFrame (WebSocketFrame frame)
  1428. {
  1429. _log.Trace ("A pong was received.");
  1430. try {
  1431. _pongReceived.Set ();
  1432. }
  1433. catch (NullReferenceException) {
  1434. return false;
  1435. }
  1436. catch (ObjectDisposedException) {
  1437. return false;
  1438. }
  1439. _log.Trace ("It has been signaled.");
  1440. return true;
  1441. }
  1442. private bool processReceivedFrame (WebSocketFrame frame)
  1443. {
  1444. string msg;
  1445. if (!checkReceivedFrame (frame, out msg)) {
  1446. _log.Error (msg);
  1447. _log.Debug (frame.ToString (false));
  1448. abort (1002, "An error has occurred while receiving.");
  1449. return false;
  1450. }
  1451. frame.Unmask ();
  1452. return frame.IsFragment
  1453. ? processFragmentFrame (frame)
  1454. : frame.IsData
  1455. ? processDataFrame (frame)
  1456. : frame.IsPing
  1457. ? processPingFrame (frame)
  1458. : frame.IsPong
  1459. ? processPongFrame (frame)
  1460. : frame.IsClose
  1461. ? processCloseFrame (frame)
  1462. : processUnsupportedFrame (frame);
  1463. }
  1464. // As server
  1465. private void processSecWebSocketExtensionsClientHeader (string value)
  1466. {
  1467. if (value == null)
  1468. return;
  1469. var buff = new StringBuilder (80);
  1470. var comp = false;
  1471. foreach (var elm in value.SplitHeaderValue (',')) {
  1472. var ext = elm.Trim ();
  1473. if (ext.Length == 0)
  1474. continue;
  1475. if (!comp) {
  1476. if (ext.IsCompressionExtension (CompressionMethod.Deflate)) {
  1477. _compression = CompressionMethod.Deflate;
  1478. var str = _compression.ToExtensionString (
  1479. "client_no_context_takeover",
  1480. "server_no_context_takeover"
  1481. );
  1482. buff.AppendFormat ("{0}, ", str);
  1483. comp = true;
  1484. }
  1485. }
  1486. }
  1487. var len = buff.Length;
  1488. if (len <= 2)
  1489. return;
  1490. buff.Length = len - 2;
  1491. _extensions = buff.ToString ();
  1492. }
  1493. private bool processUnsupportedFrame (WebSocketFrame frame)
  1494. {
  1495. _log.Fatal ("An unsupported frame was received.");
  1496. _log.Debug (frame.ToString (false));
  1497. abort (1003, "There is no way to handle it.");
  1498. return false;
  1499. }
  1500. // As server
  1501. private void refuseHandshake (ushort code, string reason)
  1502. {
  1503. createHandshakeFailureResponse ().WriteTo (_stream);
  1504. abort (code, reason);
  1505. }
  1506. // As client
  1507. private void releaseClientResources ()
  1508. {
  1509. if (_stream != null) {
  1510. _stream.Dispose ();
  1511. _stream = null;
  1512. }
  1513. if (_tcpClient != null) {
  1514. _tcpClient.Close ();
  1515. _tcpClient = null;
  1516. }
  1517. }
  1518. private void releaseCommonResources ()
  1519. {
  1520. if (_fragmentsBuffer != null) {
  1521. _fragmentsBuffer.Dispose ();
  1522. _fragmentsBuffer = null;
  1523. _inContinuation = false;
  1524. }
  1525. if (_pongReceived != null) {
  1526. _pongReceived.Close ();
  1527. _pongReceived = null;
  1528. }
  1529. if (_receivingExited != null) {
  1530. _receivingExited.Close ();
  1531. _receivingExited = null;
  1532. }
  1533. }
  1534. private void releaseResources ()
  1535. {
  1536. if (_client)
  1537. releaseClientResources ();
  1538. else
  1539. releaseServerResources ();
  1540. releaseCommonResources ();
  1541. }
  1542. // As server
  1543. private void releaseServerResources ()
  1544. {
  1545. if (_closeContext != null) {
  1546. _closeContext ();
  1547. _closeContext = null;
  1548. }
  1549. _stream = null;
  1550. _context = null;
  1551. }
  1552. private bool send (byte[] rawFrame)
  1553. {
  1554. lock (_forState) {
  1555. if (_readyState != WebSocketState.Open) {
  1556. _log.Error ("The current state of the interface is not Open.");
  1557. return false;
  1558. }
  1559. return sendBytes (rawFrame);
  1560. }
  1561. }
  1562. private bool send (Opcode opcode, Stream sourceStream)
  1563. {
  1564. lock (_forSend) {
  1565. var dataStream = sourceStream;
  1566. var compressed = false;
  1567. var sent = false;
  1568. try {
  1569. if (_compression != CompressionMethod.None) {
  1570. dataStream = sourceStream.Compress (_compression);
  1571. compressed = true;
  1572. }
  1573. sent = send (opcode, dataStream, compressed);
  1574. if (!sent)
  1575. error ("A send has failed.", null);
  1576. }
  1577. catch (Exception ex) {
  1578. _log.Error (ex.Message);
  1579. _log.Debug (ex.ToString ());
  1580. error ("An exception has occurred during a send.", ex);
  1581. }
  1582. finally {
  1583. if (compressed)
  1584. dataStream.Dispose ();
  1585. sourceStream.Dispose ();
  1586. }
  1587. return sent;
  1588. }
  1589. }
  1590. private bool send (Opcode opcode, Stream dataStream, bool compressed)
  1591. {
  1592. var len = dataStream.Length;
  1593. if (len == 0)
  1594. return send (Fin.Final, opcode, EmptyBytes, false);
  1595. var quo = len / FragmentLength;
  1596. var rem = (int) (len % FragmentLength);
  1597. byte[] buff = null;
  1598. if (quo == 0) {
  1599. buff = new byte[rem];
  1600. return dataStream.Read (buff, 0, rem) == rem
  1601. && send (Fin.Final, opcode, buff, compressed);
  1602. }
  1603. if (quo == 1 && rem == 0) {
  1604. buff = new byte[FragmentLength];
  1605. return dataStream.Read (buff, 0, FragmentLength) == FragmentLength
  1606. && send (Fin.Final, opcode, buff, compressed);
  1607. }
  1608. /* Send fragments */
  1609. // Begin
  1610. buff = new byte[FragmentLength];
  1611. var sent = dataStream.Read (buff, 0, FragmentLength) == FragmentLength
  1612. && send (Fin.More, opcode, buff, compressed);
  1613. if (!sent)
  1614. return false;
  1615. // Continue
  1616. var n = rem == 0 ? quo - 2 : quo - 1;
  1617. for (long i = 0; i < n; i++) {
  1618. sent = dataStream.Read (buff, 0, FragmentLength) == FragmentLength
  1619. && send (Fin.More, Opcode.Cont, buff, false);
  1620. if (!sent)
  1621. return false;
  1622. }
  1623. // End
  1624. if (rem == 0)
  1625. rem = FragmentLength;
  1626. else
  1627. buff = new byte[rem];
  1628. return dataStream.Read (buff, 0, rem) == rem
  1629. && send (Fin.Final, Opcode.Cont, buff, false);
  1630. }
  1631. private bool send (Fin fin, Opcode opcode, byte[] data, bool compressed)
  1632. {
  1633. var frame = new WebSocketFrame (fin, opcode, data, compressed, _client);
  1634. var rawFrame = frame.ToArray ();
  1635. return send (rawFrame);
  1636. }
  1637. private void sendAsync (
  1638. Opcode opcode, Stream sourceStream, Action<bool> completed
  1639. )
  1640. {
  1641. Func<Opcode, Stream, bool> sender = send;
  1642. sender.BeginInvoke (
  1643. opcode,
  1644. sourceStream,
  1645. ar => {
  1646. try {
  1647. var sent = sender.EndInvoke (ar);
  1648. if (completed != null)
  1649. completed (sent);
  1650. }
  1651. catch (Exception ex) {
  1652. _log.Error (ex.Message);
  1653. _log.Debug (ex.ToString ());
  1654. error (
  1655. "An exception has occurred during the callback for an async send.",
  1656. ex
  1657. );
  1658. }
  1659. },
  1660. null
  1661. );
  1662. }
  1663. private bool sendBytes (byte[] bytes)
  1664. {
  1665. try {
  1666. _stream.Write (bytes, 0, bytes.Length);
  1667. }
  1668. catch (Exception ex) {
  1669. _log.Error (ex.Message);
  1670. _log.Debug (ex.ToString ());
  1671. return false;
  1672. }
  1673. return true;
  1674. }
  1675. // As client
  1676. private HttpResponse sendHandshakeRequest ()
  1677. {
  1678. var req = createHandshakeRequest ();
  1679. var timeout = 90000;
  1680. var res = req.GetResponse (_stream, timeout);
  1681. if (res.IsUnauthorized) {
  1682. var val = res.Headers["WWW-Authenticate"];
  1683. if (val.IsNullOrEmpty ()) {
  1684. _log.Debug ("No authentication challenge is specified.");
  1685. return res;
  1686. }
  1687. var achal = AuthenticationChallenge.Parse (val);
  1688. if (achal == null) {
  1689. _log.Debug ("An invalid authentication challenge is specified.");
  1690. return res;
  1691. }
  1692. _authChallenge = achal;
  1693. if (_credentials == null)
  1694. return res;
  1695. var ares = new AuthenticationResponse (
  1696. _authChallenge, _credentials, _nonceCount
  1697. );
  1698. _nonceCount = ares.NonceCount;
  1699. req.Headers["Authorization"] = ares.ToString ();
  1700. if (res.CloseConnection) {
  1701. releaseClientResources ();
  1702. setClientStream ();
  1703. }
  1704. timeout = 15000;
  1705. res = req.GetResponse (_stream, timeout);
  1706. }
  1707. if (res.IsRedirect) {
  1708. if (!_enableRedirection)
  1709. return res;
  1710. var val = res.Headers["Location"];
  1711. if (val.IsNullOrEmpty ()) {
  1712. _log.Debug ("No URL to redirect is located.");
  1713. return res;
  1714. }
  1715. Uri uri;
  1716. string msg;
  1717. if (!val.TryCreateWebSocketUri (out uri, out msg)) {
  1718. _log.Debug ("An invalid URL to redirect is located.");
  1719. return res;
  1720. }
  1721. releaseClientResources ();
  1722. _uri = uri;
  1723. _secure = uri.Scheme == "wss";
  1724. setClientStream ();
  1725. return sendHandshakeRequest ();
  1726. }
  1727. return res;
  1728. }
  1729. // As client
  1730. private HttpResponse sendProxyConnectRequest ()
  1731. {
  1732. var req = HttpRequest.CreateConnectRequest (_uri);
  1733. var timeout = 90000;
  1734. var res = req.GetResponse (_stream, timeout);
  1735. if (res.IsProxyAuthenticationRequired) {
  1736. if (_proxyCredentials == null)
  1737. return res;
  1738. var val = res.Headers["Proxy-Authenticate"];
  1739. if (val.IsNullOrEmpty ()) {
  1740. _log.Debug ("No proxy authentication challenge is specified.");
  1741. return res;
  1742. }
  1743. var achal = AuthenticationChallenge.Parse (val);
  1744. if (achal == null) {
  1745. _log.Debug ("An invalid proxy authentication challenge is specified.");
  1746. return res;
  1747. }
  1748. var ares = new AuthenticationResponse (achal, _proxyCredentials, 0);
  1749. req.Headers["Proxy-Authorization"] = ares.ToString ();
  1750. if (res.CloseConnection) {
  1751. releaseClientResources ();
  1752. _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
  1753. _stream = _tcpClient.GetStream ();
  1754. }
  1755. timeout = 15000;
  1756. res = req.GetResponse (_stream, timeout);
  1757. }
  1758. return res;
  1759. }
  1760. // As client
  1761. private void setClientStream ()
  1762. {
  1763. if (_proxyUri != null) {
  1764. _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
  1765. _stream = _tcpClient.GetStream ();
  1766. var res = sendProxyConnectRequest ();
  1767. string msg;
  1768. if (!checkProxyConnectResponse (res, out msg))
  1769. throw new WebSocketException (msg);
  1770. }
  1771. else {
  1772. _tcpClient = new TcpClient (_uri.DnsSafeHost, _uri.Port);
  1773. _stream = _tcpClient.GetStream ();
  1774. }
  1775. if (_secure) {
  1776. var conf = getSslConfiguration ();
  1777. var host = conf.TargetHost;
  1778. if (host != _uri.DnsSafeHost) {
  1779. var msg = "An invalid host name is specified.";
  1780. throw new WebSocketException (
  1781. CloseStatusCode.TlsHandshakeFailure, msg
  1782. );
  1783. }
  1784. try {
  1785. var sslStream = new SslStream (
  1786. _stream,
  1787. false,
  1788. conf.ServerCertificateValidationCallback,
  1789. conf.ClientCertificateSelectionCallback
  1790. );
  1791. sslStream.AuthenticateAsClient (
  1792. host,
  1793. conf.ClientCertificates,
  1794. conf.EnabledSslProtocols,
  1795. conf.CheckCertificateRevocation
  1796. );
  1797. _stream = sslStream;
  1798. }
  1799. catch (Exception ex) {
  1800. throw new WebSocketException (
  1801. CloseStatusCode.TlsHandshakeFailure, ex
  1802. );
  1803. }
  1804. }
  1805. }
  1806. private void startReceiving ()
  1807. {
  1808. if (_messageEventQueue.Count > 0)
  1809. _messageEventQueue.Clear ();
  1810. _pongReceived = new ManualResetEvent (false);
  1811. _receivingExited = new ManualResetEvent (false);
  1812. Action receive = null;
  1813. receive =
  1814. () =>
  1815. WebSocketFrame.ReadFrameAsync (
  1816. _stream,
  1817. false,
  1818. frame => {
  1819. var cont = processReceivedFrame (frame)
  1820. && _readyState != WebSocketState.Closed;
  1821. if (!cont) {
  1822. var exited = _receivingExited;
  1823. if (exited != null)
  1824. exited.Set ();
  1825. return;
  1826. }
  1827. receive ();
  1828. if (_inMessage)
  1829. return;
  1830. message ();
  1831. },
  1832. ex => {
  1833. _log.Fatal (ex.Message);
  1834. _log.Debug (ex.ToString ());
  1835. abort ("An exception has occurred while receiving.", ex);
  1836. }
  1837. );
  1838. receive ();
  1839. }
  1840. // As client
  1841. private bool validateSecWebSocketExtensionsServerHeader (string value)
  1842. {
  1843. if (!_extensionsRequested)
  1844. return false;
  1845. if (value.Length == 0)
  1846. return false;
  1847. var comp = _compression != CompressionMethod.None;
  1848. foreach (var elm in value.SplitHeaderValue (',')) {
  1849. var ext = elm.Trim ();
  1850. if (comp && ext.IsCompressionExtension (_compression)) {
  1851. var param1 = "server_no_context_takeover";
  1852. var param2 = "client_no_context_takeover";
  1853. if (!ext.Contains (param1)) {
  1854. // The server did not send back "server_no_context_takeover".
  1855. return false;
  1856. }
  1857. var name = _compression.ToExtensionString ();
  1858. var invalid = ext.SplitHeaderValue (';').Contains (
  1859. t => {
  1860. t = t.Trim ();
  1861. var valid = t == name
  1862. || t == param1
  1863. || t == param2;
  1864. return !valid;
  1865. }
  1866. );
  1867. if (invalid)
  1868. return false;
  1869. comp = false;
  1870. }
  1871. else {
  1872. return false;
  1873. }
  1874. }
  1875. return true;
  1876. }
  1877. #endregion
  1878. #region Internal Methods
  1879. // As server
  1880. internal void Accept ()
  1881. {
  1882. var accepted = accept ();
  1883. if (!accepted)
  1884. return;
  1885. open ();
  1886. }
  1887. // As server
  1888. internal void AcceptAsync ()
  1889. {
  1890. Func<bool> acceptor = accept;
  1891. acceptor.BeginInvoke (
  1892. ar => {
  1893. var accepted = acceptor.EndInvoke (ar);
  1894. if (!accepted)
  1895. return;
  1896. open ();
  1897. },
  1898. null
  1899. );
  1900. }
  1901. // As server
  1902. internal void Close (PayloadData payloadData, byte[] rawFrame)
  1903. {
  1904. lock (_forState) {
  1905. if (_readyState == WebSocketState.Closing) {
  1906. _log.Trace ("The close process is already in progress.");
  1907. return;
  1908. }
  1909. if (_readyState == WebSocketState.Closed) {
  1910. _log.Trace ("The connection has already been closed.");
  1911. return;
  1912. }
  1913. _readyState = WebSocketState.Closing;
  1914. }
  1915. _log.Trace ("Begin closing the connection.");
  1916. var sent = rawFrame != null && sendBytes (rawFrame);
  1917. var received = sent && _receivingExited != null
  1918. ? _receivingExited.WaitOne (_waitTime)
  1919. : false;
  1920. var res = sent && received;
  1921. var msg = String.Format (
  1922. "The closing was clean? {0} (sent: {1} received: {2})",
  1923. res,
  1924. sent,
  1925. received
  1926. );
  1927. _log.Debug (msg);
  1928. releaseServerResources ();
  1929. releaseCommonResources ();
  1930. _log.Trace ("End closing the connection.");
  1931. _readyState = WebSocketState.Closed;
  1932. var e = new CloseEventArgs (payloadData, res);
  1933. try {
  1934. OnClose.Emit (this, e);
  1935. }
  1936. catch (Exception ex) {
  1937. _log.Error (ex.Message);
  1938. _log.Debug (ex.ToString ());
  1939. }
  1940. }
  1941. // As client
  1942. internal static string CreateBase64Key ()
  1943. {
  1944. var key = new byte[16];
  1945. RandomNumber.GetBytes (key);
  1946. return Convert.ToBase64String (key);
  1947. }
  1948. internal static string CreateResponseKey (string base64Key)
  1949. {
  1950. SHA1 sha1 = new SHA1CryptoServiceProvider ();
  1951. var src = base64Key + _guid;
  1952. var bytes = src.GetUTF8EncodedBytes ();
  1953. var key = sha1.ComputeHash (bytes);
  1954. return Convert.ToBase64String (key);
  1955. }
  1956. // As server
  1957. internal bool Ping (byte[] rawFrame)
  1958. {
  1959. if (_readyState != WebSocketState.Open)
  1960. return false;
  1961. var received = _pongReceived;
  1962. if (received == null)
  1963. return false;
  1964. lock (_forPing) {
  1965. try {
  1966. received.Reset ();
  1967. var sent = send (rawFrame);
  1968. if (!sent)
  1969. return false;
  1970. return received.WaitOne (_waitTime);
  1971. }
  1972. catch (ObjectDisposedException) {
  1973. return false;
  1974. }
  1975. }
  1976. }
  1977. // As server
  1978. internal void Send (
  1979. Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache
  1980. )
  1981. {
  1982. lock (_forSend) {
  1983. byte[] found;
  1984. if (!cache.TryGetValue (_compression, out found)) {
  1985. found = new WebSocketFrame (
  1986. Fin.Final,
  1987. opcode,
  1988. data.Compress (_compression),
  1989. _compression != CompressionMethod.None,
  1990. false
  1991. )
  1992. .ToArray ();
  1993. cache.Add (_compression, found);
  1994. }
  1995. send (found);
  1996. }
  1997. }
  1998. // As server
  1999. internal void Send (
  2000. Opcode opcode,
  2001. Stream sourceStream,
  2002. Dictionary<CompressionMethod, Stream> cache
  2003. )
  2004. {
  2005. lock (_forSend) {
  2006. Stream found;
  2007. if (!cache.TryGetValue (_compression, out found)) {
  2008. found = sourceStream.Compress (_compression);
  2009. cache.Add (_compression, found);
  2010. }
  2011. else {
  2012. found.Position = 0;
  2013. }
  2014. send (opcode, found, _compression != CompressionMethod.None);
  2015. }
  2016. }
  2017. #endregion
  2018. #region Public Methods
  2019. /// <summary>
  2020. /// Closes the connection.
  2021. /// </summary>
  2022. /// <remarks>
  2023. /// This method does nothing if the current state of the interface is
  2024. /// Closing or Closed.
  2025. /// </remarks>
  2026. public void Close ()
  2027. {
  2028. close (1005, String.Empty);
  2029. }
  2030. /// <summary>
  2031. /// Closes the connection with the specified code.
  2032. /// </summary>
  2033. /// <remarks>
  2034. /// This method does nothing if the current state of the interface is
  2035. /// Closing or Closed.
  2036. /// </remarks>
  2037. /// <param name="code">
  2038. /// <para>
  2039. /// A <see cref="ushort"/> that specifies the status code indicating
  2040. /// the reason for the close.
  2041. /// </para>
  2042. /// <para>
  2043. /// The status codes are defined in
  2044. /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
  2045. /// Section 7.4</see> of RFC 6455.
  2046. /// </para>
  2047. /// </param>
  2048. /// <exception cref="ArgumentOutOfRangeException">
  2049. /// <paramref name="code"/> is less than 1000 or greater than 4999.
  2050. /// </exception>
  2051. /// <exception cref="ArgumentException">
  2052. /// <para>
  2053. /// <paramref name="code"/> is 1011 (server error).
  2054. /// It cannot be used by a client.
  2055. /// </para>
  2056. /// <para>
  2057. /// -or-
  2058. /// </para>
  2059. /// <para>
  2060. /// <paramref name="code"/> is 1010 (mandatory extension).
  2061. /// It cannot be used by a server.
  2062. /// </para>
  2063. /// </exception>
  2064. public void Close (ushort code)
  2065. {
  2066. Close (code, String.Empty);
  2067. }
  2068. /// <summary>
  2069. /// Closes the connection with the specified code.
  2070. /// </summary>
  2071. /// <remarks>
  2072. /// This method does nothing if the current state of the interface is
  2073. /// Closing or Closed.
  2074. /// </remarks>
  2075. /// <param name="code">
  2076. /// <para>
  2077. /// One of the <see cref="CloseStatusCode"/> enum values.
  2078. /// </para>
  2079. /// <para>
  2080. /// It specifies the status code indicating the reason for the close.
  2081. /// </para>
  2082. /// </param>
  2083. /// <exception cref="ArgumentException">
  2084. /// <para>
  2085. /// <paramref name="code"/> is <see cref="CloseStatusCode.ServerError"/>.
  2086. /// It cannot be used by a client.
  2087. /// </para>
  2088. /// <para>
  2089. /// -or-
  2090. /// </para>
  2091. /// <para>
  2092. /// <paramref name="code"/> is <see cref="CloseStatusCode.MandatoryExtension"/>.
  2093. /// It cannot be used by a server.
  2094. /// </para>
  2095. /// </exception>
  2096. public void Close (CloseStatusCode code)
  2097. {
  2098. Close (code, String.Empty);
  2099. }
  2100. /// <summary>
  2101. /// Closes the connection with the specified code and reason.
  2102. /// </summary>
  2103. /// <remarks>
  2104. /// This method does nothing if the current state of the interface is
  2105. /// Closing or Closed.
  2106. /// </remarks>
  2107. /// <param name="code">
  2108. /// <para>
  2109. /// A <see cref="ushort"/> that specifies the status code indicating
  2110. /// the reason for the close.
  2111. /// </para>
  2112. /// <para>
  2113. /// The status codes are defined in
  2114. /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
  2115. /// Section 7.4</see> of RFC 6455.
  2116. /// </para>
  2117. /// </param>
  2118. /// <param name="reason">
  2119. /// <para>
  2120. /// A <see cref="string"/> that specifies the reason for the close.
  2121. /// </para>
  2122. /// <para>
  2123. /// Its size must be 123 bytes or less in UTF-8.
  2124. /// </para>
  2125. /// </param>
  2126. /// <exception cref="ArgumentOutOfRangeException">
  2127. /// <para>
  2128. /// <paramref name="code"/> is less than 1000 or greater than 4999.
  2129. /// </para>
  2130. /// <para>
  2131. /// -or-
  2132. /// </para>
  2133. /// <para>
  2134. /// The size of <paramref name="reason"/> is greater than 123 bytes.
  2135. /// </para>
  2136. /// </exception>
  2137. /// <exception cref="ArgumentException">
  2138. /// <para>
  2139. /// <paramref name="code"/> is 1011 (server error).
  2140. /// It cannot be used by a client.
  2141. /// </para>
  2142. /// <para>
  2143. /// -or-
  2144. /// </para>
  2145. /// <para>
  2146. /// <paramref name="code"/> is 1010 (mandatory extension).
  2147. /// It cannot be used by a server.
  2148. /// </para>
  2149. /// <para>
  2150. /// -or-
  2151. /// </para>
  2152. /// <para>
  2153. /// <paramref name="code"/> is 1005 (no status) and
  2154. /// <paramref name="reason"/> is specified.
  2155. /// </para>
  2156. /// <para>
  2157. /// -or-
  2158. /// </para>
  2159. /// <para>
  2160. /// <paramref name="reason"/> could not be UTF-8-encoded.
  2161. /// </para>
  2162. /// </exception>
  2163. public void Close (ushort code, string reason)
  2164. {
  2165. if (!code.IsCloseStatusCode ()) {
  2166. var msg = "Less than 1000 or greater than 4999.";
  2167. throw new ArgumentOutOfRangeException ("code", msg);
  2168. }
  2169. if (_client && code == 1011) {
  2170. var msg = "1011 cannot be used.";
  2171. throw new ArgumentException (msg, "code");
  2172. }
  2173. if (!_client && code == 1010) {
  2174. var msg = "1010 cannot be used.";
  2175. throw new ArgumentException (msg, "code");
  2176. }
  2177. if (reason.IsNullOrEmpty ()) {
  2178. close (code, String.Empty);
  2179. return;
  2180. }
  2181. if (code == 1005) {
  2182. var msg = "1005 cannot be used.";
  2183. throw new ArgumentException (msg, "code");
  2184. }
  2185. byte[] bytes;
  2186. if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
  2187. var msg = "It could not be UTF-8-encoded.";
  2188. throw new ArgumentException (msg, "reason");
  2189. }
  2190. if (bytes.Length > 123) {
  2191. var msg = "Its size is greater than 123 bytes.";
  2192. throw new ArgumentOutOfRangeException ("reason", msg);
  2193. }
  2194. close (code, reason);
  2195. }
  2196. /// <summary>
  2197. /// Closes the connection with the specified code and reason.
  2198. /// </summary>
  2199. /// <remarks>
  2200. /// This method does nothing if the current state of the interface is
  2201. /// Closing or Closed.
  2202. /// </remarks>
  2203. /// <param name="code">
  2204. /// <para>
  2205. /// One of the <see cref="CloseStatusCode"/> enum values.
  2206. /// </para>
  2207. /// <para>
  2208. /// It specifies the status code indicating the reason for the close.
  2209. /// </para>
  2210. /// </param>
  2211. /// <param name="reason">
  2212. /// <para>
  2213. /// A <see cref="string"/> that specifies the reason for the close.
  2214. /// </para>
  2215. /// <para>
  2216. /// Its size must be 123 bytes or less in UTF-8.
  2217. /// </para>
  2218. /// </param>
  2219. /// <exception cref="ArgumentException">
  2220. /// <para>
  2221. /// <paramref name="code"/> is <see cref="CloseStatusCode.ServerError"/>.
  2222. /// It cannot be used by a client.
  2223. /// </para>
  2224. /// <para>
  2225. /// -or-
  2226. /// </para>
  2227. /// <para>
  2228. /// <paramref name="code"/> is <see cref="CloseStatusCode.MandatoryExtension"/>.
  2229. /// It cannot be used by a server.
  2230. /// </para>
  2231. /// <para>
  2232. /// -or-
  2233. /// </para>
  2234. /// <para>
  2235. /// <paramref name="code"/> is <see cref="CloseStatusCode.NoStatus"/> and
  2236. /// <paramref name="reason"/> is specified.
  2237. /// </para>
  2238. /// <para>
  2239. /// -or-
  2240. /// </para>
  2241. /// <para>
  2242. /// <paramref name="reason"/> could not be UTF-8-encoded.
  2243. /// </para>
  2244. /// </exception>
  2245. /// <exception cref="ArgumentOutOfRangeException">
  2246. /// The size of <paramref name="reason"/> is greater than 123 bytes.
  2247. /// </exception>
  2248. public void Close (CloseStatusCode code, string reason)
  2249. {
  2250. if (_client && code == CloseStatusCode.ServerError) {
  2251. var msg = "ServerError cannot be used.";
  2252. throw new ArgumentException (msg, "code");
  2253. }
  2254. if (!_client && code == CloseStatusCode.MandatoryExtension) {
  2255. var msg = "MandatoryExtension cannot be used.";
  2256. throw new ArgumentException (msg, "code");
  2257. }
  2258. if (reason.IsNullOrEmpty ()) {
  2259. close ((ushort) code, String.Empty);
  2260. return;
  2261. }
  2262. if (code == CloseStatusCode.NoStatus) {
  2263. var msg = "NoStatus cannot be used.";
  2264. throw new ArgumentException (msg, "code");
  2265. }
  2266. byte[] bytes;
  2267. if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
  2268. var msg = "It could not be UTF-8-encoded.";
  2269. throw new ArgumentException (msg, "reason");
  2270. }
  2271. if (bytes.Length > 123) {
  2272. var msg = "Its size is greater than 123 bytes.";
  2273. throw new ArgumentOutOfRangeException ("reason", msg);
  2274. }
  2275. close ((ushort) code, reason);
  2276. }
  2277. /// <summary>
  2278. /// Closes the connection asynchronously.
  2279. /// </summary>
  2280. /// <remarks>
  2281. /// <para>
  2282. /// This method does not wait for the close to be complete.
  2283. /// </para>
  2284. /// <para>
  2285. /// This method does nothing if the current state of the interface is
  2286. /// Closing or Closed.
  2287. /// </para>
  2288. /// </remarks>
  2289. public void CloseAsync ()
  2290. {
  2291. closeAsync (1005, String.Empty);
  2292. }
  2293. /// <summary>
  2294. /// Closes the connection asynchronously with the specified code.
  2295. /// </summary>
  2296. /// <remarks>
  2297. /// <para>
  2298. /// This method does not wait for the close to be complete.
  2299. /// </para>
  2300. /// <para>
  2301. /// This method does nothing if the current state of the interface is
  2302. /// Closing or Closed.
  2303. /// </para>
  2304. /// </remarks>
  2305. /// <param name="code">
  2306. /// <para>
  2307. /// A <see cref="ushort"/> that specifies the status code indicating
  2308. /// the reason for the close.
  2309. /// </para>
  2310. /// <para>
  2311. /// The status codes are defined in
  2312. /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
  2313. /// Section 7.4</see> of RFC 6455.
  2314. /// </para>
  2315. /// </param>
  2316. /// <exception cref="ArgumentOutOfRangeException">
  2317. /// <paramref name="code"/> is less than 1000 or greater than 4999.
  2318. /// </exception>
  2319. /// <exception cref="ArgumentException">
  2320. /// <para>
  2321. /// <paramref name="code"/> is 1011 (server error).
  2322. /// It cannot be used by a client.
  2323. /// </para>
  2324. /// <para>
  2325. /// -or-
  2326. /// </para>
  2327. /// <para>
  2328. /// <paramref name="code"/> is 1010 (mandatory extension).
  2329. /// It cannot be used by a server.
  2330. /// </para>
  2331. /// </exception>
  2332. public void CloseAsync (ushort code)
  2333. {
  2334. CloseAsync (code, String.Empty);
  2335. }
  2336. /// <summary>
  2337. /// Closes the connection asynchronously with the specified code.
  2338. /// </summary>
  2339. /// <remarks>
  2340. /// <para>
  2341. /// This method does not wait for the close to be complete.
  2342. /// </para>
  2343. /// <para>
  2344. /// This method does nothing if the current state of the interface is
  2345. /// Closing or Closed.
  2346. /// </para>
  2347. /// </remarks>
  2348. /// <param name="code">
  2349. /// <para>
  2350. /// One of the <see cref="CloseStatusCode"/> enum values.
  2351. /// </para>
  2352. /// <para>
  2353. /// It specifies the status code indicating the reason for the close.
  2354. /// </para>
  2355. /// </param>
  2356. /// <exception cref="ArgumentException">
  2357. /// <para>
  2358. /// <paramref name="code"/> is <see cref="CloseStatusCode.ServerError"/>.
  2359. /// It cannot be used by a client.
  2360. /// </para>
  2361. /// <para>
  2362. /// -or-
  2363. /// </para>
  2364. /// <para>
  2365. /// <paramref name="code"/> is <see cref="CloseStatusCode.MandatoryExtension"/>.
  2366. /// It cannot be used by a server.
  2367. /// </para>
  2368. /// </exception>
  2369. public void CloseAsync (CloseStatusCode code)
  2370. {
  2371. CloseAsync (code, String.Empty);
  2372. }
  2373. /// <summary>
  2374. /// Closes the connection asynchronously with the specified code and reason.
  2375. /// </summary>
  2376. /// <remarks>
  2377. /// <para>
  2378. /// This method does not wait for the close to be complete.
  2379. /// </para>
  2380. /// <para>
  2381. /// This method does nothing if the current state of the interface is
  2382. /// Closing or Closed.
  2383. /// </para>
  2384. /// </remarks>
  2385. /// <param name="code">
  2386. /// <para>
  2387. /// A <see cref="ushort"/> that specifies the status code indicating
  2388. /// the reason for the close.
  2389. /// </para>
  2390. /// <para>
  2391. /// The status codes are defined in
  2392. /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
  2393. /// Section 7.4</see> of RFC 6455.
  2394. /// </para>
  2395. /// </param>
  2396. /// <param name="reason">
  2397. /// <para>
  2398. /// A <see cref="string"/> that specifies the reason for the close.
  2399. /// </para>
  2400. /// <para>
  2401. /// Its size must be 123 bytes or less in UTF-8.
  2402. /// </para>
  2403. /// </param>
  2404. /// <exception cref="ArgumentOutOfRangeException">
  2405. /// <para>
  2406. /// <paramref name="code"/> is less than 1000 or greater than 4999.
  2407. /// </para>
  2408. /// <para>
  2409. /// -or-
  2410. /// </para>
  2411. /// <para>
  2412. /// The size of <paramref name="reason"/> is greater than 123 bytes.
  2413. /// </para>
  2414. /// </exception>
  2415. /// <exception cref="ArgumentException">
  2416. /// <para>
  2417. /// <paramref name="code"/> is 1011 (server error).
  2418. /// It cannot be used by a client.
  2419. /// </para>
  2420. /// <para>
  2421. /// -or-
  2422. /// </para>
  2423. /// <para>
  2424. /// <paramref name="code"/> is 1010 (mandatory extension).
  2425. /// It cannot be used by a server.
  2426. /// </para>
  2427. /// <para>
  2428. /// -or-
  2429. /// </para>
  2430. /// <para>
  2431. /// <paramref name="code"/> is 1005 (no status) and
  2432. /// <paramref name="reason"/> is specified.
  2433. /// </para>
  2434. /// <para>
  2435. /// -or-
  2436. /// </para>
  2437. /// <para>
  2438. /// <paramref name="reason"/> could not be UTF-8-encoded.
  2439. /// </para>
  2440. /// </exception>
  2441. public void CloseAsync (ushort code, string reason)
  2442. {
  2443. if (!code.IsCloseStatusCode ()) {
  2444. var msg = "Less than 1000 or greater than 4999.";
  2445. throw new ArgumentOutOfRangeException ("code", msg);
  2446. }
  2447. if (_client && code == 1011) {
  2448. var msg = "1011 cannot be used.";
  2449. throw new ArgumentException (msg, "code");
  2450. }
  2451. if (!_client && code == 1010) {
  2452. var msg = "1010 cannot be used.";
  2453. throw new ArgumentException (msg, "code");
  2454. }
  2455. if (reason.IsNullOrEmpty ()) {
  2456. closeAsync (code, String.Empty);
  2457. return;
  2458. }
  2459. if (code == 1005) {
  2460. var msg = "1005 cannot be used.";
  2461. throw new ArgumentException (msg, "code");
  2462. }
  2463. byte[] bytes;
  2464. if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
  2465. var msg = "It could not be UTF-8-encoded.";
  2466. throw new ArgumentException (msg, "reason");
  2467. }
  2468. if (bytes.Length > 123) {
  2469. var msg = "Its size is greater than 123 bytes.";
  2470. throw new ArgumentOutOfRangeException ("reason", msg);
  2471. }
  2472. closeAsync (code, reason);
  2473. }
  2474. /// <summary>
  2475. /// Closes the connection asynchronously with the specified code and reason.
  2476. /// </summary>
  2477. /// <remarks>
  2478. /// <para>
  2479. /// This method does not wait for the close to be complete.
  2480. /// </para>
  2481. /// <para>
  2482. /// This method does nothing if the current state of the interface is
  2483. /// Closing or Closed.
  2484. /// </para>
  2485. /// </remarks>
  2486. /// <param name="code">
  2487. /// <para>
  2488. /// One of the <see cref="CloseStatusCode"/> enum values.
  2489. /// </para>
  2490. /// <para>
  2491. /// It specifies the status code indicating the reason for the close.
  2492. /// </para>
  2493. /// </param>
  2494. /// <param name="reason">
  2495. /// <para>
  2496. /// A <see cref="string"/> that specifies the reason for the close.
  2497. /// </para>
  2498. /// <para>
  2499. /// Its size must be 123 bytes or less in UTF-8.
  2500. /// </para>
  2501. /// </param>
  2502. /// <exception cref="ArgumentException">
  2503. /// <para>
  2504. /// <paramref name="code"/> is <see cref="CloseStatusCode.ServerError"/>.
  2505. /// It cannot be used by a client.
  2506. /// </para>
  2507. /// <para>
  2508. /// -or-
  2509. /// </para>
  2510. /// <para>
  2511. /// <paramref name="code"/> is <see cref="CloseStatusCode.MandatoryExtension"/>.
  2512. /// It cannot be used by a server.
  2513. /// </para>
  2514. /// <para>
  2515. /// -or-
  2516. /// </para>
  2517. /// <para>
  2518. /// <paramref name="code"/> is <see cref="CloseStatusCode.NoStatus"/> and
  2519. /// <paramref name="reason"/> is specified.
  2520. /// </para>
  2521. /// <para>
  2522. /// -or-
  2523. /// </para>
  2524. /// <para>
  2525. /// <paramref name="reason"/> could not be UTF-8-encoded.
  2526. /// </para>
  2527. /// </exception>
  2528. /// <exception cref="ArgumentOutOfRangeException">
  2529. /// The size of <paramref name="reason"/> is greater than 123 bytes.
  2530. /// </exception>
  2531. public void CloseAsync (CloseStatusCode code, string reason)
  2532. {
  2533. if (_client && code == CloseStatusCode.ServerError) {
  2534. var msg = "ServerError cannot be used.";
  2535. throw new ArgumentException (msg, "code");
  2536. }
  2537. if (!_client && code == CloseStatusCode.MandatoryExtension) {
  2538. var msg = "MandatoryExtension cannot be used.";
  2539. throw new ArgumentException (msg, "code");
  2540. }
  2541. if (reason.IsNullOrEmpty ()) {
  2542. closeAsync ((ushort) code, String.Empty);
  2543. return;
  2544. }
  2545. if (code == CloseStatusCode.NoStatus) {
  2546. var msg = "NoStatus cannot be used.";
  2547. throw new ArgumentException (msg, "code");
  2548. }
  2549. byte[] bytes;
  2550. if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
  2551. var msg = "It could not be UTF-8-encoded.";
  2552. throw new ArgumentException (msg, "reason");
  2553. }
  2554. if (bytes.Length > 123) {
  2555. var msg = "Its size is greater than 123 bytes.";
  2556. throw new ArgumentOutOfRangeException ("reason", msg);
  2557. }
  2558. closeAsync ((ushort) code, reason);
  2559. }
  2560. /// <summary>
  2561. /// Establishes a connection.
  2562. /// </summary>
  2563. /// <remarks>
  2564. /// This method does nothing if the current state of the interface is
  2565. /// Connecting or Open.
  2566. /// </remarks>
  2567. /// <exception cref="InvalidOperationException">
  2568. /// <para>
  2569. /// The interface is not for the client.
  2570. /// </para>
  2571. /// <para>
  2572. /// -or-
  2573. /// </para>
  2574. /// <para>
  2575. /// A series of reconnecting has failed.
  2576. /// </para>
  2577. /// </exception>
  2578. public void Connect ()
  2579. {
  2580. if (!_client) {
  2581. var msg = "The interface is not for the client.";
  2582. throw new InvalidOperationException (msg);
  2583. }
  2584. if (_retryCountForConnect >= _maxRetryCountForConnect) {
  2585. var msg = "A series of reconnecting has failed.";
  2586. throw new InvalidOperationException (msg);
  2587. }
  2588. var connected = connect ();
  2589. if (!connected)
  2590. return;
  2591. open ();
  2592. }
  2593. /// <summary>
  2594. /// Establishes a connection asynchronously.
  2595. /// </summary>
  2596. /// <remarks>
  2597. /// <para>
  2598. /// This method does not wait for the connect process to be complete.
  2599. /// </para>
  2600. /// <para>
  2601. /// This method does nothing if the current state of the interface is
  2602. /// Connecting or Open.
  2603. /// </para>
  2604. /// </remarks>
  2605. /// <exception cref="InvalidOperationException">
  2606. /// <para>
  2607. /// The interface is not for the client.
  2608. /// </para>
  2609. /// <para>
  2610. /// -or-
  2611. /// </para>
  2612. /// <para>
  2613. /// A series of reconnecting has failed.
  2614. /// </para>
  2615. /// </exception>
  2616. public void ConnectAsync ()
  2617. {
  2618. if (!_client) {
  2619. var msg = "The interface is not for the client.";
  2620. throw new InvalidOperationException (msg);
  2621. }
  2622. if (_retryCountForConnect >= _maxRetryCountForConnect) {
  2623. var msg = "A series of reconnecting has failed.";
  2624. throw new InvalidOperationException (msg);
  2625. }
  2626. Func<bool> connector = connect;
  2627. connector.BeginInvoke (
  2628. ar => {
  2629. var connected = connector.EndInvoke (ar);
  2630. if (!connected)
  2631. return;
  2632. open ();
  2633. },
  2634. null
  2635. );
  2636. }
  2637. /// <summary>
  2638. /// Sends a ping to the remote endpoint.
  2639. /// </summary>
  2640. /// <returns>
  2641. /// <c>true</c> if the send has successfully done and a pong has been
  2642. /// received within a time; otherwise, <c>false</c>.
  2643. /// </returns>
  2644. public bool Ping ()
  2645. {
  2646. return ping (EmptyBytes);
  2647. }
  2648. /// <summary>
  2649. /// Sends a ping with the specified message to the remote endpoint.
  2650. /// </summary>
  2651. /// <returns>
  2652. /// <c>true</c> if the send has successfully done and a pong has been
  2653. /// received within a time; otherwise, <c>false</c>.
  2654. /// </returns>
  2655. /// <param name="message">
  2656. /// <para>
  2657. /// A <see cref="string"/> that specifies the message to send.
  2658. /// </para>
  2659. /// <para>
  2660. /// Its size must be 125 bytes or less in UTF-8.
  2661. /// </para>
  2662. /// </param>
  2663. /// <exception cref="ArgumentException">
  2664. /// <paramref name="message"/> could not be UTF-8-encoded.
  2665. /// </exception>
  2666. /// <exception cref="ArgumentOutOfRangeException">
  2667. /// The size of <paramref name="message"/> is greater than 125 bytes.
  2668. /// </exception>
  2669. public bool Ping (string message)
  2670. {
  2671. if (message.IsNullOrEmpty ())
  2672. return ping (EmptyBytes);
  2673. byte[] bytes;
  2674. if (!message.TryGetUTF8EncodedBytes (out bytes)) {
  2675. var msg = "It could not be UTF-8-encoded.";
  2676. throw new ArgumentException (msg, "message");
  2677. }
  2678. if (bytes.Length > 125) {
  2679. var msg = "Its size is greater than 125 bytes.";
  2680. throw new ArgumentOutOfRangeException ("message", msg);
  2681. }
  2682. return ping (bytes);
  2683. }
  2684. /// <summary>
  2685. /// Sends the specified data to the remote endpoint.
  2686. /// </summary>
  2687. /// <param name="data">
  2688. /// An array of <see cref="byte"/> that specifies the binary data to send.
  2689. /// </param>
  2690. /// <exception cref="InvalidOperationException">
  2691. /// The current state of the interface is not Open.
  2692. /// </exception>
  2693. /// <exception cref="ArgumentNullException">
  2694. /// <paramref name="data"/> is <see langword="null"/>.
  2695. /// </exception>
  2696. public void Send (byte[] data)
  2697. {
  2698. if (_readyState != WebSocketState.Open) {
  2699. var msg = "The current state of the interface is not Open.";
  2700. throw new InvalidOperationException (msg);
  2701. }
  2702. if (data == null)
  2703. throw new ArgumentNullException ("data");
  2704. send (Opcode.Binary, new MemoryStream (data));
  2705. }
  2706. /// <summary>
  2707. /// Sends the specified file to the remote endpoint.
  2708. /// </summary>
  2709. /// <param name="fileInfo">
  2710. /// <para>
  2711. /// A <see cref="FileInfo"/> that specifies the file to send.
  2712. /// </para>
  2713. /// <para>
  2714. /// The file is sent as the binary data.
  2715. /// </para>
  2716. /// </param>
  2717. /// <exception cref="InvalidOperationException">
  2718. /// The current state of the interface is not Open.
  2719. /// </exception>
  2720. /// <exception cref="ArgumentNullException">
  2721. /// <paramref name="fileInfo"/> is <see langword="null"/>.
  2722. /// </exception>
  2723. /// <exception cref="ArgumentException">
  2724. /// <para>
  2725. /// The file does not exist.
  2726. /// </para>
  2727. /// <para>
  2728. /// -or-
  2729. /// </para>
  2730. /// <para>
  2731. /// The file could not be opened.
  2732. /// </para>
  2733. /// </exception>
  2734. public void Send (FileInfo fileInfo)
  2735. {
  2736. if (_readyState != WebSocketState.Open) {
  2737. var msg = "The current state of the interface is not Open.";
  2738. throw new InvalidOperationException (msg);
  2739. }
  2740. if (fileInfo == null)
  2741. throw new ArgumentNullException ("fileInfo");
  2742. if (!fileInfo.Exists) {
  2743. var msg = "The file does not exist.";
  2744. throw new ArgumentException (msg, "fileInfo");
  2745. }
  2746. FileStream stream;
  2747. if (!fileInfo.TryOpenRead (out stream)) {
  2748. var msg = "The file could not be opened.";
  2749. throw new ArgumentException (msg, "fileInfo");
  2750. }
  2751. send (Opcode.Binary, stream);
  2752. }
  2753. /// <summary>
  2754. /// Sends the specified data to the remote endpoint.
  2755. /// </summary>
  2756. /// <param name="data">
  2757. /// A <see cref="string"/> that specifies the text data to send.
  2758. /// </param>
  2759. /// <exception cref="InvalidOperationException">
  2760. /// The current state of the interface is not Open.
  2761. /// </exception>
  2762. /// <exception cref="ArgumentNullException">
  2763. /// <paramref name="data"/> is <see langword="null"/>.
  2764. /// </exception>
  2765. /// <exception cref="ArgumentException">
  2766. /// <paramref name="data"/> could not be UTF-8-encoded.
  2767. /// </exception>
  2768. public void Send (string data)
  2769. {
  2770. if (_readyState != WebSocketState.Open) {
  2771. var msg = "The current state of the interface is not Open.";
  2772. throw new InvalidOperationException (msg);
  2773. }
  2774. if (data == null)
  2775. throw new ArgumentNullException ("data");
  2776. byte[] bytes;
  2777. if (!data.TryGetUTF8EncodedBytes (out bytes)) {
  2778. var msg = "It could not be UTF-8-encoded.";
  2779. throw new ArgumentException (msg, "data");
  2780. }
  2781. send (Opcode.Text, new MemoryStream (bytes));
  2782. }
  2783. /// <summary>
  2784. /// Sends the data from the specified stream instance to the remote endpoint.
  2785. /// </summary>
  2786. /// <param name="stream">
  2787. /// <para>
  2788. /// A <see cref="Stream"/> instance from which to read the data to send.
  2789. /// </para>
  2790. /// <para>
  2791. /// The data is sent as the binary data.
  2792. /// </para>
  2793. /// </param>
  2794. /// <param name="length">
  2795. /// An <see cref="int"/> that specifies the number of bytes to send.
  2796. /// </param>
  2797. /// <exception cref="InvalidOperationException">
  2798. /// The current state of the interface is not Open.
  2799. /// </exception>
  2800. /// <exception cref="ArgumentNullException">
  2801. /// <paramref name="stream"/> is <see langword="null"/>.
  2802. /// </exception>
  2803. /// <exception cref="ArgumentException">
  2804. /// <para>
  2805. /// <paramref name="stream"/> cannot be read.
  2806. /// </para>
  2807. /// <para>
  2808. /// -or-
  2809. /// </para>
  2810. /// <para>
  2811. /// <paramref name="length"/> is less than 1.
  2812. /// </para>
  2813. /// <para>
  2814. /// -or-
  2815. /// </para>
  2816. /// <para>
  2817. /// No data could be read from <paramref name="stream"/>.
  2818. /// </para>
  2819. /// </exception>
  2820. public void Send (Stream stream, int length)
  2821. {
  2822. if (_readyState != WebSocketState.Open) {
  2823. var msg = "The current state of the interface is not Open.";
  2824. throw new InvalidOperationException (msg);
  2825. }
  2826. if (stream == null)
  2827. throw new ArgumentNullException ("stream");
  2828. if (!stream.CanRead) {
  2829. var msg = "It cannot be read.";
  2830. throw new ArgumentException (msg, "stream");
  2831. }
  2832. if (length < 1) {
  2833. var msg = "Less than 1.";
  2834. throw new ArgumentException (msg, "length");
  2835. }
  2836. var bytes = stream.ReadBytes (length);
  2837. var len = bytes.Length;
  2838. if (len == 0) {
  2839. var msg = "No data could be read from it.";
  2840. throw new ArgumentException (msg, "stream");
  2841. }
  2842. if (len < length) {
  2843. var fmt = "Only {0} byte(s) of data could be read from the stream.";
  2844. var msg = String.Format (fmt, len);
  2845. _log.Warn (msg);
  2846. }
  2847. send (Opcode.Binary, new MemoryStream (bytes));
  2848. }
  2849. /// <summary>
  2850. /// Sends the specified data to the remote endpoint asynchronously.
  2851. /// </summary>
  2852. /// <remarks>
  2853. /// This method does not wait for the send to be complete.
  2854. /// </remarks>
  2855. /// <param name="data">
  2856. /// An array of <see cref="byte"/> that specifies the binary data to send.
  2857. /// </param>
  2858. /// <param name="completed">
  2859. /// <para>
  2860. /// An <see cref="T:System.Action{bool}"/> delegate.
  2861. /// </para>
  2862. /// <para>
  2863. /// The delegate invokes the method called when the send is complete.
  2864. /// </para>
  2865. /// <para>
  2866. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  2867. /// if the send has successfully done; otherwise, <c>false</c>.
  2868. /// </para>
  2869. /// <para>
  2870. /// <see langword="null"/> if not necessary.
  2871. /// </para>
  2872. /// </param>
  2873. /// <exception cref="InvalidOperationException">
  2874. /// The current state of the interface is not Open.
  2875. /// </exception>
  2876. /// <exception cref="ArgumentNullException">
  2877. /// <paramref name="data"/> is <see langword="null"/>.
  2878. /// </exception>
  2879. public void SendAsync (byte[] data, Action<bool> completed)
  2880. {
  2881. if (_readyState != WebSocketState.Open) {
  2882. var msg = "The current state of the interface is not Open.";
  2883. throw new InvalidOperationException (msg);
  2884. }
  2885. if (data == null)
  2886. throw new ArgumentNullException ("data");
  2887. sendAsync (Opcode.Binary, new MemoryStream (data), completed);
  2888. }
  2889. /// <summary>
  2890. /// Sends the specified file to the remote endpoint asynchronously.
  2891. /// </summary>
  2892. /// <remarks>
  2893. /// This method does not wait for the send to be complete.
  2894. /// </remarks>
  2895. /// <param name="fileInfo">
  2896. /// <para>
  2897. /// A <see cref="FileInfo"/> that specifies the file to send.
  2898. /// </para>
  2899. /// <para>
  2900. /// The file is sent as the binary data.
  2901. /// </para>
  2902. /// </param>
  2903. /// <param name="completed">
  2904. /// <para>
  2905. /// An <see cref="T:System.Action{bool}"/> delegate.
  2906. /// </para>
  2907. /// <para>
  2908. /// The delegate invokes the method called when the send is complete.
  2909. /// </para>
  2910. /// <para>
  2911. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  2912. /// if the send has successfully done; otherwise, <c>false</c>.
  2913. /// </para>
  2914. /// <para>
  2915. /// <see langword="null"/> if not necessary.
  2916. /// </para>
  2917. /// </param>
  2918. /// <exception cref="InvalidOperationException">
  2919. /// The current state of the interface is not Open.
  2920. /// </exception>
  2921. /// <exception cref="ArgumentNullException">
  2922. /// <paramref name="fileInfo"/> is <see langword="null"/>.
  2923. /// </exception>
  2924. /// <exception cref="ArgumentException">
  2925. /// <para>
  2926. /// The file does not exist.
  2927. /// </para>
  2928. /// <para>
  2929. /// -or-
  2930. /// </para>
  2931. /// <para>
  2932. /// The file could not be opened.
  2933. /// </para>
  2934. /// </exception>
  2935. public void SendAsync (FileInfo fileInfo, Action<bool> completed)
  2936. {
  2937. if (_readyState != WebSocketState.Open) {
  2938. var msg = "The current state of the interface is not Open.";
  2939. throw new InvalidOperationException (msg);
  2940. }
  2941. if (fileInfo == null)
  2942. throw new ArgumentNullException ("fileInfo");
  2943. if (!fileInfo.Exists) {
  2944. var msg = "The file does not exist.";
  2945. throw new ArgumentException (msg, "fileInfo");
  2946. }
  2947. FileStream stream;
  2948. if (!fileInfo.TryOpenRead (out stream)) {
  2949. var msg = "The file could not be opened.";
  2950. throw new ArgumentException (msg, "fileInfo");
  2951. }
  2952. sendAsync (Opcode.Binary, stream, completed);
  2953. }
  2954. /// <summary>
  2955. /// Sends the specified data to the remote endpoint asynchronously.
  2956. /// </summary>
  2957. /// <remarks>
  2958. /// This method does not wait for the send to be complete.
  2959. /// </remarks>
  2960. /// <param name="data">
  2961. /// A <see cref="string"/> that specifies the text data to send.
  2962. /// </param>
  2963. /// <param name="completed">
  2964. /// <para>
  2965. /// An <see cref="T:System.Action{bool}"/> delegate.
  2966. /// </para>
  2967. /// <para>
  2968. /// The delegate invokes the method called when the send is complete.
  2969. /// </para>
  2970. /// <para>
  2971. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  2972. /// if the send has successfully done; otherwise, <c>false</c>.
  2973. /// </para>
  2974. /// <para>
  2975. /// <see langword="null"/> if not necessary.
  2976. /// </para>
  2977. /// </param>
  2978. /// <exception cref="InvalidOperationException">
  2979. /// The current state of the interface is not Open.
  2980. /// </exception>
  2981. /// <exception cref="ArgumentNullException">
  2982. /// <paramref name="data"/> is <see langword="null"/>.
  2983. /// </exception>
  2984. /// <exception cref="ArgumentException">
  2985. /// <paramref name="data"/> could not be UTF-8-encoded.
  2986. /// </exception>
  2987. public void SendAsync (string data, Action<bool> completed)
  2988. {
  2989. if (_readyState != WebSocketState.Open) {
  2990. var msg = "The current state of the interface is not Open.";
  2991. throw new InvalidOperationException (msg);
  2992. }
  2993. if (data == null)
  2994. throw new ArgumentNullException ("data");
  2995. byte[] bytes;
  2996. if (!data.TryGetUTF8EncodedBytes (out bytes)) {
  2997. var msg = "It could not be UTF-8-encoded.";
  2998. throw new ArgumentException (msg, "data");
  2999. }
  3000. sendAsync (Opcode.Text, new MemoryStream (bytes), completed);
  3001. }
  3002. /// <summary>
  3003. /// Sends the data from the specified stream instance to the remote
  3004. /// endpoint asynchronously.
  3005. /// </summary>
  3006. /// <remarks>
  3007. /// This method does not wait for the send to be complete.
  3008. /// </remarks>
  3009. /// <param name="stream">
  3010. /// <para>
  3011. /// A <see cref="Stream"/> instance from which to read the data to send.
  3012. /// </para>
  3013. /// <para>
  3014. /// The data is sent as the binary data.
  3015. /// </para>
  3016. /// </param>
  3017. /// <param name="length">
  3018. /// An <see cref="int"/> that specifies the number of bytes to send.
  3019. /// </param>
  3020. /// <param name="completed">
  3021. /// <para>
  3022. /// An <see cref="T:System.Action{bool}"/> delegate.
  3023. /// </para>
  3024. /// <para>
  3025. /// The delegate invokes the method called when the send is complete.
  3026. /// </para>
  3027. /// <para>
  3028. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  3029. /// if the send has successfully done; otherwise, <c>false</c>.
  3030. /// </para>
  3031. /// <para>
  3032. /// <see langword="null"/> if not necessary.
  3033. /// </para>
  3034. /// </param>
  3035. /// <exception cref="InvalidOperationException">
  3036. /// The current state of the interface is not Open.
  3037. /// </exception>
  3038. /// <exception cref="ArgumentNullException">
  3039. /// <paramref name="stream"/> is <see langword="null"/>.
  3040. /// </exception>
  3041. /// <exception cref="ArgumentException">
  3042. /// <para>
  3043. /// <paramref name="stream"/> cannot be read.
  3044. /// </para>
  3045. /// <para>
  3046. /// -or-
  3047. /// </para>
  3048. /// <para>
  3049. /// <paramref name="length"/> is less than 1.
  3050. /// </para>
  3051. /// <para>
  3052. /// -or-
  3053. /// </para>
  3054. /// <para>
  3055. /// No data could be read from <paramref name="stream"/>.
  3056. /// </para>
  3057. /// </exception>
  3058. public void SendAsync (Stream stream, int length, Action<bool> completed)
  3059. {
  3060. if (_readyState != WebSocketState.Open) {
  3061. var msg = "The current state of the interface is not Open.";
  3062. throw new InvalidOperationException (msg);
  3063. }
  3064. if (stream == null)
  3065. throw new ArgumentNullException ("stream");
  3066. if (!stream.CanRead) {
  3067. var msg = "It cannot be read.";
  3068. throw new ArgumentException (msg, "stream");
  3069. }
  3070. if (length < 1) {
  3071. var msg = "Less than 1.";
  3072. throw new ArgumentException (msg, "length");
  3073. }
  3074. var bytes = stream.ReadBytes (length);
  3075. var len = bytes.Length;
  3076. if (len == 0) {
  3077. var msg = "No data could be read from it.";
  3078. throw new ArgumentException (msg, "stream");
  3079. }
  3080. if (len < length) {
  3081. var fmt = "Only {0} byte(s) of data could be read from the stream.";
  3082. var msg = String.Format (fmt, len);
  3083. _log.Warn (msg);
  3084. }
  3085. sendAsync (Opcode.Binary, new MemoryStream (bytes), completed);
  3086. }
  3087. /// <summary>
  3088. /// Sets an HTTP cookie to send with the handshake request.
  3089. /// </summary>
  3090. /// <remarks>
  3091. /// This method works if the current state of the interface is
  3092. /// New or Closed.
  3093. /// </remarks>
  3094. /// <param name="cookie">
  3095. /// A <see cref="Cookie"/> that specifies the cookie to send.
  3096. /// </param>
  3097. /// <exception cref="InvalidOperationException">
  3098. /// The interface is not for the client.
  3099. /// </exception>
  3100. /// <exception cref="ArgumentNullException">
  3101. /// <paramref name="cookie"/> is <see langword="null"/>.
  3102. /// </exception>
  3103. public void SetCookie (Cookie cookie)
  3104. {
  3105. if (!_client) {
  3106. var msg = "The interface is not for the client.";
  3107. throw new InvalidOperationException (msg);
  3108. }
  3109. if (cookie == null)
  3110. throw new ArgumentNullException ("cookie");
  3111. lock (_forState) {
  3112. if (!canSet ())
  3113. return;
  3114. lock (_cookies.SyncRoot)
  3115. _cookies.SetOrRemove (cookie);
  3116. }
  3117. }
  3118. /// <summary>
  3119. /// Sets the credentials for the HTTP authentication (Basic/Digest).
  3120. /// </summary>
  3121. /// <remarks>
  3122. /// This method works if the current state of the interface is
  3123. /// New or Closed.
  3124. /// </remarks>
  3125. /// <param name="username">
  3126. /// <para>
  3127. /// A <see cref="string"/> that specifies the username associated
  3128. /// with the credentials.
  3129. /// </para>
  3130. /// <para>
  3131. /// <see langword="null"/> or an empty string if initializes
  3132. /// the credentials.
  3133. /// </para>
  3134. /// </param>
  3135. /// <param name="password">
  3136. /// <para>
  3137. /// A <see cref="string"/> that specifies the password for the
  3138. /// username associated with the credentials.
  3139. /// </para>
  3140. /// <para>
  3141. /// <see langword="null"/> or an empty string if not necessary.
  3142. /// </para>
  3143. /// </param>
  3144. /// <param name="preAuth">
  3145. /// A <see cref="bool"/>: <c>true</c> if sends the credentials for
  3146. /// the Basic authentication in advance with the first handshake
  3147. /// request; otherwise, <c>false</c>.
  3148. /// </param>
  3149. /// <exception cref="InvalidOperationException">
  3150. /// The interface is not for the client.
  3151. /// </exception>
  3152. /// <exception cref="ArgumentException">
  3153. /// <para>
  3154. /// <paramref name="username"/> contains an invalid character.
  3155. /// </para>
  3156. /// <para>
  3157. /// -or-
  3158. /// </para>
  3159. /// <para>
  3160. /// <paramref name="password"/> contains an invalid character.
  3161. /// </para>
  3162. /// </exception>
  3163. public void SetCredentials (string username, string password, bool preAuth)
  3164. {
  3165. if (!_client) {
  3166. var msg = "The interface is not for the client.";
  3167. throw new InvalidOperationException (msg);
  3168. }
  3169. if (!username.IsNullOrEmpty ()) {
  3170. if (username.Contains (':') || !username.IsText ()) {
  3171. var msg = "It contains an invalid character.";
  3172. throw new ArgumentException (msg, "username");
  3173. }
  3174. }
  3175. if (!password.IsNullOrEmpty ()) {
  3176. if (!password.IsText ()) {
  3177. var msg = "It contains an invalid character.";
  3178. throw new ArgumentException (msg, "password");
  3179. }
  3180. }
  3181. lock (_forState) {
  3182. if (!canSet ())
  3183. return;
  3184. if (username.IsNullOrEmpty ()) {
  3185. _credentials = null;
  3186. _preAuth = false;
  3187. return;
  3188. }
  3189. _credentials = new NetworkCredential (
  3190. username, password, _uri.PathAndQuery
  3191. );
  3192. _preAuth = preAuth;
  3193. }
  3194. }
  3195. /// <summary>
  3196. /// Sets the URL of the HTTP proxy server through which to connect and
  3197. /// the credentials for the HTTP proxy authentication (Basic/Digest).
  3198. /// </summary>
  3199. /// <remarks>
  3200. /// This method works if the current state of the interface is
  3201. /// New or Closed.
  3202. /// </remarks>
  3203. /// <param name="url">
  3204. /// <para>
  3205. /// A <see cref="string"/> that specifies the URL of the proxy
  3206. /// server through which to connect.
  3207. /// </para>
  3208. /// <para>
  3209. /// The syntax is http://&lt;host&gt;[:&lt;port&gt;].
  3210. /// </para>
  3211. /// <para>
  3212. /// <see langword="null"/> or an empty string if initializes
  3213. /// the URL and the credentials.
  3214. /// </para>
  3215. /// </param>
  3216. /// <param name="username">
  3217. /// <para>
  3218. /// A <see cref="string"/> that specifies the username associated
  3219. /// with the credentials.
  3220. /// </para>
  3221. /// <para>
  3222. /// <see langword="null"/> or an empty string if the credentials
  3223. /// are not necessary.
  3224. /// </para>
  3225. /// </param>
  3226. /// <param name="password">
  3227. /// <para>
  3228. /// A <see cref="string"/> that specifies the password for the
  3229. /// username associated with the credentials.
  3230. /// </para>
  3231. /// <para>
  3232. /// <see langword="null"/> or an empty string if not necessary.
  3233. /// </para>
  3234. /// </param>
  3235. /// <exception cref="InvalidOperationException">
  3236. /// The interface is not for the client.
  3237. /// </exception>
  3238. /// <exception cref="ArgumentException">
  3239. /// <para>
  3240. /// <paramref name="url"/> is not an absolute URI string.
  3241. /// </para>
  3242. /// <para>
  3243. /// -or-
  3244. /// </para>
  3245. /// <para>
  3246. /// The scheme of <paramref name="url"/> is not http.
  3247. /// </para>
  3248. /// <para>
  3249. /// -or-
  3250. /// </para>
  3251. /// <para>
  3252. /// <paramref name="url"/> includes the path segments.
  3253. /// </para>
  3254. /// <para>
  3255. /// -or-
  3256. /// </para>
  3257. /// <para>
  3258. /// <paramref name="username"/> contains an invalid character.
  3259. /// </para>
  3260. /// <para>
  3261. /// -or-
  3262. /// </para>
  3263. /// <para>
  3264. /// <paramref name="password"/> contains an invalid character.
  3265. /// </para>
  3266. /// </exception>
  3267. public void SetProxy (string url, string username, string password)
  3268. {
  3269. if (!_client) {
  3270. var msg = "The interface is not for the client.";
  3271. throw new InvalidOperationException (msg);
  3272. }
  3273. Uri uri = null;
  3274. if (!url.IsNullOrEmpty ()) {
  3275. if (!Uri.TryCreate (url, UriKind.Absolute, out uri)) {
  3276. var msg = "Not an absolute URI string.";
  3277. throw new ArgumentException (msg, "url");
  3278. }
  3279. if (uri.Scheme != "http") {
  3280. var msg = "The scheme part is not http.";
  3281. throw new ArgumentException (msg, "url");
  3282. }
  3283. if (uri.Segments.Length > 1) {
  3284. var msg = "It includes the path segments.";
  3285. throw new ArgumentException (msg, "url");
  3286. }
  3287. }
  3288. if (!username.IsNullOrEmpty ()) {
  3289. if (username.Contains (':') || !username.IsText ()) {
  3290. var msg = "It contains an invalid character.";
  3291. throw new ArgumentException (msg, "username");
  3292. }
  3293. }
  3294. if (!password.IsNullOrEmpty ()) {
  3295. if (!password.IsText ()) {
  3296. var msg = "It contains an invalid character.";
  3297. throw new ArgumentException (msg, "password");
  3298. }
  3299. }
  3300. lock (_forState) {
  3301. if (!canSet ())
  3302. return;
  3303. if (url.IsNullOrEmpty ()) {
  3304. _proxyUri = null;
  3305. _proxyCredentials = null;
  3306. return;
  3307. }
  3308. _proxyUri = uri;
  3309. _proxyCredentials = !username.IsNullOrEmpty ()
  3310. ? new NetworkCredential (
  3311. username,
  3312. password,
  3313. String.Format (
  3314. "{0}:{1}", _uri.DnsSafeHost, _uri.Port
  3315. )
  3316. )
  3317. : null;
  3318. }
  3319. }
  3320. #endregion
  3321. #region Explicit Interface Implementations
  3322. /// <summary>
  3323. /// Closes the connection and releases all associated resources.
  3324. /// </summary>
  3325. /// <remarks>
  3326. /// <para>
  3327. /// This method closes the connection with close status 1001 (going away).
  3328. /// </para>
  3329. /// <para>
  3330. /// This method does nothing if the current state of the interface is
  3331. /// Closing or Closed.
  3332. /// </para>
  3333. /// </remarks>
  3334. void IDisposable.Dispose ()
  3335. {
  3336. close (1001, String.Empty);
  3337. }
  3338. #endregion
  3339. }
  3340. }