HttpClientContext.cs 26 KB

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