RequestMono.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Model.Services;
  9. using Microsoft.Extensions.Primitives;
  10. using Microsoft.Net.Http.Headers;
  11. namespace Emby.Server.Implementations.SocketSharp
  12. {
  13. public partial class WebSocketSharpRequest : IHttpRequest
  14. {
  15. internal static string GetParameter(ReadOnlySpan<char> header, string attr)
  16. {
  17. int ap = header.IndexOf(attr.AsSpan(), StringComparison.Ordinal);
  18. if (ap == -1)
  19. {
  20. return null;
  21. }
  22. ap += attr.Length;
  23. if (ap >= header.Length)
  24. {
  25. return null;
  26. }
  27. char ending = header[ap];
  28. if (ending != '"')
  29. {
  30. ending = ' ';
  31. }
  32. var slice = header.Slice(ap + 1);
  33. int end = slice.IndexOf(ending);
  34. if (end == -1)
  35. {
  36. return ending == '"' ? null : header.Slice(ap).ToString();
  37. }
  38. return slice.Slice(0, end - ap - 1).ToString();
  39. }
  40. private async Task LoadMultiPart(WebROCollection form)
  41. {
  42. string boundary = GetParameter(ContentType.AsSpan(), "; boundary=");
  43. if (boundary == null)
  44. {
  45. return;
  46. }
  47. using (var requestStream = InputStream)
  48. {
  49. // DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
  50. // Not ending with \r\n?
  51. var ms = new MemoryStream(32 * 1024);
  52. await requestStream.CopyToAsync(ms).ConfigureAwait(false);
  53. var input = ms;
  54. ms.WriteByte((byte)'\r');
  55. ms.WriteByte((byte)'\n');
  56. input.Position = 0;
  57. // Uncomment to debug
  58. // var content = new StreamReader(ms).ReadToEnd();
  59. // Console.WriteLine(boundary + "::" + content);
  60. // input.Position = 0;
  61. var multi_part = new HttpMultipart(input, boundary, ContentEncoding);
  62. HttpMultipart.Element e;
  63. while ((e = multi_part.ReadNextElement()) != null)
  64. {
  65. if (e.Filename == null)
  66. {
  67. byte[] copy = new byte[e.Length];
  68. input.Position = e.Start;
  69. await input.ReadAsync(copy, 0, (int)e.Length).ConfigureAwait(false);
  70. form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
  71. }
  72. else
  73. {
  74. // We use a substream, as in 2.x we will support large uploads streamed to disk,
  75. files[e.Name] = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
  76. }
  77. }
  78. }
  79. }
  80. public async Task<QueryParamCollection> GetFormData()
  81. {
  82. var form = new WebROCollection();
  83. files = new Dictionary<string, HttpPostedFile>();
  84. if (IsContentType("multipart/form-data"))
  85. {
  86. await LoadMultiPart(form).ConfigureAwait(false);
  87. }
  88. else if (IsContentType("application/x-www-form-urlencoded"))
  89. {
  90. await LoadWwwForm(form).ConfigureAwait(false);
  91. }
  92. if (validate_form && !checked_form)
  93. {
  94. checked_form = true;
  95. ValidateNameValueCollection("Form", form);
  96. }
  97. return form;
  98. }
  99. public string Accept => StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Accept]) ? null : request.Headers[HeaderNames.Accept].ToString();
  100. public string Authorization => StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Authorization]) ? null : request.Headers[HeaderNames.Authorization].ToString();
  101. protected bool validate_form { get; set; }
  102. protected bool checked_form { get; set; }
  103. private static void ThrowValidationException(string name, string key, string value)
  104. {
  105. string v = "\"" + value + "\"";
  106. if (v.Length > 20)
  107. {
  108. v = v.Substring(0, 16) + "...\"";
  109. }
  110. string msg = string.Format(
  111. CultureInfo.InvariantCulture,
  112. "A potentially dangerous Request.{0} value was detected from the client ({1}={2}).",
  113. name,
  114. key,
  115. v);
  116. throw new Exception(msg);
  117. }
  118. private static void ValidateNameValueCollection(string name, QueryParamCollection coll)
  119. {
  120. if (coll == null)
  121. {
  122. return;
  123. }
  124. foreach (var pair in coll)
  125. {
  126. var key = pair.Name;
  127. var val = pair.Value;
  128. if (val != null && val.Length > 0 && IsInvalidString(val))
  129. {
  130. ThrowValidationException(name, key, val);
  131. }
  132. }
  133. }
  134. internal static bool IsInvalidString(string val)
  135. => IsInvalidString(val, out var validationFailureIndex);
  136. internal static bool IsInvalidString(string val, out int validationFailureIndex)
  137. {
  138. validationFailureIndex = 0;
  139. int len = val.Length;
  140. if (len < 2)
  141. {
  142. return false;
  143. }
  144. char current = val[0];
  145. for (int idx = 1; idx < len; idx++)
  146. {
  147. char next = val[idx];
  148. // See http://secunia.com/advisories/14325
  149. if (current == '<' || current == '\xff1c')
  150. {
  151. if (next == '!' || next < ' '
  152. || (next >= 'a' && next <= 'z')
  153. || (next >= 'A' && next <= 'Z'))
  154. {
  155. validationFailureIndex = idx - 1;
  156. return true;
  157. }
  158. }
  159. else if (current == '&' && next == '#')
  160. {
  161. validationFailureIndex = idx - 1;
  162. return true;
  163. }
  164. current = next;
  165. }
  166. return false;
  167. }
  168. private bool IsContentType(string ct)
  169. {
  170. if (ContentType == null)
  171. {
  172. return false;
  173. }
  174. return ContentType.StartsWith(ct, StringComparison.OrdinalIgnoreCase);
  175. }
  176. private async Task LoadWwwForm(WebROCollection form)
  177. {
  178. using (var input = InputStream)
  179. {
  180. using (var ms = new MemoryStream())
  181. {
  182. await input.CopyToAsync(ms).ConfigureAwait(false);
  183. ms.Position = 0;
  184. using (var s = new StreamReader(ms, ContentEncoding))
  185. {
  186. var key = new StringBuilder();
  187. var value = new StringBuilder();
  188. int c;
  189. while ((c = s.Read()) != -1)
  190. {
  191. if (c == '=')
  192. {
  193. value.Length = 0;
  194. while ((c = s.Read()) != -1)
  195. {
  196. if (c == '&')
  197. {
  198. AddRawKeyValue(form, key, value);
  199. break;
  200. }
  201. else
  202. {
  203. value.Append((char)c);
  204. }
  205. }
  206. if (c == -1)
  207. {
  208. AddRawKeyValue(form, key, value);
  209. return;
  210. }
  211. }
  212. else if (c == '&')
  213. {
  214. AddRawKeyValue(form, key, value);
  215. }
  216. else
  217. {
  218. key.Append((char)c);
  219. }
  220. }
  221. if (c == -1)
  222. {
  223. AddRawKeyValue(form, key, value);
  224. }
  225. }
  226. }
  227. }
  228. }
  229. private static void AddRawKeyValue(WebROCollection form, StringBuilder key, StringBuilder value)
  230. {
  231. form.Add(WebUtility.UrlDecode(key.ToString()), WebUtility.UrlDecode(value.ToString()));
  232. key.Length = 0;
  233. value.Length = 0;
  234. }
  235. private Dictionary<string, HttpPostedFile> files;
  236. private class WebROCollection : QueryParamCollection
  237. {
  238. public override string ToString()
  239. {
  240. var result = new StringBuilder();
  241. foreach (var pair in this)
  242. {
  243. if (result.Length > 0)
  244. {
  245. result.Append('&');
  246. }
  247. var key = pair.Name;
  248. if (key != null && key.Length > 0)
  249. {
  250. result.Append(key);
  251. result.Append('=');
  252. }
  253. result.Append(pair.Value);
  254. }
  255. return result.ToString();
  256. }
  257. }
  258. private class HttpMultipart
  259. {
  260. public class Element
  261. {
  262. public string ContentType { get; set; }
  263. public string Name { get; set; }
  264. public string Filename { get; set; }
  265. public Encoding Encoding { get; set; }
  266. public long Start { get; set; }
  267. public long Length { get; set; }
  268. public override string ToString()
  269. {
  270. return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
  271. Start.ToString(CultureInfo.CurrentCulture) + ", Length " + Length.ToString(CultureInfo.CurrentCulture);
  272. }
  273. }
  274. private const byte LF = (byte)'\n';
  275. private const byte CR = (byte)'\r';
  276. private Stream data;
  277. private string boundary;
  278. private byte[] boundaryBytes;
  279. private byte[] buffer;
  280. private bool atEof;
  281. private Encoding encoding;
  282. private StringBuilder sb;
  283. // See RFC 2046
  284. // In the case of multipart entities, in which one or more different
  285. // sets of data are combined in a single body, a "multipart" media type
  286. // field must appear in the entity's header. The body must then contain
  287. // one or more body parts, each preceded by a boundary delimiter line,
  288. // and the last one followed by a closing boundary delimiter line.
  289. // After its boundary delimiter line, each body part then consists of a
  290. // header area, a blank line, and a body area. Thus a body part is
  291. // similar to an RFC 822 message in syntax, but different in meaning.
  292. public HttpMultipart(Stream data, string b, Encoding encoding)
  293. {
  294. this.data = data;
  295. boundary = b;
  296. boundaryBytes = encoding.GetBytes(b);
  297. buffer = new byte[boundaryBytes.Length + 2]; // CRLF or '--'
  298. this.encoding = encoding;
  299. sb = new StringBuilder();
  300. }
  301. public Element ReadNextElement()
  302. {
  303. if (atEof || ReadBoundary())
  304. {
  305. return null;
  306. }
  307. var elem = new Element();
  308. ReadOnlySpan<char> header;
  309. while ((header = ReadLine().AsSpan()).Length != 0)
  310. {
  311. if (header.StartsWith("Content-Disposition:".AsSpan(), StringComparison.OrdinalIgnoreCase))
  312. {
  313. elem.Name = GetContentDispositionAttribute(header, "name");
  314. elem.Filename = StripPath(GetContentDispositionAttributeWithEncoding(header, "filename"));
  315. }
  316. else if (header.StartsWith("Content-Type:".AsSpan(), StringComparison.OrdinalIgnoreCase))
  317. {
  318. elem.ContentType = header.Slice("Content-Type:".Length).Trim().ToString();
  319. elem.Encoding = GetEncoding(elem.ContentType);
  320. }
  321. }
  322. long start = data.Position;
  323. elem.Start = start;
  324. long pos = MoveToNextBoundary();
  325. if (pos == -1)
  326. {
  327. return null;
  328. }
  329. elem.Length = pos - start;
  330. return elem;
  331. }
  332. private string ReadLine()
  333. {
  334. // CRLF or LF are ok as line endings.
  335. bool got_cr = false;
  336. int b = 0;
  337. sb.Length = 0;
  338. while (true)
  339. {
  340. b = data.ReadByte();
  341. if (b == -1)
  342. {
  343. return null;
  344. }
  345. if (b == LF)
  346. {
  347. break;
  348. }
  349. got_cr = b == CR;
  350. sb.Append((char)b);
  351. }
  352. if (got_cr)
  353. {
  354. sb.Length--;
  355. }
  356. return sb.ToString();
  357. }
  358. private static string GetContentDispositionAttribute(ReadOnlySpan<char> l, string name)
  359. {
  360. int idx = l.IndexOf((name + "=\"").AsSpan(), StringComparison.Ordinal);
  361. if (idx < 0)
  362. {
  363. return null;
  364. }
  365. int begin = idx + name.Length + "=\"".Length;
  366. int end = l.Slice(begin).IndexOf('"');
  367. if (end < 0)
  368. {
  369. return null;
  370. }
  371. if (begin == end)
  372. {
  373. return string.Empty;
  374. }
  375. return l.Slice(begin, end - begin).ToString();
  376. }
  377. private string GetContentDispositionAttributeWithEncoding(ReadOnlySpan<char> l, string name)
  378. {
  379. int idx = l.IndexOf((name + "=\"").AsSpan(), StringComparison.Ordinal);
  380. if (idx < 0)
  381. {
  382. return null;
  383. }
  384. int begin = idx + name.Length + "=\"".Length;
  385. int end = l.Slice(begin).IndexOf('"');
  386. if (end < 0)
  387. {
  388. return null;
  389. }
  390. if (begin == end)
  391. {
  392. return string.Empty;
  393. }
  394. ReadOnlySpan<char> temp = l.Slice(begin, end - begin);
  395. byte[] source = new byte[temp.Length];
  396. for (int i = temp.Length - 1; i >= 0; i--)
  397. {
  398. source[i] = (byte)temp[i];
  399. }
  400. return encoding.GetString(source, 0, source.Length);
  401. }
  402. private bool ReadBoundary()
  403. {
  404. try
  405. {
  406. string line;
  407. do
  408. {
  409. line = ReadLine();
  410. }
  411. while (line.Length == 0);
  412. if (line[0] != '-' || line[1] != '-')
  413. {
  414. return false;
  415. }
  416. if (!line.EndsWith(boundary, StringComparison.Ordinal))
  417. {
  418. return true;
  419. }
  420. }
  421. catch
  422. {
  423. }
  424. return false;
  425. }
  426. private static bool CompareBytes(byte[] orig, byte[] other)
  427. {
  428. for (int i = orig.Length - 1; i >= 0; i--)
  429. {
  430. if (orig[i] != other[i])
  431. {
  432. return false;
  433. }
  434. }
  435. return true;
  436. }
  437. private long MoveToNextBoundary()
  438. {
  439. long retval = 0;
  440. bool got_cr = false;
  441. int state = 0;
  442. int c = data.ReadByte();
  443. while (true)
  444. {
  445. if (c == -1)
  446. {
  447. return -1;
  448. }
  449. if (state == 0 && c == LF)
  450. {
  451. retval = data.Position - 1;
  452. if (got_cr)
  453. {
  454. retval--;
  455. }
  456. state = 1;
  457. c = data.ReadByte();
  458. }
  459. else if (state == 0)
  460. {
  461. got_cr = c == CR;
  462. c = data.ReadByte();
  463. }
  464. else if (state == 1 && c == '-')
  465. {
  466. c = data.ReadByte();
  467. if (c == -1)
  468. {
  469. return -1;
  470. }
  471. if (c != '-')
  472. {
  473. state = 0;
  474. got_cr = false;
  475. continue; // no ReadByte() here
  476. }
  477. int nread = data.Read(buffer, 0, buffer.Length);
  478. int bl = buffer.Length;
  479. if (nread != bl)
  480. {
  481. return -1;
  482. }
  483. if (!CompareBytes(boundaryBytes, buffer))
  484. {
  485. state = 0;
  486. data.Position = retval + 2;
  487. if (got_cr)
  488. {
  489. data.Position++;
  490. got_cr = false;
  491. }
  492. c = data.ReadByte();
  493. continue;
  494. }
  495. if (buffer[bl - 2] == '-' && buffer[bl - 1] == '-')
  496. {
  497. atEof = true;
  498. }
  499. else if (buffer[bl - 2] != CR || buffer[bl - 1] != LF)
  500. {
  501. state = 0;
  502. data.Position = retval + 2;
  503. if (got_cr)
  504. {
  505. data.Position++;
  506. got_cr = false;
  507. }
  508. c = data.ReadByte();
  509. continue;
  510. }
  511. data.Position = retval + 2;
  512. if (got_cr)
  513. {
  514. data.Position++;
  515. }
  516. break;
  517. }
  518. else
  519. {
  520. // state == 1
  521. state = 0; // no ReadByte() here
  522. }
  523. }
  524. return retval;
  525. }
  526. private static string StripPath(string path)
  527. {
  528. if (path == null || path.Length == 0)
  529. {
  530. return path;
  531. }
  532. if (path.IndexOf(":\\", StringComparison.Ordinal) != 1
  533. && !path.StartsWith("\\\\", StringComparison.Ordinal))
  534. {
  535. return path;
  536. }
  537. return path.Substring(path.LastIndexOf('\\') + 1);
  538. }
  539. }
  540. }
  541. }