HttpConnection.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Security;
  5. using System.Net.Sockets;
  6. using System.Security.Authentication;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Model.Cryptography;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.System;
  14. using Microsoft.Extensions.Logging;
  15. namespace SocketHttpListener.Net
  16. {
  17. sealed class HttpConnection
  18. {
  19. private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead);
  20. const int BufferSize = 8192;
  21. Socket _socket;
  22. Stream _stream;
  23. HttpEndPointListener _epl;
  24. MemoryStream _memoryStream;
  25. byte[] _buffer;
  26. HttpListenerContext _context;
  27. StringBuilder _currentLine;
  28. ListenerPrefix _prefix;
  29. HttpRequestStream _requestStream;
  30. HttpResponseStream _responseStream;
  31. bool _chunked;
  32. int _reuses;
  33. bool _contextBound;
  34. bool secure;
  35. IPEndPoint local_ep;
  36. HttpListener _lastListener;
  37. X509Certificate cert;
  38. SslStream ssl_stream;
  39. private readonly ILogger _logger;
  40. private readonly ICryptoProvider _cryptoProvider;
  41. private readonly IStreamHelper _streamHelper;
  42. private readonly IFileSystem _fileSystem;
  43. private readonly IEnvironmentInfo _environment;
  44. public HttpConnection(ILogger logger, Socket socket, HttpEndPointListener epl, bool secure,
  45. X509Certificate cert, ICryptoProvider cryptoProvider, IStreamHelper streamHelper, IFileSystem fileSystem,
  46. IEnvironmentInfo environment)
  47. {
  48. _logger = logger;
  49. this._socket = socket;
  50. this._epl = epl;
  51. this.secure = secure;
  52. this.cert = cert;
  53. _cryptoProvider = cryptoProvider;
  54. _streamHelper = streamHelper;
  55. _fileSystem = fileSystem;
  56. _environment = environment;
  57. if (secure == false)
  58. {
  59. _stream = new SocketStream(_socket, false);
  60. }
  61. else
  62. {
  63. ssl_stream = new SslStream(new SocketStream(_socket, false), false, (t, c, ch, e) =>
  64. {
  65. if (c == null)
  66. {
  67. return true;
  68. }
  69. //var c2 = c as X509Certificate2;
  70. //if (c2 == null)
  71. //{
  72. // c2 = new X509Certificate2(c.GetRawCertData());
  73. //}
  74. //_clientCert = c2;
  75. //_clientCertErrors = new int[] { (int)e };
  76. return true;
  77. });
  78. _stream = ssl_stream;
  79. }
  80. }
  81. public Stream Stream => _stream;
  82. public async Task Init()
  83. {
  84. if (ssl_stream != null)
  85. {
  86. var enableAsync = true;
  87. if (enableAsync)
  88. {
  89. await ssl_stream.AuthenticateAsServerAsync(cert, false, (SslProtocols)ServicePointManager.SecurityProtocol, false).ConfigureAwait(false);
  90. }
  91. else
  92. {
  93. ssl_stream.AuthenticateAsServer(cert, false, (SslProtocols)ServicePointManager.SecurityProtocol, false);
  94. }
  95. }
  96. InitInternal();
  97. }
  98. private void InitInternal()
  99. {
  100. _contextBound = false;
  101. _requestStream = null;
  102. _responseStream = null;
  103. _prefix = null;
  104. _chunked = false;
  105. _memoryStream = new MemoryStream();
  106. _position = 0;
  107. _inputState = InputState.RequestLine;
  108. _lineState = LineState.None;
  109. _context = new HttpListenerContext(this);
  110. }
  111. public bool IsClosed => (_socket == null);
  112. public int Reuses => _reuses;
  113. public IPEndPoint LocalEndPoint
  114. {
  115. get
  116. {
  117. if (local_ep != null)
  118. return local_ep;
  119. local_ep = (IPEndPoint)_socket.LocalEndPoint;
  120. return local_ep;
  121. }
  122. }
  123. public IPEndPoint RemoteEndPoint => _socket.RemoteEndPoint as IPEndPoint;
  124. public bool IsSecure => secure;
  125. public ListenerPrefix Prefix
  126. {
  127. get => _prefix;
  128. set => _prefix = value;
  129. }
  130. private void OnTimeout(object unused)
  131. {
  132. //_logger.LogInformation("HttpConnection timer fired");
  133. CloseSocket();
  134. Unbind();
  135. }
  136. public void BeginReadRequest()
  137. {
  138. if (_buffer == null)
  139. _buffer = new byte[BufferSize];
  140. try
  141. {
  142. _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
  143. }
  144. catch
  145. {
  146. CloseSocket();
  147. Unbind();
  148. }
  149. }
  150. public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
  151. {
  152. if (_requestStream == null)
  153. {
  154. byte[] buffer = _memoryStream.GetBuffer();
  155. int length = (int)_memoryStream.Length;
  156. _memoryStream = null;
  157. if (chunked)
  158. {
  159. _chunked = true;
  160. //_context.Response.SendChunked = true;
  161. _requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
  162. }
  163. else
  164. {
  165. _requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
  166. }
  167. }
  168. return _requestStream;
  169. }
  170. public HttpResponseStream GetResponseStream(bool isExpect100Continue = false)
  171. {
  172. // TODO: can we get this _stream before reading the input?
  173. if (_responseStream == null)
  174. {
  175. var supportsDirectSocketAccess = !_context.Response.SendChunked && !isExpect100Continue && !secure;
  176. _responseStream = new HttpResponseStream(_stream, _context.Response, false, _streamHelper, _socket, supportsDirectSocketAccess, _environment, _fileSystem, _logger);
  177. }
  178. return _responseStream;
  179. }
  180. private static void OnRead(IAsyncResult ares)
  181. {
  182. var cnc = (HttpConnection)ares.AsyncState;
  183. cnc.OnReadInternal(ares);
  184. }
  185. private void OnReadInternal(IAsyncResult ares)
  186. {
  187. int nread = -1;
  188. try
  189. {
  190. nread = _stream.EndRead(ares);
  191. _memoryStream.Write(_buffer, 0, nread);
  192. if (_memoryStream.Length > 32768)
  193. {
  194. SendError("Bad Request", 400);
  195. Close(true);
  196. return;
  197. }
  198. }
  199. catch
  200. {
  201. if (_memoryStream != null && _memoryStream.Length > 0)
  202. SendError();
  203. if (_socket != null)
  204. {
  205. CloseSocket();
  206. Unbind();
  207. }
  208. return;
  209. }
  210. if (nread == 0)
  211. {
  212. CloseSocket();
  213. Unbind();
  214. return;
  215. }
  216. if (ProcessInput(_memoryStream))
  217. {
  218. if (!_context.HaveError)
  219. _context.Request.FinishInitialization();
  220. if (_context.HaveError)
  221. {
  222. SendError();
  223. Close(true);
  224. return;
  225. }
  226. if (!_epl.BindContext(_context))
  227. {
  228. const int NotFoundErrorCode = 404;
  229. SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
  230. Close(true);
  231. return;
  232. }
  233. HttpListener listener = _epl.Listener;
  234. if (_lastListener != listener)
  235. {
  236. RemoveConnection();
  237. listener.AddConnection(this);
  238. _lastListener = listener;
  239. }
  240. _contextBound = true;
  241. listener.RegisterContext(_context);
  242. return;
  243. }
  244. _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
  245. }
  246. private void RemoveConnection()
  247. {
  248. if (_lastListener == null)
  249. _epl.RemoveConnection(this);
  250. else
  251. _lastListener.RemoveConnection(this);
  252. }
  253. private enum InputState
  254. {
  255. RequestLine,
  256. Headers
  257. }
  258. private enum LineState
  259. {
  260. None,
  261. CR,
  262. LF
  263. }
  264. InputState _inputState = InputState.RequestLine;
  265. LineState _lineState = LineState.None;
  266. int _position;
  267. // true -> done processing
  268. // false -> need more input
  269. private bool ProcessInput(MemoryStream ms)
  270. {
  271. byte[] buffer = ms.GetBuffer();
  272. int len = (int)ms.Length;
  273. int used = 0;
  274. string line;
  275. while (true)
  276. {
  277. if (_context.HaveError)
  278. return true;
  279. if (_position >= len)
  280. break;
  281. try
  282. {
  283. line = ReadLine(buffer, _position, len - _position, ref used);
  284. _position += used;
  285. }
  286. catch
  287. {
  288. _context.ErrorMessage = "Bad request";
  289. _context.ErrorStatus = 400;
  290. return true;
  291. }
  292. if (line == null)
  293. break;
  294. if (line == "")
  295. {
  296. if (_inputState == InputState.RequestLine)
  297. continue;
  298. _currentLine = null;
  299. ms = null;
  300. return true;
  301. }
  302. if (_inputState == InputState.RequestLine)
  303. {
  304. _context.Request.SetRequestLine(line);
  305. _inputState = InputState.Headers;
  306. }
  307. else
  308. {
  309. try
  310. {
  311. _context.Request.AddHeader(line);
  312. }
  313. catch (Exception e)
  314. {
  315. _context.ErrorMessage = e.Message;
  316. _context.ErrorStatus = 400;
  317. return true;
  318. }
  319. }
  320. }
  321. if (used == len)
  322. {
  323. ms.SetLength(0);
  324. _position = 0;
  325. }
  326. return false;
  327. }
  328. private string ReadLine(byte[] buffer, int offset, int len, ref int used)
  329. {
  330. if (_currentLine == null)
  331. _currentLine = new StringBuilder(128);
  332. int last = offset + len;
  333. used = 0;
  334. for (int i = offset; i < last && _lineState != LineState.LF; i++)
  335. {
  336. used++;
  337. byte b = buffer[i];
  338. if (b == 13)
  339. {
  340. _lineState = LineState.CR;
  341. }
  342. else if (b == 10)
  343. {
  344. _lineState = LineState.LF;
  345. }
  346. else
  347. {
  348. _currentLine.Append((char)b);
  349. }
  350. }
  351. string result = null;
  352. if (_lineState == LineState.LF)
  353. {
  354. _lineState = LineState.None;
  355. result = _currentLine.ToString();
  356. _currentLine.Length = 0;
  357. }
  358. return result;
  359. }
  360. public void SendError(string msg, int status)
  361. {
  362. try
  363. {
  364. HttpListenerResponse response = _context.Response;
  365. response.StatusCode = status;
  366. response.ContentType = "text/html";
  367. string description = HttpStatusDescription.Get(status);
  368. string str;
  369. if (msg != null)
  370. str = string.Format("<h1>{0} ({1})</h1>", description, msg);
  371. else
  372. str = string.Format("<h1>{0}</h1>", description);
  373. byte[] error = Encoding.UTF8.GetBytes(str);
  374. response.Close(error, false);
  375. }
  376. catch
  377. {
  378. // response was already closed
  379. }
  380. }
  381. public void SendError()
  382. {
  383. SendError(_context.ErrorMessage, _context.ErrorStatus);
  384. }
  385. private void Unbind()
  386. {
  387. if (_contextBound)
  388. {
  389. _epl.UnbindContext(_context);
  390. _contextBound = false;
  391. }
  392. }
  393. public void Close()
  394. {
  395. Close(false);
  396. }
  397. private void CloseSocket()
  398. {
  399. if (_socket == null)
  400. return;
  401. try
  402. {
  403. _socket.Close();
  404. }
  405. catch { }
  406. finally
  407. {
  408. _socket = null;
  409. }
  410. RemoveConnection();
  411. }
  412. internal void Close(bool force)
  413. {
  414. if (_socket != null)
  415. {
  416. Stream st = GetResponseStream();
  417. if (st != null)
  418. st.Close();
  419. _responseStream = null;
  420. }
  421. if (_socket != null)
  422. {
  423. force |= !_context.Request.KeepAlive;
  424. if (!force)
  425. force = (string.Equals(_context.Response.Headers["connection"], "close", StringComparison.OrdinalIgnoreCase));
  426. if (!force && _context.Request.FlushInput())
  427. {
  428. if (_chunked && _context.Response.ForceCloseChunked == false)
  429. {
  430. // Don't close. Keep working.
  431. _reuses++;
  432. Unbind();
  433. InitInternal();
  434. BeginReadRequest();
  435. return;
  436. }
  437. _reuses++;
  438. Unbind();
  439. InitInternal();
  440. BeginReadRequest();
  441. return;
  442. }
  443. Socket s = _socket;
  444. _socket = null;
  445. try
  446. {
  447. if (s != null)
  448. s.Shutdown(SocketShutdown.Both);
  449. }
  450. catch
  451. {
  452. }
  453. finally
  454. {
  455. if (s != null)
  456. {
  457. try
  458. {
  459. s.Close();
  460. }
  461. catch { }
  462. }
  463. }
  464. Unbind();
  465. RemoveConnection();
  466. return;
  467. }
  468. }
  469. }
  470. }