OCPPWSServer.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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)) break;
  85. if (session.ChargeBoxId.StartsWith(denyModel))
  86. {
  87. StringBuilder responseBuilder = new StringBuilder();
  88. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  89. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  90. responseBuilder.AppendWithCrCf();
  91. string sb = responseBuilder.ToString();
  92. byte[] data = Encoding.UTF8.GetBytes(sb);
  93. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  94. logger.LogTrace(sb);
  95. return false;
  96. }
  97. }
  98. if (configuration["MaintainMode"] == "1")
  99. {
  100. session.ChargeBoxId = session.ChargeBoxId + "_2";
  101. }
  102. logger.LogInformation(string.Format("ValidateHandshake: {0}", session.Path));
  103. bool isExistedSN = false;
  104. bool authorizated = false;
  105. var info = mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId).Result;
  106. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  107. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  108. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  109. //session.MachineId = machine == null ? String.Empty : machine.Id;
  110. //isExistedSN = machine == null ? false : true;
  111. session.CustomerName = info.CustomerName;
  112. session.CustomerId = info.CustomerId;
  113. session.MachineId = info.MachineId;
  114. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  115. if (!isExistedSN)
  116. {
  117. StringBuilder responseBuilder = new StringBuilder();
  118. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  119. (int)HttpStatusCode.NotFound, @"Not Found");
  120. responseBuilder.AppendWithCrCf();
  121. string sb = responseBuilder.ToString();
  122. byte[] data = Encoding.UTF8.GetBytes(sb);
  123. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  124. logger.LogInformation(sb);
  125. return false;
  126. }
  127. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  128. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  129. var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
  130. int.TryParse(configVaule, out securityProfile);
  131. if (session.ISOCPP20)
  132. {
  133. // 1.6 server only support change server function
  134. securityProfile = 0;
  135. }
  136. if (securityProfile == 3 && session.UriScheme == "ws")
  137. {
  138. StringBuilder responseBuilder = new StringBuilder();
  139. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  140. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  141. responseBuilder.AppendWithCrCf();
  142. string sb = responseBuilder.ToString();
  143. byte[] data = Encoding.UTF8.GetBytes(sb);
  144. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  145. logger.LogInformation(sb);
  146. return false;
  147. }
  148. if (securityProfile == 1 || securityProfile == 2)
  149. {
  150. if (securityProfile == 2 && session.UriScheme == "ws")
  151. {
  152. authorizated = false;
  153. }
  154. if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  155. {
  156. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  157. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  158. authorizationKey = mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId).Result;
  159. if (session.ISOCPP20)
  160. {
  161. // 1.6 server only support change server function
  162. securityProfile = 0;
  163. }
  164. logger.LogInformation("***********Authorization ");
  165. if (!string.IsNullOrEmpty(authorizationKey))
  166. {
  167. string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  168. byte[] data = Convert.FromBase64String(base64Encoded);
  169. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  170. logger.LogInformation("***********Authorization " + Encoding.ASCII.GetString(data));
  171. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  172. {
  173. authorizated = true;
  174. }
  175. }
  176. }
  177. else
  178. {
  179. authorizated = true;
  180. }
  181. if (!authorizated)
  182. {
  183. StringBuilder responseBuilder = new StringBuilder();
  184. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  185. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  186. responseBuilder.AppendWithCrCf();
  187. string sb = responseBuilder.ToString();
  188. byte[] data = Encoding.UTF8.GetBytes(sb);
  189. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  190. logger.LogInformation(sb);
  191. return false;
  192. }
  193. }
  194. logger.LogInformation(string.Format("ValidateHandshake PASS: {0}", session.Path));
  195. return true;
  196. }
  197. }