RequestMono.cs 21 KB

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