2
0

WebSocketSharpRequest.cs 8.1 KB

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