HttpConnection.cs 16 KB

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