You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.5 KiB

  1. #if !NET20
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text.RegularExpressions;
  5. namespace Apewer.WebSocket
  6. {
  7. internal class ConnectionInfo
  8. {
  9. const string CookiePattern = @"((;)*(\s)*(?<cookie_name>[^=]+)=(?<cookie_value>[^\;]+))+";
  10. private static readonly Regex CookieRegex = new Regex(CookiePattern, RegexOptions.Compiled);
  11. public static ConnectionInfo Create(HttpRequest request, string clientIp, int clientPort, string negotiatedSubprotocol)
  12. {
  13. var info = new ConnectionInfo
  14. {
  15. Origin = request["Origin"] ?? request["Sec-WebSocket-Origin"],
  16. Host = request["Host"],
  17. SubProtocol = request["Sec-WebSocket-Protocol"],
  18. Path = request.Path,
  19. ClientIpAddress = clientIp,
  20. ClientPort = clientPort,
  21. NegotiatedSubProtocol = negotiatedSubprotocol,
  22. Headers = new Dictionary<string, string>(request.Headers, System.StringComparer.InvariantCultureIgnoreCase)
  23. };
  24. var cookieHeader = request["Cookie"];
  25. if (cookieHeader != null)
  26. {
  27. var match = CookieRegex.Match(cookieHeader);
  28. var fields = match.Groups["cookie_name"].Captures;
  29. var values = match.Groups["cookie_value"].Captures;
  30. for (var i = 0; i < fields.Count; i++)
  31. {
  32. var name = fields[i].ToString();
  33. var value = values[i].ToString();
  34. info.Cookies[name] = value;
  35. }
  36. }
  37. return info;
  38. }
  39. ConnectionInfo()
  40. {
  41. Cookies = new Dictionary<string, string>();
  42. Id = Guid.NewGuid();
  43. }
  44. public string NegotiatedSubProtocol { get; private set; }
  45. public string SubProtocol { get; private set; }
  46. public string Origin { get; private set; }
  47. public string Host { get; private set; }
  48. public string Path { get; private set; }
  49. public string ClientIpAddress { get; set; }
  50. public int ClientPort { get; set; }
  51. public Guid Id { get; set; }
  52. public IDictionary<string, string> Cookies { get; private set; }
  53. public IDictionary<string, string> Headers { get; private set; }
  54. }
  55. }
  56. #endif