RequestMono.cs 21 KB

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