RequestMono.cs 21 KB

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