WebSocketSharpRequest.cs 8.2 KB

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