RequestMono.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. using Microsoft.Extensions.Primitives;
  10. namespace Emby.Server.Implementations.SocketSharp
  11. {
  12. public partial class WebSocketSharpRequest : IHttpRequest
  13. {
  14. internal static string GetParameter(string header, string attr)
  15. {
  16. int ap = header.IndexOf(attr, StringComparison.Ordinal);
  17. if (ap == -1)
  18. {
  19. return null;
  20. }
  21. ap += attr.Length;
  22. if (ap >= header.Length)
  23. {
  24. return null;
  25. }
  26. char ending = header[ap];
  27. if (ending != '"')
  28. {
  29. ending = ' ';
  30. }
  31. int end = header.IndexOf(ending, ap + 1);
  32. if (end == -1)
  33. {
  34. return ending == '"' ? null : header.Substring(ap);
  35. }
  36. return header.Substring(ap + 1, end - ap - 1);
  37. }
  38. private async Task LoadMultiPart(WebROCollection form)
  39. {
  40. string boundary = GetParameter(ContentType, "; boundary=");
  41. if (boundary == null)
  42. {
  43. return;
  44. }
  45. using (var requestStream = InputStream)
  46. {
  47. // DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
  48. // Not ending with \r\n?
  49. var ms = new MemoryStream(32 * 1024);
  50. await requestStream.CopyToAsync(ms).ConfigureAwait(false);
  51. var input = ms;
  52. ms.WriteByte((byte)'\r');
  53. ms.WriteByte((byte)'\n');
  54. input.Position = 0;
  55. // Uncomment to debug
  56. // var content = new StreamReader(ms).ReadToEnd();
  57. // Console.WriteLine(boundary + "::" + content);
  58. // input.Position = 0;
  59. var multi_part = new HttpMultipart(input, boundary, ContentEncoding);
  60. HttpMultipart.Element e;
  61. while ((e = multi_part.ReadNextElement()) != null)
  62. {
  63. if (e.Filename == null)
  64. {
  65. byte[] copy = new byte[e.Length];
  66. input.Position = e.Start;
  67. input.Read(copy, 0, (int)e.Length);
  68. form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
  69. }
  70. else
  71. {
  72. // We use a substream, as in 2.x we will support large uploads streamed to disk,
  73. var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
  74. files[e.Name] = sub;
  75. }
  76. }
  77. }
  78. }
  79. public async Task<QueryParamCollection> GetFormData()
  80. {
  81. var form = new WebROCollection();
  82. files = new Dictionary<string, HttpPostedFile>();
  83. if (IsContentType("multipart/form-data", true))
  84. {
  85. await LoadMultiPart(form).ConfigureAwait(false);
  86. }
  87. else if (IsContentType("application/x-www-form-urlencoded", true))
  88. {
  89. await LoadWwwForm(form).ConfigureAwait(false);
  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. public string Accept => StringValues.IsNullOrEmpty(request.Headers["Accept"]) ? null : request.Headers["Accept"].ToString();
  107. public string Authorization => StringValues.IsNullOrEmpty(request.Headers["Authorization"]) ? null : request.Headers["Authorization"].ToString();
  108. protected bool validate_cookies { get; set; }
  109. protected bool validate_query_string { get; set; }
  110. protected bool validate_form { get; set; }
  111. protected bool checked_cookies { get; set; }
  112. protected bool checked_query_string { get; set; }
  113. protected bool checked_form { get; set; }
  114. private static void ThrowValidationException(string name, string key, string value)
  115. {
  116. string v = "\"" + value + "\"";
  117. if (v.Length > 20)
  118. {
  119. v = v.Substring(0, 16) + "...\"";
  120. }
  121. string msg = string.Format(
  122. CultureInfo.InvariantCulture,
  123. "A potentially dangerous Request.{0} value was detected from the client ({1}={2}).",
  124. name,
  125. key,
  126. v);
  127. throw new Exception(msg);
  128. }
  129. private static void ValidateNameValueCollection(string name, QueryParamCollection coll)
  130. {
  131. if (coll == null)
  132. {
  133. return;
  134. }
  135. foreach (var pair in coll)
  136. {
  137. var key = pair.Name;
  138. var val = pair.Value;
  139. if (val != null && val.Length > 0 && IsInvalidString(val))
  140. {
  141. ThrowValidationException(name, key, val);
  142. }
  143. }
  144. }
  145. internal static bool IsInvalidString(string val)
  146. => IsInvalidString(val, out var validationFailureIndex);
  147. internal static bool IsInvalidString(string val, out int validationFailureIndex)
  148. {
  149. validationFailureIndex = 0;
  150. int len = val.Length;
  151. if (len < 2)
  152. {
  153. return false;
  154. }
  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. private bool IsContentType(string ct, bool starts_with)
  186. {
  187. if (ct == null || ContentType == null)
  188. {
  189. return false;
  190. }
  191. if (starts_with)
  192. {
  193. return ContentType.StartsWith(ct, StringComparison.OrdinalIgnoreCase);
  194. }
  195. return string.Equals(ContentType, ct, StringComparison.OrdinalIgnoreCase);
  196. }
  197. private async Task LoadWwwForm(WebROCollection form)
  198. {
  199. using (var input = InputStream)
  200. {
  201. using (var ms = new MemoryStream())
  202. {
  203. await input.CopyToAsync(ms).ConfigureAwait(false);
  204. ms.Position = 0;
  205. using (var s = new StreamReader(ms, ContentEncoding))
  206. {
  207. var key = new StringBuilder();
  208. var value = new StringBuilder();
  209. int c;
  210. while ((c = s.Read()) != -1)
  211. {
  212. if (c == '=')
  213. {
  214. value.Length = 0;
  215. while ((c = s.Read()) != -1)
  216. {
  217. if (c == '&')
  218. {
  219. AddRawKeyValue(form, key, value);
  220. break;
  221. }
  222. else
  223. {
  224. value.Append((char)c);
  225. }
  226. }
  227. if (c == -1)
  228. {
  229. AddRawKeyValue(form, key, value);
  230. return;
  231. }
  232. }
  233. else if (c == '&')
  234. {
  235. AddRawKeyValue(form, key, value);
  236. }
  237. else
  238. {
  239. key.Append((char)c);
  240. }
  241. }
  242. if (c == -1)
  243. {
  244. AddRawKeyValue(form, key, value);
  245. }
  246. }
  247. }
  248. }
  249. }
  250. private static void AddRawKeyValue(WebROCollection form, StringBuilder key, StringBuilder value)
  251. {
  252. form.Add(WebUtility.UrlDecode(key.ToString()), WebUtility.UrlDecode(value.ToString()));
  253. key.Length = 0;
  254. value.Length = 0;
  255. }
  256. private Dictionary<string, HttpPostedFile> files;
  257. private class WebROCollection : QueryParamCollection
  258. {
  259. public override string ToString()
  260. {
  261. var result = new StringBuilder();
  262. foreach (var pair in this)
  263. {
  264. if (result.Length > 0)
  265. {
  266. result.Append('&');
  267. }
  268. var key = pair.Name;
  269. if (key != null && key.Length > 0)
  270. {
  271. result.Append(key);
  272. result.Append('=');
  273. }
  274. result.Append(pair.Value);
  275. }
  276. return result.ToString();
  277. }
  278. }
  279. private class HttpMultipart
  280. {
  281. public class Element
  282. {
  283. public string ContentType { get; set; }
  284. public string Name { get; set; }
  285. public string Filename { get; set; }
  286. public Encoding Encoding { get; set; }
  287. public long Start { get; set; }
  288. public long Length { get; set; }
  289. public override string ToString()
  290. {
  291. return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
  292. Start.ToString(CultureInfo.CurrentCulture) + ", Length " + Length.ToString(CultureInfo.CurrentCulture);
  293. }
  294. }
  295. private const byte LF = (byte)'\n';
  296. private const byte CR = (byte)'\r';
  297. private Stream data;
  298. private string boundary;
  299. private byte[] boundaryBytes;
  300. private byte[] buffer;
  301. private bool atEof;
  302. private Encoding encoding;
  303. private StringBuilder sb;
  304. // See RFC 2046
  305. // In the case of multipart entities, in which one or more different
  306. // sets of data are combined in a single body, a "multipart" media type
  307. // field must appear in the entity's header. The body must then contain
  308. // one or more body parts, each preceded by a boundary delimiter line,
  309. // and the last one followed by a closing boundary delimiter line.
  310. // After its boundary delimiter line, each body part then consists of a
  311. // header area, a blank line, and a body area. Thus a body part is
  312. // similar to an RFC 822 message in syntax, but different in meaning.
  313. public HttpMultipart(Stream data, string b, Encoding encoding)
  314. {
  315. this.data = data;
  316. boundary = b;
  317. boundaryBytes = encoding.GetBytes(b);
  318. buffer = new byte[boundaryBytes.Length + 2]; // CRLF or '--'
  319. this.encoding = encoding;
  320. sb = new StringBuilder();
  321. }
  322. public Element ReadNextElement()
  323. {
  324. if (atEof || ReadBoundary())
  325. {
  326. return null;
  327. }
  328. var elem = new Element();
  329. string header;
  330. while ((header = ReadHeaders()) != null)
  331. {
  332. if (header.StartsWith("Content-Disposition:", StringComparison.OrdinalIgnoreCase))
  333. {
  334. elem.Name = GetContentDispositionAttribute(header, "name");
  335. elem.Filename = StripPath(GetContentDispositionAttributeWithEncoding(header, "filename"));
  336. }
  337. else if (header.StartsWith("Content-Type:", StringComparison.OrdinalIgnoreCase))
  338. {
  339. elem.ContentType = header.Substring("Content-Type:".Length).Trim();
  340. elem.Encoding = GetEncoding(elem.ContentType);
  341. }
  342. }
  343. long start = data.Position;
  344. elem.Start = start;
  345. long pos = MoveToNextBoundary();
  346. if (pos == -1)
  347. {
  348. return null;
  349. }
  350. elem.Length = pos - start;
  351. return elem;
  352. }
  353. private string ReadLine()
  354. {
  355. // CRLF or LF are ok as line endings.
  356. bool got_cr = false;
  357. int b = 0;
  358. sb.Length = 0;
  359. while (true)
  360. {
  361. b = data.ReadByte();
  362. if (b == -1)
  363. {
  364. return null;
  365. }
  366. if (b == LF)
  367. {
  368. break;
  369. }
  370. got_cr = b == CR;
  371. sb.Append((char)b);
  372. }
  373. if (got_cr)
  374. {
  375. sb.Length--;
  376. }
  377. return sb.ToString();
  378. }
  379. private static string GetContentDispositionAttribute(string l, string name)
  380. {
  381. int idx = l.IndexOf(name + "=\"", StringComparison.Ordinal);
  382. if (idx < 0)
  383. {
  384. return null;
  385. }
  386. int begin = idx + name.Length + "=\"".Length;
  387. int end = l.IndexOf('"', begin);
  388. if (end < 0)
  389. {
  390. return null;
  391. }
  392. if (begin == end)
  393. {
  394. return string.Empty;
  395. }
  396. return l.Substring(begin, end - begin);
  397. }
  398. private string GetContentDispositionAttributeWithEncoding(string l, string name)
  399. {
  400. int idx = l.IndexOf(name + "=\"", StringComparison.Ordinal);
  401. if (idx < 0)
  402. {
  403. return null;
  404. }
  405. int begin = idx + name.Length + "=\"".Length;
  406. int end = l.IndexOf('"', begin);
  407. if (end < 0)
  408. {
  409. return null;
  410. }
  411. if (begin == end)
  412. {
  413. return string.Empty;
  414. }
  415. string temp = l.Substring(begin, end - begin);
  416. byte[] source = new byte[temp.Length];
  417. for (int i = temp.Length - 1; i >= 0; i--)
  418. {
  419. source[i] = (byte)temp[i];
  420. }
  421. return encoding.GetString(source, 0, source.Length);
  422. }
  423. private bool ReadBoundary()
  424. {
  425. try
  426. {
  427. string line;
  428. do
  429. {
  430. line = ReadLine();
  431. }
  432. while (line.Length == 0);
  433. if (line[0] != '-' || line[1] != '-')
  434. {
  435. return false;
  436. }
  437. if (!line.EndsWith(boundary, StringComparison.Ordinal))
  438. {
  439. return true;
  440. }
  441. }
  442. catch
  443. {
  444. }
  445. return false;
  446. }
  447. private string ReadHeaders()
  448. {
  449. string s = ReadLine();
  450. if (s.Length == 0)
  451. {
  452. return null;
  453. }
  454. return s;
  455. }
  456. private static bool CompareBytes(byte[] orig, byte[] other)
  457. {
  458. for (int i = orig.Length - 1; i >= 0; i--)
  459. {
  460. if (orig[i] != other[i])
  461. {
  462. return false;
  463. }
  464. }
  465. return true;
  466. }
  467. private long MoveToNextBoundary()
  468. {
  469. long retval = 0;
  470. bool got_cr = false;
  471. int state = 0;
  472. int c = data.ReadByte();
  473. while (true)
  474. {
  475. if (c == -1)
  476. {
  477. return -1;
  478. }
  479. if (state == 0 && c == LF)
  480. {
  481. retval = data.Position - 1;
  482. if (got_cr)
  483. {
  484. retval--;
  485. }
  486. state = 1;
  487. c = data.ReadByte();
  488. }
  489. else if (state == 0)
  490. {
  491. got_cr = c == CR;
  492. c = data.ReadByte();
  493. }
  494. else if (state == 1 && c == '-')
  495. {
  496. c = data.ReadByte();
  497. if (c == -1)
  498. {
  499. return -1;
  500. }
  501. if (c != '-')
  502. {
  503. state = 0;
  504. got_cr = false;
  505. continue; // no ReadByte() here
  506. }
  507. int nread = data.Read(buffer, 0, buffer.Length);
  508. int bl = buffer.Length;
  509. if (nread != bl)
  510. {
  511. return -1;
  512. }
  513. if (!CompareBytes(boundaryBytes, buffer))
  514. {
  515. state = 0;
  516. data.Position = retval + 2;
  517. if (got_cr)
  518. {
  519. data.Position++;
  520. got_cr = false;
  521. }
  522. c = data.ReadByte();
  523. continue;
  524. }
  525. if (buffer[bl - 2] == '-' && buffer[bl - 1] == '-')
  526. {
  527. atEof = true;
  528. }
  529. else if (buffer[bl - 2] != CR || buffer[bl - 1] != LF)
  530. {
  531. state = 0;
  532. data.Position = retval + 2;
  533. if (got_cr)
  534. {
  535. data.Position++;
  536. got_cr = false;
  537. }
  538. c = data.ReadByte();
  539. continue;
  540. }
  541. data.Position = retval + 2;
  542. if (got_cr)
  543. {
  544. data.Position++;
  545. }
  546. break;
  547. }
  548. else
  549. {
  550. // state == 1
  551. state = 0; // no ReadByte() here
  552. }
  553. }
  554. return retval;
  555. }
  556. private static string StripPath(string path)
  557. {
  558. if (path == null || path.Length == 0)
  559. {
  560. return path;
  561. }
  562. if (path.IndexOf(":\\", StringComparison.Ordinal) != 1
  563. && !path.StartsWith("\\\\", StringComparison.Ordinal))
  564. {
  565. return path;
  566. }
  567. return path.Substring(path.LastIndexOf('\\') + 1);
  568. }
  569. }
  570. }
  571. }