HttpClientContext.cs 27 KB

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