WebSocketSharpRequest.cs 10 KB

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