RequestMono.cs 26 KB

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