RequestMono.cs 21 KB

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