OCPPWSServer.cs 9.6 KB

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