HttpListenerRequest.cs 17 KB

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