RequestMono.cs 27 KB

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