HttpClientContext.cs 25 KB

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