2
0

WebSocketSharpRequest.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Linq;
  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 partial class WebSocketSharpRequest : IHttpRequest
  16. {
  17. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  18. public const string MultiPartFormData = "multipart/form-data";
  19. public 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. }
  53. }
  54. return _remoteIp = NormalizeIp(ip).ToString();
  55. }
  56. }
  57. public string[] AcceptTypes => Request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  58. public Dictionary<string, object> Items => _items ?? (_items = new Dictionary<string, object>());
  59. public string ResponseContentType
  60. {
  61. get =>
  62. _responseContentType
  63. ?? (_responseContentType = GetResponseContentType(Request));
  64. set => this._responseContentType = value;
  65. }
  66. public string PathInfo => Request.Path.Value;
  67. public string UserAgent => Request.Headers[HeaderNames.UserAgent];
  68. public IHeaderDictionary Headers => Request.Headers;
  69. public IQueryCollection QueryString => Request.Query;
  70. public bool IsLocal => Request.HttpContext.Connection.LocalIpAddress.Equals(Request.HttpContext.Connection.RemoteIpAddress);
  71. public string HttpMethod => Request.Method;
  72. public string Verb => HttpMethod;
  73. public string ContentType => Request.ContentType;
  74. public Uri UrlReferrer => Request.GetTypedHeaders().Referer;
  75. public Stream InputStream => Request.Body;
  76. public long ContentLength => Request.ContentLength ?? 0;
  77. private string GetHeader(string name) => Request.Headers[name].ToString();
  78. private static IPAddress NormalizeIp(IPAddress ip)
  79. {
  80. if (ip.IsIPv4MappedToIPv6)
  81. {
  82. return ip.MapToIPv4();
  83. }
  84. return ip;
  85. }
  86. public static string GetResponseContentType(HttpRequest httpReq)
  87. {
  88. var specifiedContentType = GetQueryStringContentType(httpReq);
  89. if (!string.IsNullOrEmpty(specifiedContentType))
  90. {
  91. return specifiedContentType;
  92. }
  93. const string serverDefaultContentType = "application/json";
  94. var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  95. string defaultContentType = null;
  96. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  97. {
  98. defaultContentType = serverDefaultContentType;
  99. }
  100. var acceptsAnything = false;
  101. var hasDefaultContentType = defaultContentType != null;
  102. if (acceptContentTypes != null)
  103. {
  104. foreach (var acceptsType in acceptContentTypes)
  105. {
  106. // TODO: @bond move to Span when Span.Split lands
  107. // https://github.com/dotnet/corefx/issues/26528
  108. var contentType = acceptsType?.Split(';')[0].Trim();
  109. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  110. if (acceptsAnything)
  111. {
  112. break;
  113. }
  114. }
  115. if (acceptsAnything)
  116. {
  117. if (hasDefaultContentType)
  118. {
  119. return defaultContentType;
  120. }
  121. else
  122. {
  123. return serverDefaultContentType;
  124. }
  125. }
  126. }
  127. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  128. {
  129. return Soap11;
  130. }
  131. // We could also send a '406 Not Acceptable', but this is allowed also
  132. return serverDefaultContentType;
  133. }
  134. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  135. {
  136. if (contentTypes == null || request.ContentType == null)
  137. {
  138. return false;
  139. }
  140. foreach (var contentType in contentTypes)
  141. {
  142. if (IsContentType(request, contentType))
  143. {
  144. return true;
  145. }
  146. }
  147. return false;
  148. }
  149. public static bool IsContentType(HttpRequest request, string contentType)
  150. {
  151. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  152. }
  153. private static string GetQueryStringContentType(HttpRequest httpReq)
  154. {
  155. ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
  156. if (format == null)
  157. {
  158. const int formatMaxLength = 4;
  159. ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
  160. if (pi == null || pi.Length <= formatMaxLength)
  161. {
  162. return null;
  163. }
  164. if (pi[0] == '/')
  165. {
  166. pi = pi.Slice(1);
  167. }
  168. format = LeftPart(pi, '/');
  169. if (format.Length > formatMaxLength)
  170. {
  171. return null;
  172. }
  173. }
  174. format = LeftPart(format, '.');
  175. if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
  176. {
  177. return "application/json";
  178. }
  179. else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
  180. {
  181. return "application/xml";
  182. }
  183. return null;
  184. }
  185. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  186. {
  187. if (strVal == null)
  188. {
  189. return null;
  190. }
  191. var pos = strVal.IndexOf(needle);
  192. return pos == -1 ? strVal : strVal.Slice(0, pos);
  193. }
  194. }
  195. }