HttpListenerHost.cs 24 KB

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