HttpClientContext.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using OSHttpServer.Exceptions;
  9. using OSHttpServer.Parser;
  10. using System.Net.Security;
  11. using System.Security.Cryptography.X509Certificates;
  12. namespace OSHttpServer
  13. {
  14. /// <summary>
  15. /// Contains a connection to a browser/client.
  16. /// </summary>
  17. /// <remarks>
  18. /// Remember to <see cref="Start"/> after you have hooked the <see cref="RequestReceived"/> event.
  19. /// </remarks>
  20. public class HttpClientContext : IHttpClientContext, IDisposable
  21. {
  22. const int MAXREQUESTS = 20;
  23. const int MAXKEEPALIVE = 120000;
  24. static private int basecontextID;
  25. Queue<HttpRequest> m_requests;
  26. object m_requestsLock = new object();
  27. public int m_maxRequests = MAXREQUESTS;
  28. public bool m_waitingResponse;
  29. private readonly byte[] m_ReceiveBuffer;
  30. private int m_ReceiveBytesLeft;
  31. private ILogWriter m_log;
  32. private readonly IHttpRequestParser m_parser;
  33. private Socket m_sock;
  34. public bool Available = true;
  35. public bool StreamPassedOff = false;
  36. public int LastActivityTimeMS = 0;
  37. public int MonitorKeepaliveStartMS = 0;
  38. public bool TriggerKeepalive = false;
  39. public int TimeoutFirstLine = 10000; // 10 seconds
  40. public int TimeoutRequestReceived = 30000; // 30 seconds
  41. public int TimeoutMaxIdle = 180000; // 3 minutes
  42. public int m_TimeoutKeepAlive = 30000;
  43. public bool FirstRequestLineReceived;
  44. public bool FullRequestReceived;
  45. private bool isSendingResponse = false;
  46. private bool m_isClosing = false;
  47. private HttpRequest m_currentRequest;
  48. private HttpResponse m_currentResponse;
  49. public int contextID { get; private set; }
  50. public int TimeoutKeepAlive
  51. {
  52. get { return m_TimeoutKeepAlive; }
  53. set
  54. {
  55. m_TimeoutKeepAlive = (value > MAXKEEPALIVE) ? MAXKEEPALIVE : value;
  56. }
  57. }
  58. public bool IsClosing
  59. {
  60. get { return m_isClosing;}
  61. }
  62. public int MaxRequests
  63. {
  64. get { return m_maxRequests; }
  65. set
  66. {
  67. if(value <= 1)
  68. m_maxRequests = 1;
  69. else
  70. m_maxRequests = value > MAXREQUESTS ? MAXREQUESTS : value;
  71. }
  72. }
  73. public bool IsSending()
  74. {
  75. return isSendingResponse;
  76. }
  77. public bool StopMonitoring;
  78. public IPEndPoint LocalIPEndPoint {get; set;}
  79. /// <summary>
  80. /// Initializes a new instance of the <see cref="HttpClientContext"/> class.
  81. /// </summary>
  82. /// <param name="secured">true if the connection is secured (SSL/TLS)</param>
  83. /// <param name="remoteEndPoint">client that connected.</param>
  84. /// <param name="stream">Stream used for communication</param>
  85. /// <param name="parserFactory">Used to create a <see cref="IHttpRequestParser"/>.</param>
  86. /// <param name="bufferSize">Size of buffer to use when reading data. Must be at least 4096 bytes.</param>
  87. /// <exception cref="SocketException">If <see cref="Socket.BeginReceive(byte[],int,int,SocketFlags,AsyncCallback,object)"/> fails</exception>
  88. /// <exception cref="ArgumentException">Stream must be writable and readable.</exception>
  89. public HttpClientContext(bool secured, IPEndPoint remoteEndPoint,
  90. Stream stream, ILogWriter m_logWriter, Socket sock)
  91. {
  92. if (!stream.CanWrite || !stream.CanRead)
  93. throw new ArgumentException("Stream must be writable and readable.");
  94. LocalIPEndPoint = remoteEndPoint;
  95. m_log = m_logWriter;
  96. m_isClosing = false;
  97. m_parser = new HttpRequestParser(m_log);
  98. m_parser.RequestCompleted += OnRequestCompleted;
  99. m_parser.RequestLineReceived += OnRequestLine;
  100. m_parser.HeaderReceived += OnHeaderReceived;
  101. m_parser.BodyBytesReceived += OnBodyBytesReceived;
  102. m_currentRequest = new HttpRequest(this);
  103. IsSecured = secured;
  104. m_stream = stream;
  105. m_sock = sock;
  106. m_ReceiveBuffer = new byte[16384];
  107. m_requests = new Queue<HttpRequest>();
  108. SSLCommonName = "";
  109. if (secured)
  110. {
  111. SslStream _ssl = (SslStream)m_stream;
  112. X509Certificate _cert1 = _ssl.RemoteCertificate;
  113. if (_cert1 != null)
  114. {
  115. X509Certificate2 _cert2 = new X509Certificate2(_cert1);
  116. if (_cert2 != null)
  117. SSLCommonName = _cert2.GetNameInfo(X509NameType.SimpleName, false);
  118. }
  119. }
  120. ++basecontextID;
  121. if (basecontextID <= 0)
  122. basecontextID = 1;
  123. contextID = basecontextID;
  124. }
  125. public bool CanSend()
  126. {
  127. if (contextID < 0 || m_isClosing)
  128. return false;
  129. if (m_stream == null || m_sock == null || !m_sock.Connected)
  130. return false;
  131. return true;
  132. }
  133. /// <summary>
  134. /// Process incoming body bytes.
  135. /// </summary>
  136. /// <param name="sender"><see cref="IHttpRequestParser"/></param>
  137. /// <param name="e">Bytes</param>
  138. protected virtual void OnBodyBytesReceived(object sender, BodyEventArgs e)
  139. {
  140. m_currentRequest.AddToBody(e.Buffer, e.Offset, e.Count);
  141. }
  142. /// <summary>
  143. ///
  144. /// </summary>
  145. /// <param name="sender"></param>
  146. /// <param name="e"></param>
  147. protected virtual void OnHeaderReceived(object sender, HeaderEventArgs e)
  148. {
  149. if (string.Compare(e.Name, "expect", true) == 0 && e.Value.Contains("100-continue"))
  150. {
  151. lock (m_requestsLock)
  152. {
  153. if (m_maxRequests == MAXREQUESTS)
  154. Respond("HTTP/1.1", HttpStatusCode.Continue, null);
  155. }
  156. }
  157. m_currentRequest.AddHeader(e.Name, e.Value);
  158. }
  159. private void OnRequestLine(object sender, RequestLineEventArgs e)
  160. {
  161. m_currentRequest.Method = e.HttpMethod;
  162. m_currentRequest.HttpVersion = e.HttpVersion;
  163. m_currentRequest.UriPath = e.UriPath;
  164. m_currentRequest.AddHeader("remote_addr", LocalIPEndPoint.Address.ToString());
  165. m_currentRequest.AddHeader("remote_port", LocalIPEndPoint.Port.ToString());
  166. m_currentRequest.ArrivalTS = ContextTimeoutManager.GetTimeStamp();
  167. FirstRequestLineReceived = true;
  168. TriggerKeepalive = false;
  169. MonitorKeepaliveStartMS = 0;
  170. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  171. }
  172. /// <summary>
  173. /// Start reading content.
  174. /// </summary>
  175. /// <remarks>
  176. /// Make sure to call base.Start() if you override this method.
  177. /// </remarks>
  178. public virtual void Start()
  179. {
  180. Task tk = new Task(() => ReceiveLoop());
  181. tk.Start();
  182. }
  183. /// <summary>
  184. /// Clean up context.
  185. /// </summary>
  186. /// <remarks>
  187. /// </remarks>
  188. public virtual void Cleanup()
  189. {
  190. if (StreamPassedOff)
  191. return;
  192. contextID = -100;
  193. if (m_stream != null)
  194. {
  195. m_stream.Close();
  196. m_stream = null;
  197. m_sock = null;
  198. }
  199. m_currentRequest?.Clear();
  200. m_currentRequest = null;
  201. m_currentResponse?.Clear();
  202. m_currentResponse = null;
  203. if(m_requests != null)
  204. {
  205. while(m_requests.Count > 0)
  206. {
  207. HttpRequest req = m_requests.Dequeue();
  208. req.Clear();
  209. }
  210. }
  211. m_requests.Clear();
  212. m_requests = null;
  213. m_parser.Clear();
  214. FirstRequestLineReceived = false;
  215. FullRequestReceived = false;
  216. LastActivityTimeMS = 0;
  217. StopMonitoring = true;
  218. MonitorKeepaliveStartMS = 0;
  219. TriggerKeepalive = false;
  220. isSendingResponse = false;
  221. m_ReceiveBytesLeft = 0;
  222. }
  223. public void Close()
  224. {
  225. Dispose();
  226. }
  227. /// <summary>
  228. /// Using SSL or other encryption method.
  229. /// </summary>
  230. [Obsolete("Use IsSecured instead.")]
  231. public bool Secured
  232. {
  233. get { return IsSecured; }
  234. }
  235. /// <summary>
  236. /// Using SSL or other encryption method.
  237. /// </summary>
  238. public bool IsSecured { get; internal set; }
  239. // returns the SSL commonName of remote Certificate
  240. public string SSLCommonName { get; internal set; }
  241. /// <summary>
  242. /// Specify which logger to use.
  243. /// </summary>
  244. public ILogWriter LogWriter
  245. {
  246. get { return m_log; }
  247. set
  248. {
  249. m_log = value ?? NullLogWriter.Instance;
  250. m_parser.LogWriter = m_log;
  251. }
  252. }
  253. private Stream m_stream;
  254. /// <summary>
  255. /// Gets or sets the network stream.
  256. /// </summary>
  257. internal Stream Stream
  258. {
  259. get { return m_stream; }
  260. set { m_stream = value; }
  261. }
  262. /// <summary>
  263. /// Disconnect from client
  264. /// </summary>
  265. /// <param name="error">error to report in the <see cref="Disconnected"/> event.</param>
  266. public void Disconnect(SocketError error)
  267. {
  268. // disconnect may not throw any exceptions
  269. try
  270. {
  271. try
  272. {
  273. if (m_stream != null)
  274. {
  275. if (error == SocketError.Success)
  276. {
  277. try
  278. {
  279. m_stream.Flush();
  280. }
  281. catch { }
  282. }
  283. m_stream.Close();
  284. m_stream = null;
  285. }
  286. m_sock = null;
  287. }
  288. catch { }
  289. Disconnected?.Invoke(this, new DisconnectedEventArgs(error));
  290. }
  291. catch (Exception err)
  292. {
  293. LogWriter.Write(this, LogPrio.Error, "Disconnect threw an exception: " + err);
  294. }
  295. }
  296. private async void ReceiveLoop()
  297. {
  298. m_ReceiveBytesLeft = 0;
  299. try
  300. {
  301. while(true)
  302. {
  303. if (m_stream == null || !m_stream.CanRead)
  304. return;
  305. int bytesRead = await m_stream.ReadAsync(m_ReceiveBuffer, m_ReceiveBytesLeft, m_ReceiveBuffer.Length - m_ReceiveBytesLeft).ConfigureAwait(false);
  306. if (bytesRead == 0)
  307. {
  308. Disconnect(SocketError.Success);
  309. return;
  310. }
  311. if(m_isClosing)
  312. continue;
  313. m_ReceiveBytesLeft += bytesRead;
  314. int offset = m_parser.Parse(m_ReceiveBuffer, 0, m_ReceiveBytesLeft);
  315. if (m_stream == null)
  316. return; // "Connection: Close" in effect.
  317. while (offset != 0)
  318. {
  319. int nextBytesleft = m_ReceiveBytesLeft - offset;
  320. if(nextBytesleft <= 0)
  321. break;
  322. int nextOffset = m_parser.Parse(m_ReceiveBuffer, offset, nextBytesleft);
  323. if (m_stream == null)
  324. return; // "Connection: Close" in effect.
  325. if (nextOffset == 0)
  326. break;
  327. offset = nextOffset;
  328. }
  329. // copy unused bytes to the beginning of the array
  330. if (offset > 0 && m_ReceiveBytesLeft > offset)
  331. Buffer.BlockCopy(m_ReceiveBuffer, offset, m_ReceiveBuffer, 0, m_ReceiveBytesLeft - offset);
  332. m_ReceiveBytesLeft -= offset;
  333. if (StreamPassedOff)
  334. return; //?
  335. }
  336. }
  337. catch (BadRequestException err)
  338. {
  339. LogWriter.Write(this, LogPrio.Warning, "Bad request, responding with it. Error: " + err);
  340. try
  341. {
  342. Respond("HTTP/1.1", HttpStatusCode.BadRequest, err.Message);
  343. }
  344. catch (Exception err2)
  345. {
  346. LogWriter.Write(this, LogPrio.Fatal, "Failed to reply to a bad request. " + err2);
  347. }
  348. //Disconnect(SocketError.NoRecovery);
  349. Disconnect(SocketError.Success); // try to flush
  350. }
  351. catch (IOException err)
  352. {
  353. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
  354. if (err.InnerException is SocketException)
  355. Disconnect((SocketError)((SocketException)err.InnerException).ErrorCode);
  356. else
  357. Disconnect(SocketError.ConnectionReset);
  358. }
  359. catch (ObjectDisposedException err)
  360. {
  361. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : " + err.Message);
  362. Disconnect(SocketError.NotSocket);
  363. }
  364. catch (NullReferenceException err)
  365. {
  366. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : NullRef: " + err.Message);
  367. Disconnect(SocketError.NoRecovery);
  368. }
  369. catch (Exception err)
  370. {
  371. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
  372. Disconnect(SocketError.NoRecovery);
  373. }
  374. }
  375. private void OnRequestCompleted(object source, EventArgs args)
  376. {
  377. TriggerKeepalive = false;
  378. MonitorKeepaliveStartMS = 0;
  379. FullRequestReceived = true;
  380. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  381. if (m_maxRequests == 0)
  382. return;
  383. if (--m_maxRequests == 0)
  384. m_currentRequest.Connection = ConnectionType.Close;
  385. if(m_currentRequest.Uri == null)
  386. {
  387. // should not happen
  388. try
  389. {
  390. Uri uri = new Uri(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath);
  391. m_currentRequest.Uri = uri;
  392. m_currentRequest.UriPath = uri.AbsolutePath;
  393. }
  394. catch
  395. {
  396. return;
  397. }
  398. }
  399. // load cookies if they exist
  400. if(m_currentRequest.Headers["cookie"] != null)
  401. m_currentRequest.SetCookies(new RequestCookies(m_currentRequest.Headers["cookie"]));
  402. m_currentRequest.Body.Seek(0, SeekOrigin.Begin);
  403. bool donow = true;
  404. lock (m_requestsLock)
  405. {
  406. if(m_waitingResponse)
  407. {
  408. m_requests.Enqueue(m_currentRequest);
  409. donow = false;
  410. }
  411. else
  412. m_waitingResponse = true;
  413. }
  414. if(donow)
  415. RequestReceived?.Invoke(this, new RequestEventArgs(m_currentRequest));
  416. m_currentRequest = new HttpRequest(this);
  417. }
  418. public void StartSendResponse(HttpResponse response)
  419. {
  420. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  421. isSendingResponse = true;
  422. m_currentResponse = response;
  423. ContextTimeoutManager.EnqueueSend(this, response.Priority);
  424. }
  425. public bool TrySendResponse(int bytesLimit)
  426. {
  427. if(m_currentResponse == null)
  428. return false;
  429. if (m_currentResponse.Sent)
  430. return false;
  431. if(!CanSend())
  432. return false;
  433. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  434. m_currentResponse?.SendNextAsync(bytesLimit);
  435. return false;
  436. }
  437. public void ContinueSendResponse(bool notThrottled)
  438. {
  439. if(m_currentResponse == null)
  440. return;
  441. ContextTimeoutManager.EnqueueSend(this, m_currentResponse.Priority, notThrottled);
  442. }
  443. public void EndSendResponse(uint requestID, ConnectionType ctype)
  444. {
  445. isSendingResponse = false;
  446. m_currentResponse?.Clear();
  447. m_currentResponse = null;
  448. lock (m_requestsLock)
  449. m_waitingResponse = false;
  450. if(contextID < 0)
  451. return;
  452. if (ctype == ConnectionType.Close)
  453. {
  454. m_isClosing = true;
  455. m_requests.Clear();
  456. TriggerKeepalive = true;
  457. return;
  458. }
  459. else
  460. {
  461. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  462. if (Stream == null || !Stream.CanWrite)
  463. return;
  464. HttpRequest nextRequest = null;
  465. lock (m_requestsLock)
  466. {
  467. if (m_requests != null && m_requests.Count > 0)
  468. nextRequest = m_requests.Dequeue();
  469. if (nextRequest != null && RequestReceived != null)
  470. {
  471. m_waitingResponse = true;
  472. TriggerKeepalive = false;
  473. }
  474. else
  475. TriggerKeepalive = true;
  476. }
  477. if (nextRequest != null)
  478. RequestReceived?.Invoke(this, new RequestEventArgs(nextRequest));
  479. }
  480. }
  481. /// <summary>
  482. /// Send a response.
  483. /// </summary>
  484. /// <param name="httpVersion">Either <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/></param>
  485. /// <param name="statusCode">HTTP status code</param>
  486. /// <param name="reason">reason for the status code.</param>
  487. /// <param name="body">HTML body contents, can be null or empty.</param>
  488. /// <param name="contentType">A content type to return the body as, i.e. 'text/html' or 'text/plain', defaults to 'text/html' if null or empty</param>
  489. /// <exception cref="ArgumentException">If <paramref name="httpVersion"/> is invalid.</exception>
  490. public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType)
  491. {
  492. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  493. if (string.IsNullOrEmpty(reason))
  494. reason = statusCode.ToString();
  495. byte[] buffer;
  496. if(string.IsNullOrEmpty(body))
  497. buffer = Encoding.ASCII.GetBytes(httpVersion + " " + (int)statusCode + " " + reason + "\r\n\r\n");
  498. else
  499. {
  500. if (string.IsNullOrEmpty(contentType))
  501. contentType = "text/html";
  502. buffer = Encoding.UTF8.GetBytes(
  503. string.Format("{0} {1} {2}\r\nContent-Type: {5}\r\nContent-Length: {3}\r\n\r\n{4}",
  504. httpVersion, (int)statusCode, reason ?? statusCode.ToString(),
  505. body.Length, body, contentType));
  506. }
  507. Send(buffer);
  508. }
  509. /// <summary>
  510. /// Send a response.
  511. /// </summary>
  512. /// <param name="httpVersion">Either <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/></param>
  513. /// <param name="statusCode">HTTP status code</param>
  514. /// <param name="reason">reason for the status code.</param>
  515. public void Respond(string httpVersion, HttpStatusCode statusCode, string reason)
  516. {
  517. if (string.IsNullOrEmpty(reason))
  518. reason = statusCode.ToString();
  519. byte[] buffer = Encoding.ASCII.GetBytes(httpVersion + " " + (int)statusCode + " " + reason + "\r\n\r\n");
  520. Send(buffer);
  521. }
  522. /// <summary>
  523. /// send a whole buffer
  524. /// </summary>
  525. /// <param name="buffer">buffer to send</param>
  526. /// <exception cref="ArgumentNullException"></exception>
  527. public bool Send(byte[] buffer)
  528. {
  529. if (buffer == null)
  530. throw new ArgumentNullException("buffer");
  531. return Send(buffer, 0, buffer.Length);
  532. }
  533. /// <summary>
  534. /// Send data using the stream
  535. /// </summary>
  536. /// <param name="buffer">Contains data to send</param>
  537. /// <param name="offset">Start position in buffer</param>
  538. /// <param name="size">number of bytes to send</param>
  539. /// <exception cref="ArgumentNullException"></exception>
  540. /// <exception cref="ArgumentOutOfRangeException"></exception>
  541. private object sendLock = new object();
  542. public bool Send(byte[] buffer, int offset, int size)
  543. {
  544. if (m_stream == null || m_sock == null || !m_sock.Connected)
  545. return false;
  546. if (offset + size > buffer.Length)
  547. throw new ArgumentOutOfRangeException("offset", offset, "offset + size is beyond end of buffer.");
  548. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  549. bool ok = true;
  550. ContextTimeoutManager.ContextEnterActiveSend();
  551. lock (sendLock) // can't have overlaps here
  552. {
  553. try
  554. {
  555. m_stream.Write(buffer, offset, size);
  556. }
  557. catch
  558. {
  559. ok = false;
  560. }
  561. }
  562. ContextTimeoutManager.ContextLeaveActiveSend();
  563. if (!ok && m_stream != null)
  564. Disconnect(SocketError.NoRecovery);
  565. return ok;
  566. }
  567. public async Task<bool> SendAsync(byte[] buffer, int offset, int size)
  568. {
  569. if (m_stream == null || m_sock == null || !m_sock.Connected)
  570. return false;
  571. if (offset + size > buffer.Length)
  572. throw new ArgumentOutOfRangeException("offset", offset, "offset + size is beyond end of buffer.");
  573. bool ok = true;
  574. ContextTimeoutManager.ContextEnterActiveSend();
  575. try
  576. {
  577. await m_stream.WriteAsync(buffer, offset, size).ConfigureAwait(false);
  578. }
  579. catch
  580. {
  581. ok = false;
  582. }
  583. ContextTimeoutManager.ContextLeaveActiveSend();
  584. if (!ok && m_stream != null)
  585. Disconnect(SocketError.NoRecovery);
  586. return ok;
  587. }
  588. /// <summary>
  589. /// The context have been disconnected.
  590. /// </summary>
  591. /// <remarks>
  592. /// Event can be used to clean up a context, or to reuse it.
  593. /// </remarks>
  594. public event EventHandler<DisconnectedEventArgs> Disconnected;
  595. /// <summary>
  596. /// A request have been received in the context.
  597. /// </summary>
  598. public event EventHandler<RequestEventArgs> RequestReceived;
  599. public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing()
  600. {
  601. StreamPassedOff = true;
  602. m_parser.RequestCompleted -= OnRequestCompleted;
  603. m_parser.RequestLineReceived -= OnRequestLine;
  604. m_parser.HeaderReceived -= OnHeaderReceived;
  605. m_parser.BodyBytesReceived -= OnBodyBytesReceived;
  606. m_parser.Clear();
  607. m_currentRequest?.Clear();
  608. m_currentRequest = null;
  609. m_currentResponse?.Clear();
  610. m_currentResponse = null;
  611. if (m_requests != null)
  612. {
  613. while (m_requests.Count > 0)
  614. {
  615. HttpRequest req = m_requests.Dequeue();
  616. req.Clear();
  617. }
  618. }
  619. m_requests.Clear();
  620. m_requests = null;
  621. return new HTTPNetworkContext() { Socket = m_sock, Stream = m_stream as NetworkStream };
  622. }
  623. public void Dispose()
  624. {
  625. Dispose(true);
  626. GC.SuppressFinalize(this);
  627. }
  628. protected void Dispose(bool disposing)
  629. {
  630. if (contextID >= 0)
  631. {
  632. StreamPassedOff = false;
  633. Cleanup();
  634. }
  635. }
  636. }
  637. }