WebSocketSharpRequest.cs 8.2 KB

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