WebSocketSharpRequest.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. }
  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 => _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 = MediaTypeNames.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 (ReadOnlySpan<char> acceptsType in acceptContentTypes)
  105. {
  106. ReadOnlySpan<char> contentType = acceptsType;
  107. var index = contentType.IndexOf(';');
  108. if (index != -1)
  109. {
  110. contentType = contentType.Slice(0, index);
  111. }
  112. contentType = contentType.Trim();
  113. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  114. if (acceptsAnything)
  115. {
  116. break;
  117. }
  118. }
  119. if (acceptsAnything)
  120. {
  121. if (hasDefaultContentType)
  122. {
  123. return defaultContentType;
  124. }
  125. else
  126. {
  127. return ServerDefaultContentType;
  128. }
  129. }
  130. }
  131. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  132. {
  133. return Soap11;
  134. }
  135. // We could also send a '406 Not Acceptable', but this is allowed also
  136. return ServerDefaultContentType;
  137. }
  138. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  139. {
  140. if (contentTypes == null || request.ContentType == null)
  141. {
  142. return false;
  143. }
  144. foreach (var contentType in contentTypes)
  145. {
  146. if (IsContentType(request, contentType))
  147. {
  148. return true;
  149. }
  150. }
  151. return false;
  152. }
  153. public static bool IsContentType(HttpRequest request, string contentType)
  154. {
  155. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  156. }
  157. private static string GetQueryStringContentType(HttpRequest httpReq)
  158. {
  159. ReadOnlySpan<char> format = httpReq.Query["format"].ToString();
  160. if (format == null)
  161. {
  162. const int FormatMaxLength = 4;
  163. ReadOnlySpan<char> pi = httpReq.Path.ToString();
  164. if (pi == null || pi.Length <= FormatMaxLength)
  165. {
  166. return null;
  167. }
  168. if (pi[0] == '/')
  169. {
  170. pi = pi.Slice(1);
  171. }
  172. format = LeftPart(pi, '/');
  173. if (format.Length > FormatMaxLength)
  174. {
  175. return null;
  176. }
  177. }
  178. format = LeftPart(format, '.');
  179. if (format.Contains("json", StringComparison.OrdinalIgnoreCase))
  180. {
  181. return "application/json";
  182. }
  183. else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
  184. {
  185. return "application/xml";
  186. }
  187. return null;
  188. }
  189. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  190. {
  191. if (strVal == null)
  192. {
  193. return null;
  194. }
  195. var pos = strVal.IndexOf(needle);
  196. return pos == -1 ? strVal : strVal.Slice(0, pos);
  197. }
  198. }
  199. }