using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using CoreAgent.ProtocolClient.Context; using CoreAgent.ProtocolClient.Models; using Microsoft.Extensions.Logging; namespace CoreAgent.ProtocolClient.BuildProtocolParser { public class SIPProtocolParser : IGeneralProtocolParser { private readonly ProtocolClientContext context; private readonly ILogger _logger; // 修复正则表达式,使其更加严谨 private readonly Regex _regMnc = new Regex(@"mnc(\d+)", RegexOptions.Compiled); private readonly Regex _regMcc = new Regex(@"mcc(\d+)", RegexOptions.Compiled); private readonly Regex _regIMSI = new Regex(@"(); } public void GeneralParse(ref BuildProtocolLog log) { // 参数验证 if (log == null) { _logger.LogWarning("SIP协议解析失败:BuildProtocolLog参数为空"); return; } var SIPInfoMatch = ProtocolLogPatterns.RegExpSIP.Match(log.Message); if (SIPInfoMatch.Success) { var info = context.UeIdentifier.StringToId(SIPInfoMatch.Groups[2].Value); // 修复返回值检查逻辑 - StringToId返回0表示空字符串,不是-1 if (info == 0) { _logger.LogWarning("SIP协议解析失败:StringToId返回0,表示空字符串,消息内容: {Message}", log.Message); return; } log.Info = info; // 验证Groups数量 if (SIPInfoMatch.Groups.Count < 4) { _logger.LogWarning("SIP协议解析失败:正则匹配Groups数量不足,期望至少4个,实际{ActualCount}个,消息内容: {Message}", SIPInfoMatch.Groups.Count, log.Message); return; } string Direction = log.Direction == 1 ? "to" : "from"; log.Message = $"{SIPInfoMatch.Groups[3].Value} {Direction} {SIPInfoMatch.Groups[1].Value}"; // 修复变量名错误和空引用风险 var mncValue = log.Data?.Select(line => _regMnc.Match(line)) .Where(match => match.Success) .Select(match => match.Groups[1].Value) .FirstOrDefault(); var mccValue = log.Data?.Select(line => _regMcc.Match(line)) .Where(match => match.Success) .Select(match => match.Groups[1].Value) .FirstOrDefault(); var imsiValue = log.Data?.Select(line => _regIMSI.Match(line)) .Where(match => match.Success) .Select(match => match.Groups[1].Value) .FirstOrDefault(); // 设置PLMN - 修复逻辑错误 if (!string.IsNullOrEmpty(mccValue) && !string.IsNullOrEmpty(mncValue)) { log.SIP.Plmn = $"{mccValue}{mncValue}"; } // 设置IMSI - 使用正确的属性 if (!string.IsNullOrEmpty(imsiValue)) { log.SIP.IMSI = imsiValue; } } } } }