RequestMono.cs 28 KB

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