RequestMono.cs 28 KB

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