RequestMono.cs 28 KB

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