2
0

HttpConnection.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. {
  140. _buffer = new byte[BufferSize];
  141. }
  142. try
  143. {
  144. _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
  145. }
  146. catch
  147. {
  148. CloseSocket();
  149. Unbind();
  150. }
  151. }
  152. public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
  153. {
  154. if (_requestStream == null)
  155. {
  156. byte[] buffer = _memoryStream.GetBuffer();
  157. int length = (int)_memoryStream.Length;
  158. _memoryStream = null;
  159. if (chunked)
  160. {
  161. _chunked = true;
  162. //_context.Response.SendChunked = true;
  163. _requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
  164. }
  165. else
  166. {
  167. _requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
  168. }
  169. }
  170. return _requestStream;
  171. }
  172. public HttpResponseStream GetResponseStream(bool isExpect100Continue = false)
  173. {
  174. // TODO: can we get this _stream before reading the input?
  175. if (_responseStream == null)
  176. {
  177. var supportsDirectSocketAccess = !_context.Response.SendChunked && !isExpect100Continue && !secure;
  178. _responseStream = new HttpResponseStream(_stream, _context.Response, false, _streamHelper, _socket, supportsDirectSocketAccess, _environment, _fileSystem, _logger);
  179. }
  180. return _responseStream;
  181. }
  182. private static void OnRead(IAsyncResult ares)
  183. {
  184. var cnc = (HttpConnection)ares.AsyncState;
  185. cnc.OnReadInternal(ares);
  186. }
  187. private void OnReadInternal(IAsyncResult ares)
  188. {
  189. int nread = -1;
  190. try
  191. {
  192. nread = _stream.EndRead(ares);
  193. _memoryStream.Write(_buffer, 0, nread);
  194. if (_memoryStream.Length > 32768)
  195. {
  196. SendError("Bad Request", 400);
  197. Close(true);
  198. return;
  199. }
  200. }
  201. catch
  202. {
  203. if (_memoryStream != null && _memoryStream.Length > 0)
  204. {
  205. SendError();
  206. }
  207. if (_socket != null)
  208. {
  209. CloseSocket();
  210. Unbind();
  211. }
  212. return;
  213. }
  214. if (nread == 0)
  215. {
  216. CloseSocket();
  217. Unbind();
  218. return;
  219. }
  220. if (ProcessInput(_memoryStream))
  221. {
  222. if (!_context.HaveError)
  223. _context.Request.FinishInitialization();
  224. if (_context.HaveError)
  225. {
  226. SendError();
  227. Close(true);
  228. return;
  229. }
  230. if (!_epl.BindContext(_context))
  231. {
  232. const int NotFoundErrorCode = 404;
  233. SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
  234. Close(true);
  235. return;
  236. }
  237. HttpListener listener = _epl.Listener;
  238. if (_lastListener != listener)
  239. {
  240. RemoveConnection();
  241. listener.AddConnection(this);
  242. _lastListener = listener;
  243. }
  244. _contextBound = true;
  245. listener.RegisterContext(_context);
  246. return;
  247. }
  248. _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
  249. }
  250. private void RemoveConnection()
  251. {
  252. if (_lastListener == null)
  253. _epl.RemoveConnection(this);
  254. else
  255. _lastListener.RemoveConnection(this);
  256. }
  257. private enum InputState
  258. {
  259. RequestLine,
  260. Headers
  261. }
  262. private enum LineState
  263. {
  264. None,
  265. CR,
  266. LF
  267. }
  268. InputState _inputState = InputState.RequestLine;
  269. LineState _lineState = LineState.None;
  270. int _position;
  271. // true -> done processing
  272. // false -> need more input
  273. private bool ProcessInput(MemoryStream ms)
  274. {
  275. byte[] buffer = ms.GetBuffer();
  276. int len = (int)ms.Length;
  277. int used = 0;
  278. string line;
  279. while (true)
  280. {
  281. if (_context.HaveError)
  282. return true;
  283. if (_position >= len)
  284. break;
  285. try
  286. {
  287. line = ReadLine(buffer, _position, len - _position, ref used);
  288. _position += used;
  289. }
  290. catch
  291. {
  292. _context.ErrorMessage = "Bad request";
  293. _context.ErrorStatus = 400;
  294. return true;
  295. }
  296. if (line == null)
  297. break;
  298. if (line == "")
  299. {
  300. if (_inputState == InputState.RequestLine)
  301. continue;
  302. _currentLine = null;
  303. ms = null;
  304. return true;
  305. }
  306. if (_inputState == InputState.RequestLine)
  307. {
  308. _context.Request.SetRequestLine(line);
  309. _inputState = InputState.Headers;
  310. }
  311. else
  312. {
  313. try
  314. {
  315. _context.Request.AddHeader(line);
  316. }
  317. catch (Exception e)
  318. {
  319. _context.ErrorMessage = e.Message;
  320. _context.ErrorStatus = 400;
  321. return true;
  322. }
  323. }
  324. }
  325. if (used == len)
  326. {
  327. ms.SetLength(0);
  328. _position = 0;
  329. }
  330. return false;
  331. }
  332. private string ReadLine(byte[] buffer, int offset, int len, ref int used)
  333. {
  334. if (_currentLine == null)
  335. _currentLine = new StringBuilder(128);
  336. int last = offset + len;
  337. used = 0;
  338. for (int i = offset; i < last && _lineState != LineState.LF; i++)
  339. {
  340. used++;
  341. byte b = buffer[i];
  342. if (b == 13)
  343. {
  344. _lineState = LineState.CR;
  345. }
  346. else if (b == 10)
  347. {
  348. _lineState = LineState.LF;
  349. }
  350. else
  351. {
  352. _currentLine.Append((char)b);
  353. }
  354. }
  355. string result = null;
  356. if (_lineState == LineState.LF)
  357. {
  358. _lineState = LineState.None;
  359. result = _currentLine.ToString();
  360. _currentLine.Length = 0;
  361. }
  362. return result;
  363. }
  364. public void SendError(string msg, int status)
  365. {
  366. try
  367. {
  368. HttpListenerResponse response = _context.Response;
  369. response.StatusCode = status;
  370. response.ContentType = "text/html";
  371. string description = HttpStatusDescription.Get(status);
  372. string str;
  373. if (msg != null)
  374. str = string.Format("<h1>{0} ({1})</h1>", description, msg);
  375. else
  376. str = string.Format("<h1>{0}</h1>", description);
  377. byte[] error = Encoding.UTF8.GetBytes(str);
  378. response.Close(error, false);
  379. }
  380. catch
  381. {
  382. // response was already closed
  383. }
  384. }
  385. public void SendError()
  386. {
  387. SendError(_context.ErrorMessage, _context.ErrorStatus);
  388. }
  389. private void Unbind()
  390. {
  391. if (_contextBound)
  392. {
  393. _epl.UnbindContext(_context);
  394. _contextBound = false;
  395. }
  396. }
  397. public void Close()
  398. {
  399. Close(false);
  400. }
  401. private void CloseSocket()
  402. {
  403. if (_socket == null)
  404. return;
  405. try
  406. {
  407. _socket.Close();
  408. }
  409. catch { }
  410. finally
  411. {
  412. _socket = null;
  413. }
  414. RemoveConnection();
  415. }
  416. internal void Close(bool force)
  417. {
  418. if (_socket != null)
  419. {
  420. Stream st = GetResponseStream();
  421. if (st != null)
  422. st.Close();
  423. _responseStream = null;
  424. }
  425. if (_socket != null)
  426. {
  427. force |= !_context.Request.KeepAlive;
  428. if (!force)
  429. {
  430. force = string.Equals(_context.Response.Headers["connection"], "close", StringComparison.OrdinalIgnoreCase);
  431. }
  432. if (!force && _context.Request.FlushInput())
  433. {
  434. if (_chunked && _context.Response.ForceCloseChunked == false)
  435. {
  436. // Don't close. Keep working.
  437. _reuses++;
  438. Unbind();
  439. InitInternal();
  440. BeginReadRequest();
  441. return;
  442. }
  443. _reuses++;
  444. Unbind();
  445. InitInternal();
  446. BeginReadRequest();
  447. return;
  448. }
  449. Socket s = _socket;
  450. _socket = null;
  451. try
  452. {
  453. s?.Shutdown(SocketShutdown.Both);
  454. }
  455. catch
  456. {
  457. }
  458. finally
  459. {
  460. try
  461. {
  462. s?.Close();
  463. }
  464. catch { }
  465. }
  466. Unbind();
  467. RemoveConnection();
  468. return;
  469. }
  470. }
  471. }
  472. }