OCPPWSServer.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using EVCB_OCPP.WSServer.Service;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.Logging;
  4. using OCPPServer.Protocol;
  5. using SuperSocket.SocketBase;
  6. using SuperWebSocket;
  7. using SuperWebSocket.SubProtocol;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Security;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.Text;
  15. namespace EVCB_OCPP.WSServer.SuperSocket;
  16. public class OCPPWSServer : WebSocketServer<ClientData>
  17. {
  18. private readonly ILogger logger;
  19. private readonly IConfiguration configuration;
  20. private readonly IMainDbService mainDbService;
  21. /// <summary>
  22. /// 可允許連線Clinet數
  23. /// </summary>
  24. public int connectNum { get; set; }
  25. /// <summary>
  26. /// 是否限制連線Clinet數
  27. /// </summary>
  28. public bool beConnectLimit { get; set; }
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  31. /// </summary>
  32. /// <param name="subProtocols">The sub protocols.</param>
  33. public OCPPWSServer(
  34. IConfiguration configuration,
  35. IMainDbService mainDbService,
  36. ILogger<OCPPWSServer> logger)
  37. : base(new List<ISubProtocol<ClientData>>())
  38. {
  39. this.configuration = configuration;
  40. this.mainDbService = mainDbService;
  41. this.logger = logger;
  42. }
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  45. /// </summary>
  46. /// <param name="subProtocol">The sub protocol.</param>
  47. //public OCPPWSServer(ISubProtocol<ClientData> subProtocol, IServiceProvider serviceProvider)
  48. // : base(subProtocol)
  49. //{
  50. // this.configuration = serviceProvider.GetService<IConfiguration>();
  51. // logger = serviceProvider.GetService<ILogger<OCPPWSServer>>();
  52. //}
  53. /// <summary>
  54. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  55. /// </summary>
  56. //public OCPPWSServer(IServiceProvider serviceProvider)
  57. // : base(new List<ISubProtocol<ClientData>>())
  58. //{
  59. // this.configuration = serviceProvider.GetService<IConfiguration>();
  60. // logger = serviceProvider.GetService<ILogger<OCPPWSServer>>();
  61. //}
  62. protected override bool ValidateClientCertificate(ClientData session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  63. {
  64. // Console.WriteLine(string.Format("{0} :{1}", session.ChargeBoxId + " ValidateClientCertificate", sslPolicyErrors));
  65. return true;
  66. // return base.ValidateClientCertificate(session, sender, certificate, chain, sslPolicyErrors);
  67. }
  68. protected override bool ValidateHandshake(ClientData session, string origin)
  69. {
  70. session.ISOCPP20 = session.SecWebSocketProtocol.ToLower().Contains("ocpp2.0");
  71. int securityProfile = 0;
  72. string authorizationKey = string.Empty;
  73. if (string.IsNullOrEmpty(session.Path))
  74. {
  75. //logger.Log();
  76. logger.LogWarning("===========================================");
  77. logger.LogWarning("session.Path EMPTY");
  78. logger.LogWarning("===========================================");
  79. }
  80. string[] words = session.Path.Split('/');
  81. session.ChargeBoxId = words.Last();
  82. foreach (var denyModel in GlobalConfig.DenyModelNames)
  83. {
  84. if (string.IsNullOrEmpty(denyModel))
  85. {
  86. continue;
  87. }
  88. if (session.ChargeBoxId.StartsWith(denyModel))
  89. {
  90. StringBuilder responseBuilder = new StringBuilder();
  91. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  92. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  93. responseBuilder.AppendWithCrCf();
  94. string sb = responseBuilder.ToString();
  95. byte[] data = Encoding.UTF8.GetBytes(sb);
  96. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  97. logger.LogTrace(sb);
  98. return false;
  99. }
  100. }
  101. if (configuration["MaintainMode"] == "1")
  102. {
  103. session.ChargeBoxId = session.ChargeBoxId + "_2";
  104. }
  105. logger.LogInformation(string.Format("ValidateHandshake: {0}", session.Path));
  106. bool isExistedSN = false;
  107. bool authorizated = false;
  108. var info = mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId).Result;
  109. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  110. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  111. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  112. //session.MachineId = machine == null ? String.Empty : machine.Id;
  113. //isExistedSN = machine == null ? false : true;
  114. session.CustomerName = info.CustomerName;
  115. session.CustomerId = info.CustomerId;
  116. session.MachineId = info.MachineId;
  117. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  118. if (!isExistedSN)
  119. {
  120. StringBuilder responseBuilder = new StringBuilder();
  121. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  122. (int)HttpStatusCode.NotFound, @"Not Found");
  123. responseBuilder.AppendWithCrCf();
  124. string sb = responseBuilder.ToString();
  125. byte[] data = Encoding.UTF8.GetBytes(sb);
  126. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  127. logger.LogInformation(sb);
  128. return false;
  129. }
  130. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  131. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  132. var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
  133. int.TryParse(configVaule, out securityProfile);
  134. if (session.ISOCPP20)
  135. {
  136. // 1.6 server only support change server function
  137. securityProfile = 0;
  138. }
  139. if (securityProfile == 3 && session.UriScheme == "ws")
  140. {
  141. StringBuilder responseBuilder = new StringBuilder();
  142. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  143. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  144. responseBuilder.AppendWithCrCf();
  145. string sb = responseBuilder.ToString();
  146. byte[] data = Encoding.UTF8.GetBytes(sb);
  147. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  148. logger.LogInformation(sb);
  149. return false;
  150. }
  151. if (securityProfile == 1 || securityProfile == 2)
  152. {
  153. if (securityProfile == 2 && session.UriScheme == "ws")
  154. {
  155. authorizated = false;
  156. }
  157. if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  158. {
  159. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  160. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  161. authorizationKey = mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId).Result;
  162. if (session.ISOCPP20)
  163. {
  164. // 1.6 server only support change server function
  165. securityProfile = 0;
  166. }
  167. logger.LogInformation("***********Authorization ");
  168. if (!string.IsNullOrEmpty(authorizationKey))
  169. {
  170. string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  171. byte[] data = Convert.FromBase64String(base64Encoded);
  172. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  173. logger.LogInformation("***********Authorization " + Encoding.ASCII.GetString(data));
  174. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  175. {
  176. authorizated = true;
  177. }
  178. }
  179. }
  180. else
  181. {
  182. authorizated = true;
  183. }
  184. if (!authorizated)
  185. {
  186. StringBuilder responseBuilder = new StringBuilder();
  187. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  188. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  189. responseBuilder.AppendWithCrCf();
  190. string sb = responseBuilder.ToString();
  191. byte[] data = Encoding.UTF8.GetBytes(sb);
  192. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  193. logger.LogInformation(sb);
  194. return false;
  195. }
  196. }
  197. logger.LogInformation(string.Format("ValidateHandshake PASS: {0}", session.Path));
  198. return true;
  199. }
  200. }