OcppWebsocketService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using EVCB_OCPP.WSServer.Helper;
  2. using EVCB_OCPP.WSServer.Service.DbService;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Logging;
  8. using System.Net.WebSockets;
  9. using System.Text;
  10. namespace EVCB_OCPP.WSServer.Service.WsService;
  11. public static partial class AppExtention
  12. {
  13. public static void AddOcppWsServer(this IServiceCollection services)
  14. {
  15. services.AddTransient<WsClientData>();
  16. services.AddSingleton<OcppWebsocketService>();
  17. }
  18. public static void UseOcppWsService(this WebApplication webApplication)
  19. {
  20. webApplication.UseWebSockets(new WebSocketOptions()
  21. {
  22. KeepAliveInterval = TimeSpan.FromSeconds(10)
  23. });
  24. webApplication.Use(async (context, next) =>
  25. {
  26. if (!context.WebSockets.IsWebSocketRequest)
  27. {
  28. await next(context);
  29. return;
  30. }
  31. var servcie = context.RequestServices.GetService<OcppWebsocketService>();
  32. await servcie.AcceptWebSocket(context);
  33. return;
  34. });
  35. }
  36. }
  37. public class OcppWebsocketService : WebsocketService<WsClientData>
  38. {
  39. public static List<string> protocals = new List<string>() { "ocpp1.6"};
  40. private readonly IConfiguration configuration;
  41. private readonly IMainDbService mainDbService;
  42. private readonly ILogger<OcppWebsocketService> logger;
  43. private readonly QueueSemaphore handshakeSemaphore;
  44. public OcppWebsocketService(
  45. IConfiguration configuration,
  46. IServiceProvider serviceProvider,
  47. IMainDbService mainDbService,
  48. ILogger<OcppWebsocketService> logger
  49. ) : base(serviceProvider, logger)
  50. {
  51. this.configuration = configuration;
  52. this.mainDbService = mainDbService;
  53. this.logger = logger;
  54. handshakeSemaphore = new QueueSemaphore(5);
  55. }
  56. internal override async ValueTask<string> ValidateSupportedPortocol(HttpContext context)
  57. {
  58. logger.LogInformation("{id} {function}:{Path}/{SubProtocol}", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);
  59. var protocol = GetSupportedPortocol(context.WebSockets.WebSocketRequestedProtocols, protocals);
  60. if (string.IsNullOrEmpty(protocol))
  61. {
  62. logger.LogInformation("{id} {function}:{Path} Protocol Not Supported, Disconnecting", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path);
  63. using WebSocket toRejectwebSocket = await context.WebSockets.AcceptWebSocketAsync();
  64. await toRejectwebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
  65. return string.Empty;
  66. }
  67. return protocol;
  68. }
  69. internal override async ValueTask<bool> ValidateHandshake(HttpContext context, WsClientData session)
  70. {
  71. try
  72. {
  73. using var canValidate = await handshakeSemaphore.GetToken();
  74. var result = await ValidateHandshakeUnsafe(context, session);
  75. return result;
  76. }
  77. catch (Exception ex)
  78. {
  79. logger.LogError(ex.Message);
  80. logger.LogError(ex.StackTrace);
  81. }
  82. return false;
  83. }
  84. internal async ValueTask<bool> ValidateHandshakeUnsafe(HttpContext context, WsClientData session)
  85. {
  86. if (context.RequestAborted.IsCancellationRequested) return false;
  87. string authHeader = context?.Request?.Headers?.Authorization;
  88. session.ISOCPP20 = context.WebSockets.WebSocketRequestedProtocols.Any(x => x.ToLower() == "ocpp2.0");
  89. int securityProfile = 0;
  90. string authorizationKey = string.Empty;
  91. if (string.IsNullOrEmpty(session.Path))
  92. {
  93. //logger.Log();
  94. logger.LogWarning("===========================================");
  95. logger.LogWarning("{id} session.Path EMPTY", context.TraceIdentifier);
  96. logger.LogWarning("===========================================");
  97. }
  98. string[] words = session.Path.ToString().Split('/');
  99. session.ChargeBoxId = words.Last();
  100. logger.LogDebug("{id} {0}:{1}", context.TraceIdentifier, session.ChargeBoxId, session.UriScheme);
  101. foreach (var denyModel in GlobalConfig.DenyModelNames)
  102. {
  103. if (string.IsNullOrEmpty(denyModel))
  104. {
  105. continue;
  106. }
  107. if (session.ChargeBoxId.StartsWith(denyModel))
  108. {
  109. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  110. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  111. return false;
  112. }
  113. }
  114. if (configuration["MaintainMode"] == "1")
  115. {
  116. session.ChargeBoxId = session.ChargeBoxId + "_2";
  117. }
  118. logger.LogInformation("{id} ValidateHandshake: {0}", context.TraceIdentifier, session.Path);
  119. bool isExistedSN = false;
  120. bool authorizated = false;
  121. var info = await mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId, context.RequestAborted);
  122. if (context.RequestAborted.IsCancellationRequested) return false;
  123. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  124. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  125. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  126. //session.MachineId = machine == null ? String.Empty : machine.Id;
  127. //isExistedSN = machine == null ? false : true;
  128. session.CustomerName = info.CustomerName;
  129. session.CustomerId = info.CustomerId;
  130. session.MachineId = info.MachineId;
  131. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  132. if (!isExistedSN)
  133. {
  134. logger.LogTrace("{id} {func} not found", context.TraceIdentifier, nameof(ValidateHandshake));
  135. context.Response.StatusCode = StatusCodes.Status404NotFound;
  136. return false;
  137. }
  138. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  139. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  140. var configVaule = await mainDbService.GetMachineSecurityProfile(session.ChargeBoxId, context.RequestAborted);
  141. if (context.RequestAborted.IsCancellationRequested) return false;
  142. if (string.IsNullOrEmpty(configVaule))
  143. {
  144. return true;
  145. }
  146. if (!int.TryParse(configVaule, out securityProfile))
  147. {
  148. logger.LogCritical("ERROR securityProfile setted {securityProfile}", configVaule);
  149. return false;
  150. }
  151. if (session.ISOCPP20)
  152. {
  153. // 1.6 server only support change server function
  154. securityProfile = 0;
  155. }
  156. if (securityProfile == 0)
  157. {
  158. authorizated = true;
  159. }
  160. if (securityProfile == 3 && session.UriScheme == "ws")
  161. {
  162. logger.LogTrace("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  163. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  164. return false;
  165. }
  166. if (securityProfile == 1 || securityProfile == 2)
  167. {
  168. if (securityProfile == 2 && session.UriScheme == "ws")
  169. {
  170. logger.LogTrace("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  171. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  172. return false;
  173. }
  174. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  175. if (string.IsNullOrEmpty(authHeader))
  176. {
  177. logger.LogTrace("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  178. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  179. return false;
  180. }
  181. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  182. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  183. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId, context.RequestAborted);
  184. if (context.RequestAborted.IsCancellationRequested) return false;
  185. if (session.ISOCPP20)
  186. {
  187. // 1.6 server only support change server function
  188. securityProfile = 0;
  189. }
  190. logger.LogInformation("{id} ***********Authorization ", context.TraceIdentifier);
  191. if (!string.IsNullOrEmpty(authorizationKey))
  192. {
  193. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  194. string base64Encoded = authHeader.Replace("Basic ", "");
  195. byte[] data = Convert.FromBase64String(base64Encoded);
  196. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  197. logger.LogInformation("{id} ***********Authorization " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
  198. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  199. {
  200. authorizated = true;
  201. }
  202. }
  203. if (!authorizated)
  204. {
  205. logger.LogTrace("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  206. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  207. return false;
  208. }
  209. }
  210. logger.LogInformation("{id} ValidateHandshake PASS: {0}", context.TraceIdentifier, session.Path);
  211. return true;
  212. }
  213. private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
  214. {
  215. int supportedProtocolIndex = supportedProtocols.Count - 1;
  216. for (; supportedProtocolIndex >= 0; supportedProtocolIndex--)
  217. {
  218. var testProtocol = supportedProtocols[supportedProtocolIndex];
  219. if (clientProtocols.Contains(testProtocol))
  220. {
  221. return testProtocol;
  222. }
  223. }
  224. return string.Empty;
  225. }
  226. }