HttpListenerHost.cs 22 KB

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