OcppWebsocketService.cs 9.4 KB

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