HttpListenerHost.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. }
  115. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  116. {
  117. var types = _restServices.Select(r => r.GetType()).ToArray();
  118. return new ServiceController(this, () => types);
  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 = 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. public static string GetHandlerPathIfAny(string listenerUrl)
  139. {
  140. if (listenerUrl == null) return null;
  141. var pos = listenerUrl.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  142. if (pos == -1) return null;
  143. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  144. var endPos = startHostUrl.IndexOf('/');
  145. if (endPos == -1) return null;
  146. var endHostUrl = startHostUrl.Substring(endPos + 1);
  147. return string.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  148. }
  149. private IHttpListener GetListener()
  150. {
  151. var cert = !string.IsNullOrWhiteSpace(CertificatePath) && File.Exists(CertificatePath)
  152. ? GetCert(CertificatePath) :
  153. null;
  154. var enableDualMode = Environment.OSVersion.Platform == PlatformID.Win32NT;
  155. return new WebSocketSharpListener(_logger, cert, _memoryStreamProvider, _textEncoding, _networkManager, _socketFactory, _cryptoProvider, new StreamFactory(), enableDualMode, GetRequest);
  156. }
  157. public static ICertificate GetCert(string certificateLocation)
  158. {
  159. X509Certificate2 localCert = new X509Certificate2(certificateLocation);
  160. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  161. if (localCert.PrivateKey == null)
  162. {
  163. //throw new FileNotFoundException("Secure requested, no private key included", certificateLocation);
  164. return null;
  165. }
  166. return new Certificate(localCert);
  167. }
  168. private IHttpRequest GetRequest(HttpListenerContext httpContext)
  169. {
  170. var operationName = httpContext.Request.GetOperationName();
  171. var req = new WebSocketSharpRequest(httpContext, operationName, _logger, _memoryStreamProvider);
  172. return req;
  173. }
  174. private void OnWebSocketConnecting(WebSocketConnectingEventArgs args)
  175. {
  176. if (_disposed)
  177. {
  178. return;
  179. }
  180. if (WebSocketConnecting != null)
  181. {
  182. WebSocketConnecting(this, args);
  183. }
  184. }
  185. private void OnWebSocketConnected(WebSocketConnectEventArgs args)
  186. {
  187. if (_disposed)
  188. {
  189. return;
  190. }
  191. if (WebSocketConnected != null)
  192. {
  193. WebSocketConnected(this, args);
  194. }
  195. }
  196. private void ErrorHandler(Exception ex, IRequest httpReq)
  197. {
  198. try
  199. {
  200. var httpRes = httpReq.Response;
  201. if (httpRes.IsClosed)
  202. {
  203. return;
  204. }
  205. var errorResponse = new ErrorResponse
  206. {
  207. ResponseStatus = new ResponseStatus
  208. {
  209. ErrorCode = ex.GetType().GetOperationName(),
  210. Message = ex.Message,
  211. StackTrace = ex.StackTrace
  212. }
  213. };
  214. var contentType = httpReq.ResponseContentType;
  215. var serializer = ContentTypes.Instance.GetResponseSerializer(contentType);
  216. if (serializer == null)
  217. {
  218. contentType = HostContext.Config.DefaultContentType;
  219. serializer = ContentTypes.Instance.GetResponseSerializer(contentType);
  220. }
  221. var httpError = ex as IHttpError;
  222. if (httpError != null)
  223. {
  224. httpRes.StatusCode = httpError.Status;
  225. httpRes.StatusDescription = httpError.StatusDescription;
  226. }
  227. else
  228. {
  229. httpRes.StatusCode = 500;
  230. }
  231. httpRes.ContentType = contentType;
  232. serializer(httpReq, errorResponse, httpRes);
  233. httpRes.Close();
  234. }
  235. catch
  236. {
  237. //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  238. }
  239. }
  240. /// <summary>
  241. /// Shut down the Web Service
  242. /// </summary>
  243. public void Stop()
  244. {
  245. if (_listener != null)
  246. {
  247. _listener.Stop();
  248. }
  249. }
  250. private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
  251. {
  252. {".js", 0},
  253. {".css", 0},
  254. {".woff", 0},
  255. {".woff2", 0},
  256. {".ttf", 0},
  257. {".html", 0}
  258. };
  259. private bool EnableLogging(string url, string localPath)
  260. {
  261. var extension = GetExtension(url);
  262. if (string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension))
  263. {
  264. if (string.IsNullOrWhiteSpace(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  265. {
  266. return true;
  267. }
  268. }
  269. return false;
  270. }
  271. private string GetExtension(string url)
  272. {
  273. var parts = url.Split(new[] { '?' }, 2);
  274. return Path.GetExtension(parts[0]);
  275. }
  276. public static string RemoveQueryStringByKey(string url, string key)
  277. {
  278. var uri = new Uri(url);
  279. // this gets all the query string key value pairs as a collection
  280. var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
  281. if (newQueryString.Count == 0)
  282. {
  283. return url;
  284. }
  285. // this removes the key if exists
  286. newQueryString.Remove(key);
  287. // this gets the page path from root without QueryString
  288. string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
  289. return newQueryString.Count > 0
  290. ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
  291. : pagePathWithoutQueryString;
  292. }
  293. private string GetUrlToLog(string url)
  294. {
  295. url = RemoveQueryStringByKey(url, "api_key");
  296. return url;
  297. }
  298. private string NormalizeConfiguredLocalAddress(string address)
  299. {
  300. var index = address.Trim('/').IndexOf('/');
  301. if (index != -1)
  302. {
  303. address = address.Substring(index + 1);
  304. }
  305. return address.Trim('/');
  306. }
  307. private bool ValidateHost(Uri url)
  308. {
  309. var hosts = _config
  310. .Configuration
  311. .LocalNetworkAddresses
  312. .Select(NormalizeConfiguredLocalAddress)
  313. .ToList();
  314. if (hosts.Count == 0)
  315. {
  316. return true;
  317. }
  318. var host = url.Host ?? string.Empty;
  319. _logger.Debug("Validating host {0}", host);
  320. if (_networkManager.IsInPrivateAddressSpace(host))
  321. {
  322. hosts.Add("localhost");
  323. hosts.Add("127.0.0.1");
  324. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  325. }
  326. return true;
  327. }
  328. /// <summary>
  329. /// Overridable method that can be used to implement a custom hnandler
  330. /// </summary>
  331. /// <param name="httpReq">The HTTP req.</param>
  332. /// <param name="url">The URL.</param>
  333. /// <returns>Task.</returns>
  334. protected async Task RequestHandler(IHttpRequest httpReq, Uri url)
  335. {
  336. var date = DateTime.Now;
  337. var httpRes = httpReq.Response;
  338. bool enableLog = false;
  339. string urlToLog = null;
  340. string remoteIp = null;
  341. try
  342. {
  343. if (_disposed)
  344. {
  345. httpRes.StatusCode = 503;
  346. return;
  347. }
  348. if (!ValidateHost(url))
  349. {
  350. httpRes.StatusCode = 400;
  351. httpRes.ContentType = "text/plain";
  352. httpRes.Write("Invalid host");
  353. return;
  354. }
  355. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  356. {
  357. httpRes.StatusCode = 200;
  358. httpRes.AddHeader("Access-Control-Allow-Origin", "*");
  359. httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  360. httpRes.AddHeader("Access-Control-Allow-Headers",
  361. "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  362. httpRes.ContentType = "text/html";
  363. return;
  364. }
  365. var operationName = httpReq.OperationName;
  366. var localPath = url.LocalPath;
  367. var urlString = url.OriginalString;
  368. enableLog = EnableLogging(urlString, localPath);
  369. urlToLog = urlString;
  370. if (enableLog)
  371. {
  372. urlToLog = GetUrlToLog(urlString);
  373. remoteIp = httpReq.RemoteIp;
  374. LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
  375. }
  376. if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
  377. string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  378. {
  379. RedirectToUrl(httpRes, DefaultRedirectPath);
  380. return;
  381. }
  382. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
  383. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  384. {
  385. RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath);
  386. return;
  387. }
  388. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
  389. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
  390. localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
  391. {
  392. httpRes.StatusCode = 200;
  393. httpRes.ContentType = "text/html";
  394. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  395. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  396. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  397. {
  398. httpRes.Write(
  399. "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
  400. newUrl + "\">" + newUrl + "</a></body></html>");
  401. return;
  402. }
  403. }
  404. if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
  405. localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
  406. {
  407. httpRes.StatusCode = 200;
  408. httpRes.ContentType = "text/html";
  409. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  410. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  411. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  412. {
  413. httpRes.Write(
  414. "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
  415. newUrl + "\">" + newUrl + "</a></body></html>");
  416. return;
  417. }
  418. }
  419. if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
  420. {
  421. RedirectToUrl(httpRes, DefaultRedirectPath);
  422. return;
  423. }
  424. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  425. {
  426. RedirectToUrl(httpRes, "../" + DefaultRedirectPath);
  427. return;
  428. }
  429. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  430. {
  431. RedirectToUrl(httpRes, DefaultRedirectPath);
  432. return;
  433. }
  434. if (string.IsNullOrEmpty(localPath))
  435. {
  436. RedirectToUrl(httpRes, "/" + DefaultRedirectPath);
  437. return;
  438. }
  439. if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
  440. {
  441. RedirectToUrl(httpRes, "web/pin.html");
  442. return;
  443. }
  444. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  445. {
  446. httpRes.StatusCode = 503;
  447. httpRes.ContentType = "text/html";
  448. httpRes.Write(GlobalResponse);
  449. return;
  450. }
  451. var handler = HttpHandlerFactory.GetHandler(httpReq);
  452. if (handler != null)
  453. {
  454. await handler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false);
  455. }
  456. }
  457. catch (Exception ex)
  458. {
  459. ErrorHandler(ex, httpReq);
  460. }
  461. finally
  462. {
  463. httpRes.Close();
  464. if (enableLog)
  465. {
  466. var statusCode = httpRes.StatusCode;
  467. var duration = DateTime.Now - date;
  468. LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
  469. }
  470. }
  471. }
  472. public static void RedirectToUrl(IResponse httpRes, string url)
  473. {
  474. httpRes.StatusCode = 302;
  475. httpRes.AddHeader(HttpHeaders.Location, url);
  476. }
  477. /// <summary>
  478. /// Adds the rest handlers.
  479. /// </summary>
  480. /// <param name="services">The services.</param>
  481. public void Init(IEnumerable<IService> services)
  482. {
  483. _restServices.AddRange(services);
  484. ServiceController = CreateServiceController();
  485. _logger.Info("Calling ServiceStack AppHost.Init");
  486. base.Init();
  487. }
  488. public override Model.Services.RouteAttribute[] GetRouteAttributes(Type requestType)
  489. {
  490. var routes = base.GetRouteAttributes(requestType).ToList();
  491. var clone = routes.ToList();
  492. foreach (var route in clone)
  493. {
  494. routes.Add(new Model.Services.RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  495. {
  496. Notes = route.Notes,
  497. Priority = route.Priority,
  498. Summary = route.Summary
  499. });
  500. routes.Add(new Model.Services.RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  501. {
  502. Notes = route.Notes,
  503. Priority = route.Priority,
  504. Summary = route.Summary
  505. });
  506. routes.Add(new Model.Services.RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  507. {
  508. Notes = route.Notes,
  509. Priority = route.Priority,
  510. Summary = route.Summary
  511. });
  512. }
  513. return routes.ToArray();
  514. }
  515. private string NormalizeEmbyRoutePath(string path)
  516. {
  517. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  518. {
  519. return "/emby" + path;
  520. }
  521. return "emby/" + path;
  522. }
  523. private string DoubleNormalizeEmbyRoutePath(string path)
  524. {
  525. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  526. {
  527. return "/emby/emby" + path;
  528. }
  529. return "emby/emby/" + path;
  530. }
  531. private string NormalizeRoutePath(string path)
  532. {
  533. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  534. {
  535. return "/mediabrowser" + path;
  536. }
  537. return "mediabrowser/" + path;
  538. }
  539. private bool _disposed;
  540. private readonly object _disposeLock = new object();
  541. protected virtual void Dispose(bool disposing)
  542. {
  543. if (_disposed) return;
  544. base.Dispose();
  545. lock (_disposeLock)
  546. {
  547. if (_disposed) return;
  548. if (disposing)
  549. {
  550. Stop();
  551. }
  552. //release unmanaged resources here...
  553. _disposed = true;
  554. }
  555. }
  556. public override void Dispose()
  557. {
  558. Dispose(true);
  559. GC.SuppressFinalize(this);
  560. }
  561. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  562. {
  563. CertificatePath = certificatePath;
  564. UrlPrefixes = urlPrefixes.ToList();
  565. Start(UrlPrefixes.First());
  566. }
  567. }
  568. public class StreamFactory : IStreamFactory
  569. {
  570. public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
  571. {
  572. var netSocket = (NetSocket)socket;
  573. return new NetworkStream(netSocket.Socket, ownsSocket);
  574. }
  575. public Task AuthenticateSslStreamAsServer(Stream stream, ICertificate certificate)
  576. {
  577. var sslStream = (SslStream)stream;
  578. var cert = (Certificate)certificate;
  579. return sslStream.AuthenticateAsServerAsync(cert.X509Certificate);
  580. }
  581. public Stream CreateSslStream(Stream innerStream, bool leaveInnerStreamOpen)
  582. {
  583. return new SslStream(innerStream, leaveInnerStreamOpen);
  584. }
  585. }
  586. public class Certificate : ICertificate
  587. {
  588. public Certificate(X509Certificate x509Certificate)
  589. {
  590. X509Certificate = x509Certificate;
  591. }
  592. public X509Certificate X509Certificate { get; private set; }
  593. }
  594. }