HttpListenerHost.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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.Host;
  10. using ServiceStack.Host.Handlers;
  11. using ServiceStack.Web;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net.Security;
  17. using System.Net.Sockets;
  18. using System.Reflection;
  19. using System.Security.Cryptography.X509Certificates;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using Emby.Common.Implementations.Net;
  23. using Emby.Server.Implementations.HttpServer;
  24. using Emby.Server.Implementations.HttpServer.SocketSharp;
  25. using MediaBrowser.Common.Net;
  26. using MediaBrowser.Common.Security;
  27. using MediaBrowser.Controller;
  28. using MediaBrowser.Model.Cryptography;
  29. using MediaBrowser.Model.Extensions;
  30. using MediaBrowser.Model.IO;
  31. using MediaBrowser.Model.Net;
  32. using MediaBrowser.Model.Services;
  33. using MediaBrowser.Model.Text;
  34. using SocketHttpListener.Net;
  35. using SocketHttpListener.Primitives;
  36. namespace MediaBrowser.Server.Implementations.HttpServer
  37. {
  38. public class HttpListenerHost : ServiceStackHost, IHttpServer
  39. {
  40. private string DefaultRedirectPath { get; set; }
  41. private readonly ILogger _logger;
  42. public IEnumerable<string> UrlPrefixes { get; private set; }
  43. private readonly List<IService> _restServices = new List<IService>();
  44. private IHttpListener _listener;
  45. private readonly ContainerAdapter _containerAdapter;
  46. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  47. public event EventHandler<WebSocketConnectingEventArgs> WebSocketConnecting;
  48. public string CertificatePath { get; private set; }
  49. private readonly IServerConfigurationManager _config;
  50. private readonly INetworkManager _networkManager;
  51. private readonly IMemoryStreamFactory _memoryStreamProvider;
  52. private readonly IServerApplicationHost _appHost;
  53. private readonly ITextEncoding _textEncoding;
  54. private readonly ISocketFactory _socketFactory;
  55. private readonly ICryptoProvider _cryptoProvider;
  56. public HttpListenerHost(IServerApplicationHost applicationHost,
  57. ILogManager logManager,
  58. IServerConfigurationManager config,
  59. string serviceName,
  60. string defaultRedirectPath, INetworkManager networkManager, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding, ISocketFactory socketFactory, ICryptoProvider cryptoProvider)
  61. : base(serviceName, new Assembly[] { })
  62. {
  63. _appHost = applicationHost;
  64. DefaultRedirectPath = defaultRedirectPath;
  65. _networkManager = networkManager;
  66. _memoryStreamProvider = memoryStreamProvider;
  67. _textEncoding = textEncoding;
  68. _socketFactory = socketFactory;
  69. _cryptoProvider = cryptoProvider;
  70. _config = config;
  71. _logger = logManager.GetLogger("HttpServer");
  72. _containerAdapter = new ContainerAdapter(applicationHost);
  73. }
  74. public string GlobalResponse { get; set; }
  75. public override void Configure()
  76. {
  77. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  78. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  79. {
  80. {typeof (InvalidOperationException), 500},
  81. {typeof (NotImplementedException), 500},
  82. {typeof (ResourceNotFoundException), 404},
  83. {typeof (FileNotFoundException), 404},
  84. {typeof (DirectoryNotFoundException), 404},
  85. {typeof (SecurityException), 401},
  86. {typeof (PaymentRequiredException), 402},
  87. {typeof (UnauthorizedAccessException), 500},
  88. {typeof (ApplicationException), 500},
  89. {typeof (PlatformNotSupportedException), 500},
  90. {typeof (NotSupportedException), 500}
  91. };
  92. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  93. // Custom format allows images
  94. HostConfig.Instance.EnableFeatures = Feature.Html | Feature.Json | Feature.Xml | Feature.CustomFormat;
  95. Container.Adapter = _containerAdapter;
  96. var requestFilters = _appHost.GetExports<IRequestFilter>().ToList();
  97. foreach (var filter in requestFilters)
  98. {
  99. HostContext.GlobalRequestFilters.Add(filter.Filter);
  100. }
  101. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  102. }
  103. protected override ILogger Logger
  104. {
  105. get
  106. {
  107. return _logger;
  108. }
  109. }
  110. public override void OnConfigLoad()
  111. {
  112. base.OnConfigLoad();
  113. Config.HandlerFactoryPath = null;
  114. Config.MetadataRedirectPath = "metadata";
  115. }
  116. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  117. {
  118. var types = _restServices.Select(r => r.GetType()).ToArray();
  119. return new ServiceController(this, () => types);
  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 = 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. public static string GetHandlerPathIfAny(string listenerUrl)
  140. {
  141. if (listenerUrl == null) return null;
  142. var pos = listenerUrl.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  143. if (pos == -1) return null;
  144. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  145. var endPos = startHostUrl.IndexOf('/');
  146. if (endPos == -1) return null;
  147. var endHostUrl = startHostUrl.Substring(endPos + 1);
  148. return string.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  149. }
  150. private IHttpListener GetListener()
  151. {
  152. var cert = !string.IsNullOrWhiteSpace(CertificatePath) && File.Exists(CertificatePath)
  153. ? GetCert(CertificatePath) :
  154. null;
  155. var enableDualMode = Environment.OSVersion.Platform == PlatformID.Win32NT;
  156. return new WebSocketSharpListener(_logger, cert, _memoryStreamProvider, _textEncoding, _networkManager, _socketFactory, _cryptoProvider, new StreamFactory(), enableDualMode, GetRequest);
  157. }
  158. public static ICertificate GetCert(string certificateLocation)
  159. {
  160. X509Certificate2 localCert = new X509Certificate2(certificateLocation);
  161. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  162. if (localCert.PrivateKey == null)
  163. {
  164. //throw new FileNotFoundException("Secure requested, no private key included", certificateLocation);
  165. return null;
  166. }
  167. return new Certificate(localCert);
  168. }
  169. private IHttpRequest GetRequest(HttpListenerContext httpContext)
  170. {
  171. var operationName = httpContext.Request.GetOperationName();
  172. var req = new WebSocketSharpRequest(httpContext, operationName, _logger, _memoryStreamProvider);
  173. return req;
  174. }
  175. private void OnWebSocketConnecting(WebSocketConnectingEventArgs args)
  176. {
  177. if (_disposed)
  178. {
  179. return;
  180. }
  181. if (WebSocketConnecting != null)
  182. {
  183. WebSocketConnecting(this, args);
  184. }
  185. }
  186. private void OnWebSocketConnected(WebSocketConnectEventArgs args)
  187. {
  188. if (_disposed)
  189. {
  190. return;
  191. }
  192. if (WebSocketConnected != null)
  193. {
  194. WebSocketConnected(this, args);
  195. }
  196. }
  197. private void ErrorHandler(Exception ex, IRequest httpReq)
  198. {
  199. try
  200. {
  201. var httpRes = httpReq.Response;
  202. if (httpRes.IsClosed)
  203. {
  204. return;
  205. }
  206. var errorResponse = new ErrorResponse
  207. {
  208. ResponseStatus = new ResponseStatus
  209. {
  210. ErrorCode = ex.GetType().GetOperationName(),
  211. Message = ex.Message,
  212. StackTrace = ex.StackTrace
  213. }
  214. };
  215. var contentType = httpReq.ResponseContentType;
  216. var serializer = ContentTypes.Instance.GetResponseSerializer(contentType);
  217. if (serializer == null)
  218. {
  219. contentType = HostContext.Config.DefaultContentType;
  220. serializer = ContentTypes.Instance.GetResponseSerializer(contentType);
  221. }
  222. var httpError = ex as IHttpError;
  223. if (httpError != null)
  224. {
  225. httpRes.StatusCode = httpError.Status;
  226. httpRes.StatusDescription = httpError.StatusDescription;
  227. }
  228. else
  229. {
  230. httpRes.StatusCode = 500;
  231. }
  232. httpRes.ContentType = contentType;
  233. serializer(httpReq, errorResponse, httpRes);
  234. httpRes.Close();
  235. }
  236. catch
  237. {
  238. //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  239. }
  240. }
  241. /// <summary>
  242. /// Shut down the Web Service
  243. /// </summary>
  244. public void Stop()
  245. {
  246. if (_listener != null)
  247. {
  248. _listener.Stop();
  249. }
  250. }
  251. private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
  252. {
  253. {".js", 0},
  254. {".css", 0},
  255. {".woff", 0},
  256. {".woff2", 0},
  257. {".ttf", 0},
  258. {".html", 0}
  259. };
  260. private bool EnableLogging(string url, string localPath)
  261. {
  262. var extension = GetExtension(url);
  263. if (string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension))
  264. {
  265. if (string.IsNullOrWhiteSpace(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  266. {
  267. return true;
  268. }
  269. }
  270. return false;
  271. }
  272. private string GetExtension(string url)
  273. {
  274. var parts = url.Split(new[] { '?' }, 2);
  275. return Path.GetExtension(parts[0]);
  276. }
  277. public static string RemoveQueryStringByKey(string url, string key)
  278. {
  279. var uri = new Uri(url);
  280. // this gets all the query string key value pairs as a collection
  281. var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
  282. if (newQueryString.Count == 0)
  283. {
  284. return url;
  285. }
  286. // this removes the key if exists
  287. newQueryString.Remove(key);
  288. // this gets the page path from root without QueryString
  289. string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
  290. return newQueryString.Count > 0
  291. ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
  292. : pagePathWithoutQueryString;
  293. }
  294. private string GetUrlToLog(string url)
  295. {
  296. url = RemoveQueryStringByKey(url, "api_key");
  297. return url;
  298. }
  299. private string NormalizeConfiguredLocalAddress(string address)
  300. {
  301. var index = address.Trim('/').IndexOf('/');
  302. if (index != -1)
  303. {
  304. address = address.Substring(index + 1);
  305. }
  306. return address.Trim('/');
  307. }
  308. private bool ValidateHost(Uri url)
  309. {
  310. var hosts = _config
  311. .Configuration
  312. .LocalNetworkAddresses
  313. .Select(NormalizeConfiguredLocalAddress)
  314. .ToList();
  315. if (hosts.Count == 0)
  316. {
  317. return true;
  318. }
  319. var host = url.Host ?? string.Empty;
  320. _logger.Debug("Validating host {0}", host);
  321. if (_networkManager.IsInPrivateAddressSpace(host))
  322. {
  323. hosts.Add("localhost");
  324. hosts.Add("127.0.0.1");
  325. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  326. }
  327. return true;
  328. }
  329. /// <summary>
  330. /// Overridable method that can be used to implement a custom hnandler
  331. /// </summary>
  332. /// <param name="httpReq">The HTTP req.</param>
  333. /// <param name="url">The URL.</param>
  334. /// <returns>Task.</returns>
  335. protected async Task RequestHandler(IHttpRequest httpReq, Uri url)
  336. {
  337. var date = DateTime.Now;
  338. var httpRes = httpReq.Response;
  339. bool enableLog = false;
  340. string urlToLog = null;
  341. string remoteIp = null;
  342. try
  343. {
  344. if (_disposed)
  345. {
  346. httpRes.StatusCode = 503;
  347. return;
  348. }
  349. if (!ValidateHost(url))
  350. {
  351. httpRes.StatusCode = 400;
  352. httpRes.ContentType = "text/plain";
  353. httpRes.Write("Invalid host");
  354. return;
  355. }
  356. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  357. {
  358. httpRes.StatusCode = 200;
  359. httpRes.AddHeader("Access-Control-Allow-Origin", "*");
  360. httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  361. httpRes.AddHeader("Access-Control-Allow-Headers",
  362. "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  363. httpRes.ContentType = "text/html";
  364. return;
  365. }
  366. var operationName = httpReq.OperationName;
  367. var localPath = url.LocalPath;
  368. var urlString = url.OriginalString;
  369. enableLog = EnableLogging(urlString, localPath);
  370. urlToLog = urlString;
  371. if (enableLog)
  372. {
  373. urlToLog = GetUrlToLog(urlString);
  374. remoteIp = httpReq.RemoteIp;
  375. LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
  376. }
  377. if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
  378. string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  379. {
  380. RedirectToUrl(httpRes, DefaultRedirectPath);
  381. return;
  382. }
  383. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
  384. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  385. {
  386. RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath);
  387. return;
  388. }
  389. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
  390. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
  391. localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
  392. {
  393. httpRes.StatusCode = 200;
  394. httpRes.ContentType = "text/html";
  395. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  396. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  397. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  398. {
  399. httpRes.Write(
  400. "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
  401. newUrl + "\">" + newUrl + "</a></body></html>");
  402. return;
  403. }
  404. }
  405. if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
  406. localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
  407. {
  408. httpRes.StatusCode = 200;
  409. httpRes.ContentType = "text/html";
  410. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  411. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  412. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  413. {
  414. httpRes.Write(
  415. "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
  416. newUrl + "\">" + newUrl + "</a></body></html>");
  417. return;
  418. }
  419. }
  420. if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
  421. {
  422. RedirectToUrl(httpRes, DefaultRedirectPath);
  423. return;
  424. }
  425. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  426. {
  427. RedirectToUrl(httpRes, "../" + DefaultRedirectPath);
  428. return;
  429. }
  430. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  431. {
  432. RedirectToUrl(httpRes, DefaultRedirectPath);
  433. return;
  434. }
  435. if (string.IsNullOrEmpty(localPath))
  436. {
  437. RedirectToUrl(httpRes, "/" + DefaultRedirectPath);
  438. return;
  439. }
  440. if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
  441. {
  442. RedirectToUrl(httpRes, "web/pin.html");
  443. return;
  444. }
  445. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  446. {
  447. httpRes.StatusCode = 503;
  448. httpRes.ContentType = "text/html";
  449. httpRes.Write(GlobalResponse);
  450. return;
  451. }
  452. var handler = HttpHandlerFactory.GetHandler(httpReq);
  453. if (handler != null)
  454. {
  455. await handler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false);
  456. }
  457. }
  458. catch (Exception ex)
  459. {
  460. ErrorHandler(ex, httpReq);
  461. }
  462. finally
  463. {
  464. httpRes.Close();
  465. if (enableLog)
  466. {
  467. var statusCode = httpRes.StatusCode;
  468. var duration = DateTime.Now - date;
  469. LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
  470. }
  471. }
  472. }
  473. public static void RedirectToUrl(IResponse httpRes, string url)
  474. {
  475. httpRes.StatusCode = 302;
  476. httpRes.AddHeader(HttpHeaders.Location, url);
  477. httpRes.EndRequest();
  478. }
  479. /// <summary>
  480. /// Adds the rest handlers.
  481. /// </summary>
  482. /// <param name="services">The services.</param>
  483. public void Init(IEnumerable<IService> services)
  484. {
  485. _restServices.AddRange(services);
  486. ServiceController = CreateServiceController();
  487. _logger.Info("Calling ServiceStack AppHost.Init");
  488. base.Init();
  489. }
  490. public override Model.Services.RouteAttribute[] GetRouteAttributes(Type requestType)
  491. {
  492. var routes = base.GetRouteAttributes(requestType).ToList();
  493. var clone = routes.ToList();
  494. foreach (var route in clone)
  495. {
  496. routes.Add(new Model.Services.RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  497. {
  498. Notes = route.Notes,
  499. Priority = route.Priority,
  500. Summary = route.Summary
  501. });
  502. routes.Add(new Model.Services.RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  503. {
  504. Notes = route.Notes,
  505. Priority = route.Priority,
  506. Summary = route.Summary
  507. });
  508. routes.Add(new Model.Services.RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  509. {
  510. Notes = route.Notes,
  511. Priority = route.Priority,
  512. Summary = route.Summary
  513. });
  514. }
  515. return routes.ToArray();
  516. }
  517. private string NormalizeEmbyRoutePath(string path)
  518. {
  519. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  520. {
  521. return "/emby" + path;
  522. }
  523. return "emby/" + path;
  524. }
  525. private string DoubleNormalizeEmbyRoutePath(string path)
  526. {
  527. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  528. {
  529. return "/emby/emby" + path;
  530. }
  531. return "emby/emby/" + path;
  532. }
  533. private string NormalizeRoutePath(string path)
  534. {
  535. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  536. {
  537. return "/mediabrowser" + path;
  538. }
  539. return "mediabrowser/" + path;
  540. }
  541. private bool _disposed;
  542. private readonly object _disposeLock = new object();
  543. protected virtual void Dispose(bool disposing)
  544. {
  545. if (_disposed) return;
  546. base.Dispose();
  547. lock (_disposeLock)
  548. {
  549. if (_disposed) return;
  550. if (disposing)
  551. {
  552. Stop();
  553. }
  554. //release unmanaged resources here...
  555. _disposed = true;
  556. }
  557. }
  558. public override void Dispose()
  559. {
  560. Dispose(true);
  561. GC.SuppressFinalize(this);
  562. }
  563. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  564. {
  565. CertificatePath = certificatePath;
  566. UrlPrefixes = urlPrefixes.ToList();
  567. Start(UrlPrefixes.First());
  568. }
  569. }
  570. public class StreamFactory : IStreamFactory
  571. {
  572. public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
  573. {
  574. var netSocket = (NetSocket)socket;
  575. return new NetworkStream(netSocket.Socket, ownsSocket);
  576. }
  577. public Task AuthenticateSslStreamAsServer(Stream stream, ICertificate certificate)
  578. {
  579. var sslStream = (SslStream)stream;
  580. var cert = (Certificate)certificate;
  581. return sslStream.AuthenticateAsServerAsync(cert.X509Certificate);
  582. }
  583. public Stream CreateSslStream(Stream innerStream, bool leaveInnerStreamOpen)
  584. {
  585. return new SslStream(innerStream, leaveInnerStreamOpen);
  586. }
  587. }
  588. public class Certificate : ICertificate
  589. {
  590. public Certificate(X509Certificate x509Certificate)
  591. {
  592. X509Certificate = x509Certificate;
  593. }
  594. public X509Certificate X509Certificate { get; private set; }
  595. }
  596. }