HttpListenerHost.cs 22 KB

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