OcppWebsocketService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.FromDays(1)
  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. session.ISOCPP20 = context.WebSockets.WebSocketRequestedProtocols.Any(x => x.ToLower() == "ocpp2.0");
  88. int securityProfile = 0;
  89. string authorizationKey = string.Empty;
  90. if (string.IsNullOrEmpty(session.Path))
  91. {
  92. //logger.Log();
  93. logger.LogWarning("===========================================");
  94. logger.LogWarning("{id} session.Path EMPTY", context.TraceIdentifier);
  95. logger.LogWarning("===========================================");
  96. }
  97. string[] words = session.Path.ToString().Split('/');
  98. session.ChargeBoxId = words.Last();
  99. logger.LogDebug("{id} {0}:{1}", context.TraceIdentifier, session.ChargeBoxId, session.UriScheme);
  100. foreach (var denyModel in GlobalConfig.DenyModelNames)
  101. {
  102. if (string.IsNullOrEmpty(denyModel))
  103. {
  104. continue;
  105. }
  106. if (session.ChargeBoxId.StartsWith(denyModel))
  107. {
  108. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  109. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  110. return false;
  111. }
  112. }
  113. if (configuration["MaintainMode"] == "1")
  114. {
  115. session.ChargeBoxId = session.ChargeBoxId + "_2";
  116. }
  117. logger.LogInformation("{id} ValidateHandshake: {0}", context.TraceIdentifier, session.Path);
  118. bool isExistedSN = false;
  119. bool authorizated = false;
  120. var info = await mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId, context.RequestAborted);
  121. if (context.RequestAborted.IsCancellationRequested) return false;
  122. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  123. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  124. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  125. //session.MachineId = machine == null ? String.Empty : machine.Id;
  126. //isExistedSN = machine == null ? false : true;
  127. session.CustomerName = info.CustomerName;
  128. session.CustomerId = info.CustomerId;
  129. session.MachineId = info.MachineId;
  130. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  131. if (!isExistedSN)
  132. {
  133. logger.LogInformation("{id} {func} not found", context.TraceIdentifier, nameof(ValidateHandshake));
  134. context.Response.StatusCode = StatusCodes.Status404NotFound;
  135. return false;
  136. }
  137. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  138. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  139. var configVaule = await mainDbService.GetMachineSecurityProfile(session.ChargeBoxId, context.RequestAborted);
  140. if (context.RequestAborted.IsCancellationRequested) return false;
  141. if (string.IsNullOrEmpty(configVaule))
  142. {
  143. logger.LogInformation("{id} {func} security profile not set", context.TraceIdentifier, nameof(ValidateHandshake));
  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. logger.LogInformation("{id} {func} {securityProfile} is ocpp20", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  155. securityProfile = 0;
  156. }
  157. if (securityProfile == 0)
  158. {
  159. authorizated = true;
  160. }
  161. if (securityProfile == 3 && session.UriScheme == "ws")
  162. {
  163. logger.LogInformation("{id} {func} {securityProfile} connection unsecured", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  164. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  165. return false;
  166. }
  167. if (securityProfile == 2 && session.UriScheme == "ws")
  168. {
  169. logger.LogInformation("{id} {func} {securityProfile} connection unsecured", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  170. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  171. return false;
  172. }
  173. if (securityProfile == 1 || securityProfile == 2)
  174. {
  175. string authHeader = context?.Request?.Headers?.Authorization;
  176. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  177. if (string.IsNullOrEmpty(authHeader))
  178. {
  179. logger.LogInformation("{id} {func} {securityProfile} missing auth header", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  180. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  181. return false;
  182. }
  183. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  184. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  185. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId, context.RequestAborted);
  186. if (context.RequestAborted.IsCancellationRequested) return false;
  187. if (session.ISOCPP20)
  188. {
  189. // 1.6 server only support change server function
  190. securityProfile = 0;
  191. }
  192. logger.LogInformation("{id} ***********Authorization ", context.TraceIdentifier);
  193. if (string.IsNullOrEmpty(authorizationKey))
  194. {
  195. logger.LogInformation("{id} {func} {securityProfile} auth key not defined in server", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  196. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  197. return false;
  198. }
  199. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  200. string base64Encoded = authHeader.Replace("Basic ", "");
  201. byte[] data = Convert.FromBase64String(base64Encoded);
  202. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  203. logger.LogInformation("{id} ***********Authorization " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
  204. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  205. {
  206. authorizated = true;
  207. }
  208. if (!authorizated)
  209. {
  210. logger.LogInformation("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
  211. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  212. return false;
  213. }
  214. }
  215. logger.LogInformation("{id} ValidateHandshake PASS: {0}", context.TraceIdentifier, session.Path);
  216. return true;
  217. }
  218. private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
  219. {
  220. int supportedProtocolIndex = supportedProtocols.Count - 1;
  221. for (; supportedProtocolIndex >= 0; supportedProtocolIndex--)
  222. {
  223. var testProtocol = supportedProtocols[supportedProtocolIndex];
  224. if (clientProtocols.Contains(testProtocol))
  225. {
  226. return testProtocol;
  227. }
  228. }
  229. return string.Empty;
  230. }
  231. }