OCPPWSServer.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. 
  2. using EVCB_OCPP.Domain;
  3. using EVCB_OCPP.WSServer;
  4. using NLog;
  5. using OCPPPackage.Profiles;
  6. using SuperWebSocket;
  7. using SuperWebSocket.SubProtocol;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Configuration;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Security;
  14. using System.Security.Cryptography.X509Certificates;
  15. using System.Text;
  16. namespace OCPPServer.Protocol
  17. {
  18. public class OCPPWSServer : WebSocketServer<ClientData>
  19. {
  20. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  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(IEnumerable<ISubProtocol<ClientData>> subProtocols)
  34. : base(subProtocols)
  35. {
  36. }
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  39. /// </summary>
  40. /// <param name="subProtocol">The sub protocol.</param>
  41. public OCPPWSServer(ISubProtocol<ClientData> subProtocol)
  42. : base(subProtocol)
  43. {
  44. }
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  47. /// </summary>
  48. public OCPPWSServer()
  49. : base(new List<ISubProtocol<ClientData>>())
  50. {
  51. }
  52. protected override bool ValidateClientCertificate(ClientData session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  53. {
  54. // Console.WriteLine(string.Format("{0} :{1}", session.ChargeBoxId + " ValidateClientCertificate", sslPolicyErrors));
  55. return true;
  56. // return base.ValidateClientCertificate(session, sender, certificate, chain, sslPolicyErrors);
  57. }
  58. protected override bool ValidateHandshake(ClientData session, string origin)
  59. {
  60. session.ISOCPP20 = session.SecWebSocketProtocol.ToLower().Contains("ocpp2.0");
  61. int securityProfile = 0;
  62. string authorizationKey = string.Empty;
  63. if (string.IsNullOrEmpty(session.Path))
  64. {
  65. logger.Warn("===========================================");
  66. logger.Warn("session.Path EMPTY");
  67. logger.Warn("===========================================");
  68. }
  69. string[] words = session.Path.Split('/');
  70. session.ChargeBoxId = words.Last();
  71. foreach(var denyModel in GlobalConfig.DenyModelNames)
  72. {
  73. if (string.IsNullOrEmpty(denyModel)) break;
  74. if (session.ChargeBoxId.StartsWith(denyModel))
  75. {
  76. StringBuilder responseBuilder = new StringBuilder();
  77. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  78. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  79. responseBuilder.AppendWithCrCf();
  80. string sb = responseBuilder.ToString();
  81. byte[] data = Encoding.UTF8.GetBytes(sb);
  82. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  83. logger.Info(sb);
  84. return false;
  85. }
  86. }
  87. if (ConfigurationManager.AppSettings["MaintainMode"] == "1")
  88. {
  89. session.ChargeBoxId = session.ChargeBoxId + "_2";
  90. }
  91. logger.Info(string.Format("ValidateHandshake: {0}", session.Path));
  92. bool isExistedSN = false;
  93. bool authorizated = false;
  94. using (var db = new MainDBContext())
  95. {
  96. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).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.Info(sb);
  111. return false;
  112. }
  113. var configVaule = db.MachineConfiguration.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.Info(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 = new MainDBContext())
  143. {
  144. authorizationKey = db.MachineConfiguration.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.Info("***********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.Info("***********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.Info(sb);
  179. return false;
  180. }
  181. }
  182. return true;
  183. }
  184. }
  185. }