WebSocketSharpRequest.cs 7.8 KB

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