HttpListenerHost.cs 19 KB

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