HttpListenerRequest.cs 17 KB

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