WebSocketSharpRequest.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 MediaBrowser.Model.Services;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Http.Extensions;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.Extensions.Primitives;
  12. using Microsoft.Net.Http.Headers;
  13. using HeaderNames = MediaBrowser.Common.Net.MoreHeaderNames;
  14. using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
  15. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  16. using IResponse = MediaBrowser.Model.Services.IResponse;
  17. namespace Emby.Server.Implementations.SocketSharp
  18. {
  19. public partial class WebSocketSharpRequest : IHttpRequest
  20. {
  21. private readonly HttpRequest request;
  22. public WebSocketSharpRequest(HttpRequest httpContext, HttpResponse response, string operationName, ILogger logger)
  23. {
  24. this.OperationName = operationName;
  25. this.request = httpContext;
  26. this.Response = new WebSocketSharpResponse(logger, response);
  27. }
  28. public HttpRequest HttpRequest => request;
  29. public IResponse Response { get; }
  30. public string OperationName { get; set; }
  31. public object Dto { get; set; }
  32. public string RawUrl => request.GetEncodedPathAndQuery();
  33. public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');
  34. // Header[name] returns "" when undefined
  35. private string GetHeader(string name) => request.Headers[name].ToString();
  36. private string remoteIp;
  37. public string RemoteIp
  38. {
  39. get
  40. {
  41. if (remoteIp != null)
  42. {
  43. return remoteIp;
  44. }
  45. IPAddress ip;
  46. // "Real" remote ip might be in X-Forwarded-For of X-Real-Ip
  47. // (if the server is behind a reverse proxy for example)
  48. if (!IPAddress.TryParse(GetHeader(HeaderNames.XForwardedFor), out ip))
  49. {
  50. if (!IPAddress.TryParse(GetHeader(HeaderNames.XRealIP), out ip))
  51. {
  52. ip = request.HttpContext.Connection.RemoteIpAddress;
  53. }
  54. }
  55. return remoteIp = NormalizeIp(ip).ToString();
  56. }
  57. }
  58. private static IPAddress NormalizeIp(IPAddress ip)
  59. {
  60. if (ip.IsIPv4MappedToIPv6)
  61. {
  62. return ip.MapToIPv4();
  63. }
  64. return ip;
  65. }
  66. public string[] AcceptTypes => request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  67. private Dictionary<string, object> items;
  68. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  69. private string responseContentType;
  70. public string ResponseContentType
  71. {
  72. get =>
  73. responseContentType
  74. ?? (responseContentType = GetResponseContentType(HttpRequest));
  75. set => this.responseContentType = value;
  76. }
  77. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  78. public const string MultiPartFormData = "multipart/form-data";
  79. public static string GetResponseContentType(HttpRequest httpReq)
  80. {
  81. var specifiedContentType = GetQueryStringContentType(httpReq);
  82. if (!string.IsNullOrEmpty(specifiedContentType))
  83. {
  84. return specifiedContentType;
  85. }
  86. const string serverDefaultContentType = "application/json";
  87. var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  88. string defaultContentType = null;
  89. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  90. {
  91. defaultContentType = serverDefaultContentType;
  92. }
  93. var acceptsAnything = false;
  94. var hasDefaultContentType = defaultContentType != null;
  95. if (acceptContentTypes != null)
  96. {
  97. foreach (var acceptsType in acceptContentTypes)
  98. {
  99. // TODO: @bond move to Span when Span.Split lands
  100. // https://github.com/dotnet/corefx/issues/26528
  101. var contentType = acceptsType?.Split(';')[0].Trim();
  102. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  103. if (acceptsAnything)
  104. {
  105. break;
  106. }
  107. }
  108. if (acceptsAnything)
  109. {
  110. if (hasDefaultContentType)
  111. {
  112. return defaultContentType;
  113. }
  114. else
  115. {
  116. return serverDefaultContentType;
  117. }
  118. }
  119. }
  120. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  121. {
  122. return Soap11;
  123. }
  124. // We could also send a '406 Not Acceptable', but this is allowed also
  125. return serverDefaultContentType;
  126. }
  127. public const string Soap11 = "text/xml; charset=utf-8";
  128. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  129. {
  130. if (contentTypes == null || request.ContentType == null)
  131. {
  132. return false;
  133. }
  134. foreach (var contentType in contentTypes)
  135. {
  136. if (IsContentType(request, contentType))
  137. {
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. public static bool IsContentType(HttpRequest request, string contentType)
  144. {
  145. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  146. }
  147. private static string GetQueryStringContentType(HttpRequest httpReq)
  148. {
  149. ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
  150. if (format == null)
  151. {
  152. const int formatMaxLength = 4;
  153. ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
  154. if (pi == null || pi.Length <= formatMaxLength)
  155. {
  156. return null;
  157. }
  158. if (pi[0] == '/')
  159. {
  160. pi = pi.Slice(1);
  161. }
  162. format = LeftPart(pi, '/');
  163. if (format.Length > formatMaxLength)
  164. {
  165. return null;
  166. }
  167. }
  168. format = LeftPart(format, '.');
  169. if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
  170. {
  171. return "application/json";
  172. }
  173. else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
  174. {
  175. return "application/xml";
  176. }
  177. return null;
  178. }
  179. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  180. {
  181. if (strVal == null)
  182. {
  183. return null;
  184. }
  185. var pos = strVal.IndexOf(needle);
  186. return pos == -1 ? strVal : strVal.Slice(0, pos);
  187. }
  188. public string PathInfo => this.request.Path.Value;
  189. public string UserAgent => request.Headers[HeaderNames.UserAgent];
  190. public IHeaderDictionary Headers => request.Headers;
  191. public IQueryCollection QueryString => request.Query;
  192. public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
  193. private string httpMethod;
  194. public string HttpMethod =>
  195. httpMethod
  196. ?? (httpMethod = request.Method);
  197. public string Verb => HttpMethod;
  198. public string ContentType => request.ContentType;
  199. private Encoding ContentEncoding
  200. {
  201. get
  202. {
  203. // TODO is this necessary?
  204. if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
  205. {
  206. string postDataCharset = Headers["x-up-devcap-post-charset"];
  207. if (!string.IsNullOrEmpty(postDataCharset))
  208. {
  209. try
  210. {
  211. return Encoding.GetEncoding(postDataCharset);
  212. }
  213. catch (ArgumentException)
  214. {
  215. }
  216. }
  217. }
  218. return request.GetTypedHeaders().ContentType.Encoding ?? Encoding.UTF8;
  219. }
  220. }
  221. public Uri UrlReferrer => request.GetTypedHeaders().Referer;
  222. public static Encoding GetEncoding(string contentTypeHeader)
  223. {
  224. var param = GetParameter(contentTypeHeader.AsSpan(), "charset=");
  225. if (param == null)
  226. {
  227. return null;
  228. }
  229. try
  230. {
  231. return Encoding.GetEncoding(param);
  232. }
  233. catch (ArgumentException)
  234. {
  235. return null;
  236. }
  237. }
  238. public Stream InputStream => request.Body;
  239. public long ContentLength => request.ContentLength ?? 0;
  240. private IHttpFile[] httpFiles;
  241. public IHttpFile[] Files
  242. {
  243. get
  244. {
  245. if (httpFiles == null)
  246. {
  247. if (files == null)
  248. {
  249. return httpFiles = Array.Empty<IHttpFile>();
  250. }
  251. httpFiles = new IHttpFile[files.Count];
  252. var i = 0;
  253. foreach (var pair in files)
  254. {
  255. var reqFile = pair.Value;
  256. httpFiles[i] = new HttpFile
  257. {
  258. ContentType = reqFile.ContentType,
  259. ContentLength = reqFile.ContentLength,
  260. FileName = reqFile.FileName,
  261. InputStream = reqFile.InputStream,
  262. };
  263. i++;
  264. }
  265. }
  266. return httpFiles;
  267. }
  268. }
  269. }
  270. }