HttpClientContext.cs 29 KB

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