HttpListenerRequest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Net;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Net;
  10. using MediaBrowser.Model.Services;
  11. using MediaBrowser.Model.Text;
  12. using SocketHttpListener.Primitives;
  13. using System.Collections.Generic;
  14. using SocketHttpListener.Net.WebSockets;
  15. namespace SocketHttpListener.Net
  16. {
  17. public sealed unsafe partial class HttpListenerRequest
  18. {
  19. private CookieCollection _cookies;
  20. private bool? _keepAlive;
  21. private string _rawUrl;
  22. private Uri _requestUri;
  23. private Version _version;
  24. public string[] AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]);
  25. public string[] UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]);
  26. private CookieCollection ParseCookies(Uri uri, string setCookieHeader)
  27. {
  28. CookieCollection cookies = new CookieCollection();
  29. return cookies;
  30. }
  31. public CookieCollection Cookies
  32. {
  33. get
  34. {
  35. if (_cookies == null)
  36. {
  37. string cookieString = Headers[HttpKnownHeaderNames.Cookie];
  38. if (!string.IsNullOrEmpty(cookieString))
  39. {
  40. _cookies = ParseCookies(RequestUri, cookieString);
  41. }
  42. if (_cookies == null)
  43. {
  44. _cookies = new CookieCollection();
  45. }
  46. }
  47. return _cookies;
  48. }
  49. }
  50. public Encoding ContentEncoding
  51. {
  52. get
  53. {
  54. if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
  55. {
  56. string postDataCharset = Headers["x-up-devcap-post-charset"];
  57. if (postDataCharset != null && postDataCharset.Length > 0)
  58. {
  59. try
  60. {
  61. return Encoding.GetEncoding(postDataCharset);
  62. }
  63. catch (ArgumentException)
  64. {
  65. }
  66. }
  67. }
  68. if (HasEntityBody)
  69. {
  70. if (ContentType != null)
  71. {
  72. string charSet = Helpers.GetCharSetValueFromHeader(ContentType);
  73. if (charSet != null)
  74. {
  75. try
  76. {
  77. return Encoding.GetEncoding(charSet);
  78. }
  79. catch (ArgumentException)
  80. {
  81. }
  82. }
  83. }
  84. }
  85. return TextEncodingExtensions.GetDefaultEncoding();
  86. }
  87. }
  88. public string ContentType => Headers[HttpKnownHeaderNames.ContentType];
  89. public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
  90. public bool IsWebSocketRequest
  91. {
  92. get
  93. {
  94. if (!SupportsWebSockets)
  95. {
  96. return false;
  97. }
  98. bool foundConnectionUpgradeHeader = false;
  99. if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade]))
  100. {
  101. return false;
  102. }
  103. foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection))
  104. {
  105. if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
  106. {
  107. foundConnectionUpgradeHeader = true;
  108. break;
  109. }
  110. }
  111. if (!foundConnectionUpgradeHeader)
  112. {
  113. return false;
  114. }
  115. foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade))
  116. {
  117. if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase))
  118. {
  119. return true;
  120. }
  121. }
  122. return false;
  123. }
  124. }
  125. public bool KeepAlive
  126. {
  127. get
  128. {
  129. if (!_keepAlive.HasValue)
  130. {
  131. string header = Headers[HttpKnownHeaderNames.ProxyConnection];
  132. if (string.IsNullOrEmpty(header))
  133. {
  134. header = Headers[HttpKnownHeaderNames.Connection];
  135. }
  136. if (string.IsNullOrEmpty(header))
  137. {
  138. if (ProtocolVersion >= HttpVersion.Version11)
  139. {
  140. _keepAlive = true;
  141. }
  142. else
  143. {
  144. header = Headers[HttpKnownHeaderNames.KeepAlive];
  145. _keepAlive = !string.IsNullOrEmpty(header);
  146. }
  147. }
  148. else
  149. {
  150. header = header.ToLower(CultureInfo.InvariantCulture);
  151. _keepAlive =
  152. header.IndexOf("close", StringComparison.OrdinalIgnoreCase) < 0 ||
  153. header.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0;
  154. }
  155. }
  156. return _keepAlive.Value;
  157. }
  158. }
  159. public QueryParamCollection QueryString
  160. {
  161. get
  162. {
  163. QueryParamCollection queryString = new QueryParamCollection();
  164. Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
  165. return queryString;
  166. }
  167. }
  168. public string RawUrl => _rawUrl;
  169. private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http;
  170. public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent];
  171. public string UserHostAddress => LocalEndPoint.ToString();
  172. public string UserHostName => Headers[HttpKnownHeaderNames.Host];
  173. public Uri UrlReferrer
  174. {
  175. get
  176. {
  177. string referrer = Headers[HttpKnownHeaderNames.Referer];
  178. if (referrer == null)
  179. {
  180. return null;
  181. }
  182. bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri urlReferrer);
  183. return success ? urlReferrer : null;
  184. }
  185. }
  186. public Uri Url => RequestUri;
  187. public Version ProtocolVersion => _version;
  188. private static class Helpers
  189. {
  190. //
  191. // Get attribute off header value
  192. //
  193. internal static string GetCharSetValueFromHeader(string headerValue)
  194. {
  195. const string AttrName = "charset";
  196. if (headerValue == null)
  197. return null;
  198. int l = headerValue.Length;
  199. int k = AttrName.Length;
  200. // find properly separated attribute name
  201. int i = 1; // start searching from 1
  202. while (i < l)
  203. {
  204. i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, AttrName, i, CompareOptions.IgnoreCase);
  205. if (i < 0)
  206. break;
  207. if (i + k >= l)
  208. break;
  209. char chPrev = headerValue[i - 1];
  210. char chNext = headerValue[i + k];
  211. if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext)))
  212. break;
  213. i += k;
  214. }
  215. if (i < 0 || i >= l)
  216. return null;
  217. // skip to '=' and the following whitespace
  218. i += k;
  219. while (i < l && char.IsWhiteSpace(headerValue[i]))
  220. i++;
  221. if (i >= l || headerValue[i] != '=')
  222. return null;
  223. i++;
  224. while (i < l && char.IsWhiteSpace(headerValue[i]))
  225. i++;
  226. if (i >= l)
  227. return null;
  228. // parse the value
  229. string attrValue = null;
  230. int j;
  231. if (i < l && headerValue[i] == '"')
  232. {
  233. if (i == l - 1)
  234. return null;
  235. j = headerValue.IndexOf('"', i + 1);
  236. if (j < 0 || j == i + 1)
  237. return null;
  238. attrValue = headerValue.Substring(i + 1, j - i - 1).Trim();
  239. }
  240. else
  241. {
  242. for (j = i; j < l; j++)
  243. {
  244. if (headerValue[j] == ';')
  245. break;
  246. }
  247. if (j == i)
  248. return null;
  249. attrValue = headerValue.Substring(i, j - i).Trim();
  250. }
  251. return attrValue;
  252. }
  253. internal static string[] ParseMultivalueHeader(string s)
  254. {
  255. if (s == null)
  256. return null;
  257. int l = s.Length;
  258. // collect comma-separated values into list
  259. List<string> values = new List<string>();
  260. int i = 0;
  261. while (i < l)
  262. {
  263. // find next ,
  264. int ci = s.IndexOf(',', i);
  265. if (ci < 0)
  266. ci = l;
  267. // append corresponding server value
  268. values.Add(s.Substring(i, ci - i));
  269. // move to next
  270. i = ci + 1;
  271. // skip leading space
  272. if (i < l && s[i] == ' ')
  273. i++;
  274. }
  275. // return list as array of strings
  276. int n = values.Count;
  277. string[] strings;
  278. // if n is 0 that means s was empty string
  279. if (n == 0)
  280. {
  281. strings = new string[1];
  282. strings[0] = string.Empty;
  283. }
  284. else
  285. {
  286. strings = new string[n];
  287. values.CopyTo(0, strings, 0, n);
  288. }
  289. return strings;
  290. }
  291. private static string UrlDecodeStringFromStringInternal(string s, Encoding e)
  292. {
  293. int count = s.Length;
  294. UrlDecoder helper = new UrlDecoder(count, e);
  295. // go through the string's chars collapsing %XX and %uXXXX and
  296. // appending each char as char, with exception of %XX constructs
  297. // that are appended as bytes
  298. for (int pos = 0; pos < count; pos++)
  299. {
  300. char ch = s[pos];
  301. if (ch == '+')
  302. {
  303. ch = ' ';
  304. }
  305. else if (ch == '%' && pos < count - 2)
  306. {
  307. if (s[pos + 1] == 'u' && pos < count - 5)
  308. {
  309. int h1 = HexToInt(s[pos + 2]);
  310. int h2 = HexToInt(s[pos + 3]);
  311. int h3 = HexToInt(s[pos + 4]);
  312. int h4 = HexToInt(s[pos + 5]);
  313. if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
  314. { // valid 4 hex chars
  315. ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
  316. pos += 5;
  317. // only add as char
  318. helper.AddChar(ch);
  319. continue;
  320. }
  321. }
  322. else
  323. {
  324. int h1 = HexToInt(s[pos + 1]);
  325. int h2 = HexToInt(s[pos + 2]);
  326. if (h1 >= 0 && h2 >= 0)
  327. { // valid 2 hex chars
  328. byte b = (byte)((h1 << 4) | h2);
  329. pos += 2;
  330. // don't add as char
  331. helper.AddByte(b);
  332. continue;
  333. }
  334. }
  335. }
  336. if ((ch & 0xFF80) == 0)
  337. helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
  338. else
  339. helper.AddChar(ch);
  340. }
  341. return helper.GetString();
  342. }
  343. private static int HexToInt(char h)
  344. {
  345. return (h >= '0' && h <= '9') ? h - '0' :
  346. (h >= 'a' && h <= 'f') ? h - 'a' + 10 :
  347. (h >= 'A' && h <= 'F') ? h - 'A' + 10 :
  348. -1;
  349. }
  350. private class UrlDecoder
  351. {
  352. private int _bufferSize;
  353. // Accumulate characters in a special array
  354. private int _numChars;
  355. private char[] _charBuffer;
  356. // Accumulate bytes for decoding into characters in a special array
  357. private int _numBytes;
  358. private byte[] _byteBuffer;
  359. // Encoding to convert chars to bytes
  360. private Encoding _encoding;
  361. private void FlushBytes()
  362. {
  363. if (_numBytes > 0)
  364. {
  365. _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
  366. _numBytes = 0;
  367. }
  368. }
  369. internal UrlDecoder(int bufferSize, Encoding encoding)
  370. {
  371. _bufferSize = bufferSize;
  372. _encoding = encoding;
  373. _charBuffer = new char[bufferSize];
  374. // byte buffer created on demand
  375. }
  376. internal void AddChar(char ch)
  377. {
  378. if (_numBytes > 0)
  379. FlushBytes();
  380. _charBuffer[_numChars++] = ch;
  381. }
  382. internal void AddByte(byte b)
  383. {
  384. {
  385. if (_byteBuffer == null)
  386. _byteBuffer = new byte[_bufferSize];
  387. _byteBuffer[_numBytes++] = b;
  388. }
  389. }
  390. internal string GetString()
  391. {
  392. if (_numBytes > 0)
  393. FlushBytes();
  394. if (_numChars > 0)
  395. return new string(_charBuffer, 0, _numChars);
  396. else
  397. return string.Empty;
  398. }
  399. }
  400. internal static void FillFromString(QueryParamCollection nvc, string s, bool urlencoded, Encoding encoding)
  401. {
  402. int l = (s != null) ? s.Length : 0;
  403. int i = (s.Length > 0 && s[0] == '?') ? 1 : 0;
  404. while (i < l)
  405. {
  406. // find next & while noting first = on the way (and if there are more)
  407. int si = i;
  408. int ti = -1;
  409. while (i < l)
  410. {
  411. char ch = s[i];
  412. if (ch == '=')
  413. {
  414. if (ti < 0)
  415. ti = i;
  416. }
  417. else if (ch == '&')
  418. {
  419. break;
  420. }
  421. i++;
  422. }
  423. // extract the name / value pair
  424. string name = null;
  425. string value = null;
  426. if (ti >= 0)
  427. {
  428. name = s.Substring(si, ti - si);
  429. value = s.Substring(ti + 1, i - ti - 1);
  430. }
  431. else
  432. {
  433. value = s.Substring(si, i - si);
  434. }
  435. // add name / value pair to the collection
  436. if (urlencoded)
  437. nvc.Add(
  438. name == null ? null : UrlDecodeStringFromStringInternal(name, encoding),
  439. UrlDecodeStringFromStringInternal(value, encoding));
  440. else
  441. nvc.Add(name, value);
  442. // trailing '&'
  443. if (i == l - 1 && s[i] == '&')
  444. nvc.Add(null, "");
  445. i++;
  446. }
  447. }
  448. }
  449. }
  450. }