HttpListenerHost.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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.LogUnobservedTaskExceptions = false;
  58. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  59. {
  60. {typeof (InvalidOperationException), 500},
  61. {typeof (NotImplementedException), 500},
  62. {typeof (ResourceNotFoundException), 404},
  63. {typeof (FileNotFoundException), 404},
  64. {typeof (DirectoryNotFoundException), 404},
  65. {typeof (SecurityException), 401},
  66. {typeof (PaymentRequiredException), 402},
  67. {typeof (UnauthorizedAccessException), 500},
  68. {typeof (ApplicationException), 500},
  69. {typeof (PlatformNotSupportedException), 500},
  70. {typeof (NotSupportedException), 500}
  71. };
  72. HostConfig.Instance.GlobalResponseHeaders = new Dictionary<string, string>();
  73. HostConfig.Instance.DebugMode = false;
  74. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  75. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  76. // Custom format allows images
  77. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  78. container.Adapter = _containerAdapter;
  79. Plugins.Add(new SwaggerFeature());
  80. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"));
  81. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  82. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  83. //}));
  84. //PreRequestFilters.Add((httpReq, httpRes) =>
  85. //{
  86. // //Handles Request and closes Responses after emitting global HTTP Headers
  87. // if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  88. // {
  89. // httpRes.EndRequest(); //add a 'using ServiceStack;'
  90. // }
  91. //});
  92. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  93. }
  94. public override void OnAfterInit()
  95. {
  96. SetAppDomainData();
  97. base.OnAfterInit();
  98. }
  99. public override void OnConfigLoad()
  100. {
  101. base.OnConfigLoad();
  102. Config.HandlerFactoryPath = null;
  103. Config.MetadataRedirectPath = "metadata";
  104. }
  105. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  106. {
  107. var types = _restServices.Select(r => r.GetType()).ToArray();
  108. return new ServiceController(this, () => types);
  109. }
  110. public virtual void SetAppDomainData()
  111. {
  112. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  113. var domain = Thread.GetDomain(); // or AppDomain.Current
  114. domain.SetData(".appDomain", "1");
  115. domain.SetData(".appVPath", "/");
  116. domain.SetData(".appPath", domain.BaseDirectory);
  117. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  118. {
  119. domain.SetData(".appId", "1");
  120. }
  121. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  122. {
  123. domain.SetData(".domainId", "1");
  124. }
  125. }
  126. public override ServiceStackHost Start(string listeningAtUrlBase)
  127. {
  128. StartListener();
  129. return this;
  130. }
  131. /// <summary>
  132. /// Starts the Web Service
  133. /// </summary>
  134. private void StartListener()
  135. {
  136. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  137. _listener = GetListener();
  138. _listener.WebSocketConnected = OnWebSocketConnected;
  139. _listener.WebSocketConnecting = OnWebSocketConnecting;
  140. _listener.ErrorHandler = ErrorHandler;
  141. _listener.RequestHandler = RequestHandler;
  142. _listener.Start(UrlPrefixes);
  143. }
  144. private IHttpListener GetListener()
  145. {
  146. return new WebSocketSharpListener(_logger, CertificatePath);
  147. }
  148. private void OnWebSocketConnecting(WebSocketConnectingEventArgs args)
  149. {
  150. if (_disposed)
  151. {
  152. return;
  153. }
  154. if (WebSocketConnecting != null)
  155. {
  156. WebSocketConnecting(this, args);
  157. }
  158. }
  159. private void OnWebSocketConnected(WebSocketConnectEventArgs args)
  160. {
  161. if (_disposed)
  162. {
  163. return;
  164. }
  165. if (WebSocketConnected != null)
  166. {
  167. WebSocketConnected(this, args);
  168. }
  169. }
  170. private void ErrorHandler(Exception ex, IRequest httpReq)
  171. {
  172. try
  173. {
  174. var httpRes = httpReq.Response;
  175. if (httpRes.IsClosed)
  176. {
  177. return;
  178. }
  179. var errorResponse = new ErrorResponse
  180. {
  181. ResponseStatus = new ResponseStatus
  182. {
  183. ErrorCode = ex.GetType().GetOperationName(),
  184. Message = ex.Message,
  185. StackTrace = ex.StackTrace
  186. }
  187. };
  188. var contentType = httpReq.ResponseContentType;
  189. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  190. if (serializer == null)
  191. {
  192. contentType = HostContext.Config.DefaultContentType;
  193. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  194. }
  195. var httpError = ex as IHttpError;
  196. if (httpError != null)
  197. {
  198. httpRes.StatusCode = httpError.Status;
  199. httpRes.StatusDescription = httpError.StatusDescription;
  200. }
  201. else
  202. {
  203. httpRes.StatusCode = 500;
  204. }
  205. httpRes.ContentType = contentType;
  206. serializer(httpReq, errorResponse, httpRes);
  207. httpRes.Close();
  208. }
  209. catch
  210. {
  211. //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  212. }
  213. }
  214. /// <summary>
  215. /// Shut down the Web Service
  216. /// </summary>
  217. public void Stop()
  218. {
  219. if (_listener != null)
  220. {
  221. _listener.Stop();
  222. }
  223. }
  224. private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
  225. {
  226. {".js", 0},
  227. {".css", 0},
  228. {".woff", 0},
  229. {".woff2", 0},
  230. {".ttf", 0},
  231. {".html", 0}
  232. };
  233. private bool EnableLogging(string url, string localPath)
  234. {
  235. var extension = GetExtension(url);
  236. if (string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension))
  237. {
  238. if (string.IsNullOrWhiteSpace(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  239. {
  240. return true;
  241. }
  242. }
  243. return false;
  244. }
  245. private string GetExtension(string url)
  246. {
  247. var parts = url.Split(new[] { '?' }, 2);
  248. return Path.GetExtension(parts[0]);
  249. }
  250. public static string RemoveQueryStringByKey(string url, string key)
  251. {
  252. var uri = new Uri(url);
  253. // this gets all the query string key value pairs as a collection
  254. var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
  255. if (newQueryString.Count == 0)
  256. {
  257. return url;
  258. }
  259. // this removes the key if exists
  260. newQueryString.Remove(key);
  261. // this gets the page path from root without QueryString
  262. string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
  263. return newQueryString.Count > 0
  264. ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
  265. : pagePathWithoutQueryString;
  266. }
  267. private string GetUrlToLog(string url)
  268. {
  269. url = RemoveQueryStringByKey(url, "api_key");
  270. return url;
  271. }
  272. private string NormalizeConfiguredLocalAddress(string address)
  273. {
  274. var index = address.Trim('/').IndexOf('/');
  275. if (index != -1)
  276. {
  277. address = address.Substring(index + 1);
  278. }
  279. return address.Trim('/');
  280. }
  281. private bool ValidateHost(Uri url)
  282. {
  283. var hosts = _config
  284. .Configuration
  285. .LocalNetworkAddresses
  286. .Select(NormalizeConfiguredLocalAddress)
  287. .ToList();
  288. if (hosts.Count == 0)
  289. {
  290. return true;
  291. }
  292. var host = url.Host ?? string.Empty;
  293. _logger.Debug("Validating host {0}", host);
  294. if (_networkManager.IsInPrivateAddressSpace(host))
  295. {
  296. hosts.Add("localhost");
  297. hosts.Add("127.0.0.1");
  298. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  299. }
  300. return true;
  301. }
  302. /// <summary>
  303. /// Overridable method that can be used to implement a custom hnandler
  304. /// </summary>
  305. /// <param name="httpReq">The HTTP req.</param>
  306. /// <param name="url">The URL.</param>
  307. /// <returns>Task.</returns>
  308. protected async Task RequestHandler(IHttpRequest httpReq, Uri url)
  309. {
  310. var date = DateTime.Now;
  311. var httpRes = httpReq.Response;
  312. if (_disposed)
  313. {
  314. httpRes.StatusCode = 503;
  315. httpRes.Close();
  316. return ;
  317. }
  318. if (!ValidateHost(url))
  319. {
  320. httpRes.StatusCode = 400;
  321. httpRes.ContentType = "text/plain";
  322. httpRes.Write("Invalid host");
  323. httpRes.Close();
  324. return;
  325. }
  326. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  327. {
  328. httpRes.StatusCode = 200;
  329. httpRes.AddHeader("Access-Control-Allow-Origin", "*");
  330. httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  331. httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  332. httpRes.ContentType = "text/html";
  333. httpRes.Close();
  334. }
  335. var operationName = httpReq.OperationName;
  336. var localPath = url.LocalPath;
  337. var urlString = url.OriginalString;
  338. var enableLog = EnableLogging(urlString, localPath);
  339. var urlToLog = urlString;
  340. if (enableLog)
  341. {
  342. urlToLog = GetUrlToLog(urlString);
  343. LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
  344. }
  345. if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
  346. string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  347. {
  348. httpRes.RedirectToUrl(DefaultRedirectPath);
  349. return;
  350. }
  351. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
  352. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  353. {
  354. httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
  355. return;
  356. }
  357. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
  358. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
  359. localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
  360. {
  361. httpRes.StatusCode = 200;
  362. httpRes.ContentType = "text/html";
  363. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  364. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  365. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  366. {
  367. httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");
  368. httpRes.Close();
  369. return;
  370. }
  371. }
  372. if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
  373. localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
  374. {
  375. httpRes.StatusCode = 200;
  376. httpRes.ContentType = "text/html";
  377. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  378. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  379. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  380. {
  381. httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");
  382. httpRes.Close();
  383. return;
  384. }
  385. }
  386. if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
  387. {
  388. httpRes.RedirectToUrl(DefaultRedirectPath);
  389. return;
  390. }
  391. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  392. {
  393. httpRes.RedirectToUrl("../" + DefaultRedirectPath);
  394. return;
  395. }
  396. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  397. {
  398. httpRes.RedirectToUrl(DefaultRedirectPath);
  399. return;
  400. }
  401. if (string.IsNullOrEmpty(localPath))
  402. {
  403. httpRes.RedirectToUrl("/" + DefaultRedirectPath);
  404. return;
  405. }
  406. if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
  407. {
  408. httpRes.RedirectToUrl("web/pin.html");
  409. return;
  410. }
  411. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  412. {
  413. httpRes.StatusCode = 503;
  414. httpRes.ContentType = "text/html";
  415. httpRes.Write(GlobalResponse);
  416. httpRes.Close();
  417. return;
  418. }
  419. var handler = HttpHandlerFactory.GetHandler(httpReq);
  420. var remoteIp = httpReq.RemoteIp;
  421. var serviceStackHandler = handler as IServiceStackHandler;
  422. if (serviceStackHandler != null)
  423. {
  424. var restHandler = serviceStackHandler as RestHandler;
  425. if (restHandler != null)
  426. {
  427. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  428. }
  429. try
  430. {
  431. await serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false);
  432. }
  433. finally
  434. {
  435. httpRes.Close();
  436. var statusCode = httpRes.StatusCode;
  437. var duration = DateTime.Now - date;
  438. if (enableLog)
  439. {
  440. LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
  441. }
  442. }
  443. }
  444. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  445. }
  446. /// <summary>
  447. /// Adds the rest handlers.
  448. /// </summary>
  449. /// <param name="services">The services.</param>
  450. public void Init(IEnumerable<IRestfulService> services)
  451. {
  452. _restServices.AddRange(services);
  453. ServiceController = CreateServiceController();
  454. _logger.Info("Calling ServiceStack AppHost.Init");
  455. base.Init();
  456. }
  457. public override RouteAttribute[] GetRouteAttributes(Type requestType)
  458. {
  459. var routes = base.GetRouteAttributes(requestType).ToList();
  460. var clone = routes.ToList();
  461. foreach (var route in clone)
  462. {
  463. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  464. {
  465. Notes = route.Notes,
  466. Priority = route.Priority,
  467. Summary = route.Summary
  468. });
  469. routes.Add(new RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  470. {
  471. Notes = route.Notes,
  472. Priority = route.Priority,
  473. Summary = route.Summary
  474. });
  475. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  476. {
  477. Notes = route.Notes,
  478. Priority = route.Priority,
  479. Summary = route.Summary
  480. });
  481. }
  482. return routes.ToArray();
  483. }
  484. private string NormalizeEmbyRoutePath(string path)
  485. {
  486. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  487. {
  488. return "/emby" + path;
  489. }
  490. return "emby/" + path;
  491. }
  492. private string DoubleNormalizeEmbyRoutePath(string path)
  493. {
  494. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  495. {
  496. return "/emby/emby" + path;
  497. }
  498. return "emby/emby/" + path;
  499. }
  500. private string NormalizeRoutePath(string path)
  501. {
  502. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  503. {
  504. return "/mediabrowser" + path;
  505. }
  506. return "mediabrowser/" + path;
  507. }
  508. /// <summary>
  509. /// Releases the specified instance.
  510. /// </summary>
  511. /// <param name="instance">The instance.</param>
  512. public override void Release(object instance)
  513. {
  514. // Leave this empty so SS doesn't try to dispose our objects
  515. }
  516. private bool _disposed;
  517. private readonly object _disposeLock = new object();
  518. protected virtual void Dispose(bool disposing)
  519. {
  520. if (_disposed) return;
  521. base.Dispose();
  522. lock (_disposeLock)
  523. {
  524. if (_disposed) return;
  525. if (disposing)
  526. {
  527. Stop();
  528. }
  529. //release unmanaged resources here...
  530. _disposed = true;
  531. }
  532. }
  533. public override void Dispose()
  534. {
  535. Dispose(true);
  536. GC.SuppressFinalize(this);
  537. }
  538. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  539. {
  540. CertificatePath = certificatePath;
  541. UrlPrefixes = urlPrefixes.ToList();
  542. Start(UrlPrefixes.First());
  543. }
  544. }
  545. }