RequestMono.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. namespace Jellyfin.SocketSharp
  10. {
  11. public partial class WebSocketSharpRequest : IHttpRequest
  12. {
  13. static internal string GetParameter(string header, string attr)
  14. {
  15. int ap = header.IndexOf(attr);
  16. if (ap == -1)
  17. return null;
  18. ap += attr.Length;
  19. if (ap >= header.Length)
  20. return null;
  21. char ending = header[ap];
  22. if (ending != '"')
  23. ending = ' ';
  24. int end = header.IndexOf(ending, ap + 1);
  25. if (end == -1)
  26. return ending == '"' ? null : header.Substring(ap);
  27. return header.Substring(ap + 1, end - ap - 1);
  28. }
  29. async Task LoadMultiPart(WebROCollection form)
  30. {
  31. string boundary = GetParameter(ContentType, "; boundary=");
  32. if (boundary == null)
  33. return;
  34. using (var requestStream = InputStream)
  35. {
  36. //DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
  37. //Not ending with \r\n?
  38. var ms = new MemoryStream(32 * 1024);
  39. await requestStream.CopyToAsync(ms).ConfigureAwait(false);
  40. var input = ms;
  41. ms.WriteByte((byte)'\r');
  42. ms.WriteByte((byte)'\n');
  43. input.Position = 0;
  44. // Uncomment to debug
  45. //var content = new StreamReader(ms).ReadToEnd();
  46. //Console.WriteLine(boundary + "::" + content);
  47. //input.Position = 0;
  48. var multi_part = new HttpMultipart(input, boundary, ContentEncoding);
  49. HttpMultipart.Element e;
  50. while ((e = multi_part.ReadNextElement()) != null)
  51. {
  52. if (e.Filename == null)
  53. {
  54. byte[] copy = new byte[e.Length];
  55. input.Position = e.Start;
  56. input.Read(copy, 0, (int)e.Length);
  57. form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
  58. }
  59. else
  60. {
  61. //
  62. // We use a substream, as in 2.x we will support large uploads streamed to disk,
  63. //
  64. var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
  65. files[e.Name] = sub;
  66. }
  67. }
  68. }
  69. }
  70. public async Task<QueryParamCollection> GetFormData()
  71. {
  72. var form = new WebROCollection();
  73. files = new Dictionary<string, HttpPostedFile>();
  74. if (IsContentType("multipart/form-data", true))
  75. {
  76. await LoadMultiPart(form).ConfigureAwait(false);
  77. }
  78. else if (IsContentType("application/x-www-form-urlencoded", true))
  79. {
  80. await LoadWwwForm(form).ConfigureAwait(false);
  81. }
  82. #if NET_4_0
  83. if (validateRequestNewMode && !checked_form) {
  84. // Setting this before calling the validator prevents
  85. // possible endless recursion
  86. checked_form = true;
  87. ValidateNameValueCollection ("Form", query_string_nvc, RequestValidationSource.Form);
  88. } else
  89. #endif
  90. if (validate_form && !checked_form)
  91. {
  92. checked_form = true;
  93. ValidateNameValueCollection("Form", form);
  94. }
  95. return form;
  96. }
  97. public string Accept => string.IsNullOrEmpty(request.Headers["Accept"]) ? null : request.Headers["Accept"];
  98. public string Authorization => string.IsNullOrEmpty(request.Headers["Authorization"]) ? null : request.Headers["Authorization"];
  99. protected bool validate_cookies, validate_query_string, validate_form;
  100. protected bool checked_cookies, checked_query_string, checked_form;
  101. static void ThrowValidationException(string name, string key, string value)
  102. {
  103. string v = "\"" + value + "\"";
  104. if (v.Length > 20)
  105. v = v.Substring(0, 16) + "...\"";
  106. string msg = string.Format("A potentially dangerous Request.{0} value was " +
  107. "detected from the client ({1}={2}).", name, key, v);
  108. throw new Exception(msg);
  109. }
  110. static void ValidateNameValueCollection(string name, QueryParamCollection coll)
  111. {
  112. if (coll == null)
  113. return;
  114. foreach (var pair in coll)
  115. {
  116. var key = pair.Name;
  117. var val = pair.Value;
  118. if (val != null && val.Length > 0 && IsInvalidString(val))
  119. ThrowValidationException(name, key, val);
  120. }
  121. }
  122. internal static bool IsInvalidString(string val)
  123. {
  124. return IsInvalidString(val, out var validationFailureIndex);
  125. }
  126. internal static bool IsInvalidString(string val, out int validationFailureIndex)
  127. {
  128. validationFailureIndex = 0;
  129. int len = val.Length;
  130. if (len < 2)
  131. return false;
  132. char current = val[0];
  133. for (int idx = 1; idx < len; idx++)
  134. {
  135. char next = val[idx];
  136. // See http://secunia.com/advisories/14325
  137. if (current == '<' || current == '\xff1c')
  138. {
  139. if (next == '!' || next < ' '
  140. || (next >= 'a' && next <= 'z')
  141. || (next >= 'A' && next <= 'Z'))
  142. {
  143. validationFailureIndex = idx - 1;
  144. return true;
  145. }
  146. }
  147. else if (current == '&' && next == '#')
  148. {
  149. validationFailureIndex = idx - 1;
  150. return true;
  151. }
  152. current = next;
  153. }
  154. return false;
  155. }
  156. public void ValidateInput()
  157. {
  158. validate_cookies = true;
  159. validate_query_string = true;
  160. validate_form = true;
  161. }
  162. bool IsContentType(string ct, bool starts_with)
  163. {
  164. if (ct == null || ContentType == null) return false;
  165. if (starts_with)
  166. return StrUtils.StartsWith(ContentType, ct, true);
  167. return string.Equals(ContentType, ct, StringComparison.OrdinalIgnoreCase);
  168. }
  169. async Task LoadWwwForm(WebROCollection form)
  170. {
  171. using (var input = InputStream)
  172. {
  173. using (var ms = new MemoryStream())
  174. {
  175. await input.CopyToAsync(ms).ConfigureAwait(false);
  176. ms.Position = 0;
  177. using (var s = new StreamReader(ms, ContentEncoding))
  178. {
  179. var key = new StringBuilder();
  180. var value = new StringBuilder();
  181. int c;
  182. while ((c = s.Read()) != -1)
  183. {
  184. if (c == '=')
  185. {
  186. value.Length = 0;
  187. while ((c = s.Read()) != -1)
  188. {
  189. if (c == '&')
  190. {
  191. AddRawKeyValue(form, key, value);
  192. break;
  193. }
  194. else
  195. value.Append((char)c);
  196. }
  197. if (c == -1)
  198. {
  199. AddRawKeyValue(form, key, value);
  200. return;
  201. }
  202. }
  203. else if (c == '&')
  204. AddRawKeyValue(form, key, value);
  205. else
  206. key.Append((char)c);
  207. }
  208. if (c == -1)
  209. AddRawKeyValue(form, key, value);
  210. }
  211. }
  212. }
  213. }
  214. void AddRawKeyValue(WebROCollection form, StringBuilder key, StringBuilder value)
  215. {
  216. string decodedKey = WebUtility.UrlDecode(key.ToString());
  217. form.Add(decodedKey,
  218. WebUtility.UrlDecode(value.ToString()));
  219. key.Length = 0;
  220. value.Length = 0;
  221. }
  222. Dictionary<string, HttpPostedFile> files;
  223. class WebROCollection : QueryParamCollection
  224. {
  225. public override string ToString()
  226. {
  227. var result = new StringBuilder();
  228. foreach (var pair in this)
  229. {
  230. if (result.Length > 0)
  231. result.Append('&');
  232. var key = pair.Name;
  233. if (key != null && key.Length > 0)
  234. {
  235. result.Append(key);
  236. result.Append('=');
  237. }
  238. result.Append(pair.Value);
  239. }
  240. return result.ToString();
  241. }
  242. }
  243. public sealed class HttpPostedFile
  244. {
  245. string name;
  246. string content_type;
  247. Stream stream;
  248. class ReadSubStream : Stream
  249. {
  250. Stream s;
  251. long offset;
  252. long end;
  253. long position;
  254. public ReadSubStream(Stream s, long offset, long length)
  255. {
  256. this.s = s;
  257. this.offset = offset;
  258. this.end = offset + length;
  259. position = offset;
  260. }
  261. public override void Flush()
  262. {
  263. }
  264. public override int Read(byte[] buffer, int dest_offset, int count)
  265. {
  266. if (buffer == null)
  267. throw new ArgumentNullException(nameof(buffer));
  268. if (dest_offset < 0)
  269. throw new ArgumentOutOfRangeException(nameof(dest_offset), "< 0");
  270. if (count < 0)
  271. throw new ArgumentOutOfRangeException(nameof(count), "< 0");
  272. int len = buffer.Length;
  273. if (dest_offset > len)
  274. throw new ArgumentException("destination offset is beyond array size");
  275. // reordered to avoid possible integer overflow
  276. if (dest_offset > len - count)
  277. throw new ArgumentException("Reading would overrun buffer");
  278. if (count > end - position)
  279. count = (int)(end - position);
  280. if (count <= 0)
  281. return 0;
  282. s.Position = position;
  283. int result = s.Read(buffer, dest_offset, count);
  284. if (result > 0)
  285. position += result;
  286. else
  287. position = end;
  288. return result;
  289. }
  290. public override int ReadByte()
  291. {
  292. if (position >= end)
  293. return -1;
  294. s.Position = position;
  295. int result = s.ReadByte();
  296. if (result < 0)
  297. position = end;
  298. else
  299. position++;
  300. return result;
  301. }
  302. public override long Seek(long d, SeekOrigin origin)
  303. {
  304. long real;
  305. switch (origin)
  306. {
  307. case SeekOrigin.Begin:
  308. real = offset + d;
  309. break;
  310. case SeekOrigin.End:
  311. real = end + d;
  312. break;
  313. case SeekOrigin.Current:
  314. real = position + d;
  315. break;
  316. default:
  317. throw new ArgumentException();
  318. }
  319. long virt = real - offset;
  320. if (virt < 0 || virt > Length)
  321. throw new ArgumentException();
  322. position = s.Seek(real, SeekOrigin.Begin);
  323. return position;
  324. }
  325. public override void SetLength(long value)
  326. {
  327. throw new NotSupportedException();
  328. }
  329. public override void Write(byte[] buffer, int offset, int count)
  330. {
  331. throw new NotSupportedException();
  332. }
  333. public override bool CanRead => true;
  334. public override bool CanSeek => true;
  335. public override bool CanWrite => false;
  336. public override long Length => end - offset;
  337. public override long Position
  338. {
  339. get => position - offset;
  340. set
  341. {
  342. if (value > Length)
  343. throw new ArgumentOutOfRangeException();
  344. position = Seek(value, SeekOrigin.Begin);
  345. }
  346. }
  347. }
  348. internal HttpPostedFile(string name, string content_type, Stream base_stream, long offset, long length)
  349. {
  350. this.name = name;
  351. this.content_type = content_type;
  352. this.stream = new ReadSubStream(base_stream, offset, length);
  353. }
  354. public string ContentType => content_type;
  355. public int ContentLength => (int)stream.Length;
  356. public string FileName => name;
  357. public Stream InputStream => stream;
  358. }
  359. class Helpers
  360. {
  361. public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture;
  362. }
  363. internal sealed class StrUtils
  364. {
  365. public static bool StartsWith(string str1, string str2, bool ignore_case)
  366. {
  367. if (string.IsNullOrEmpty(str1))
  368. {
  369. return false;
  370. }
  371. var comparison = ignore_case ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
  372. return str1.IndexOf(str2, comparison) == 0;
  373. }
  374. public static bool EndsWith(string str1, string str2, bool ignore_case)
  375. {
  376. int l2 = str2.Length;
  377. if (l2 == 0)
  378. return true;
  379. int l1 = str1.Length;
  380. if (l2 > l1)
  381. return false;
  382. var comparison = ignore_case ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
  383. return str1.IndexOf(str2, comparison) == str1.Length - str2.Length - 1;
  384. }
  385. }
  386. class HttpMultipart
  387. {
  388. public class Element
  389. {
  390. public string ContentType;
  391. public string Name;
  392. public string Filename;
  393. public Encoding Encoding;
  394. public long Start;
  395. public long Length;
  396. public override string ToString()
  397. {
  398. return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
  399. Start.ToString() + ", Length " + Length.ToString();
  400. }
  401. }
  402. Stream data;
  403. string boundary;
  404. byte[] boundary_bytes;
  405. byte[] buffer;
  406. bool at_eof;
  407. Encoding encoding;
  408. StringBuilder sb;
  409. const byte HYPHEN = (byte)'-', LF = (byte)'\n', CR = (byte)'\r';
  410. // See RFC 2046
  411. // In the case of multipart entities, in which one or more different
  412. // sets of data are combined in a single body, a "multipart" media type
  413. // field must appear in the entity's header. The body must then contain
  414. // one or more body parts, each preceded by a boundary delimiter line,
  415. // and the last one followed by a closing boundary delimiter line.
  416. // After its boundary delimiter line, each body part then consists of a
  417. // header area, a blank line, and a body area. Thus a body part is
  418. // similar to an RFC 822 message in syntax, but different in meaning.
  419. public HttpMultipart(Stream data, string b, Encoding encoding)
  420. {
  421. this.data = data;
  422. //DB: 30/01/11: cannot set or read the Position in HttpListener in Win.NET
  423. //var ms = new MemoryStream(32 * 1024);
  424. //data.CopyTo(ms);
  425. //this.data = ms;
  426. boundary = b;
  427. boundary_bytes = encoding.GetBytes(b);
  428. buffer = new byte[boundary_bytes.Length + 2]; // CRLF or '--'
  429. this.encoding = encoding;
  430. sb = new StringBuilder();
  431. }
  432. string ReadLine()
  433. {
  434. // CRLF or LF are ok as line endings.
  435. bool got_cr = false;
  436. int b = 0;
  437. sb.Length = 0;
  438. while (true)
  439. {
  440. b = data.ReadByte();
  441. if (b == -1)
  442. {
  443. return null;
  444. }
  445. if (b == LF)
  446. {
  447. break;
  448. }
  449. got_cr = b == CR;
  450. sb.Append((char)b);
  451. }
  452. if (got_cr)
  453. sb.Length--;
  454. return sb.ToString();
  455. }
  456. static string GetContentDispositionAttribute(string l, string name)
  457. {
  458. int idx = l.IndexOf(name + "=\"");
  459. if (idx < 0)
  460. return null;
  461. int begin = idx + name.Length + "=\"".Length;
  462. int end = l.IndexOf('"', begin);
  463. if (end < 0)
  464. return null;
  465. if (begin == end)
  466. return "";
  467. return l.Substring(begin, end - begin);
  468. }
  469. string GetContentDispositionAttributeWithEncoding(string l, string name)
  470. {
  471. int idx = l.IndexOf(name + "=\"");
  472. if (idx < 0)
  473. return null;
  474. int begin = idx + name.Length + "=\"".Length;
  475. int end = l.IndexOf('"', begin);
  476. if (end < 0)
  477. return null;
  478. if (begin == end)
  479. return "";
  480. string temp = l.Substring(begin, end - begin);
  481. byte[] source = new byte[temp.Length];
  482. for (int i = temp.Length - 1; i >= 0; i--)
  483. source[i] = (byte)temp[i];
  484. return encoding.GetString(source, 0, source.Length);
  485. }
  486. bool ReadBoundary()
  487. {
  488. try
  489. {
  490. string line = ReadLine();
  491. while (line == "")
  492. line = ReadLine();
  493. if (line[0] != '-' || line[1] != '-')
  494. return false;
  495. if (!StrUtils.EndsWith(line, boundary, false))
  496. return true;
  497. }
  498. catch
  499. {
  500. }
  501. return false;
  502. }
  503. string ReadHeaders()
  504. {
  505. string s = ReadLine();
  506. if (s == "")
  507. return null;
  508. return s;
  509. }
  510. bool CompareBytes(byte[] orig, byte[] other)
  511. {
  512. for (int i = orig.Length - 1; i >= 0; i--)
  513. if (orig[i] != other[i])
  514. return false;
  515. return true;
  516. }
  517. long MoveToNextBoundary()
  518. {
  519. long retval = 0;
  520. bool got_cr = false;
  521. int state = 0;
  522. int c = data.ReadByte();
  523. while (true)
  524. {
  525. if (c == -1)
  526. return -1;
  527. if (state == 0 && c == LF)
  528. {
  529. retval = data.Position - 1;
  530. if (got_cr)
  531. retval--;
  532. state = 1;
  533. c = data.ReadByte();
  534. }
  535. else if (state == 0)
  536. {
  537. got_cr = c == CR;
  538. c = data.ReadByte();
  539. }
  540. else if (state == 1 && c == '-')
  541. {
  542. c = data.ReadByte();
  543. if (c == -1)
  544. return -1;
  545. if (c != '-')
  546. {
  547. state = 0;
  548. got_cr = false;
  549. continue; // no ReadByte() here
  550. }
  551. int nread = data.Read(buffer, 0, buffer.Length);
  552. int bl = buffer.Length;
  553. if (nread != bl)
  554. return -1;
  555. if (!CompareBytes(boundary_bytes, buffer))
  556. {
  557. state = 0;
  558. data.Position = retval + 2;
  559. if (got_cr)
  560. {
  561. data.Position++;
  562. got_cr = false;
  563. }
  564. c = data.ReadByte();
  565. continue;
  566. }
  567. if (buffer[bl - 2] == '-' && buffer[bl - 1] == '-')
  568. {
  569. at_eof = true;
  570. }
  571. else if (buffer[bl - 2] != CR || buffer[bl - 1] != LF)
  572. {
  573. state = 0;
  574. data.Position = retval + 2;
  575. if (got_cr)
  576. {
  577. data.Position++;
  578. got_cr = false;
  579. }
  580. c = data.ReadByte();
  581. continue;
  582. }
  583. data.Position = retval + 2;
  584. if (got_cr)
  585. data.Position++;
  586. break;
  587. }
  588. else
  589. {
  590. // state == 1
  591. state = 0; // no ReadByte() here
  592. }
  593. }
  594. return retval;
  595. }
  596. public Element ReadNextElement()
  597. {
  598. if (at_eof || ReadBoundary())
  599. return null;
  600. var elem = new Element();
  601. string header;
  602. while ((header = ReadHeaders()) != null)
  603. {
  604. if (StrUtils.StartsWith(header, "Content-Disposition:", true))
  605. {
  606. elem.Name = GetContentDispositionAttribute(header, "name");
  607. elem.Filename = StripPath(GetContentDispositionAttributeWithEncoding(header, "filename"));
  608. }
  609. else if (StrUtils.StartsWith(header, "Content-Type:", true))
  610. {
  611. elem.ContentType = header.Substring("Content-Type:".Length).Trim();
  612. elem.Encoding = GetEncoding(elem.ContentType);
  613. }
  614. }
  615. long start = 0;
  616. start = data.Position;
  617. elem.Start = start;
  618. long pos = MoveToNextBoundary();
  619. if (pos == -1)
  620. return null;
  621. elem.Length = pos - start;
  622. return elem;
  623. }
  624. static string StripPath(string path)
  625. {
  626. if (path == null || path.Length == 0)
  627. return path;
  628. if (path.IndexOf(":\\") != 1 && !path.StartsWith("\\\\"))
  629. return path;
  630. return path.Substring(path.LastIndexOf('\\') + 1);
  631. }
  632. }
  633. }
  634. }