OcppWebsocketService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. using EVCB_OCPP.WSServer.Helper;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using System.Net.WebSockets;
  8. using System.Text;
  9. namespace EVCB_OCPP.WSServer.Service.WsService;
  10. public static partial class AppExtention
  11. {
  12. public static void AddOcppWsServer(this IServiceCollection services)
  13. {
  14. services.AddTransient<WsClientData>();
  15. services.AddSingleton<OcppWebsocketService>();
  16. }
  17. public static void UseOcppWsService(this WebApplication webApplication)
  18. {
  19. webApplication.UseWebSockets(new WebSocketOptions()
  20. {
  21. KeepAliveInterval = TimeSpan.FromSeconds(10)
  22. });
  23. webApplication.Use(async (context, next) =>
  24. {
  25. if (!context.WebSockets.IsWebSocketRequest)
  26. {
  27. await next(context);
  28. return;
  29. }
  30. var servcie = context.RequestServices.GetService<OcppWebsocketService>();
  31. await servcie.AcceptWebSocket(context);
  32. return;
  33. });
  34. }
  35. }
  36. public class OcppWebsocketService : WebsocketService<WsClientData>
  37. {
  38. public static List<string> protocals = new List<string>() { "", "ocpp1.6", "ocpp2.0.1" };
  39. private readonly IConfiguration configuration;
  40. private readonly IMainDbService mainDbService;
  41. private readonly ILogger<OcppWebsocketService> logger;
  42. private readonly QueueSemaphore handshakeSemaphore;
  43. public OcppWebsocketService(
  44. IConfiguration configuration,
  45. IServiceProvider serviceProvider,
  46. IMainDbService mainDbService,
  47. ILogger<OcppWebsocketService> logger
  48. ) : base(serviceProvider)
  49. {
  50. this.configuration = configuration;
  51. this.mainDbService = mainDbService;
  52. this.logger = logger;
  53. handshakeSemaphore = new QueueSemaphore(5);
  54. }
  55. internal override async ValueTask<string> ValidateSupportedPortocol(HttpContext context)
  56. {
  57. logger.LogInformation("{id} {function}:{Path}/{SubProtocol}", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);
  58. var protocol = GetSupportedPortocol(context.WebSockets.WebSocketRequestedProtocols, protocals);
  59. if (string.IsNullOrEmpty(protocol))
  60. {
  61. logger.LogInformation("{id} {function}:{Path} Protocol Not Supported, Disconnecting", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path);
  62. using WebSocket toRejectwebSocket = await context.WebSockets.AcceptWebSocketAsync();
  63. await toRejectwebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
  64. return string.Empty;
  65. }
  66. return protocol;
  67. }
  68. internal override async ValueTask<bool> ValidateHandshake(HttpContext context, WsClientData session)
  69. {
  70. try
  71. {
  72. using var canValidate = await handshakeSemaphore.GetToken();
  73. var result = await ValidateHandshakeUnsafe(context, session);
  74. return result;
  75. }
  76. catch (Exception ex)
  77. {
  78. logger.LogError(ex.Message);
  79. logger.LogError(ex.StackTrace);
  80. }
  81. return false;
  82. }
  83. internal async ValueTask<bool> ValidateHandshakeUnsafe(HttpContext context, WsClientData session)
  84. {
  85. if (context.RequestAborted.IsCancellationRequested) return false;
  86. string authHeader = context?.Request?.Headers?.Authorization;
  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. context.Response.StatusCode = StatusCodes.Status404NotFound;
  134. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  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. int.TryParse(configVaule, out securityProfile);
  142. if (session.ISOCPP20)
  143. {
  144. // 1.6 server only support change server function
  145. securityProfile = 0;
  146. }
  147. if (securityProfile == 3 && session.UriScheme == "ws")
  148. {
  149. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  150. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  151. return false;
  152. }
  153. if (securityProfile == 1 || securityProfile == 2)
  154. {
  155. if (securityProfile == 2 && session.UriScheme == "ws")
  156. {
  157. authorizated = false;
  158. }
  159. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  160. if (!string.IsNullOrEmpty(authHeader))
  161. {
  162. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  163. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  164. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId, context.RequestAborted);
  165. if (context.RequestAborted.IsCancellationRequested) return false;
  166. if (session.ISOCPP20)
  167. {
  168. // 1.6 server only support change server function
  169. securityProfile = 0;
  170. }
  171. logger.LogInformation("{id} ***********Authorization ", context.TraceIdentifier);
  172. if (!string.IsNullOrEmpty(authorizationKey))
  173. {
  174. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  175. string base64Encoded = authHeader.Replace("Basic ", "");
  176. byte[] data = Convert.FromBase64String(base64Encoded);
  177. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  178. logger.LogInformation("{id} ***********Authorization " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
  179. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  180. {
  181. authorizated = true;
  182. }
  183. }
  184. }
  185. else
  186. {
  187. authorizated = true;
  188. }
  189. if (!authorizated)
  190. {
  191. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  192. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  193. return false;
  194. }
  195. }
  196. logger.LogInformation("{id} ValidateHandshake PASS: {0}", context.TraceIdentifier, session.Path);
  197. return true;
  198. }
  199. private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
  200. {
  201. int supportedProtocolIndex = supportedProtocols.Count - 1;
  202. for (; supportedProtocolIndex >= 0; supportedProtocolIndex--)
  203. {
  204. var testProtocol = supportedProtocols[supportedProtocolIndex];
  205. if (clientProtocols.Contains(testProtocol))
  206. {
  207. return testProtocol;
  208. }
  209. }
  210. return string.Empty;
  211. }
  212. }