OCPPWSServer.cs 9.3 KB

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