HttpClientContext.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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 OSHttpServer.Exceptions;
  8. using OSHttpServer.Parser;
  9. using System.Net.Security;
  10. using System.Security.Cryptography.X509Certificates;
  11. using OpenMetaverse;
  12. using System.Threading.Tasks;
  13. namespace OSHttpServer
  14. {
  15. /// <summary>
  16. /// Contains a connection to a browser/client.
  17. /// </summary>
  18. /// <remarks>
  19. /// Remember to <see cref="Start"/> after you have hooked the <see cref="RequestReceived"/> event.
  20. /// </remarks>
  21. public class HttpClientContext : IHttpClientContext, IDisposable
  22. {
  23. const int MAXREQUESTS = 20;
  24. const int MAXKEEPALIVE = 120000;
  25. static private int basecontextID;
  26. Queue<HttpRequest> m_requests;
  27. readonly object m_requestsLock = new();
  28. public int m_maxRequests = MAXREQUESTS;
  29. public bool m_waitingResponse;
  30. private readonly byte[] m_ReceiveBuffer;
  31. private int m_ReceiveBytesLeft;
  32. private ILogWriter m_log;
  33. private readonly IHttpRequestParser m_parser;
  34. private Socket m_sock;
  35. public bool Available = true;
  36. public bool StreamPassedOff = false;
  37. public int LastActivityTimeMS = 0;
  38. public int MonitorKeepaliveStartMS = 0;
  39. public bool TriggerKeepalive = false;
  40. public int TimeoutFirstLine = 10000; // 10 seconds
  41. public int TimeoutRequestReceived = 30000; // 30 seconds
  42. public int TimeoutMaxIdle = 180000; // 3 minutes
  43. public int m_TimeoutKeepAlive = 30000;
  44. public bool FirstRequestLineReceived;
  45. public bool FullRequestReceived;
  46. private bool isSendingResponse = false;
  47. private bool m_isClosing = false;
  48. private HttpRequest m_currentRequest;
  49. private HttpResponse m_currentResponse;
  50. public int contextID { get; private set; }
  51. public int TimeoutKeepAlive
  52. {
  53. get { return m_TimeoutKeepAlive; }
  54. set
  55. {
  56. m_TimeoutKeepAlive = (value > MAXKEEPALIVE) ? MAXKEEPALIVE : value;
  57. }
  58. }
  59. public bool IsClosing
  60. {
  61. get { return m_isClosing;}
  62. }
  63. public int MaxRequests
  64. {
  65. get { return m_maxRequests; }
  66. set
  67. {
  68. if(value <= 1)
  69. m_maxRequests = 1;
  70. else
  71. m_maxRequests = value > MAXREQUESTS ? MAXREQUESTS : value;
  72. }
  73. }
  74. public bool IsSending()
  75. {
  76. return isSendingResponse;
  77. }
  78. public bool StopMonitoring;
  79. public IPEndPoint LocalIPEndPoint {get; set;}
  80. /// <summary>
  81. /// Initializes a new instance of the <see cref="HttpClientContext"/> class.
  82. /// </summary>
  83. /// <param name="secured">true if the connection is secured (SSL/TLS)</param>
  84. /// <param name="remoteEndPoint">client that connected.</param>
  85. /// <param name="stream">Stream used for communication</param>
  86. /// <param name="parserFactory">Used to create a <see cref="IHttpRequestParser"/>.</param>
  87. /// <param name="bufferSize">Size of buffer to use when reading data. Must be at least 4096 bytes.</param>
  88. /// <exception cref="SocketException">If <see cref="Socket.BeginReceive(byte[],int,int,SocketFlags,AsyncCallback,object)"/> fails</exception>
  89. /// <exception cref="ArgumentException">Stream must be writable and readable.</exception>
  90. public HttpClientContext(bool secured, IPEndPoint remoteEndPoint,
  91. Stream stream, ILogWriter m_logWriter, Socket sock)
  92. {
  93. if (!stream.CanWrite || !stream.CanRead)
  94. throw new ArgumentException("Stream must be writable and readable.");
  95. LocalIPEndPoint = remoteEndPoint;
  96. m_log = m_logWriter;
  97. m_isClosing = false;
  98. m_currentRequest = new HttpRequest(this);
  99. m_parser = new HttpRequestParser(m_log);
  100. m_parser.RequestCompleted += OnRequestCompleted;
  101. m_parser.RequestLineReceived += OnRequestLine;
  102. m_parser.HeaderReceived += OnHeaderReceived;
  103. m_parser.BodyBytesReceived += OnBodyBytesReceived;
  104. IsSecured = secured;
  105. m_stream = stream;
  106. m_sock = sock;
  107. m_ReceiveBuffer = new byte[16384];
  108. m_requests = new Queue<HttpRequest>();
  109. SSLCommonName = "";
  110. if (secured)
  111. {
  112. SslStream _ssl = (SslStream)m_stream;
  113. X509Certificate _cert1 = _ssl.RemoteCertificate;
  114. if (_cert1 is not null)
  115. {
  116. X509Certificate2 _cert2 = new(_cert1);
  117. if (_cert2 is not null)
  118. SSLCommonName = _cert2.GetNameInfo(X509NameType.SimpleName, false);
  119. }
  120. }
  121. ++basecontextID;
  122. if (basecontextID <= 0)
  123. basecontextID = 1;
  124. contextID = basecontextID;
  125. }
  126. public bool CanSend()
  127. {
  128. if (contextID < 0 || m_isClosing)
  129. return false;
  130. if (m_stream is null || m_sock is 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. private static readonly byte[] OSUTF8expect = osUTF8.GetASCIIBytes("expect");
  144. /// <summary>
  145. ///
  146. /// </summary>
  147. /// <param name="sender"></param>
  148. /// <param name="e"></param>
  149. protected virtual void OnHeaderReceived(object sender, HeaderEventArgs e)
  150. {
  151. if (e.Name.ACSIILowerEquals(OSUTF8expect) && e.Value.Contains("100-continue"))
  152. {
  153. lock (m_requestsLock)
  154. {
  155. if (m_maxRequests == MAXREQUESTS)
  156. Respond("HTTP/1.1", HttpStatusCode.Continue, null);
  157. }
  158. }
  159. m_currentRequest.AddHeader(e.Name.ToString(), e.Value.ToString());
  160. }
  161. private void OnRequestLine(object sender, RequestLineEventArgs e)
  162. {
  163. m_currentRequest.Method = e.HttpMethod.ToString();
  164. m_currentRequest.HttpVersion = e.HttpVersion.ToString();
  165. m_currentRequest.UriPath = e.UriPath.ToString();
  166. m_currentRequest.AddHeader("remote_addr", LocalIPEndPoint.Address.ToString());
  167. m_currentRequest.AddHeader("remote_port", LocalIPEndPoint.Port.ToString());
  168. m_currentRequest.ArrivalTS = ContextTimeoutManager.GetTimeStamp();
  169. FirstRequestLineReceived = true;
  170. TriggerKeepalive = false;
  171. MonitorKeepaliveStartMS = 0;
  172. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  173. }
  174. /// <summary>
  175. /// Start reading content.
  176. /// </summary>
  177. /// <remarks>
  178. /// Make sure to call base.Start() if you override this method.
  179. /// </remarks>
  180. public virtual void Start()
  181. {
  182. Task.Run(ReceiveLoop).ConfigureAwait(false);
  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 is not 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. m_requests = null;
  212. }
  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 is not 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. try
  299. {
  300. while (true)
  301. {
  302. if (m_stream == null || !m_stream.CanRead)
  303. return;
  304. int bytesRead =
  305. 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. return;
  313. m_ReceiveBytesLeft += bytesRead;
  314. int offset = m_parser.Parse(m_ReceiveBuffer, 0, m_ReceiveBytesLeft);
  315. if (m_stream is null)
  316. return; // "Connection: Close" in effect.
  317. if(offset > 0)
  318. {
  319. int nextBytesleft, nextOffset;
  320. while ((nextBytesleft = m_ReceiveBytesLeft - offset) > 0)
  321. {
  322. nextOffset = m_parser.Parse(m_ReceiveBuffer, offset, nextBytesleft);
  323. if (m_stream is null)
  324. return; // "Connection: Close" in effect.
  325. if (nextOffset == 0)
  326. break;
  327. offset = nextOffset;
  328. }
  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 (HttpException err)
  353. {
  354. LogWriter.Write(this, LogPrio.Warning, "Bad request, responding with it. Error: " + err.Message);
  355. try
  356. {
  357. Respond("HTTP/1.1", err.HttpStatusCode, err.Message);
  358. }
  359. catch (Exception err2)
  360. {
  361. LogWriter.Write(this, LogPrio.Fatal, "Failed to reply to a bad request. " + err2);
  362. }
  363. //Disconnect(SocketError.NoRecovery);
  364. Disconnect(SocketError.Success); // try to flush
  365. }
  366. catch (IOException err)
  367. {
  368. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
  369. if (err.InnerException is SocketException exception)
  370. Disconnect((SocketError)exception.ErrorCode);
  371. else
  372. Disconnect(SocketError.ConnectionReset);
  373. }
  374. catch (ObjectDisposedException err)
  375. {
  376. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : " + err.Message);
  377. Disconnect(SocketError.NotSocket);
  378. }
  379. catch (NullReferenceException err)
  380. {
  381. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : NullRef: " + err.Message);
  382. Disconnect(SocketError.NoRecovery);
  383. }
  384. catch (Exception err)
  385. {
  386. LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
  387. Disconnect(SocketError.NoRecovery);
  388. }
  389. }
  390. private void OnRequestCompleted(object source, EventArgs args)
  391. {
  392. TriggerKeepalive = false;
  393. MonitorKeepaliveStartMS = 0;
  394. FullRequestReceived = true;
  395. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  396. if (m_maxRequests <= 0 || RequestReceived is null)
  397. return;
  398. if (--m_maxRequests == 0)
  399. m_currentRequest.Connection = ConnectionType.Close;
  400. if(m_currentRequest.Uri is null)
  401. {
  402. // should not happen
  403. try
  404. {
  405. Uri uri = new(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath);
  406. m_currentRequest.Uri = uri;
  407. m_currentRequest.UriPath = uri.AbsolutePath;
  408. }
  409. catch
  410. {
  411. return;
  412. }
  413. }
  414. // load cookies if they exist
  415. if(m_currentRequest.Headers["cookie"] is not null)
  416. m_currentRequest.SetCookies(new RequestCookies(m_currentRequest.Headers["cookie"]));
  417. m_currentRequest.Body.Seek(0, SeekOrigin.Begin);
  418. HttpRequest currentRequest = m_currentRequest;
  419. m_currentRequest = new HttpRequest(this);
  420. lock (m_requestsLock)
  421. {
  422. if(m_waitingResponse)
  423. {
  424. m_requests.Enqueue(currentRequest);
  425. return;
  426. }
  427. else
  428. m_waitingResponse = true;
  429. }
  430. RequestReceived?.Invoke(this, new RequestEventArgs(currentRequest));
  431. }
  432. public void StartSendResponse(HttpResponse response)
  433. {
  434. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  435. isSendingResponse = true;
  436. m_currentResponse = response;
  437. ContextTimeoutManager.EnqueueSend(this, response.Priority);
  438. }
  439. public bool TrySendResponse(int bytesLimit)
  440. {
  441. if (m_currentResponse is null)
  442. return false;
  443. try
  444. {
  445. if (m_currentResponse.Sent)
  446. return false;
  447. if(!CanSend())
  448. return false;
  449. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  450. return m_currentResponse.SendNextAsync(bytesLimit);
  451. }
  452. catch
  453. {
  454. return false;
  455. }
  456. }
  457. public void ContinueSendResponse()
  458. {
  459. if(m_currentResponse is null)
  460. return;
  461. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  462. ContextTimeoutManager.EnqueueSend(this, m_currentResponse.Priority);
  463. }
  464. public void EndSendResponse(uint requestID, ConnectionType ctype)
  465. {
  466. isSendingResponse = false;
  467. m_currentResponse?.Clear();
  468. m_currentResponse = null;
  469. lock (m_requestsLock)
  470. m_waitingResponse = false;
  471. if(contextID < 0)
  472. return;
  473. if (ctype == ConnectionType.Close)
  474. {
  475. m_isClosing = true;
  476. m_requests.Clear();
  477. TriggerKeepalive = true;
  478. return;
  479. }
  480. else
  481. {
  482. if (Stream is null || !Stream.CanWrite)
  483. return;
  484. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  485. HttpRequest nextRequest = null;
  486. lock (m_requestsLock)
  487. {
  488. if (m_requests is not null && m_requests.Count > 0)
  489. nextRequest = m_requests.Dequeue();
  490. if (nextRequest is not null && RequestReceived is not null)
  491. {
  492. m_waitingResponse = true;
  493. TriggerKeepalive = false;
  494. }
  495. else
  496. TriggerKeepalive = true;
  497. }
  498. if (nextRequest is not null)
  499. RequestReceived?.Invoke(this, new RequestEventArgs(nextRequest));
  500. }
  501. ContextTimeoutManager.PulseWaitSend();
  502. }
  503. /// <summary>
  504. /// Send a response.
  505. /// </summary>
  506. /// <param name="httpVersion">Either <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/></param>
  507. /// <param name="statusCode">HTTP status code</param>
  508. /// <param name="reason">reason for the status code.</param>
  509. /// <param name="body">HTML body contents, can be null or empty.</param>
  510. /// <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>
  511. /// <exception cref="ArgumentException">If <paramref name="httpVersion"/> is invalid.</exception>
  512. public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType)
  513. {
  514. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  515. if (string.IsNullOrEmpty(reason))
  516. reason = statusCode.ToString();
  517. byte[] buffer;
  518. if(string.IsNullOrEmpty(body))
  519. buffer = Encoding.ASCII.GetBytes(httpVersion + " " + (int)statusCode + " " + reason + "\r\n\r\n");
  520. else
  521. {
  522. if (string.IsNullOrEmpty(contentType))
  523. contentType = "text/html";
  524. buffer = Encoding.UTF8.GetBytes(
  525. string.Format("{0} {1} {2}\r\nContent-Type: {5}\r\nContent-Length: {3}\r\n\r\n{4}",
  526. httpVersion, (int)statusCode, reason ?? statusCode.ToString(),
  527. body.Length, body, contentType));
  528. }
  529. Send(buffer);
  530. }
  531. /// <summary>
  532. /// Send a response.
  533. /// </summary>
  534. /// <param name="httpVersion">Either <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/></param>
  535. /// <param name="statusCode">HTTP status code</param>
  536. /// <param name="reason">reason for the status code.</param>
  537. public void Respond(string httpVersion, HttpStatusCode statusCode, string reason)
  538. {
  539. if (string.IsNullOrEmpty(reason))
  540. reason = statusCode.ToString();
  541. byte[] buffer = Encoding.ASCII.GetBytes(httpVersion + " " + (int)statusCode + " " + reason + "\r\n\r\n");
  542. Send(buffer);
  543. }
  544. /// <summary>
  545. /// send a whole buffer
  546. /// </summary>
  547. /// <param name="buffer">buffer to send</param>
  548. /// <exception cref="ArgumentNullException"></exception>
  549. public bool Send(byte[] buffer)
  550. {
  551. if (buffer is null)
  552. throw new ArgumentNullException("buffer");
  553. return Send(buffer, 0, buffer.Length);
  554. }
  555. /// <summary>
  556. /// Send data using the stream
  557. /// </summary>
  558. /// <param name="buffer">Contains data to send</param>
  559. /// <param name="offset">Start position in buffer</param>
  560. /// <param name="size">number of bytes to send</param>
  561. /// <exception cref="ArgumentNullException"></exception>
  562. /// <exception cref="ArgumentOutOfRangeException"></exception>
  563. private readonly object sendLock = new();
  564. public bool Send(byte[] buffer, int offset, int size)
  565. {
  566. if (m_stream is null || m_sock is null || !m_sock.Connected)
  567. return false;
  568. if (offset + size > buffer.Length)
  569. throw new ArgumentOutOfRangeException("offset", offset, "offset + size is beyond end of buffer.");
  570. LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
  571. bool ok = true;
  572. ContextTimeoutManager.ContextEnterActiveSend();
  573. lock (sendLock) // can't have overlaps here
  574. {
  575. try
  576. {
  577. m_stream.Write(buffer, offset, size);
  578. }
  579. catch
  580. {
  581. ok = false;
  582. }
  583. }
  584. ContextTimeoutManager.ContextLeaveActiveSend();
  585. if (!ok && m_stream is not null)
  586. Disconnect(SocketError.NoRecovery);
  587. return ok;
  588. }
  589. private void SendAsyncEnd(IAsyncResult res)
  590. {
  591. bool didleave = false;
  592. try
  593. {
  594. m_stream.EndWrite(res);
  595. ContextTimeoutManager.ContextLeaveActiveSend();
  596. m_currentResponse.CheckSendNextAsyncContinue();
  597. didleave = true;
  598. }
  599. catch (Exception e)
  600. {
  601. e.GetHashCode();
  602. if (m_stream is not null)
  603. Disconnect(SocketError.NoRecovery);
  604. }
  605. if(!didleave)
  606. ContextTimeoutManager.ContextLeaveActiveSend();
  607. }
  608. public bool SendAsyncStart(byte[] buffer, int offset, int size)
  609. {
  610. if (m_stream is null || m_sock is null || !m_sock.Connected)
  611. return false;
  612. if (offset + size > buffer.Length)
  613. throw new ArgumentOutOfRangeException("offset", offset, "offset + size is beyond end of buffer.");
  614. bool ok = true;
  615. ContextTimeoutManager.ContextEnterActiveSend();
  616. try
  617. {
  618. m_stream.BeginWrite(buffer, offset, size, SendAsyncEnd, null);
  619. }
  620. catch (Exception e)
  621. {
  622. e.GetHashCode();
  623. ContextTimeoutManager.ContextLeaveActiveSend();
  624. ok = false;
  625. }
  626. if (!ok && m_stream is not null)
  627. Disconnect(SocketError.NoRecovery);
  628. return ok;
  629. }
  630. /// <summary>
  631. /// The context have been disconnected.
  632. /// </summary>
  633. /// <remarks>
  634. /// Event can be used to clean up a context, or to reuse it.
  635. /// </remarks>
  636. public event EventHandler<DisconnectedEventArgs> Disconnected;
  637. /// <summary>
  638. /// A request have been received in the context.
  639. /// </summary>
  640. public event EventHandler<RequestEventArgs> RequestReceived;
  641. public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing()
  642. {
  643. StreamPassedOff = true;
  644. m_parser.RequestCompleted -= OnRequestCompleted;
  645. m_parser.RequestLineReceived -= OnRequestLine;
  646. m_parser.HeaderReceived -= OnHeaderReceived;
  647. m_parser.BodyBytesReceived -= OnBodyBytesReceived;
  648. m_parser.Clear();
  649. m_currentRequest?.Clear();
  650. m_currentRequest = null;
  651. m_currentResponse?.Clear();
  652. m_currentResponse = null;
  653. if (m_requests is not null)
  654. {
  655. while (m_requests.Count > 0)
  656. {
  657. HttpRequest req = m_requests.Dequeue();
  658. req.Clear();
  659. }
  660. }
  661. m_requests.Clear();
  662. m_requests = null;
  663. return new HTTPNetworkContext() { Socket = m_sock, Stream = m_stream as NetworkStream };
  664. }
  665. public void Dispose()
  666. {
  667. Dispose(true);
  668. GC.SuppressFinalize(this);
  669. }
  670. protected void Dispose(bool disposing)
  671. {
  672. if (contextID >= 0)
  673. {
  674. StreamPassedOff = false;
  675. Cleanup();
  676. }
  677. }
  678. }
  679. }