WebSocketSharpRequest.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Mime;
  6. using MediaBrowser.Common.Net;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Http.Extensions;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.Primitives;
  11. using Microsoft.Net.Http.Headers;
  12. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  13. namespace Emby.Server.Implementations.SocketSharp
  14. {
  15. public class WebSocketSharpRequest : IHttpRequest
  16. {
  17. private const string FormUrlEncoded = "application/x-www-form-urlencoded";
  18. private const string MultiPartFormData = "multipart/form-data";
  19. private const string Soap11 = "text/xml; charset=utf-8";
  20. private string _remoteIp;
  21. private Dictionary<string, object> _items;
  22. private string _responseContentType;
  23. public WebSocketSharpRequest(HttpRequest httpRequest, HttpResponse httpResponse, string operationName, ILogger logger)
  24. {
  25. this.OperationName = operationName;
  26. this.Request = httpRequest;
  27. this.Response = httpResponse;
  28. }
  29. public string Accept => StringValues.IsNullOrEmpty(Request.Headers[HeaderNames.Accept]) ? null : Request.Headers[HeaderNames.Accept].ToString();
  30. public string Authorization => StringValues.IsNullOrEmpty(Request.Headers[HeaderNames.Authorization]) ? null : Request.Headers[HeaderNames.Authorization].ToString();
  31. public HttpRequest Request { get; }
  32. public HttpResponse Response { get; }
  33. public string OperationName { get; set; }
  34. public string RawUrl => Request.GetEncodedPathAndQuery();
  35. public string AbsoluteUri => Request.GetDisplayUrl().TrimEnd('/');
  36. public string RemoteIp
  37. {
  38. get
  39. {
  40. if (_remoteIp != null)
  41. {
  42. return _remoteIp;
  43. }
  44. IPAddress ip;
  45. // "Real" remote ip might be in X-Forwarded-For of X-Real-Ip
  46. // (if the server is behind a reverse proxy for example)
  47. if (!IPAddress.TryParse(GetHeader(CustomHeaderNames.XForwardedFor), out ip))
  48. {
  49. if (!IPAddress.TryParse(GetHeader(CustomHeaderNames.XRealIP), out ip))
  50. {
  51. ip = Request.HttpContext.Connection.RemoteIpAddress;
  52. // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
  53. ip ??= IPAddress.Loopback;
  54. }
  55. }
  56. return _remoteIp = NormalizeIp(ip).ToString();
  57. }
  58. }
  59. public string[] AcceptTypes => Request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  60. public Dictionary<string, object> Items => _items ?? (_items = new Dictionary<string, object>());
  61. public string ResponseContentType
  62. {
  63. get =>
  64. _responseContentType
  65. ?? (_responseContentType = GetResponseContentType(Request));
  66. set => _responseContentType = value;
  67. }
  68. public string PathInfo => Request.Path.Value;
  69. public string UserAgent => Request.Headers[HeaderNames.UserAgent];
  70. public IHeaderDictionary Headers => Request.Headers;
  71. public IQueryCollection QueryString => Request.Query;
  72. public bool IsLocal =>
  73. (Request.HttpContext.Connection.LocalIpAddress == null
  74. && Request.HttpContext.Connection.RemoteIpAddress == null)
  75. || Request.HttpContext.Connection.LocalIpAddress.Equals(Request.HttpContext.Connection.RemoteIpAddress);
  76. public string HttpMethod => Request.Method;
  77. public string Verb => HttpMethod;
  78. public string ContentType => Request.ContentType;
  79. public Uri UrlReferrer => Request.GetTypedHeaders().Referer;
  80. public Stream InputStream => Request.Body;
  81. public long ContentLength => Request.ContentLength ?? 0;
  82. private string GetHeader(string name) => Request.Headers[name].ToString();
  83. private static IPAddress NormalizeIp(IPAddress ip)
  84. {
  85. if (ip.IsIPv4MappedToIPv6)
  86. {
  87. return ip.MapToIPv4();
  88. }
  89. return ip;
  90. }
  91. public static string GetResponseContentType(HttpRequest httpReq)
  92. {
  93. var specifiedContentType = GetQueryStringContentType(httpReq);
  94. if (!string.IsNullOrEmpty(specifiedContentType))
  95. {
  96. return specifiedContentType;
  97. }
  98. const string ServerDefaultContentType = MediaTypeNames.Application.Json;
  99. var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  100. string defaultContentType = null;
  101. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  102. {
  103. defaultContentType = ServerDefaultContentType;
  104. }
  105. var acceptsAnything = false;
  106. var hasDefaultContentType = defaultContentType != null;
  107. if (acceptContentTypes != null)
  108. {
  109. foreach (ReadOnlySpan<char> acceptsType in acceptContentTypes)
  110. {
  111. ReadOnlySpan<char> contentType = acceptsType;
  112. var index = contentType.IndexOf(';');
  113. if (index != -1)
  114. {
  115. contentType = contentType.Slice(0, index);
  116. }
  117. contentType = contentType.Trim();
  118. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  119. if (acceptsAnything)
  120. {
  121. break;
  122. }
  123. }
  124. if (acceptsAnything)
  125. {
  126. if (hasDefaultContentType)
  127. {
  128. return defaultContentType;
  129. }
  130. else
  131. {
  132. return ServerDefaultContentType;
  133. }
  134. }
  135. }
  136. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  137. {
  138. return Soap11;
  139. }
  140. // We could also send a '406 Not Acceptable', but this is allowed also
  141. return ServerDefaultContentType;
  142. }
  143. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  144. {
  145. if (contentTypes == null || request.ContentType == null)
  146. {
  147. return false;
  148. }
  149. foreach (var contentType in contentTypes)
  150. {
  151. if (IsContentType(request, contentType))
  152. {
  153. return true;
  154. }
  155. }
  156. return false;
  157. }
  158. public static bool IsContentType(HttpRequest request, string contentType)
  159. {
  160. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  161. }
  162. private static string GetQueryStringContentType(HttpRequest httpReq)
  163. {
  164. ReadOnlySpan<char> format = httpReq.Query["format"].ToString();
  165. if (format == null)
  166. {
  167. const int FormatMaxLength = 4;
  168. ReadOnlySpan<char> pi = httpReq.Path.ToString();
  169. if (pi == null || pi.Length <= FormatMaxLength)
  170. {
  171. return null;
  172. }
  173. if (pi[0] == '/')
  174. {
  175. pi = pi.Slice(1);
  176. }
  177. format = LeftPart(pi, '/');
  178. if (format.Length > FormatMaxLength)
  179. {
  180. return null;
  181. }
  182. }
  183. format = LeftPart(format, '.');
  184. if (format.Contains("json", StringComparison.OrdinalIgnoreCase))
  185. {
  186. return "application/json";
  187. }
  188. else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
  189. {
  190. return "application/xml";
  191. }
  192. return null;
  193. }
  194. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  195. {
  196. if (strVal == null)
  197. {
  198. return null;
  199. }
  200. var pos = strVal.IndexOf(needle);
  201. return pos == -1 ? strVal : strVal.Slice(0, pos);
  202. }
  203. }
  204. }