RequestMono.cs 27 KB

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