HttpListenerHost.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. using Funq;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Server.Implementations.HttpServer.SocketSharp;
  8. using ServiceStack;
  9. using ServiceStack.Api.Swagger;
  10. using ServiceStack.Host;
  11. using ServiceStack.Host.Handlers;
  12. using ServiceStack.Host.HttpListener;
  13. using ServiceStack.Logging;
  14. using ServiceStack.Web;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using MediaBrowser.Common.Net;
  23. using MediaBrowser.Common.Security;
  24. using MediaBrowser.Model.Extensions;
  25. namespace MediaBrowser.Server.Implementations.HttpServer
  26. {
  27. public class HttpListenerHost : ServiceStackHost, IHttpServer
  28. {
  29. private string DefaultRedirectPath { get; set; }
  30. private readonly ILogger _logger;
  31. public IEnumerable<string> UrlPrefixes { get; private set; }
  32. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  33. private IHttpListener _listener;
  34. private readonly ContainerAdapter _containerAdapter;
  35. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  36. public event EventHandler<WebSocketConnectingEventArgs> WebSocketConnecting;
  37. public string CertificatePath { get; private set; }
  38. private readonly IServerConfigurationManager _config;
  39. private readonly INetworkManager _networkManager;
  40. public HttpListenerHost(IApplicationHost applicationHost,
  41. ILogManager logManager,
  42. IServerConfigurationManager config,
  43. string serviceName,
  44. string defaultRedirectPath, INetworkManager networkManager, params Assembly[] assembliesWithServices)
  45. : base(serviceName, assembliesWithServices)
  46. {
  47. DefaultRedirectPath = defaultRedirectPath;
  48. _networkManager = networkManager;
  49. _config = config;
  50. _logger = logManager.GetLogger("HttpServer");
  51. _containerAdapter = new ContainerAdapter(applicationHost);
  52. }
  53. public string GlobalResponse { get; set; }
  54. public override void Configure(Container container)
  55. {
  56. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  57. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  58. {
  59. {typeof (InvalidOperationException), 422},
  60. {typeof (ResourceNotFoundException), 404},
  61. {typeof (FileNotFoundException), 404},
  62. {typeof (DirectoryNotFoundException), 404},
  63. {typeof (SecurityException), 401},
  64. {typeof (PaymentRequiredException), 402},
  65. {typeof (UnauthorizedAccessException), 500},
  66. {typeof (ApplicationException), 500}
  67. };
  68. HostConfig.Instance.DebugMode = true;
  69. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  70. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  71. // Custom format allows images
  72. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  73. container.Adapter = _containerAdapter;
  74. Plugins.Add(new SwaggerFeature());
  75. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"));
  76. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  77. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  78. //}));
  79. PreRequestFilters.Add((httpReq, httpRes) =>
  80. {
  81. //Handles Request and closes Responses after emitting global HTTP Headers
  82. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  83. {
  84. httpRes.EndRequest(); //add a 'using ServiceStack;'
  85. }
  86. });
  87. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger, () => _config.Configuration.DenyIFrameEmbedding).FilterResponse);
  88. }
  89. public override void OnAfterInit()
  90. {
  91. SetAppDomainData();
  92. base.OnAfterInit();
  93. }
  94. public override void OnConfigLoad()
  95. {
  96. base.OnConfigLoad();
  97. Config.HandlerFactoryPath = null;
  98. Config.MetadataRedirectPath = "metadata";
  99. }
  100. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  101. {
  102. var types = _restServices.Select(r => r.GetType()).ToArray();
  103. return new ServiceController(this, () => types);
  104. }
  105. public virtual void SetAppDomainData()
  106. {
  107. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  108. var domain = Thread.GetDomain(); // or AppDomain.Current
  109. domain.SetData(".appDomain", "1");
  110. domain.SetData(".appVPath", "/");
  111. domain.SetData(".appPath", domain.BaseDirectory);
  112. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  113. {
  114. domain.SetData(".appId", "1");
  115. }
  116. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  117. {
  118. domain.SetData(".domainId", "1");
  119. }
  120. }
  121. public override ServiceStackHost Start(string listeningAtUrlBase)
  122. {
  123. StartListener();
  124. return this;
  125. }
  126. /// <summary>
  127. /// Starts the Web Service
  128. /// </summary>
  129. private void StartListener()
  130. {
  131. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  132. _listener = GetListener();
  133. _listener.WebSocketConnected = OnWebSocketConnected;
  134. _listener.WebSocketConnecting = OnWebSocketConnecting;
  135. _listener.ErrorHandler = ErrorHandler;
  136. _listener.RequestHandler = RequestHandler;
  137. _listener.Start(UrlPrefixes);
  138. }
  139. private IHttpListener GetListener()
  140. {
  141. return new WebSocketSharpListener(_logger, CertificatePath);
  142. }
  143. private void OnWebSocketConnecting(WebSocketConnectingEventArgs args)
  144. {
  145. if (WebSocketConnecting != null)
  146. {
  147. WebSocketConnecting(this, args);
  148. }
  149. }
  150. private void OnWebSocketConnected(WebSocketConnectEventArgs args)
  151. {
  152. if (WebSocketConnected != null)
  153. {
  154. WebSocketConnected(this, args);
  155. }
  156. }
  157. private void ErrorHandler(Exception ex, IRequest httpReq)
  158. {
  159. try
  160. {
  161. var httpRes = httpReq.Response;
  162. if (httpRes.IsClosed)
  163. {
  164. return;
  165. }
  166. var errorResponse = new ErrorResponse
  167. {
  168. ResponseStatus = new ResponseStatus
  169. {
  170. ErrorCode = ex.GetType().GetOperationName(),
  171. Message = ex.Message,
  172. StackTrace = ex.StackTrace
  173. }
  174. };
  175. var contentType = httpReq.ResponseContentType;
  176. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  177. if (serializer == null)
  178. {
  179. contentType = HostContext.Config.DefaultContentType;
  180. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  181. }
  182. var httpError = ex as IHttpError;
  183. if (httpError != null)
  184. {
  185. httpRes.StatusCode = httpError.Status;
  186. httpRes.StatusDescription = httpError.StatusDescription;
  187. }
  188. else
  189. {
  190. httpRes.StatusCode = 500;
  191. }
  192. httpRes.ContentType = contentType;
  193. serializer(httpReq, errorResponse, httpRes);
  194. httpRes.Close();
  195. }
  196. catch (Exception errorEx)
  197. {
  198. //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  199. }
  200. }
  201. /// <summary>
  202. /// Shut down the Web Service
  203. /// </summary>
  204. public void Stop()
  205. {
  206. if (_listener != null)
  207. {
  208. _listener.Stop();
  209. }
  210. }
  211. private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
  212. {
  213. {".js", 0},
  214. {".css", 0},
  215. {".woff", 0},
  216. {".woff2", 0},
  217. {".ttf", 0},
  218. {".html", 0}
  219. };
  220. private bool EnableLogging(string url, string localPath)
  221. {
  222. var extension = GetExtension(url);
  223. if (string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension))
  224. {
  225. if (string.IsNullOrWhiteSpace(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  226. {
  227. return true;
  228. }
  229. }
  230. return false;
  231. }
  232. private string GetExtension(string url)
  233. {
  234. var parts = url.Split(new[] { '?' }, 2);
  235. return Path.GetExtension(parts[0]);
  236. }
  237. public static string RemoveQueryStringByKey(string url, string key)
  238. {
  239. var uri = new Uri(url);
  240. // this gets all the query string key value pairs as a collection
  241. var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
  242. if (newQueryString.Count == 0)
  243. {
  244. return url;
  245. }
  246. // this removes the key if exists
  247. newQueryString.Remove(key);
  248. // this gets the page path from root without QueryString
  249. string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
  250. return newQueryString.Count > 0
  251. ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
  252. : pagePathWithoutQueryString;
  253. }
  254. private string GetUrlToLog(string url)
  255. {
  256. url = RemoveQueryStringByKey(url, "api_key");
  257. return url;
  258. }
  259. /// <summary>
  260. /// Overridable method that can be used to implement a custom hnandler
  261. /// </summary>
  262. /// <param name="httpReq">The HTTP req.</param>
  263. /// <param name="url">The URL.</param>
  264. /// <returns>Task.</returns>
  265. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  266. {
  267. var date = DateTime.Now;
  268. var httpRes = httpReq.Response;
  269. var operationName = httpReq.OperationName;
  270. var localPath = url.LocalPath;
  271. var urlString = url.OriginalString;
  272. var enableLog = EnableLogging(urlString, localPath);
  273. var urlToLog = urlString;
  274. if (enableLog)
  275. {
  276. urlToLog = GetUrlToLog(urlString);
  277. LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
  278. }
  279. if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
  280. string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  281. {
  282. httpRes.RedirectToUrl(DefaultRedirectPath);
  283. return Task.FromResult(true);
  284. }
  285. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
  286. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  287. {
  288. httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
  289. return Task.FromResult(true);
  290. }
  291. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
  292. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
  293. localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1 ||
  294. localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1)
  295. {
  296. httpRes.StatusCode = 200;
  297. httpRes.ContentType = "text/html";
  298. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  299. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  300. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  301. {
  302. httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");
  303. httpRes.Close();
  304. return Task.FromResult(true);
  305. }
  306. }
  307. if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
  308. {
  309. httpRes.RedirectToUrl(DefaultRedirectPath);
  310. return Task.FromResult(true);
  311. }
  312. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  313. {
  314. httpRes.RedirectToUrl("../" + DefaultRedirectPath);
  315. return Task.FromResult(true);
  316. }
  317. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  318. {
  319. httpRes.RedirectToUrl(DefaultRedirectPath);
  320. return Task.FromResult(true);
  321. }
  322. if (string.IsNullOrEmpty(localPath))
  323. {
  324. httpRes.RedirectToUrl("/" + DefaultRedirectPath);
  325. return Task.FromResult(true);
  326. }
  327. if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
  328. {
  329. httpRes.RedirectToUrl("web/pin.html");
  330. return Task.FromResult(true);
  331. }
  332. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  333. {
  334. httpRes.StatusCode = 503;
  335. httpRes.ContentType = "text/html";
  336. httpRes.Write(GlobalResponse);
  337. httpRes.Close();
  338. return Task.FromResult(true);
  339. }
  340. var handler = HttpHandlerFactory.GetHandler(httpReq);
  341. var remoteIp = httpReq.RemoteIp;
  342. var serviceStackHandler = handler as IServiceStackHandler;
  343. if (serviceStackHandler != null)
  344. {
  345. var restHandler = serviceStackHandler as RestHandler;
  346. if (restHandler != null)
  347. {
  348. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  349. }
  350. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  351. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  352. //Matches Exceptions handled in HttpListenerBase.InitTask()
  353. task.ContinueWith(x =>
  354. {
  355. var statusCode = httpRes.StatusCode;
  356. var duration = DateTime.Now - date;
  357. if (enableLog)
  358. {
  359. LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
  360. }
  361. }, TaskContinuationOptions.None);
  362. return task;
  363. }
  364. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  365. .AsTaskException();
  366. }
  367. /// <summary>
  368. /// Adds the rest handlers.
  369. /// </summary>
  370. /// <param name="services">The services.</param>
  371. public void Init(IEnumerable<IRestfulService> services)
  372. {
  373. _restServices.AddRange(services);
  374. ServiceController = CreateServiceController();
  375. _logger.Info("Calling ServiceStack AppHost.Init");
  376. base.Init();
  377. }
  378. public override RouteAttribute[] GetRouteAttributes(Type requestType)
  379. {
  380. var routes = base.GetRouteAttributes(requestType).ToList();
  381. var clone = routes.ToList();
  382. foreach (var route in clone)
  383. {
  384. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  385. {
  386. Notes = route.Notes,
  387. Priority = route.Priority,
  388. Summary = route.Summary
  389. });
  390. routes.Add(new RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  391. {
  392. Notes = route.Notes,
  393. Priority = route.Priority,
  394. Summary = route.Summary
  395. });
  396. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  397. {
  398. Notes = route.Notes,
  399. Priority = route.Priority,
  400. Summary = route.Summary
  401. });
  402. }
  403. return routes.ToArray();
  404. }
  405. private string NormalizeEmbyRoutePath(string path)
  406. {
  407. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  408. {
  409. return "/emby" + path;
  410. }
  411. return "emby/" + path;
  412. }
  413. private string DoubleNormalizeEmbyRoutePath(string path)
  414. {
  415. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  416. {
  417. return "/emby/emby" + path;
  418. }
  419. return "emby/emby/" + path;
  420. }
  421. private string NormalizeRoutePath(string path)
  422. {
  423. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  424. {
  425. return "/mediabrowser" + path;
  426. }
  427. return "mediabrowser/" + path;
  428. }
  429. /// <summary>
  430. /// Releases the specified instance.
  431. /// </summary>
  432. /// <param name="instance">The instance.</param>
  433. public override void Release(object instance)
  434. {
  435. // Leave this empty so SS doesn't try to dispose our objects
  436. }
  437. private bool _disposed;
  438. private readonly object _disposeLock = new object();
  439. protected virtual void Dispose(bool disposing)
  440. {
  441. if (_disposed) return;
  442. base.Dispose();
  443. lock (_disposeLock)
  444. {
  445. if (_disposed) return;
  446. if (disposing)
  447. {
  448. Stop();
  449. }
  450. //release unmanaged resources here...
  451. _disposed = true;
  452. }
  453. }
  454. public override void Dispose()
  455. {
  456. Dispose(true);
  457. GC.SuppressFinalize(this);
  458. }
  459. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  460. {
  461. CertificatePath = certificatePath;
  462. UrlPrefixes = urlPrefixes.ToList();
  463. Start(UrlPrefixes.First());
  464. }
  465. }
  466. }