diff --git a/internal/gtp/handler/handler.go b/internal/gtp/handler/handler.go index 9536df95..d838858b 100644 --- a/internal/gtp/handler/handler.go +++ b/internal/gtp/handler/handler.go @@ -27,10 +27,12 @@ func HandleQoSTPDU(c gtp.Conn, senderAddr net.Addr, msg gtpMsg.Message) error { // Forward user plane packets from N3 to UE with GRE header and new IP header encapsulated func forward(packet gtpQoSMsg.QoSTPDUPacket) { + gtpLog := logger.GTPLog + defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.GTPLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + gtpLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } }() @@ -41,18 +43,18 @@ func forward(packet gtpQoSMsg.QoSTPDUPacket) { NWuConn := self.NWuIPv4PacketConn pktTEID := packet.GetTEID() - logger.GTPLog.Tracef("pkt teid : %d", pktTEID) + gtpLog.Tracef("pkt teid : %d", pktTEID) // Find UE information ranUe, ok := self.AllocatedUETEIDLoad(pktTEID) if !ok { - logger.GTPLog.Errorf("Cannot find RanUE context from QosPacket TEID : %+v", pktTEID) + gtpLog.Errorf("Cannot find RanUE context from QosPacket TEID : %+v", pktTEID) return } ikeUe, err := self.IkeUeLoadFromNgapId(ranUe.RanUeNgapId) if err != nil { - logger.GTPLog.Errorf("Cannot find IkeUe context from RanUe , NgapID : %+v", ranUe.RanUeNgapId) + gtpLog.Errorf("Cannot find IkeUe context from RanUe , NgapID : %+v", ranUe.RanUeNgapId) return } @@ -64,7 +66,7 @@ func forward(packet gtpQoSMsg.QoSTPDUPacket) { for _, childSA := range ikeUe.N3IWFChildSecurityAssociation { pdusession := ranUe.FindPDUSession(childSA.PDUSessionIds[0]) if pdusession != nil && pdusession.GTPConnection.IncomingTEID == pktTEID { - logger.GTPLog.Tracef("forwarding IPSec xfrm interfaceid : %d", childSA.XfrmIface.Attrs().Index) + gtpLog.Tracef("forwarding IPSec xfrm interfaceid : %d", childSA.XfrmIface.Attrs().Index) cm = &ipv4.ControlMessage{ IfIndex: childSA.XfrmIface.Attrs().Index, } @@ -80,7 +82,7 @@ func forward(packet gtpQoSMsg.QoSTPDUPacket) { // QoS Related Parameter if packet.HasQoS() { qfi, rqi = packet.GetQoSParameters() - logger.GTPLog.Tracef("QFI: %v, RQI: %v", qfi, rqi) + gtpLog.Tracef("QFI: %v, RQI: %v", qfi, rqi) } // Encasulate IPv4 packet with GRE header before forward to UE through IPsec @@ -93,10 +95,10 @@ func forward(packet gtpQoSMsg.QoSTPDUPacket) { // Send to UE through Nwu if n, err := NWuConn.WriteTo(forwardData, cm, ueInnerIPAddr); err != nil { - logger.GTPLog.Errorf("Write to UE failed: %+v", err) + gtpLog.Errorf("Write to UE failed: %+v", err) return } else { - logger.GTPLog.Trace("Forward NWu <- N3") - logger.GTPLog.Tracef("Wrote %d bytes", n) + gtpLog.Trace("Forward NWu <- N3") + gtpLog.Tracef("Wrote %d bytes", n) } } diff --git a/internal/gtp/message/message.go b/internal/gtp/message/message.go index 550192d4..bbd27536 100644 --- a/internal/gtp/message/message.go +++ b/internal/gtp/message/message.go @@ -58,16 +58,18 @@ func (p *QoSTPDUPacket) Unmarshal(pdu *gtpMessage.TPDU) error { // [TS 38.415] // Define PDU Session User Plane protocol func (p *QoSTPDUPacket) unmarshalExtensionHeader() error { + gtpLog := logger.GTPLog + for _, eh := range p.tPDU.ExtensionHeaders { switch eh.Type { case gtpMessage.ExtHeaderTypePDUSessionContainer: p.qos = true p.rqi = ((int(eh.Content[1]) >> 6) & 0x1) == 1 p.qfi = eh.Content[1] & 0x3F - logger.GTPLog.Tracef("Parsed Extension Header: Len=%d, Next Type=%d, Content Dump:\n%s", + gtpLog.Tracef("Parsed Extension Header: Len=%d, Next Type=%d, Content Dump:\n%s", eh.Length, eh.NextType, hex.Dump(eh.Content)) default: - logger.GTPLog.Warningf("Unsupported Extension Header Field Value: %x", eh.Type) + gtpLog.Warningf("Unsupported Extension Header Field Value: %x", eh.Type) } } diff --git a/internal/gtp/service/service.go b/internal/gtp/service/service.go index 8b33842f..c2b1aa86 100644 --- a/internal/gtp/service/service.go +++ b/internal/gtp/service/service.go @@ -18,6 +18,7 @@ var gtpContext context.Context = context.TODO() // SetupGTPTunnelWithUPF set up GTP connection with UPF // return *gtp.UPlaneConn, net.Addr and error func SetupGTPTunnelWithUPF(upfIPAddr string) (*gtp.UPlaneConn, net.Addr, error) { + gtpLog := logger.GTPLog n3iwfSelf := n3iwfContext.N3IWFSelf() // Set up GTP connection @@ -25,7 +26,7 @@ func SetupGTPTunnelWithUPF(upfIPAddr string) (*gtp.UPlaneConn, net.Addr, error) remoteUDPAddr, err := net.ResolveUDPAddr("udp", upfUDPAddr) if err != nil { - logger.GTPLog.Errorf("Resolve UDP address %s failed: %+v", upfUDPAddr, err) + gtpLog.Errorf("Resolve UDP address %s failed: %+v", upfUDPAddr, err) return nil, nil, errors.New("Resolve Address Failed") } @@ -33,14 +34,14 @@ func SetupGTPTunnelWithUPF(upfIPAddr string) (*gtp.UPlaneConn, net.Addr, error) localUDPAddr, err := net.ResolveUDPAddr("udp", n3iwfUDPAddr) if err != nil { - logger.GTPLog.Errorf("Resolve UDP address %s failed: %+v", n3iwfUDPAddr, err) + gtpLog.Errorf("Resolve UDP address %s failed: %+v", n3iwfUDPAddr, err) return nil, nil, errors.New("Resolve Address Failed") } // Dial to UPF userPlaneConnection, err := gtp.DialUPlane(gtpContext, localUDPAddr, remoteUDPAddr) if err != nil { - logger.GTPLog.Errorf("Dial to UPF failed: %+v", err) + gtpLog.Errorf("Dial to UPF failed: %+v", err) return nil, nil, errors.New("Dial failed") } diff --git a/internal/ngap/dispatcher.go b/internal/ngap/dispatcher.go index 2ed68d2e..34f0b265 100644 --- a/internal/ngap/dispatcher.go +++ b/internal/ngap/dispatcher.go @@ -12,10 +12,12 @@ import ( ) func NGAPDispatch(conn *sctp.SCTPConn, msg []byte) { + ngapLog := logger.NgapLog + defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NgapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ngapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } }() @@ -26,7 +28,7 @@ func NGAPDispatch(conn *sctp.SCTPConn, msg []byte) { // Decode pdu, err := ngap.Decoder(msg) if err != nil { - logger.NgapLog.Errorf("NGAP decode error: %+v\n", err) + ngapLog.Errorf("NGAP decode error: %+v\n", err) return } @@ -34,7 +36,7 @@ func NGAPDispatch(conn *sctp.SCTPConn, msg []byte) { case ngapType.NGAPPDUPresentInitiatingMessage: initiatingMessage := pdu.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Errorln("Initiating Message is nil") + ngapLog.Errorln("Initiating Message is nil") return } @@ -76,13 +78,13 @@ func NGAPDispatch(conn *sctp.SCTPConn, msg []byte) { case ngapType.ProcedureCodeOverloadStop: handler.HandleOverloadStop(amf, pdu) default: - logger.NgapLog.Warnf("Not implemented NGAP message(initiatingMessage), procedureCode:%d]\n", + ngapLog.Warnf("Not implemented NGAP message(initiatingMessage), procedureCode:%d]\n", initiatingMessage.ProcedureCode.Value) } case ngapType.NGAPPDUPresentSuccessfulOutcome: successfulOutcome := pdu.SuccessfulOutcome if successfulOutcome == nil { - logger.NgapLog.Errorln("Successful Outcome is nil") + ngapLog.Errorln("Successful Outcome is nil") return } @@ -96,13 +98,13 @@ func NGAPDispatch(conn *sctp.SCTPConn, msg []byte) { case ngapType.ProcedureCodeRANConfigurationUpdate: handler.HandleRANConfigurationUpdateAcknowledge(amf, pdu) default: - logger.NgapLog.Warnf("Not implemented NGAP message(successfulOutcome), procedureCode:%d]\n", + ngapLog.Warnf("Not implemented NGAP message(successfulOutcome), procedureCode:%d]\n", successfulOutcome.ProcedureCode.Value) } case ngapType.NGAPPDUPresentUnsuccessfulOutcome: unsuccessfulOutcome := pdu.UnsuccessfulOutcome if unsuccessfulOutcome == nil { - logger.NgapLog.Errorln("Unsuccessful Outcome is nil") + ngapLog.Errorln("Unsuccessful Outcome is nil") return } @@ -112,7 +114,7 @@ func NGAPDispatch(conn *sctp.SCTPConn, msg []byte) { case ngapType.ProcedureCodeRANConfigurationUpdate: handler.HandleRANConfigurationUpdateFailure(amf, pdu) default: - logger.NgapLog.Warnf("Not implemented NGAP message(unsuccessfulOutcome), procedureCode:%d]\n", + ngapLog.Warnf("Not implemented NGAP message(unsuccessfulOutcome), procedureCode:%d]\n", unsuccessfulOutcome.ProcedureCode.Value) } } diff --git a/internal/ngap/handler/handler.go b/internal/ngap/handler/handler.go index 73118a6d..ae575ead 100644 --- a/internal/ngap/handler/handler.go +++ b/internal/ngap/handler/handler.go @@ -16,7 +16,8 @@ import ( ) func HandleNGSetupResponse(sctpAddr string, conn *sctp.SCTPConn, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle NG Setup Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle NG Setup Response") var amfName *ngapType.AMFName var servedGUAMIList *ngapType.ServedGUAMIList @@ -29,62 +30,62 @@ func HandleNGSetupResponse(sctpAddr string, conn *sctp.SCTPConn, message *ngapTy n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } successfulOutcome := message.SuccessfulOutcome if successfulOutcome == nil { - logger.NgapLog.Error("Successful Outcome is nil") + ngapLog.Error("Successful Outcome is nil") return } ngSetupResponse := successfulOutcome.Value.NGSetupResponse if ngSetupResponse == nil { - logger.NgapLog.Error("ngSetupResponse is nil") + ngapLog.Error("ngSetupResponse is nil") return } for _, ie := range ngSetupResponse.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFName: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFName") + ngapLog.Traceln("[NGAP] Decode IE AMFName") amfName = ie.Value.AMFName if amfName == nil { - logger.NgapLog.Errorf("AMFName is nil") + ngapLog.Errorf("AMFName is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDServedGUAMIList: - logger.NgapLog.Traceln("[NGAP] Decode IE ServedGUAMIList") + ngapLog.Traceln("[NGAP] Decode IE ServedGUAMIList") servedGUAMIList = ie.Value.ServedGUAMIList if servedGUAMIList == nil { - logger.NgapLog.Errorf("ServedGUAMIList is nil") + ngapLog.Errorf("ServedGUAMIList is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRelativeAMFCapacity: - logger.NgapLog.Traceln("[NGAP] Decode IE RelativeAMFCapacity") + ngapLog.Traceln("[NGAP] Decode IE RelativeAMFCapacity") relativeAMFCapacity = ie.Value.RelativeAMFCapacity case ngapType.ProtocolIEIDPLMNSupportList: - logger.NgapLog.Traceln("[NGAP] Decode IE PLMNSupportList") + ngapLog.Traceln("[NGAP] Decode IE PLMNSupportList") plmnSupportList = ie.Value.PLMNSupportList if plmnSupportList == nil { - logger.NgapLog.Errorf("PLMNSupportList is nil") + ngapLog.Errorf("PLMNSupportList is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDCriticalityDiagnostics: - logger.NgapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") criticalityDiagnostics = ie.Value.CriticalityDiagnostics } } if len(iesCriticalityDiagnostics.List) != 0 { - logger.NgapLog.Traceln("[NGAP] Sending error indication to AMF, because some mandatory IEs were not included") + ngapLog.Traceln("[NGAP] Sending error indication to AMF, because some mandatory IEs were not included") cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentAbstractSyntaxErrorReject) @@ -125,7 +126,8 @@ func HandleNGSetupResponse(sctpAddr string, conn *sctp.SCTPConn, message *ngapTy } func HandleNGSetupFailure(sctpAddr string, conn *sctp.SCTPConn, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle NG Setup Failure") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle NG Setup Failure") var cause *ngapType.Cause var timeToWait *ngapType.TimeToWait @@ -136,45 +138,45 @@ func HandleNGSetupFailure(sctpAddr string, conn *sctp.SCTPConn, message *ngapTyp n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } unsuccessfulOutcome := message.UnsuccessfulOutcome if unsuccessfulOutcome == nil { - logger.NgapLog.Error("Unsuccessful Message is nil") + ngapLog.Error("Unsuccessful Message is nil") return } ngSetupFailure := unsuccessfulOutcome.Value.NGSetupFailure if ngSetupFailure == nil { - logger.NgapLog.Error("NGSetupFailure is nil") + ngapLog.Error("NGSetupFailure is nil") return } for _, ie := range ngSetupFailure.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDCause: - logger.NgapLog.Traceln("[NGAP] Decode IE Cause") + ngapLog.Traceln("[NGAP] Decode IE Cause") cause = ie.Value.Cause if cause == nil { - logger.NgapLog.Error("Cause is nil") + ngapLog.Error("Cause is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDTimeToWait: - logger.NgapLog.Traceln("[NGAP] Decode IE TimeToWait") + ngapLog.Traceln("[NGAP] Decode IE TimeToWait") timeToWait = ie.Value.TimeToWait case ngapType.ProtocolIEIDCriticalityDiagnostics: - logger.NgapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") criticalityDiagnostics = ie.Value.CriticalityDiagnostics } } if len(iesCriticalityDiagnostics.List) > 0 { // TODO: Send error indication - logger.NgapLog.Traceln("[NGAP] Sending error indication to AMF, because some mandatory IEs were not included") + ngapLog.Traceln("[NGAP] Sending error indication to AMF, because some mandatory IEs were not included") cause = ngap_message.BuildCause( ngapType.CausePresentProtocol, @@ -220,7 +222,7 @@ func HandleNGSetupFailure(sctpAddr string, conn *sctp.SCTPConn, message *ngapTyp } if waitingTime != 0 { - logger.NgapLog.Infof("Wait at lease %ds to reinitialize with same AMF[%s]", waitingTime, sctpAddr) + ngapLog.Infof("Wait at lease %ds to reinitialize with same AMF[%s]", waitingTime, sctpAddr) n3iwfSelf.AMFReInitAvailableListStore(sctpAddr, false) time.AfterFunc(time.Duration(waitingTime)*time.Second, func() { n3iwfSelf.AMFReInitAvailableListStore(sctpAddr, true) @@ -231,7 +233,8 @@ func HandleNGSetupFailure(sctpAddr string, conn *sctp.SCTPConn, message *ngapTyp } func HandleNGReset(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle NG Reset") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle NG Reset") var cause *ngapType.Cause var resetType *ngapType.ResetType @@ -241,37 +244,37 @@ func HandleNGReset(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { n3iwfSelf := context.N3IWFSelf() if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("InitiatingMessage is nil") + ngapLog.Error("InitiatingMessage is nil") return } nGReset := initiatingMessage.Value.NGReset if nGReset == nil { - logger.NgapLog.Error("nGReset is nil") + ngapLog.Error("nGReset is nil") return } for _, ie := range nGReset.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDCause: - logger.NgapLog.Traceln("[NGAP] Decode IE Cause") + ngapLog.Traceln("[NGAP] Decode IE Cause") cause = ie.Value.Cause case ngapType.ProtocolIEIDResetType: - logger.NgapLog.Traceln("[NGAP] Decode IE ResetType") + ngapLog.Traceln("[NGAP] Decode IE ResetType") resetType = ie.Value.ResetType if resetType == nil { - logger.NgapLog.Error("ResetType is nil") + ngapLog.Error("ResetType is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) @@ -293,19 +296,19 @@ func HandleNGReset(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { switch resetType.Present { case ngapType.ResetTypePresentNGInterface: - logger.NgapLog.Trace("ResetType Present: NG Interface") + ngapLog.Trace("ResetType Present: NG Interface") // TODO: Release Uu Interface related to this amf(IPSec) // Remove all Ue if err := amf.RemoveAllRelatedUe(); err != nil { - logger.NgapLog.Errorf("RemoveAllRelatedUe error : %+v", err) + ngapLog.Errorf("RemoveAllRelatedUe error : %+v", err) } ngap_message.SendNGResetAcknowledge(amf, nil, nil) case ngapType.ResetTypePresentPartOfNGInterface: - logger.NgapLog.Trace("ResetType Present: Part of NG Interface") + ngapLog.Trace("ResetType Present: Part of NG Interface") partOfNGInterface := resetType.PartOfNGInterface if partOfNGInterface == nil { - logger.NgapLog.Error("PartOfNGInterface is nil") + ngapLog.Error("PartOfNGInterface is nil") return } @@ -313,83 +316,84 @@ func HandleNGReset(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { for _, ueAssociatedLogicalNGConnectionItem := range partOfNGInterface.List { if ueAssociatedLogicalNGConnectionItem.RANUENGAPID != nil { - logger.NgapLog.Tracef("RanUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.RANUENGAPID.Value) + ngapLog.Tracef("RanUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.RANUENGAPID.Value) ranUe, _ = n3iwfSelf.RanUePoolLoad(ueAssociatedLogicalNGConnectionItem.RANUENGAPID.Value) } else if ueAssociatedLogicalNGConnectionItem.AMFUENGAPID != nil { - logger.NgapLog.Tracef("AmfUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.AMFUENGAPID.Value) + ngapLog.Tracef("AmfUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.AMFUENGAPID.Value) ranUe = amf.FindUeByAmfUeNgapID(ueAssociatedLogicalNGConnectionItem.AMFUENGAPID.Value) } if ranUe == nil { - logger.NgapLog.Warn("Cannot not find RanUE Context") + ngapLog.Warn("Cannot not find RanUE Context") if ueAssociatedLogicalNGConnectionItem.AMFUENGAPID != nil { - logger.NgapLog.Warnf("AmfUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.AMFUENGAPID.Value) + ngapLog.Warnf("AmfUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.AMFUENGAPID.Value) } if ueAssociatedLogicalNGConnectionItem.RANUENGAPID != nil { - logger.NgapLog.Warnf("RanUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.RANUENGAPID.Value) + ngapLog.Warnf("RanUeNgapID[%d]", ueAssociatedLogicalNGConnectionItem.RANUENGAPID.Value) } continue } // TODO: Release Uu Interface (IPSec) if err := ranUe.Remove(); err != nil { - logger.NgapLog.Errorf("Remove RanUE Context error : %+v", err) + ngapLog.Errorf("Remove RanUE Context error : %+v", err) } } ngap_message.SendNGResetAcknowledge(amf, partOfNGInterface, nil) default: - logger.NgapLog.Warnf("Invalid ResetType[%d]", resetType.Present) + ngapLog.Warnf("Invalid ResetType[%d]", resetType.Present) } } func HandleNGResetAcknowledge(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle NG Reset Acknowledge") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle NG Reset Acknowledge") var uEAssociatedLogicalNGConnectionList *ngapType.UEAssociatedLogicalNGConnectionList var criticalityDiagnostics *ngapType.CriticalityDiagnostics if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } successfulOutcome := message.SuccessfulOutcome if successfulOutcome == nil { - logger.NgapLog.Error("SuccessfulOutcome is nil") + ngapLog.Error("SuccessfulOutcome is nil") return } nGResetAcknowledge := successfulOutcome.Value.NGResetAcknowledge if nGResetAcknowledge == nil { - logger.NgapLog.Error("nGResetAcknowledge is nil") + ngapLog.Error("nGResetAcknowledge is nil") return } for _, ie := range nGResetAcknowledge.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDUEAssociatedLogicalNGConnectionList: - logger.NgapLog.Traceln("[NGAP] Decode IE UEAssociatedLogicalNGConnectionList") + ngapLog.Traceln("[NGAP] Decode IE UEAssociatedLogicalNGConnectionList") uEAssociatedLogicalNGConnectionList = ie.Value.UEAssociatedLogicalNGConnectionList case ngapType.ProtocolIEIDCriticalityDiagnostics: - logger.NgapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") criticalityDiagnostics = ie.Value.CriticalityDiagnostics } } if uEAssociatedLogicalNGConnectionList != nil { - logger.NgapLog.Tracef("%d RanUE association(s) has been reset", len(uEAssociatedLogicalNGConnectionList.List)) + ngapLog.Tracef("%d RanUE association(s) has been reset", len(uEAssociatedLogicalNGConnectionList.List)) for i, item := range uEAssociatedLogicalNGConnectionList.List { if item.AMFUENGAPID != nil && item.RANUENGAPID != nil { - logger.NgapLog.Tracef("%d: AmfUeNgapID[%d] RanUeNgapID[%d]", + ngapLog.Tracef("%d: AmfUeNgapID[%d] RanUeNgapID[%d]", i+1, item.AMFUENGAPID.Value, item.RANUENGAPID.Value) } else if item.AMFUENGAPID != nil { - logger.NgapLog.Tracef("%d: AmfUeNgapID[%d] RanUeNgapID[unknown]", i+1, item.AMFUENGAPID.Value) + ngapLog.Tracef("%d: AmfUeNgapID[%d] RanUeNgapID[unknown]", i+1, item.AMFUENGAPID.Value) } else if item.RANUENGAPID != nil { - logger.NgapLog.Tracef("%d: AmfUeNgapID[unknown] RanUeNgapID[%d]", i+1, item.RANUENGAPID.Value) + ngapLog.Tracef("%d: AmfUeNgapID[unknown] RanUeNgapID[%d]", i+1, item.RANUENGAPID.Value) } } } @@ -400,7 +404,8 @@ func HandleNGResetAcknowledge(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) } func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Initial Context Setup Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Initial Context Setup Request") var amfUeNgapID *ngapType.AMFUENGAPID var ranUeNgapID *ngapType.RANUENGAPID @@ -424,122 +429,122 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } initialContextSetupRequest := initiatingMessage.Value.InitialContextSetupRequest if initialContextSetupRequest == nil { - logger.NgapLog.Error("InitialContextSetupRequest is nil") + ngapLog.Error("InitialContextSetupRequest is nil") return } for _, ie := range initialContextSetupRequest.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") amfUeNgapID = ie.Value.AMFUENGAPID if amfUeNgapID == nil { - logger.NgapLog.Errorf("AMFUENGAPID is nil") + ngapLog.Errorf("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") ranUeNgapID = ie.Value.RANUENGAPID if ranUeNgapID == nil { - logger.NgapLog.Errorf("RANUENGAPID is nil") + ngapLog.Errorf("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDOldAMF: - logger.NgapLog.Traceln("[NGAP] Decode IE OldAMF") + ngapLog.Traceln("[NGAP] Decode IE OldAMF") oldAMF = ie.Value.OldAMF case ngapType.ProtocolIEIDUEAggregateMaximumBitRate: - logger.NgapLog.Traceln("[NGAP] Decode IE UEAggregateMaximumBitRate") + ngapLog.Traceln("[NGAP] Decode IE UEAggregateMaximumBitRate") ueAggregateMaximumBitRate = ie.Value.UEAggregateMaximumBitRate case ngapType.ProtocolIEIDCoreNetworkAssistanceInformation: - logger.NgapLog.Traceln("[NGAP] Decode IE CoreNetworkAssistanceInformation") + ngapLog.Traceln("[NGAP] Decode IE CoreNetworkAssistanceInformation") coreNetworkAssistanceInformation = ie.Value.CoreNetworkAssistanceInformation if coreNetworkAssistanceInformation != nil { - logger.NgapLog.Warnln("Not Supported IE [CoreNetworkAssistanceInformation]") + ngapLog.Warnln("Not Supported IE [CoreNetworkAssistanceInformation]") } case ngapType.ProtocolIEIDGUAMI: - logger.NgapLog.Traceln("[NGAP] Decode IE GUAMI") + ngapLog.Traceln("[NGAP] Decode IE GUAMI") guami = ie.Value.GUAMI if guami == nil { - logger.NgapLog.Errorf("GUAMI is nil") + ngapLog.Errorf("GUAMI is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDPDUSessionResourceSetupListCxtReq: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionResourceSetupListCxtReq") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionResourceSetupListCxtReq") pduSessionResourceSetupListCxtReq = ie.Value.PDUSessionResourceSetupListCxtReq case ngapType.ProtocolIEIDAllowedNSSAI: - logger.NgapLog.Traceln("[NGAP] Decode IE AllowedNSSAI") + ngapLog.Traceln("[NGAP] Decode IE AllowedNSSAI") allowedNSSAI = ie.Value.AllowedNSSAI if allowedNSSAI == nil { - logger.NgapLog.Errorf("AllowedNSSAI is nil") + ngapLog.Errorf("AllowedNSSAI is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDUESecurityCapabilities: - logger.NgapLog.Traceln("[NGAP] Decode IE UESecurityCapabilities") + ngapLog.Traceln("[NGAP] Decode IE UESecurityCapabilities") ueSecurityCapabilities = ie.Value.UESecurityCapabilities if ueSecurityCapabilities == nil { - logger.NgapLog.Errorf("UESecurityCapabilities is nil") + ngapLog.Errorf("UESecurityCapabilities is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDSecurityKey: - logger.NgapLog.Traceln("[NGAP] Decode IE SecurityKey") + ngapLog.Traceln("[NGAP] Decode IE SecurityKey") securityKey = ie.Value.SecurityKey if securityKey == nil { - logger.NgapLog.Errorf("SecurityKey is nil") + ngapLog.Errorf("SecurityKey is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDTraceActivation: - logger.NgapLog.Traceln("[NGAP] Decode IE TraceActivation") + ngapLog.Traceln("[NGAP] Decode IE TraceActivation") traceActivation = ie.Value.TraceActivation if traceActivation != nil { - logger.NgapLog.Warnln("Not Supported IE [TraceActivation]") + ngapLog.Warnln("Not Supported IE [TraceActivation]") } case ngapType.ProtocolIEIDUERadioCapability: - logger.NgapLog.Traceln("[NGAP] Decode IE UERadioCapability") + ngapLog.Traceln("[NGAP] Decode IE UERadioCapability") ueRadioCapability = ie.Value.UERadioCapability case ngapType.ProtocolIEIDIndexToRFSP: - logger.NgapLog.Traceln("[NGAP] Decode IE IndexToRFSP") + ngapLog.Traceln("[NGAP] Decode IE IndexToRFSP") indexToRFSP = ie.Value.IndexToRFSP case ngapType.ProtocolIEIDMaskedIMEISV: - logger.NgapLog.Traceln("[NGAP] Decode IE MaskedIMEISV") + ngapLog.Traceln("[NGAP] Decode IE MaskedIMEISV") maskedIMEISV = ie.Value.MaskedIMEISV case ngapType.ProtocolIEIDNASPDU: - logger.NgapLog.Traceln("[NGAP] Decode IE NAS PDU") + ngapLog.Traceln("[NGAP] Decode IE NAS PDU") // nasPDU = ie.Value.NASPDU case ngapType.ProtocolIEIDEmergencyFallbackIndicator: - logger.NgapLog.Traceln("[NGAP] Decode IE EmergencyFallbackIndicator") + ngapLog.Traceln("[NGAP] Decode IE EmergencyFallbackIndicator") emergencyFallbackIndicator = ie.Value.EmergencyFallbackIndicator if emergencyFallbackIndicator != nil { - logger.NgapLog.Warnln("Not Supported IE [EmergencyFallbackIndicator]") + ngapLog.Warnln("Not Supported IE [EmergencyFallbackIndicator]") } } } if len(iesCriticalityDiagnostics.List) > 0 { - logger.NgapLog.Traceln( + ngapLog.Traceln( "[NGAP] Sending unsuccessful outcome to AMF, because some mandatory IEs were not included") cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentAbstractSyntaxErrorFalselyConstructedMessage) @@ -550,7 +555,7 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N for _, item := range pduSessionResourceSetupListCxtReq.List { transfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } ngap_message.AppendPDUSessionResourceFailedToSetupListCxtfail( failedListCxtFail, item.PDUSessionID.Value, transfer) @@ -565,21 +570,20 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N var ok bool ranUe, ok = n3iwfSelf.RanUePoolLoad(ranUeNgapID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) // TODO: build cause and handle error // Cause: Unknown local UE NGAP ID return - } else { - if ranUe.AmfUeNgapId != amfUeNgapID.Value { - // TODO: build cause and handle error - // Cause: Inconsistent remote UE NGAP ID - return - } + } + if ranUe.AmfUeNgapId != amfUeNgapID.Value { + // TODO: build cause and handle error + // Cause: Inconsistent remote UE NGAP ID + return } } if ranUe == nil { - logger.NgapLog.Errorf("RAN UE context is nil") + ngapLog.Errorf("RAN UE context is nil") return } @@ -590,7 +594,7 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N if ueAggregateMaximumBitRate != nil { ranUe.Ambr = ueAggregateMaximumBitRate } else { - logger.NgapLog.Errorln("IE[UEAggregateMaximumBitRate] is nil") + ngapLog.Errorln("IE[UEAggregateMaximumBitRate] is nil") cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentAbstractSyntaxErrorFalselyConstructedMessage) @@ -603,7 +607,7 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N for _, item := range pduSessionResourceSetupListCxtReq.List { transfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } ngap_message.AppendPDUSessionResourceFailedToSetupListCxtfail( failedListCxtFail, item.PDUSessionID.Value, transfer) @@ -632,20 +636,20 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N transfer := ngapType.PDUSessionResourceSetupRequestTransfer{} err := aper.UnmarshalWithParams(item.PDUSessionResourceSetupRequestTransfer, &transfer, "valueExt") if err != nil { - logger.NgapLog.Errorf("[PDUSessionID: %d] PDUSessionResourceSetupRequestTransfer Decode Error: %+v\n", + ngapLog.Errorf("[PDUSessionID: %d] PDUSessionResourceSetupRequestTransfer Decode Error: %+v\n", pduSessionID, err) } pduSession, err := ranUe.CreatePDUSession(pduSessionID, snssai) if err != nil { - logger.NgapLog.Errorf("Create PDU Session Error: %+v\n", err) + ngapLog.Errorf("Create PDU Session Error: %+v\n", err) cause := ngap_message.BuildCause(ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentMultiplePDUSessionIDInstances) unsuccessfulTransfer, buildErr := ngap_message. BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if buildErr != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", buildErr) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", buildErr) } ngap_message.AppendPDUSessionResourceFailedToSetupListCxtRes( failedListCxtRes, pduSessionID, unsuccessfulTransfer) @@ -668,7 +672,7 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N } if oldAMF != nil { - logger.NgapLog.Debugf("Old AMF: %s\n", oldAMF.Value) + ngapLog.Debugf("Old AMF: %s\n", oldAMF.Value) } if guami != nil { @@ -701,7 +705,7 @@ func HandleInitialContextSetupRequest(amf *context.N3IWFAMF, message *ngapType.N spi, ok := n3iwfSelf.IkeSpiLoad(ranUe.RanUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get spi from ngapid : %+v", ranUe.RanUeNgapId) + ngapLog.Errorf("Cannot get spi from ngapid : %+v", ranUe.RanUeNgapId) return } @@ -765,6 +769,8 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu } } + ngapLog := logger.NgapLog + if len(iesCriticalityDiagnostics.List) > 0 { cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentAbstractSyntaxErrorFalselyConstructedMessage) @@ -772,7 +778,7 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer( *cause, &criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -791,11 +797,11 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu case ngapType.IntegrityProtectionIndicationPresentRequired: pduSession.SecurityIntegrity = true default: - logger.NgapLog.Error("Unknown security integrity indication") + ngapLog.Error("Unknown security integrity indication") cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentSemanticError) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -808,11 +814,11 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu case ngapType.ConfidentialityProtectionIndicationPresentRequired: pduSession.SecurityCipher = true default: - logger.NgapLog.Error("Unknown security confidentiality indication") + ngapLog.Error("Unknown security confidentiality indication") cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentSemanticError) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -847,12 +853,12 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu // UPF UDP address upfUDPAddr, err := net.ResolveUDPAddr("udp", upfIPv4+":2152") if err != nil { - logger.NgapLog.Errorf("Resolve UDP address failed: %+v", err) + ngapLog.Errorf("Resolve UDP address failed: %+v", err) cause := ngap_message.BuildCause(ngapType.CausePresentTransport, ngapType.CauseTransportPresentTransportResourceUnavailable) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -860,13 +866,13 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu // UE TEID ueTEID := n3iwfSelf.NewTEID(ranUe) if ueTEID == 0 { - logger.NgapLog.Error("Invalid TEID (0).") + ngapLog.Error("Invalid TEID (0).") cause := ngap_message.BuildCause( ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentUnspecified) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -879,12 +885,12 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu // Setup GTP connection with UPF userPlaneConnection, upfUDPAddr, err := gtp_service.SetupGTPTunnelWithUPF(upfIPv4) if err != nil { - logger.NgapLog.Errorf("Setup GTP connection with UPF failed: %+v", err) + ngapLog.Errorf("Setup GTP connection with UPF failed: %+v", err) cause := ngap_message.BuildCause(ngapType.CausePresentTransport, ngapType.CauseTransportPresentTransportResourceUnavailable) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -892,13 +898,13 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu // UE TEID ueTEID := n3iwfSelf.NewTEID(ranUe) if ueTEID == 0 { - logger.NgapLog.Error("Invalid TEID (0).") + ngapLog.Error("Invalid TEID (0).") cause := ngap_message.BuildCause( ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentUnspecified) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -914,13 +920,13 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu pduSession.GTPConnection = gtpConnection } else { - logger.NgapLog.Error( + ngapLog.Error( "Cannot parse \"PDU session resource setup request transfer\" message \"UL NG-U UP TNL Information\"") cause := ngap_message.BuildCause(ngapType.CausePresentProtocol, ngapType.CauseProtocolPresentAbstractSyntaxErrorReject) responseTransfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", err) } return false, responseTransfer } @@ -929,10 +935,11 @@ func handlePDUSessionResourceSetupRequestTransfer(ranUe *context.N3IWFRanUe, pdu } func HandleUEContextModificationRequest(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle UE Context Modification Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle UE Context Modification Request") if amf == nil { - logger.NgapLog.Error("Corresponding AMF context not found") + ngapLog.Error("Corresponding AMF context not found") return } @@ -949,62 +956,62 @@ func HandleUEContextModificationRequest(amf *context.N3IWFAMF, message *ngapType n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } ueContextModificationRequest := initiatingMessage.Value.UEContextModificationRequest if ueContextModificationRequest == nil { - logger.NgapLog.Error("UEContextModificationRequest is nil") + ngapLog.Error("UEContextModificationRequest is nil") return } for _, ie := range ueContextModificationRequest.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") amfUeNgapID = ie.Value.AMFUENGAPID if amfUeNgapID == nil { - logger.NgapLog.Errorf("AMFUENGAPID is nil") + ngapLog.Errorf("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") ranUeNgapID = ie.Value.RANUENGAPID if ranUeNgapID == nil { - logger.NgapLog.Errorf("RANUENGAPID is nil") + ngapLog.Errorf("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDSecurityKey: - logger.NgapLog.Traceln("[NGAP] Decode IE SecurityKey") + ngapLog.Traceln("[NGAP] Decode IE SecurityKey") securityKey = ie.Value.SecurityKey case ngapType.ProtocolIEIDIndexToRFSP: - logger.NgapLog.Traceln("[NGAP] Decode IE IndexToRFSP") + ngapLog.Traceln("[NGAP] Decode IE IndexToRFSP") indexToRFSP = ie.Value.IndexToRFSP case ngapType.ProtocolIEIDUEAggregateMaximumBitRate: - logger.NgapLog.Traceln("[NGAP] Decode IE UEAggregateMaximumBitRate") + ngapLog.Traceln("[NGAP] Decode IE UEAggregateMaximumBitRate") ueAggregateMaximumBitRate = ie.Value.UEAggregateMaximumBitRate case ngapType.ProtocolIEIDUESecurityCapabilities: - logger.NgapLog.Traceln("[NGAP] Decode IE UESecurityCapabilities") + ngapLog.Traceln("[NGAP] Decode IE UESecurityCapabilities") ueSecurityCapabilities = ie.Value.UESecurityCapabilities case ngapType.ProtocolIEIDCoreNetworkAssistanceInformation: - logger.NgapLog.Traceln("[NGAP] Decode IE CoreNetworkAssistanceInformation") - logger.NgapLog.Warnln("Not Supported IE [CoreNetworkAssistanceInformation]") + ngapLog.Traceln("[NGAP] Decode IE CoreNetworkAssistanceInformation") + ngapLog.Warnln("Not Supported IE [CoreNetworkAssistanceInformation]") case ngapType.ProtocolIEIDEmergencyFallbackIndicator: - logger.NgapLog.Traceln("[NGAP] Decode IE EmergencyFallbackIndicator") - logger.NgapLog.Warnln("Not Supported IE [EmergencyFallbackIndicator]") + ngapLog.Traceln("[NGAP] Decode IE EmergencyFallbackIndicator") + ngapLog.Warnln("Not Supported IE [EmergencyFallbackIndicator]") case ngapType.ProtocolIEIDNewAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE NewAMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE NewAMFUENGAPID") newAmfUeNgapID = ie.Value.NewAMFUENGAPID } } @@ -1019,21 +1026,20 @@ func HandleUEContextModificationRequest(amf *context.N3IWFAMF, message *ngapType var ok bool ranUe, ok = n3iwfSelf.RanUePoolLoad(ranUeNgapID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) // TODO: build cause and handle error // Cause: Unknown local UE NGAP ID return - } else { - if ranUe.AmfUeNgapId != amfUeNgapID.Value { - // TODO: build cause and handle error - // Cause: Inconsistent remote UE NGAP ID - return - } + } + if ranUe.AmfUeNgapId != amfUeNgapID.Value { + // TODO: build cause and handle error + // Cause: Inconsistent remote UE NGAP ID + return } } if newAmfUeNgapID != nil { - logger.NgapLog.Debugf("New AmfUeNgapID[%d]\n", newAmfUeNgapID.Value) + ngapLog.Debugf("New AmfUeNgapID[%d]\n", newAmfUeNgapID.Value) ranUe.AmfUeNgapId = newAmfUeNgapID.Value } @@ -1056,7 +1062,7 @@ func HandleUEContextModificationRequest(amf *context.N3IWFAMF, message *ngapType spi, ok := n3iwfSelf.IkeSpiLoad(ranUe.RanUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get spi from ngapid : %+v", ranUe.RanUeNgapId) + ngapLog.Errorf("Cannot get spi from ngapid : %+v", ranUe.RanUeNgapId) return } @@ -1065,10 +1071,11 @@ func HandleUEContextModificationRequest(amf *context.N3IWFAMF, message *ngapType } func HandleUEContextReleaseCommand(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle UE Context Release Command") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle UE Context Release Command") if amf == nil { - logger.NgapLog.Error("Corresponding AMF context not found") + ngapLog.Error("Corresponding AMF context not found") return } @@ -1080,35 +1087,35 @@ func HandleUEContextReleaseCommand(amf *context.N3IWFAMF, message *ngapType.NGAP n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } ueContextReleaseCommand := initiatingMessage.Value.UEContextReleaseCommand if ueContextReleaseCommand == nil { - logger.NgapLog.Error("UEContextReleaseCommand is nil") + ngapLog.Error("UEContextReleaseCommand is nil") return } for _, ie := range ueContextReleaseCommand.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDUENGAPIDs: - logger.NgapLog.Traceln("[NGAP] Decode IE UENGAPIDs") + ngapLog.Traceln("[NGAP] Decode IE UENGAPIDs") ueNgapIDs = ie.Value.UENGAPIDs if ueNgapIDs == nil { - logger.NgapLog.Errorf("UENGAPIDs is nil") + ngapLog.Errorf("UENGAPIDs is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDCause: - logger.NgapLog.Traceln("[NGAP] Decode IE Cause") + ngapLog.Traceln("[NGAP] Decode IE Cause") cause = ie.Value.Cause } } @@ -1144,7 +1151,7 @@ func HandleUEContextReleaseCommand(amf *context.N3IWFAMF, message *ngapType.NGAP localSPI, ok := n3iwfSelf.IkeSpiLoad(ranUe.RanUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get SPI from RanUeNgapID : %+v", ranUe.RanUeNgapId) + ngapLog.Errorf("Cannot get SPI from RanUeNgapID : %+v", ranUe.RanUeNgapId) return } @@ -1165,10 +1172,11 @@ func encapNasMsgToEnvelope(nasPDU *ngapType.NASPDU) []byte { } func HandleDownlinkNASTransport(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Downlink NAS Transport") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Downlink NAS Transport") if amf == nil { - logger.NgapLog.Error("Corresponding AMF context not found") + ngapLog.Error("Corresponding AMF context not found") return } @@ -1185,62 +1193,62 @@ func HandleDownlinkNASTransport(amf *context.N3IWFAMF, message *ngapType.NGAPPDU var n3iwfSelf *context.N3IWFContext = context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } downlinkNASTransport := initiatingMessage.Value.DownlinkNASTransport if downlinkNASTransport == nil { - logger.NgapLog.Error("DownlinkNASTransport is nil") + ngapLog.Error("DownlinkNASTransport is nil") return } for _, ie := range downlinkNASTransport.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") amfUeNgapID = ie.Value.AMFUENGAPID if amfUeNgapID == nil { - logger.NgapLog.Errorf("AMFUENGAPID is nil") + ngapLog.Errorf("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") ranUeNgapID = ie.Value.RANUENGAPID if ranUeNgapID == nil { - logger.NgapLog.Errorf("RANUENGAPID is nil") + ngapLog.Errorf("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDOldAMF: - logger.NgapLog.Traceln("[NGAP] Decode IE OldAMF") + ngapLog.Traceln("[NGAP] Decode IE OldAMF") oldAMF = ie.Value.OldAMF case ngapType.ProtocolIEIDNASPDU: - logger.NgapLog.Traceln("[NGAP] Decode IE NASPDU") + ngapLog.Traceln("[NGAP] Decode IE NASPDU") nasPDU = ie.Value.NASPDU if nasPDU == nil { - logger.NgapLog.Errorf("NASPDU is nil") + ngapLog.Errorf("NASPDU is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDIndexToRFSP: - logger.NgapLog.Traceln("[NGAP] Decode IE IndexToRFSP") + ngapLog.Traceln("[NGAP] Decode IE IndexToRFSP") indexToRFSP = ie.Value.IndexToRFSP case ngapType.ProtocolIEIDUEAggregateMaximumBitRate: - logger.NgapLog.Traceln("[NGAP] Decode IE UEAggregateMaximumBitRate") + ngapLog.Traceln("[NGAP] Decode IE UEAggregateMaximumBitRate") ueAggregateMaximumBitRate = ie.Value.UEAggregateMaximumBitRate case ngapType.ProtocolIEIDAllowedNSSAI: - logger.NgapLog.Traceln("[NGAP] Decode IE AllowedNSSAI") + ngapLog.Traceln("[NGAP] Decode IE AllowedNSSAI") allowedNSSAI = ie.Value.AllowedNSSAI } } @@ -1253,25 +1261,25 @@ func HandleDownlinkNASTransport(amf *context.N3IWFAMF, message *ngapType.NGAPPDU var ok bool ranUe, ok = n3iwfSelf.RanUePoolLoad(ranUeNgapID.Value) if !ok { - logger.NgapLog.Warnf("No UE Context[RanUeNgapID:%d]\n", ranUeNgapID.Value) + ngapLog.Warnf("No UE Context[RanUeNgapID:%d]\n", ranUeNgapID.Value) return } } if amfUeNgapID != nil { if ranUe.AmfUeNgapId == context.AmfUeNgapIdUnspecified { - logger.NgapLog.Tracef("Create new logical UE-associated NG-connection") + ngapLog.Tracef("Create new logical UE-associated NG-connection") ranUe.AmfUeNgapId = amfUeNgapID.Value } else { if ranUe.AmfUeNgapId != amfUeNgapID.Value { - logger.NgapLog.Warn("AMFUENGAPID unmatched") + ngapLog.Warn("AMFUENGAPID unmatched") return } } } if oldAMF != nil { - logger.NgapLog.Debugf("Old AMF: %s\n", oldAMF.Value) + ngapLog.Debugf("Old AMF: %s\n", oldAMF.Value) } if indexToRFSP != nil { @@ -1292,7 +1300,7 @@ func HandleDownlinkNASTransport(amf *context.N3IWFAMF, message *ngapType.NGAPPDU // Send EAP5G NAS to UE spi, ok := n3iwfSelf.IkeSpiLoad(ranUe.RanUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get SPI from RanUeNGAPId : %+v", ranUe.RanUeNgapId) + ngapLog.Errorf("Cannot get SPI from RanUeNGAPId : %+v", ranUe.RanUeNgapId) return } @@ -1307,10 +1315,10 @@ func HandleDownlinkNASTransport(amf *context.N3IWFAMF, message *ngapType.NGAPPDU if ranUe.IsNASTCPConnEstablishedComplete { // Send to UE if n, err := ranUe.TCPConnection.Write(nasEnv); err != nil { - logger.NgapLog.Errorf("Writing via IPSec signalling SA failed: %+v", err) + ngapLog.Errorf("Writing via IPSec signalling SA failed: %+v", err) } else { - logger.NgapLog.Trace("Forward NWu <- N2") - logger.NgapLog.Tracef("Wrote %d bytes", n) + ngapLog.Trace("Forward NWu <- N2") + ngapLog.Tracef("Wrote %d bytes", n) } } else { ranUe.TemporaryCachedNASMessage = nasEnv @@ -1320,10 +1328,11 @@ func HandleDownlinkNASTransport(amf *context.N3IWFAMF, message *ngapType.NGAPPDU } func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle PDU Session Resource Setup Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle PDU Session Resource Setup Request") if amf == nil { - logger.NgapLog.Error("Corresponding AMF context not found") + ngapLog.Error("Corresponding AMF context not found") return } @@ -1338,50 +1347,50 @@ func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapTy n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } pduSessionResourceSetupRequest := initiatingMessage.Value.PDUSessionResourceSetupRequest if pduSessionResourceSetupRequest == nil { - logger.NgapLog.Error("PDUSessionResourceSetupRequest is nil") + ngapLog.Error("PDUSessionResourceSetupRequest is nil") return } for _, ie := range pduSessionResourceSetupRequest.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") amfUeNgapID = ie.Value.AMFUENGAPID if amfUeNgapID == nil { - logger.NgapLog.Errorf("AMFUENGAPID is nil") + ngapLog.Errorf("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") ranUeNgapID = ie.Value.RANUENGAPID if ranUeNgapID == nil { - logger.NgapLog.Errorf("RANUENGAPID is nil") + ngapLog.Errorf("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDNASPDU: - logger.NgapLog.Traceln("[NGAP] Decode IE NASPDU") + ngapLog.Traceln("[NGAP] Decode IE NASPDU") nasPDU = ie.Value.NASPDU case ngapType.ProtocolIEIDPDUSessionResourceSetupListSUReq: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionResourceSetupRequestList") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionResourceSetupRequestList") pduSessionResourceSetupListSUReq = ie.Value.PDUSessionResourceSetupListSUReq if pduSessionResourceSetupListSUReq == nil { - logger.NgapLog.Errorf("PDUSessionResourceSetupRequestList is nil") + ngapLog.Errorf("PDUSessionResourceSetupRequestList is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) @@ -1391,7 +1400,7 @@ func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapTy if len(iesCriticalityDiagnostics.List) > 0 { // TODO: Send error indication to AMF - logger.NgapLog.Errorln("Sending error indication to AMF") + ngapLog.Errorln("Sending error indication to AMF") return } @@ -1400,36 +1409,35 @@ func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapTy var ok bool ranUe, ok = n3iwfSelf.RanUePoolLoad(ranUeNgapID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) // TODO: build cause and handle error // Cause: Unknown local UE NGAP ID return - } else { - if ranUe.AmfUeNgapId != amfUeNgapID.Value { - // TODO: build cause and handle error - // Cause: Inconsistent remote UE NGAP ID - return - } + } + if ranUe.AmfUeNgapId != amfUeNgapID.Value { + // TODO: build cause and handle error + // Cause: Inconsistent remote UE NGAP ID + return } } if nasPDU != nil { // TODO: Send NAS to UE if ranUe.TCPConnection == nil { - logger.NgapLog.Error("No IPSec NAS signalling SA for this UE") + ngapLog.Error("No IPSec NAS signalling SA for this UE") return - } else { - // Using a "NAS message envelope" to transport a NAS message - // over the non-3GPP access between the UE and the N3IWF - nasEnv := encapNasMsgToEnvelope(nasPDU) + } - if n, err := ranUe.TCPConnection.Write(nasEnv); err != nil { - logger.NgapLog.Errorf("Send NAS to UE failed: %+v", err) - return - } else { - logger.NgapLog.Tracef("Wrote %d bytes", n) - } + // Using a "NAS message envelope" to transport a NAS message + // over the non-3GPP access between the UE and the N3IWF + nasEnv := encapNasMsgToEnvelope(nasPDU) + + n, err := ranUe.TCPConnection.Write(nasEnv) + if err != nil { + ngapLog.Errorf("Send NAS to UE failed: %+v", err) + return } + ngapLog.Tracef("Wrote %d bytes", n) } tempPDUSessionSetupData := ranUe.TemporaryPDUSessionSetupData @@ -1453,20 +1461,20 @@ func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapTy transfer := ngapType.PDUSessionResourceSetupRequestTransfer{} err := aper.UnmarshalWithParams(item.PDUSessionResourceSetupRequestTransfer, &transfer, "valueExt") if err != nil { - logger.NgapLog.Errorf("[PDUSessionID: %d] PDUSessionResourceSetupRequestTransfer Decode Error: %+v\n", + ngapLog.Errorf("[PDUSessionID: %d] PDUSessionResourceSetupRequestTransfer Decode Error: %+v\n", pduSessionID, err) } pduSession, err := ranUe.CreatePDUSession(pduSessionID, snssai) if err != nil { - logger.NgapLog.Errorf("Create PDU Session Error: %+v\n", err) + ngapLog.Errorf("Create PDU Session Error: %+v\n", err) cause := ngap_message.BuildCause(ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentMultiplePDUSessionIDInstances) unsuccessfulTransfer, buildErr := ngap_message. BuildPDUSessionResourceSetupUnsuccessfulTransfer(*cause, nil) if buildErr != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", buildErr) + ngapLog.Errorf("Build PDUSessionResourceSetupUnsuccessfulTransfer Error: %+v\n", buildErr) } ngap_message.AppendPDUSessionResourceFailedToSetupListSURes( failedListSURes, pduSessionID, unsuccessfulTransfer) @@ -1492,7 +1500,7 @@ func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapTy if tempPDUSessionSetupData != nil { spi, ok := n3iwfSelf.IkeSpiLoad(ranUe.RanUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get SPI from ranNgapID : %+v", ranUeNgapID) + ngapLog.Errorf("Cannot get SPI from ranNgapID : %+v", ranUeNgapID) return } n3iwfSelf.IKEServer.RcvEventCh <- context.NewCreatePDUSessionEvt(spi, @@ -1509,10 +1517,11 @@ func HandlePDUSessionResourceSetupRequest(amf *context.N3IWFAMF, message *ngapTy } func HandlePDUSessionResourceModifyRequest(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle PDU Session Resource Modify Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle PDU Session Resource Modify Request") if amf == nil { - logger.NgapLog.Error("Corresponding AMF context not found") + ngapLog.Error("Corresponding AMF context not found") return } @@ -1525,47 +1534,47 @@ func HandlePDUSessionResourceModifyRequest(amf *context.N3IWFAMF, message *ngapT n3iwfSelf := context.N3IWFSelf() if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } pduSessionResourceModifyRequest := initiatingMessage.Value.PDUSessionResourceModifyRequest if pduSessionResourceModifyRequest == nil { - logger.NgapLog.Error("PDUSessionResourceModifyRequest is nil") + ngapLog.Error("PDUSessionResourceModifyRequest is nil") return } for _, ie := range pduSessionResourceModifyRequest.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") amfUeNgapID = ie.Value.AMFUENGAPID if amfUeNgapID == nil { - logger.NgapLog.Error("AMFUENGAPID is nil") + ngapLog.Error("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") ranUeNgapID = ie.Value.RANUENGAPID if ranUeNgapID == nil { - logger.NgapLog.Error("RANUENGAPID is nil") + ngapLog.Error("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDPDUSessionResourceModifyListModReq: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionResourceModifyListModReq") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionResourceModifyListModReq") pduSessionResourceModifyListModReq = ie.Value.PDUSessionResourceModifyListModReq if pduSessionResourceModifyListModReq == nil { - logger.NgapLog.Error("PDUSessionResourceModifyListModReq is nil") + ngapLog.Error("PDUSessionResourceModifyListModReq is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) @@ -1584,16 +1593,15 @@ func HandlePDUSessionResourceModifyRequest(amf *context.N3IWFAMF, message *ngapT var ok bool ranUe, ok = n3iwfSelf.RanUePoolLoad(ranUeNgapID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", ranUeNgapID.Value) // TODO: build cause and send error indication // Cause: Unknown local UE NGAP ID return - } else { - if ranUe.AmfUeNgapId != amfUeNgapID.Value { - // TODO: build cause and send error indication - // Cause: Inconsistent remote UE NGAP ID - return - } + } + if ranUe.AmfUeNgapId != amfUeNgapID.Value { + // TODO: build cause and send error indication + // Cause: Inconsistent remote UE NGAP ID + return } } @@ -1608,20 +1616,20 @@ func HandlePDUSessionResourceModifyRequest(amf *context.N3IWFAMF, message *ngapT transfer := ngapType.PDUSessionResourceModifyRequestTransfer{} err := aper.UnmarshalWithParams(item.PDUSessionResourceModifyRequestTransfer, transfer, "valueExt") if err != nil { - logger.NgapLog.Errorf( + ngapLog.Errorf( "[PDUSessionID: %d] PDUSessionResourceModifyRequestTransfer Decode Error: %+v\n", pduSessionID, err) } if pduSession = ranUe.FindPDUSession(pduSessionID); pduSession == nil { - logger.NgapLog.Errorf("[PDUSessionID: %d] Unknown PDU session ID", pduSessionID) + ngapLog.Errorf("[PDUSessionID: %d] Unknown PDU session ID", pduSessionID) cause := ngap_message.BuildCause(ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentUnknownPDUSessionID) unsuccessfulTransfer, buildErr := ngap_message. BuildPDUSessionResourceModifyUnsuccessfulTransfer(*cause, nil) if buildErr != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceModifyUnsuccessfulTransfer Error: %+v\n", buildErr) + ngapLog.Errorf("Build PDUSessionResourceModifyUnsuccessfulTransfer Error: %+v\n", buildErr) } ngap_message.AppendPDUSessionResourceFailedToModifyListModRes( failedListModRes, pduSessionID, unsuccessfulTransfer) @@ -1645,7 +1653,8 @@ func handlePDUSessionResourceModifyRequestTransfer( pduSession *context.PDUSession, transfer ngapType.PDUSessionResourceModifyRequestTransfer) ( success bool, responseTransfer []byte, ) { - logger.NgapLog.Trace("[N3IWF] Handle PDU Session Resource Modify Request Transfer") + ngapLog := logger.NgapLog + ngapLog.Trace("[N3IWF] Handle PDU Session Resource Modify Request Transfer") var pduSessionAMBR *ngapType.PDUSessionAggregateMaximumBitRate var ulNGUUPTNLModifyList *ngapType.ULNGUUPTNLModifyList @@ -1665,40 +1674,40 @@ func handlePDUSessionResourceModifyRequestTransfer( for _, ie := range transfer.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDPDUSessionAggregateMaximumBitRate: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionAggregateMaximumBitRate") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionAggregateMaximumBitRate") pduSessionAMBR = ie.Value.PDUSessionAggregateMaximumBitRate case ngapType.ProtocolIEIDULNGUUPTNLModifyList: - logger.NgapLog.Traceln("[NGAP] Decode IE ULNGUUPTNLModifyList") + ngapLog.Traceln("[NGAP] Decode IE ULNGUUPTNLModifyList") ulNGUUPTNLModifyList = ie.Value.ULNGUUPTNLModifyList if ulNGUUPTNLModifyList != nil && len(ulNGUUPTNLModifyList.List) == 0 { - logger.NgapLog.Error("ULNGUUPTNLModifyList should have at least one element") + ngapLog.Error("ULNGUUPTNLModifyList should have at least one element") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDNetworkInstance: - logger.NgapLog.Traceln("[NGAP] Decode IE NetworkInstance") + ngapLog.Traceln("[NGAP] Decode IE NetworkInstance") networkInstance = ie.Value.NetworkInstance case ngapType.ProtocolIEIDQosFlowAddOrModifyRequestList: - logger.NgapLog.Traceln("[NGAP] Decode IE QosFLowAddOrModifyRequestList") + ngapLog.Traceln("[NGAP] Decode IE QosFLowAddOrModifyRequestList") qosFlowAddOrModifyRequestList = ie.Value.QosFlowAddOrModifyRequestList if qosFlowAddOrModifyRequestList != nil && len(qosFlowAddOrModifyRequestList.List) == 0 { - logger.NgapLog.Error("QosFlowAddOrModifyRequestList should have at least one element") + ngapLog.Error("QosFlowAddOrModifyRequestList should have at least one element") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDQosFlowToReleaseList: - logger.NgapLog.Traceln("[NGAP] Decode IE QosFlowToReleaseList") + ngapLog.Traceln("[NGAP] Decode IE QosFlowToReleaseList") qosFlowToReleaseList = ie.Value.QosFlowToReleaseList if qosFlowToReleaseList != nil && len(qosFlowToReleaseList.List) == 0 { - logger.NgapLog.Error("qosFlowToReleaseList should have at least one element") + ngapLog.Error("qosFlowToReleaseList should have at least one element") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDAdditionalULNGUUPTNLInformation: - logger.NgapLog.Traceln("[NGAP] Decode IE AdditionalULNGUUPTNLInformation") + ngapLog.Traceln("[NGAP] Decode IE AdditionalULNGUUPTNLInformation") // additionalULNGUUPTNLInformation = ie.Value.AdditionalULNGUUPTNLInformation } } @@ -1711,7 +1720,7 @@ func handlePDUSessionResourceModifyRequestTransfer( unsuccessfulTransfer, err := ngap_message.BuildPDUSessionResourceModifyUnsuccessfulTransfer( *cause, &criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceModifyUnsuccessfulTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceModifyUnsuccessfulTransfer Error: %+v\n", err) } responseTransfer = unsuccessfulTransfer @@ -1723,7 +1732,7 @@ func handlePDUSessionResourceModifyRequestTransfer( // TODO: update GTP tunnel - logger.NgapLog.Info("Update uplink NG-U user plane tunnel information") + ngapLog.Info("Update uplink NG-U user plane tunnel information") resULNGUUPTNLInfo = &updateItem.ULNGUUPTNLInformation resDLNGUUPTNLInfo = &updateItem.DLNGUUPTNLInformation @@ -1733,7 +1742,7 @@ func handlePDUSessionResourceModifyRequestTransfer( for _, updateItem := range qosFlowAddOrModifyRequestList.List { target, ok := pduSession.QosFlows[updateItem.QosFlowIdentifier.Value] if ok { - logger.NgapLog.Trace("Update qos flow level qos parameters") + ngapLog.Trace("Update qos flow level qos parameters") target.Parameters = *updateItem.QosFlowLevelQosParameters @@ -1743,7 +1752,7 @@ func handlePDUSessionResourceModifyRequestTransfer( resQosFlowAddOrModifyRequestList.List = append(resQosFlowAddOrModifyRequestList.List, item) } else { - logger.NgapLog.Errorf("Requested Qos flow not found, QosFlowID: %d", updateItem.QosFlowIdentifier) + ngapLog.Errorf("Requested Qos flow not found, QosFlowID: %d", updateItem.QosFlowIdentifier) cause := ngap_message.BuildCause( ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentUnkownQosFlowID) @@ -1759,13 +1768,13 @@ func handlePDUSessionResourceModifyRequestTransfer( } if pduSessionAMBR != nil { - logger.NgapLog.Trace("Store PDU session AMBR") + ngapLog.Trace("Store PDU session AMBR") pduSession.Ambr = pduSessionAMBR } if networkInstance != nil { // Used to select transport layer resource - logger.NgapLog.Trace("Store network instance") + ngapLog.Trace("Store network instance") pduSession.NetworkInstance = networkInstance } @@ -1773,7 +1782,7 @@ func handlePDUSessionResourceModifyRequestTransfer( for _, releaseItem := range qosFlowToReleaseList.List { _, ok := pduSession.QosFlows[releaseItem.QosFlowIdentifier.Value] if ok { - logger.NgapLog.Tracef("Delete QosFlow. ID: %d", releaseItem.QosFlowIdentifier.Value) + ngapLog.Tracef("Delete QosFlow. ID: %d", releaseItem.QosFlowIdentifier.Value) printAndGetCause(&releaseItem.Cause) delete(pduSession.QosFlows, releaseItem.QosFlowIdentifier.Value) } @@ -1787,7 +1796,7 @@ func handlePDUSessionResourceModifyRequestTransfer( encodeData, err := ngap_message.BuildPDUSessionResourceModifyResponseTransfer( resULNGUUPTNLInfo, resDLNGUUPTNLInfo, &resQosFlowAddOrModifyRequestList, &resQosFlowFailedToAddOrModifyList) if err != nil { - logger.NgapLog.Errorf("Build PDUSessionResourceModifyTransfer Error: %+v\n", err) + ngapLog.Errorf("Build PDUSessionResourceModifyTransfer Error: %+v\n", err) } success = true @@ -1797,7 +1806,8 @@ func handlePDUSessionResourceModifyRequestTransfer( } func HandlePDUSessionResourceModifyConfirm(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle PDU Session Resource Modify Confirm") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle PDU Session Resource Modify Confirm") var aMFUENGAPID *ngapType.AMFUENGAPID var rANUENGAPID *ngapType.RANUENGAPID @@ -1808,43 +1818,43 @@ func HandlePDUSessionResourceModifyConfirm(amf *context.N3IWFAMF, message *ngapT // var iesCriticalityDiagnostics ngapType.CriticalityDiagnosticsIEList if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } successfulOutcome := message.SuccessfulOutcome if successfulOutcome == nil { - logger.NgapLog.Error("Successful Outcome is nil") + ngapLog.Error("Successful Outcome is nil") return } pDUSessionResourceModifyConfirm := successfulOutcome.Value.PDUSessionResourceModifyConfirm if pDUSessionResourceModifyConfirm == nil { - logger.NgapLog.Error("pDUSessionResourceModifyConfirm is nil") + ngapLog.Error("pDUSessionResourceModifyConfirm is nil") return } for _, ie := range pDUSessionResourceModifyConfirm.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") aMFUENGAPID = ie.Value.AMFUENGAPID case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") rANUENGAPID = ie.Value.RANUENGAPID case ngapType.ProtocolIEIDPDUSessionResourceModifyListModCfm: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionResourceModifyListModCfm") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionResourceModifyListModCfm") pDUSessionResourceModifyListModCfm = ie.Value.PDUSessionResourceModifyListModCfm case ngapType.ProtocolIEIDPDUSessionResourceFailedToModifyListModCfm: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionResourceFailedToModifyListModCfm") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionResourceFailedToModifyListModCfm") pDUSessionResourceFailedToModifyListModCfm = ie.Value.PDUSessionResourceFailedToModifyListModCfm case ngapType.ProtocolIEIDCriticalityDiagnostics: - logger.NgapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") criticalityDiagnostics = ie.Value.CriticalityDiagnostics } } @@ -1856,48 +1866,48 @@ func HandlePDUSessionResourceModifyConfirm(amf *context.N3IWFAMF, message *ngapT var ok bool ranUe, ok = n3iwfSelf.RanUePoolLoad(rANUENGAPID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", rANUENGAPID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", rANUENGAPID.Value) return } } if aMFUENGAPID != nil { if ranUe != nil { if ranUe.AmfUeNgapId != aMFUENGAPID.Value { - logger.NgapLog.Errorf("Inconsistent remote UE NGAP ID, AMFUENGAPID: %d, RanUe.AmfUeNgapId: %d", + ngapLog.Errorf("Inconsistent remote UE NGAP ID, AMFUENGAPID: %d, RanUe.AmfUeNgapId: %d", aMFUENGAPID.Value, ranUe.AmfUeNgapId) return } } else { ranUe = amf.FindUeByAmfUeNgapID(aMFUENGAPID.Value) if ranUe == nil { - logger.NgapLog.Errorf("Inconsistent remote UE NGAP ID, AMFUENGAPID: %d, RanUe.AmfUeNgapId: %d", - aMFUENGAPID.Value, ranUe.AmfUeNgapId) + ngapLog.Errorf("Inconsistent remote UE NGAP ID, AMFUENGAPID: %d", + aMFUENGAPID.Value) return } } } if ranUe == nil { - logger.NgapLog.Warn("RANUENGAPID and AMFUENGAPID are both nil") + ngapLog.Warn("RANUENGAPID and AMFUENGAPID are both nil") return } if pDUSessionResourceModifyListModCfm != nil { for _, item := range pDUSessionResourceModifyListModCfm.List { pduSessionId := item.PDUSessionID.Value - logger.NgapLog.Tracef("PDU Session Id[%d] in Pdu Session Resource Modification Confrim List", pduSessionId) + ngapLog.Tracef("PDU Session Id[%d] in Pdu Session Resource Modification Confrim List", pduSessionId) sess, exist := ranUe.PduSessionList[pduSessionId] if !exist { - logger.NgapLog.Warnf( + ngapLog.Warnf( "PDU Session Id[%d] is not exist in Ue[ranUeNgapId:%d]", pduSessionId, ranUe.RanUeNgapId) } else { transfer := ngapType.PDUSessionResourceModifyConfirmTransfer{} err := aper.UnmarshalWithParams(item.PDUSessionResourceModifyConfirmTransfer, &transfer, "valueExt") if err != nil { - logger.NgapLog.Warnf( + ngapLog.Warnf( "[PDUSessionID: %d] PDUSessionResourceSetupRequestTransfer Decode Error: %+v\n", pduSessionId, err) } else if transfer.QosFlowFailedToModifyList != nil { for _, flow := range transfer.QosFlowFailedToModifyList.List { - logger.NgapLog.Warnf( + ngapLog.Warnf( "Delete QFI[%d] due to Qos Flow Failure in Pdu Session Resource Modification Confrim List", flow.QosFlowIdentifier.Value) delete(sess.QosFlows, flow.QosFlowIdentifier.Value) @@ -1913,13 +1923,13 @@ func HandlePDUSessionResourceModifyConfirm(amf *context.N3IWFAMF, message *ngapT err := aper.UnmarshalWithParams( item.PDUSessionResourceModifyIndicationUnsuccessfulTransfer, &transfer, "valueExt") if err != nil { - logger.NgapLog.Warnf( + ngapLog.Warnf( "[PDUSessionID: %d] PDUSessionResourceModifyIndicationUnsuccessfulTransfer Decode Error: %+v\n", pduSessionId, err) } else { printAndGetCause(&transfer.Cause) } - logger.NgapLog.Tracef( + ngapLog.Tracef( "Release PDU Session Id[%d] due to PDU Session Resource Modify Indication Unsuccessful", pduSessionId) delete(ranUe.PduSessionList, pduSessionId) } @@ -1931,7 +1941,8 @@ func HandlePDUSessionResourceModifyConfirm(amf *context.N3IWFAMF, message *ngapT } func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle PDU Session Resource Release Command") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle PDU Session Resource Release Command") var aMFUENGAPID *ngapType.AMFUENGAPID var rANUENGAPID *ngapType.RANUENGAPID // var rANPagingPriority *ngapType.RANPagingPriority @@ -1941,58 +1952,58 @@ func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngap var iesCriticalityDiagnostics ngapType.CriticalityDiagnosticsIEList if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("Initiating Message is nil") + ngapLog.Error("Initiating Message is nil") return } pDUSessionResourceReleaseCommand := initiatingMessage.Value.PDUSessionResourceReleaseCommand if pDUSessionResourceReleaseCommand == nil { - logger.NgapLog.Error("pDUSessionResourceReleaseCommand is nil") + ngapLog.Error("pDUSessionResourceReleaseCommand is nil") return } for _, ie := range pDUSessionResourceReleaseCommand.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") aMFUENGAPID = ie.Value.AMFUENGAPID if aMFUENGAPID == nil { - logger.NgapLog.Error("AMFUENGAPID is nil") + ngapLog.Error("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") rANUENGAPID = ie.Value.RANUENGAPID if rANUENGAPID == nil { - logger.NgapLog.Error("RANUENGAPID is nil") + ngapLog.Error("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANPagingPriority: - logger.NgapLog.Traceln("[NGAP] Decode IE RANPagingPriority") + ngapLog.Traceln("[NGAP] Decode IE RANPagingPriority") // rANPagingPriority = ie.Value.RANPagingPriority case ngapType.ProtocolIEIDNASPDU: - logger.NgapLog.Traceln("[NGAP] Decode IE NASPDU") + ngapLog.Traceln("[NGAP] Decode IE NASPDU") // nASPDU = ie.Value.NASPDU case ngapType.ProtocolIEIDPDUSessionResourceToReleaseListRelCmd: - logger.NgapLog.Traceln("[NGAP] Decode IE PDUSessionResourceToReleaseListRelCmd") + ngapLog.Traceln("[NGAP] Decode IE PDUSessionResourceToReleaseListRelCmd") pDUSessionResourceToReleaseListRelCmd = ie.Value.PDUSessionResourceToReleaseListRelCmd if pDUSessionResourceToReleaseListRelCmd == nil { - logger.NgapLog.Error("PDUSessionResourceToReleaseListRelCmd is nil") + ngapLog.Error("PDUSessionResourceToReleaseListRelCmd is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) @@ -2013,7 +2024,7 @@ func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngap n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(rANUENGAPID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", rANUENGAPID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", rANUENGAPID.Value) cause := ngap_message.BuildCause(ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentUnknownLocalUENGAPID) ngap_message.SendErrorIndication(amf, nil, nil, cause, nil) @@ -2021,7 +2032,7 @@ func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngap } if ranUe.AmfUeNgapId != aMFUENGAPID.Value { - logger.NgapLog.Errorf("Inconsistent remote UE NGAP ID, AMFUENGAPID: %d, RanUe.AmfUeNgapId: %d", + ngapLog.Errorf("Inconsistent remote UE NGAP ID, AMFUENGAPID: %d, RanUe.AmfUeNgapId: %d", aMFUENGAPID.Value, ranUe.AmfUeNgapId) cause := ngap_message.BuildCause(ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentInconsistentRemoteUENGAPID) @@ -2040,13 +2051,13 @@ func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngap transfer := ngapType.PDUSessionResourceReleaseCommandTransfer{} err := aper.UnmarshalWithParams(item.PDUSessionResourceReleaseCommandTransfer, &transfer, "valueExt") if err != nil { - logger.NgapLog.Warnf( + ngapLog.Warnf( "[PDUSessionID: %d] PDUSessionResourceReleaseCommandTransfer Decode Error: %+v\n", pduSessionId, err) } else { printAndGetCause(&transfer.Cause) } - logger.NgapLog.Tracef("Release PDU Session Id[%d] due to PDU Session Resource Release Command", pduSessionId) + ngapLog.Tracef("Release PDU Session Id[%d] due to PDU Session Resource Release Command", pduSessionId) delete(ranUe.PduSessionList, pduSessionId) // response list @@ -2061,7 +2072,7 @@ func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngap localSPI, ok := n3iwfSelf.IkeSpiLoad(rANUENGAPID.Value) if !ok { - logger.NgapLog.Errorf("Cannot get SPI from RanUeNgapID : %+v", rANUENGAPID.Value) + ngapLog.Errorf("Cannot get SPI from RanUeNgapID : %+v", rANUENGAPID.Value) return } @@ -2075,7 +2086,8 @@ func HandlePDUSessionResourceReleaseCommand(amf *context.N3IWFAMF, message *ngap } func HandleErrorIndication(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Error Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Error Indication") var aMFUENGAPID *ngapType.AMFUENGAPID var rANUENGAPID *ngapType.RANUENGAPID @@ -2083,21 +2095,21 @@ func HandleErrorIndication(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { var criticalityDiagnostics *ngapType.CriticalityDiagnostics if amf == nil { - logger.NgapLog.Error("Corresponding AMF context not found") + ngapLog.Error("Corresponding AMF context not found") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("InitiatingMessage is nil") + ngapLog.Error("InitiatingMessage is nil") return } errorIndication := initiatingMessage.Value.ErrorIndication if errorIndication == nil { - logger.NgapLog.Error("ErrorIndication is nil") + ngapLog.Error("ErrorIndication is nil") return } @@ -2105,33 +2117,33 @@ func HandleErrorIndication(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: aMFUENGAPID = ie.Value.AMFUENGAPID - logger.NgapLog.Trace("[NGAP] Decode IE AmfUeNgapID") + ngapLog.Trace("[NGAP] Decode IE AmfUeNgapID") case ngapType.ProtocolIEIDRANUENGAPID: rANUENGAPID = ie.Value.RANUENGAPID - logger.NgapLog.Trace("[NGAP] Decode IE RanUeNgapID") + ngapLog.Trace("[NGAP] Decode IE RanUeNgapID") case ngapType.ProtocolIEIDCause: cause = ie.Value.Cause - logger.NgapLog.Trace("[NGAP] Decode IE Cause") + ngapLog.Trace("[NGAP] Decode IE Cause") case ngapType.ProtocolIEIDCriticalityDiagnostics: criticalityDiagnostics = ie.Value.CriticalityDiagnostics - logger.NgapLog.Trace("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Trace("[NGAP] Decode IE CriticalityDiagnostics") } } if cause == nil && criticalityDiagnostics == nil { - logger.NgapLog.Error("Both Cause IE and CriticalityDiagnostics IE are nil, should have at least one") + ngapLog.Error("Both Cause IE and CriticalityDiagnostics IE are nil, should have at least one") return } if (aMFUENGAPID == nil) != (rANUENGAPID == nil) { - logger.NgapLog.Error("One of UE NGAP ID is not included in this message") + ngapLog.Error("One of UE NGAP ID is not included in this message") return } if (aMFUENGAPID != nil) && (rANUENGAPID != nil) { - logger.NgapLog.Trace("UE-associated procedure error") - logger.NgapLog.Warnf("AMF UE NGAP ID is defined, value = %d", aMFUENGAPID.Value) - logger.NgapLog.Warnf("RAN UE NGAP ID is defined, value = %d", rANUENGAPID.Value) + ngapLog.Trace("UE-associated procedure error") + ngapLog.Warnf("AMF UE NGAP ID is defined, value = %d", aMFUENGAPID.Value) + ngapLog.Warnf("RAN UE NGAP ID is defined, value = %d", rANUENGAPID.Value) } if cause != nil { @@ -2146,7 +2158,8 @@ func HandleErrorIndication(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { } func HandleUERadioCapabilityCheckRequest(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle UE Radio Capability Check Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle UE Radio Capability Check Request") var aMFUENGAPID *ngapType.AMFUENGAPID var rANUENGAPID *ngapType.RANUENGAPID var uERadioCapability *ngapType.UERadioCapability @@ -2154,49 +2167,49 @@ func HandleUERadioCapabilityCheckRequest(amf *context.N3IWFAMF, message *ngapTyp var iesCriticalityDiagnostics ngapType.CriticalityDiagnosticsIEList if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("InitiatingMessage is nil") + ngapLog.Error("InitiatingMessage is nil") return } uERadioCapabilityCheckRequest := initiatingMessage.Value.UERadioCapabilityCheckRequest if uERadioCapabilityCheckRequest == nil { - logger.NgapLog.Error("uERadioCapabilityCheckRequest is nil") + ngapLog.Error("uERadioCapabilityCheckRequest is nil") return } for _, ie := range uERadioCapabilityCheckRequest.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE AMFUENGAPID") aMFUENGAPID = ie.Value.AMFUENGAPID if aMFUENGAPID == nil { - logger.NgapLog.Error("AMFUENGAPID is nil") + ngapLog.Error("AMFUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDRANUENGAPID: - logger.NgapLog.Traceln("[NGAP] Decode IE RANUENGAPID") + ngapLog.Traceln("[NGAP] Decode IE RANUENGAPID") rANUENGAPID = ie.Value.RANUENGAPID if rANUENGAPID == nil { - logger.NgapLog.Error("RANUENGAPID is nil") + ngapLog.Error("RANUENGAPID is nil") item := buildCriticalityDiagnosticsIEItem( ngapType.CriticalityPresentReject, ie.Id.Value, ngapType.TypeOfErrorPresentMissing) iesCriticalityDiagnostics.List = append(iesCriticalityDiagnostics.List, item) } case ngapType.ProtocolIEIDUERadioCapability: - logger.NgapLog.Traceln("[NGAP] Decode IE UERadioCapability") + ngapLog.Traceln("[NGAP] Decode IE UERadioCapability") uERadioCapability = ie.Value.UERadioCapability } } @@ -2214,7 +2227,7 @@ func HandleUERadioCapabilityCheckRequest(amf *context.N3IWFAMF, message *ngapTyp n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(rANUENGAPID.Value) if !ok { - logger.NgapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", rANUENGAPID.Value) + ngapLog.Errorf("Unknown local UE NGAP ID. RanUENGAPID: %d", rANUENGAPID.Value) cause := ngap_message.BuildCause(ngapType.CausePresentRadioNetwork, ngapType.CauseRadioNetworkPresentUnknownLocalUENGAPID) ngap_message.SendErrorIndication(amf, nil, nil, cause, nil) @@ -2225,7 +2238,8 @@ func HandleUERadioCapabilityCheckRequest(amf *context.N3IWFAMF, message *ngapTyp } func HandleAMFConfigurationUpdate(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle AMF Configuration Updaet") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle AMF Configuration Updaet") var aMFName *ngapType.AMFName var servedGUAMIList *ngapType.ServedGUAMIList @@ -2236,49 +2250,49 @@ func HandleAMFConfigurationUpdate(amf *context.N3IWFAMF, message *ngapType.NGAPP var aMFTNLAssociationToUpdateList *ngapType.AMFTNLAssociationToUpdateList if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("InitiatingMessage is nil") + ngapLog.Error("InitiatingMessage is nil") return } aMFConfigurationUpdate := initiatingMessage.Value.AMFConfigurationUpdate if aMFConfigurationUpdate == nil { - logger.NgapLog.Error("aMFConfigurationUpdate is nil") + ngapLog.Error("aMFConfigurationUpdate is nil") return } for _, ie := range aMFConfigurationUpdate.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFName: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFName") + ngapLog.Traceln("[NGAP] Decode IE AMFName") aMFName = ie.Value.AMFName case ngapType.ProtocolIEIDServedGUAMIList: - logger.NgapLog.Traceln("[NGAP] Decode IE ServedGUAMIList") + ngapLog.Traceln("[NGAP] Decode IE ServedGUAMIList") servedGUAMIList = ie.Value.ServedGUAMIList case ngapType.ProtocolIEIDRelativeAMFCapacity: - logger.NgapLog.Traceln("[NGAP] Decode IE RelativeAMFCapacity") + ngapLog.Traceln("[NGAP] Decode IE RelativeAMFCapacity") relativeAMFCapacity = ie.Value.RelativeAMFCapacity case ngapType.ProtocolIEIDPLMNSupportList: - logger.NgapLog.Traceln("[NGAP] Decode IE PLMNSupportList") + ngapLog.Traceln("[NGAP] Decode IE PLMNSupportList") pLMNSupportList = ie.Value.PLMNSupportList case ngapType.ProtocolIEIDAMFTNLAssociationToAddList: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFTNLAssociationToAddList") + ngapLog.Traceln("[NGAP] Decode IE AMFTNLAssociationToAddList") aMFTNLAssociationToAddList = ie.Value.AMFTNLAssociationToAddList case ngapType.ProtocolIEIDAMFTNLAssociationToRemoveList: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFTNLAssociationToRemoveList") + ngapLog.Traceln("[NGAP] Decode IE AMFTNLAssociationToRemoveList") aMFTNLAssociationToRemoveList = ie.Value.AMFTNLAssociationToRemoveList case ngapType.ProtocolIEIDAMFTNLAssociationToUpdateList: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFTNLAssociationToUpdateList") + ngapLog.Traceln("[NGAP] Decode IE AMFTNLAssociationToUpdateList") aMFTNLAssociationToUpdateList = ie.Value.AMFTNLAssociationToUpdateList } } @@ -2345,36 +2359,37 @@ func HandleAMFConfigurationUpdate(amf *context.N3IWFAMF, message *ngapType.NGAPP } func HandleRANConfigurationUpdateAcknowledge(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle RAN Configuration Update Acknowledge") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle RAN Configuration Update Acknowledge") var criticalityDiagnostics *ngapType.CriticalityDiagnostics if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } successfulOutcome := message.SuccessfulOutcome if successfulOutcome == nil { - logger.NgapLog.Error("SuccessfulOutcome is nil") + ngapLog.Error("SuccessfulOutcome is nil") return } rANConfigurationUpdateAcknowledge := successfulOutcome.Value.RANConfigurationUpdateAcknowledge if rANConfigurationUpdateAcknowledge == nil { - logger.NgapLog.Error("rANConfigurationUpdateAcknowledge is nil") + ngapLog.Error("rANConfigurationUpdateAcknowledge is nil") return } for _, ie := range rANConfigurationUpdateAcknowledge.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDCriticalityDiagnostics: - logger.NgapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") criticalityDiagnostics = ie.Value.CriticalityDiagnostics } } @@ -2385,7 +2400,8 @@ func HandleRANConfigurationUpdateAcknowledge(amf *context.N3IWFAMF, message *nga } func HandleRANConfigurationUpdateFailure(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle RAN Configuration Update Failure") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle RAN Configuration Update Failure") var cause *ngapType.Cause var timeToWait *ngapType.TimeToWait @@ -2394,37 +2410,37 @@ func HandleRANConfigurationUpdateFailure(amf *context.N3IWFAMF, message *ngapTyp n3iwfSelf := context.N3IWFSelf() if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } unsuccessfulOutcome := message.UnsuccessfulOutcome if unsuccessfulOutcome == nil { - logger.NgapLog.Error("UnsuccessfulOutcome is nil") + ngapLog.Error("UnsuccessfulOutcome is nil") return } rANConfigurationUpdateFailure := unsuccessfulOutcome.Value.RANConfigurationUpdateFailure if rANConfigurationUpdateFailure == nil { - logger.NgapLog.Error("rANConfigurationUpdateFailure is nil") + ngapLog.Error("rANConfigurationUpdateFailure is nil") return } for _, ie := range rANConfigurationUpdateFailure.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDCause: - logger.NgapLog.Traceln("[NGAP] Decode IE Cause") + ngapLog.Traceln("[NGAP] Decode IE Cause") cause = ie.Value.Cause case ngapType.ProtocolIEIDTimeToWait: - logger.NgapLog.Traceln("[NGAP] Decode IE TimeToWait") + ngapLog.Traceln("[NGAP] Decode IE TimeToWait") timeToWait = ie.Value.TimeToWait case ngapType.ProtocolIEIDCriticalityDiagnostics: - logger.NgapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") + ngapLog.Traceln("[NGAP] Decode IE CriticalityDiagnostics") criticalityDiagnostics = ie.Value.CriticalityDiagnostics } } @@ -2455,11 +2471,11 @@ func HandleRANConfigurationUpdateFailure(amf *context.N3IWFAMF, message *ngapTyp } if waitingTime != 0 { - logger.NgapLog.Infof("Wait at lease %ds to resend RAN Configuration Update to same AMF[%s]", + ngapLog.Infof("Wait at lease %ds to resend RAN Configuration Update to same AMF[%s]", waitingTime, amf.SCTPAddr) n3iwfSelf.AMFReInitAvailableListStore(amf.SCTPAddr, false) time.AfterFunc(time.Duration(waitingTime)*time.Second, func() { - logger.NgapLog.Infof("Re-send Ran Configuration Update Message when waiting time expired") + ngapLog.Infof("Re-send Ran Configuration Update Message when waiting time expired") n3iwfSelf.AMFReInitAvailableListStore(amf.SCTPAddr, true) ngap_message.SendRANConfigurationUpdate(amf) }) @@ -2469,64 +2485,70 @@ func HandleRANConfigurationUpdateFailure(amf *context.N3IWFAMF, message *ngapTyp } func HandleDownlinkRANConfigurationTransfer(message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Downlink RAN Configuration Transfer") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Downlink RAN Configuration Transfer") } func HandleDownlinkRANStatusTransfer(message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Downlink RAN Status Transfer") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Downlink RAN Status Transfer") } func HandleAMFStatusIndication(message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle AMF Status Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle AMF Status Indication") } func HandleLocationReportingControl(message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Location Reporting Control") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Location Reporting Control") } func HandleUETNLAReleaseRequest(message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle UE TNLA Release Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle UE TNLA Release Request") } func HandleOverloadStart(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Overload Start") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Overload Start") var aMFOverloadResponse *ngapType.OverloadResponse var aMFTrafficLoadReductionIndication *ngapType.TrafficLoadReductionIndication var overloadStartNSSAIList *ngapType.OverloadStartNSSAIList if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } if message == nil { - logger.NgapLog.Error("NGAP Message is nil") + ngapLog.Error("NGAP Message is nil") return } initiatingMessage := message.InitiatingMessage if initiatingMessage == nil { - logger.NgapLog.Error("InitiatingMessage is nil") + ngapLog.Error("InitiatingMessage is nil") return } overloadStart := initiatingMessage.Value.OverloadStart if overloadStart == nil { - logger.NgapLog.Error("overloadStart is nil") + ngapLog.Error("overloadStart is nil") return } for _, ie := range overloadStart.ProtocolIEs.List { switch ie.Id.Value { case ngapType.ProtocolIEIDAMFOverloadResponse: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFOverloadResponse") + ngapLog.Traceln("[NGAP] Decode IE AMFOverloadResponse") aMFOverloadResponse = ie.Value.AMFOverloadResponse case ngapType.ProtocolIEIDAMFTrafficLoadReductionIndication: - logger.NgapLog.Traceln("[NGAP] Decode IE AMFTrafficLoadReductionIndication") + ngapLog.Traceln("[NGAP] Decode IE AMFTrafficLoadReductionIndication") aMFTrafficLoadReductionIndication = ie.Value.AMFTrafficLoadReductionIndication case ngapType.ProtocolIEIDOverloadStartNSSAIList: - logger.NgapLog.Traceln("[NGAP] Decode IE OverloadStartNSSAIList") + ngapLog.Traceln("[NGAP] Decode IE OverloadStartNSSAIList") overloadStartNSSAIList = ie.Value.OverloadStartNSSAIList } } @@ -2535,10 +2557,11 @@ func HandleOverloadStart(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { } func HandleOverloadStop(amf *context.N3IWFAMF, message *ngapType.NGAPPDU) { - logger.NgapLog.Infoln("[N3IWF] Handle Overload Stop") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Handle Overload Stop") if amf == nil { - logger.NgapLog.Error("AMF Context is nil") + ngapLog.Error("AMF Context is nil") return } // TODO: remove restrict about overload action @@ -2593,73 +2616,77 @@ func buildCriticalityDiagnosticsIEItem(ieCriticality aper.Enumerated, ieID int64 } func printAndGetCause(cause *ngapType.Cause) (present int, value aper.Enumerated) { + ngapLog := logger.NgapLog present = cause.Present switch cause.Present { case ngapType.CausePresentRadioNetwork: - logger.NgapLog.Warnf("Cause RadioNetwork[%d]", cause.RadioNetwork.Value) + ngapLog.Warnf("Cause RadioNetwork[%d]", cause.RadioNetwork.Value) value = cause.RadioNetwork.Value case ngapType.CausePresentTransport: - logger.NgapLog.Warnf("Cause Transport[%d]", cause.Transport.Value) + ngapLog.Warnf("Cause Transport[%d]", cause.Transport.Value) value = cause.Transport.Value case ngapType.CausePresentProtocol: - logger.NgapLog.Warnf("Cause Protocol[%d]", cause.Protocol.Value) + ngapLog.Warnf("Cause Protocol[%d]", cause.Protocol.Value) value = cause.Protocol.Value case ngapType.CausePresentNas: - logger.NgapLog.Warnf("Cause Nas[%d]", cause.Nas.Value) + ngapLog.Warnf("Cause Nas[%d]", cause.Nas.Value) value = cause.Nas.Value case ngapType.CausePresentMisc: - logger.NgapLog.Warnf("Cause Misc[%d]", cause.Misc.Value) + ngapLog.Warnf("Cause Misc[%d]", cause.Misc.Value) value = cause.Misc.Value default: - logger.NgapLog.Errorf("Invalid Cause group[%d]", cause.Present) + ngapLog.Errorf("Invalid Cause group[%d]", cause.Present) } return } func printCriticalityDiagnostics(criticalityDiagnostics *ngapType.CriticalityDiagnostics) { + ngapLog := logger.NgapLog if criticalityDiagnostics == nil { return } else { iesCriticalityDiagnostics := criticalityDiagnostics.IEsCriticalityDiagnostics if iesCriticalityDiagnostics != nil { for index, item := range iesCriticalityDiagnostics.List { - logger.NgapLog.Warnf("Criticality IE item %d:", index+1) - logger.NgapLog.Warnf("IE ID: %d", item.IEID.Value) + ngapLog.Warnf("Criticality IE item %d:", index+1) + ngapLog.Warnf("IE ID: %d", item.IEID.Value) switch item.IECriticality.Value { case ngapType.CriticalityPresentReject: - logger.NgapLog.Warn("IE Criticality: Reject") + ngapLog.Warn("IE Criticality: Reject") case ngapType.CriticalityPresentIgnore: - logger.NgapLog.Warn("IE Criticality: Ignore") + ngapLog.Warn("IE Criticality: Ignore") case ngapType.CriticalityPresentNotify: - logger.NgapLog.Warn("IE Criticality: Notify") + ngapLog.Warn("IE Criticality: Notify") } switch item.TypeOfError.Value { case ngapType.TypeOfErrorPresentNotUnderstood: - logger.NgapLog.Warn("Type of error: Not Understood") + ngapLog.Warn("Type of error: Not Understood") case ngapType.TypeOfErrorPresentMissing: - logger.NgapLog.Warn("Type of error: Missing") + ngapLog.Warn("Type of error: Missing") } } } else { - logger.NgapLog.Error("IEsCriticalityDiagnostics is nil") + ngapLog.Error("IEsCriticalityDiagnostics is nil") } return } } func getPDUSessionResourceReleaseResponseTransfer() []byte { + ngapLog := logger.NgapLog data := ngapType.PDUSessionResourceReleaseResponseTransfer{} encodeData, err := aper.MarshalWithParams(data, "valueExt") if err != nil { - logger.NgapLog.Errorf("aper MarshalWithParams error in getPDUSessionResourceReleaseResponseTransfer: %d", err) + ngapLog.Errorf("aper MarshalWithParams error in getPDUSessionResourceReleaseResponseTransfer: %d", err) } return encodeData } func HandleEvent(ngapEvent context.NgapEvt) { - logger.NgapLog.Infof("NGAP event handle") + ngapLog := logger.NgapLog + ngapLog.Infof("NGAP event handle") switch ngapEvent.Type() { case context.UnmarshalEAP5GData: @@ -2683,13 +2710,14 @@ func HandleEvent(ngapEvent context.NgapEvt) { case context.GetNGAPContext: HandleGetNGAPContext(ngapEvent) default: - logger.NgapLog.Errorf("Undefine NGAP event type") + ngapLog.Errorf("Undefine NGAP event type") return } } func HandleGetNGAPContext(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle HandleGetNGAPContext Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle HandleGetNGAPContext Event") getNGAPContextEvt := ngapEvent.(*context.GetNGAPContextEvt) ranUeNgapId := getNGAPContextEvt.RanUeNgapId @@ -2698,7 +2726,7 @@ func HandleGetNGAPContext(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } @@ -2709,13 +2737,13 @@ func HandleGetNGAPContext(ngapEvent context.NgapEvt) { case context.CxtTempPDUSessionSetupData: ngapCxt = append(ngapCxt, ranUe.TemporaryPDUSessionSetupData) default: - logger.NgapLog.Errorf("Receive undefine NGAP Context Request number : %d", num) + ngapLog.Errorf("Receive undefine NGAP Context Request number : %d", num) } } spi, ok := n3iwfSelf.IkeSpiLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get spi from ngapid : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get spi from ngapid : %+v", ranUeNgapId) return } @@ -2724,7 +2752,8 @@ func HandleGetNGAPContext(ngapEvent context.NgapEvt) { } func HandleUnmarshalEAP5GData(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle UnmarshalEAP5GData Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle UnmarshalEAP5GData Event") unmarshalEAP5GDataEvt := ngapEvent.(*context.UnmarshalEAP5GDataEvt) spi := unmarshalEAP5GDataEvt.LocalSPI @@ -2735,38 +2764,38 @@ func HandleUnmarshalEAP5GData(ngapEvent context.NgapEvt) { anParameters, nasPDU, err := ngap_message.UnmarshalEAP5GData(eapVendorData) if err != nil { - logger.NgapLog.Errorf("Unmarshalling EAP-5G packet failed: %+v", err) + ngapLog.Errorf("Unmarshalling EAP-5G packet failed: %+v", err) return } if !isInitialUE { // ikeSA.ikeUE == nil - logger.NgapLog.Debug("Select AMF with the following AN parameters:") + ngapLog.Debug("Select AMF with the following AN parameters:") if anParameters.GUAMI == nil { - logger.NgapLog.Debug("\tGUAMI: nil") + ngapLog.Debug("\tGUAMI: nil") } else { - logger.NgapLog.Debugf("\tGUAMI: PLMNIdentity[% x], "+ + ngapLog.Debugf("\tGUAMI: PLMNIdentity[% x], "+ "AMFRegionID[% x], AMFSetID[% x], AMFPointer[% x]", anParameters.GUAMI.PLMNIdentity, anParameters.GUAMI.AMFRegionID, anParameters.GUAMI.AMFSetID, anParameters.GUAMI.AMFPointer) } if anParameters.SelectedPLMNID == nil { - logger.NgapLog.Debug("\tSelectedPLMNID: nil") + ngapLog.Debug("\tSelectedPLMNID: nil") } else { - logger.NgapLog.Debugf("\tSelectedPLMNID: % v", anParameters.SelectedPLMNID.Value) + ngapLog.Debugf("\tSelectedPLMNID: % v", anParameters.SelectedPLMNID.Value) } if anParameters.RequestedNSSAI == nil { - logger.NgapLog.Debug("\tRequestedNSSAI: nil") + ngapLog.Debug("\tRequestedNSSAI: nil") } else { - logger.NgapLog.Debugf("\tRequestedNSSAI:") + ngapLog.Debugf("\tRequestedNSSAI:") for i := 0; i < len(anParameters.RequestedNSSAI.List); i++ { - logger.NgapLog.Debugf("\tRequestedNSSAI:") - logger.NgapLog.Debugf("\t\tSNSSAI %d:", i+1) - logger.NgapLog.Debugf("\t\t\tSST: % x", anParameters.RequestedNSSAI.List[i].SNSSAI.SST.Value) + ngapLog.Debugf("\tRequestedNSSAI:") + ngapLog.Debugf("\t\tSNSSAI %d:", i+1) + ngapLog.Debugf("\t\t\tSST: % x", anParameters.RequestedNSSAI.List[i].SNSSAI.SST.Value) sd := anParameters.RequestedNSSAI.List[i].SNSSAI.SD if sd == nil { - logger.NgapLog.Debugf("\t\t\tSD: nil") + ngapLog.Debugf("\t\t\tSD: nil") } else { - logger.NgapLog.Debugf("\t\t\tSD: % x", sd.Value) + ngapLog.Debugf("\t\t\tSD: % x", sd.Value) } } } @@ -2788,7 +2817,7 @@ func HandleUnmarshalEAP5GData(ngapEvent context.NgapEvt) { ranUeNgapId := unmarshalEAP5GDataEvt.RanUeNgapId ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } ngap_message.SendUplinkNASTransport(ranUe, nasPDU) @@ -2796,7 +2825,8 @@ func HandleUnmarshalEAP5GData(ngapEvent context.NgapEvt) { } func HandleSendInitialUEMessage(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle SendInitialUEMessage Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle SendInitialUEMessage Event") sendInitialUEMessageEvt := ngapEvent.(*context.SendInitialUEMessageEvt) ranUeNgapId := sendInitialUEMessageEvt.RanUeNgapId @@ -2807,7 +2837,7 @@ func HandleSendInitialUEMessage(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } ranUe.IPAddrv4 = ipv4Addr @@ -2816,7 +2846,8 @@ func HandleSendInitialUEMessage(ngapEvent context.NgapEvt) { } func HandleSendPDUSessionResourceSetupResponse(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle SendPDUSessionResourceSetupResponse Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle SendPDUSessionResourceSetupResponse Event") sendPDUSessionResourceSetupResEvt := ngapEvent.(*context.SendPDUSessionResourceSetupResEvt) ranUeNgapId := sendPDUSessionResourceSetupResEvt.RanUeNgapId @@ -2824,7 +2855,7 @@ func HandleSendPDUSessionResourceSetupResponse(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } @@ -2844,13 +2875,13 @@ func HandleSendPDUSessionResourceSetupResponse(ngapEvent context.NgapEvt) { }, } default: - logger.NgapLog.Errorf("Undefine event error string : %+s", errStr.Error()) + ngapLog.Errorf("Undefine event error string : %+s", errStr.Error()) return } transfer, err := ngap_message.BuildPDUSessionResourceSetupUnsuccessfulTransfer(cause, nil) if err != nil { - logger.NgapLog.Errorf("Build PDU Session Resource Setup Unsuccessful Transfer Failed: %+v", err) + ngapLog.Errorf("Build PDU Session Resource Setup Unsuccessful Transfer Failed: %+v", err) continue } @@ -2865,7 +2896,7 @@ func HandleSendPDUSessionResourceSetupResponse(ngapEvent context.NgapEvt) { // Append NGAP PDU session resource setup response transfer transfer, err := ngap_message.BuildPDUSessionResourceSetupResponseTransfer(pduSession) if err != nil { - logger.NgapLog.Errorf("Build PDU session resource setup response transfer failed: %+v", err) + ngapLog.Errorf("Build PDU session resource setup response transfer failed: %+v", err) return } if temporaryPDUSessionSetupData.NGAPProcedureCode.Value == ngapType.ProcedureCodeInitialContextSetup { @@ -2893,7 +2924,8 @@ func HandleSendPDUSessionResourceSetupResponse(ngapEvent context.NgapEvt) { } func HandleSendNASMsg(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle SendNASMsg Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle SendNASMsg Event") sendNASMsgEvt := ngapEvent.(*context.SendNASMsgEvt) ranUeNgapId := sendNASMsgEvt.RanUeNgapId @@ -2901,20 +2933,21 @@ func HandleSendNASMsg(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } if n, ikeErr := ranUe.TCPConnection.Write(ranUe.TemporaryCachedNASMessage); ikeErr != nil { - logger.NgapLog.Errorf("Writing via IPSec signalling SA failed: %+v", ikeErr) + ngapLog.Errorf("Writing via IPSec signalling SA failed: %+v", ikeErr) } else { - logger.NgapLog.Tracef("Forward PDU Seesion Establishment Accept to UE. Wrote %d bytes", n) + ngapLog.Tracef("Forward PDU Seesion Establishment Accept to UE. Wrote %d bytes", n) ranUe.TemporaryCachedNASMessage = nil } } func HandleStartTCPSignalNASMsg(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle StartTCPSignalNASMsg Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle StartTCPSignalNASMsg Event") startTCPSignalNASMsgEvt := ngapEvent.(*context.StartTCPSignalNASMsgEvt) ranUeNgapId := startTCPSignalNASMsgEvt.RanUeNgapId @@ -2922,7 +2955,7 @@ func HandleStartTCPSignalNASMsg(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } @@ -2930,7 +2963,8 @@ func HandleStartTCPSignalNASMsg(ngapEvent context.NgapEvt) { } func HandleNASTCPConnEstablishedComplete(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle NASTCPConnEstablishedComplete Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle NASTCPConnEstablishedComplete Event") nasTCPConnEstablishedCompleteEvt := ngapEvent.(*context.NASTCPConnEstablishedCompleteEvt) ranUeNgapId := nasTCPConnEstablishedCompleteEvt.RanUeNgapId @@ -2938,7 +2972,7 @@ func HandleNASTCPConnEstablishedComplete(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } @@ -2947,17 +2981,18 @@ func HandleNASTCPConnEstablishedComplete(ngapEvent context.NgapEvt) { if ranUe.TemporaryCachedNASMessage != nil { // Send to UE if n, err := ranUe.TCPConnection.Write(ranUe.TemporaryCachedNASMessage); err != nil { - logger.NgapLog.Errorf("Writing via IPSec signalling SA failed: %+v", err) + ngapLog.Errorf("Writing via IPSec signalling SA failed: %+v", err) } else { - logger.NgapLog.Trace("Forward NWu <- N2") - logger.NgapLog.Tracef("Wrote %d bytes", n) + ngapLog.Trace("Forward NWu <- N2") + ngapLog.Tracef("Wrote %d bytes", n) } ranUe.TemporaryCachedNASMessage = nil } } func HandleSendUEContextReleaseRequest(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle SendUEContextReleaseRequest Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle SendUEContextReleaseRequest Event") sendUEContextReleaseReqEvt := ngapEvent.(*context.SendUEContextReleaseRequestEvt) @@ -2971,14 +3006,14 @@ func HandleSendUEContextReleaseRequest(ngapEvent context.NgapEvt) { ngapType.CauseRadioNetworkPresentRadioConnectionWithUeLost) case context.ErrNil: default: - logger.NgapLog.Errorf("Undefine event error string : %+s", errMsg.Error()) + ngapLog.Errorf("Undefine event error string : %+s", errMsg.Error()) return } n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } @@ -2986,7 +3021,8 @@ func HandleSendUEContextReleaseRequest(ngapEvent context.NgapEvt) { } func HandleSendUEContextReleaseComplete(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle SendUEContextReleaseComplete Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle SendUEContextReleaseComplete Event") sendUEContextReleaseCompleteEvt := ngapEvent.(*context.SendUEContextReleaseCompleteEvt) ranUeNgapId := sendUEContextReleaseCompleteEvt.RanUeNgapId @@ -2994,18 +3030,19 @@ func HandleSendUEContextReleaseComplete(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } if err := ranUe.Remove(); err != nil { - logger.NgapLog.Errorf("Delete RanUe Context error : %+v", err) + ngapLog.Errorf("Delete RanUe Context error : %+v", err) } ngap_message.SendUEContextReleaseComplete(ranUe, nil) } func HandleSendPDUSessionResourceReleaseRes(ngapEvent context.NgapEvt) { - logger.NgapLog.Tracef("Handle SendPDUSessionResourceReleaseResponse Event") + ngapLog := logger.NgapLog + ngapLog.Tracef("Handle SendPDUSessionResourceReleaseResponse Event") sendPDUSessionResourceReleaseResEvt := ngapEvent.(*context.SendPDUSessionResourceReleaseResEvt) ranUeNgapId := sendPDUSessionResourceReleaseResEvt.RanUeNgapId @@ -3013,7 +3050,7 @@ func HandleSendPDUSessionResourceReleaseRes(ngapEvent context.NgapEvt) { n3iwfSelf := context.N3IWFSelf() ranUe, ok := n3iwfSelf.RanUePoolLoad(ranUeNgapId) if !ok { - logger.NgapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) + ngapLog.Errorf("Cannot get RanUE from ranUeNgapId : %+v", ranUeNgapId) return } diff --git a/internal/ngap/message/3gpp_type.go b/internal/ngap/message/3gpp_type.go index f225e0b9..05dd4d48 100644 --- a/internal/ngap/message/3gpp_type.go +++ b/internal/ngap/message/3gpp_type.go @@ -20,263 +20,254 @@ type ANParameters struct { } func UnmarshalEAP5GData(codedData []byte) (anParameters *ANParameters, nasPDU []byte, err error) { - if len(codedData) >= 2 { - logger.NgapLog.Debug("===== Unmarshal EAP5G Data (Ref: TS24.502 Fig. 9.3.2.2.2-1) =====") + ngapLog := logger.NgapLog + if len(codedData) < 2 { + return nil, nil, errors.New("No data to decode") + } + + ngapLog.Debug("===== Unmarshal EAP5G Data (Ref: TS24.502 Fig. 9.3.2.2.2-1) =====") + + codedData = codedData[2:] - codedData = codedData[2:] + // [TS 24.502 f30] 9.3.2.2.2.3 + // AN-parameter value field in GUAMI, PLMN ID and NSSAI is coded as value part + // Therefore, IEI of AN-parameter is not needed to be included. + // anParameter = AN-parameter Type | AN-parameter Length | Value part of IE - // [TS 24.502 f30] 9.3.2.2.2.3 - // AN-parameter value field in GUAMI, PLMN ID and NSSAI is coded as value part - // Therefore, IEI of AN-parameter is not needed to be included. - // anParameter = AN-parameter Type | AN-parameter Length | Value part of IE + if len(codedData) < 2 { + ngapLog.Error("No AN-Parameter type or length specified") + return nil, nil, errors.New("Error formatting") + } + + // Length of the AN-Parameter field + anParameterLength := binary.BigEndian.Uint16(codedData[:2]) + ngapLog.Debugf("AN-parameters length: %d", anParameterLength) - if len(codedData) >= 2 { - // Length of the AN-Parameter field - anParameterLength := binary.BigEndian.Uint16(codedData[:2]) - logger.NgapLog.Debugf("AN-parameters length: %d", anParameterLength) + if anParameterLength != 0 { + anParameterField := codedData[2:] + + // Bound checking + if len(anParameterField) < int(anParameterLength) { + ngapLog.Error("Packet contained error length of value") + return nil, nil, errors.New("Error formatting") + } + anParameterField = anParameterField[:anParameterLength] + + ngapLog.Debugf("Parsing AN-parameters...: % v", anParameterField) + + anParameters = new(ANParameters) + + // Parse AN-Parameters + for len(anParameterField) >= 2 { + parameterType := anParameterField[0] + // The AN-parameter length field indicates the length of the AN-parameter value field. + parameterLength := anParameterField[1] + + switch parameterType { + case ANParametersTypeGUAMI: + ngapLog.Debugf("-> Parameter type: GUAMI") + if parameterLength != 0 { + parameterValue := anParameterField[2:] + + if len(parameterValue) < int(parameterLength) { + return nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - if anParameterLength != 0 { - anParameterField := codedData[2:] + if len(parameterValue) != ANParametersLenGUAMI { + return nil, nil, errors.New("Unmatched GUAMI length") + } - // Bound checking - if len(anParameterField) < int(anParameterLength) { - logger.NgapLog.Error("Packet contained error length of value") - return nil, nil, errors.New("Error formatting") + guamiField := make([]byte, 1) + guamiField = append(guamiField, parameterValue...) + // Decode GUAMI using aper + ngapGUAMI := new(ngapType.GUAMI) + err = aper.UnmarshalWithParams(guamiField, ngapGUAMI, "valueExt") + if err != nil { + ngapLog.Errorf("APER unmarshal with parameter failed: %+v", err) + return nil, nil, errors.New("Unmarshal failed when decoding GUAMI") + } + anParameters.GUAMI = ngapGUAMI + ngapLog.Debugf("Unmarshal GUAMI: % x", guamiField) + ngapLog.Debugf("\tGUAMI: PLMNIdentity[% x], "+ + "AMFRegionID[% x], AMFSetID[% x], AMFPointer[% x]", + anParameters.GUAMI.PLMNIdentity, anParameters.GUAMI.AMFRegionID, + anParameters.GUAMI.AMFSetID, anParameters.GUAMI.AMFPointer) } else { - anParameterField = anParameterField[:anParameterLength] + ngapLog.Warn("AN-Parameter GUAMI field empty") } + case ANParametersTypeSelectedPLMNID: + ngapLog.Debugf("-> Parameter type: ANParametersTypeSelectedPLMNID") + if parameterLength != 0 { + parameterValue := anParameterField[2:] - logger.NgapLog.Debugf("Parsing AN-parameters...: % v", anParameterField) + if len(parameterValue) < int(parameterLength) { + return nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - anParameters = new(ANParameters) + if len(parameterValue) != ANParametersLenPLMNID { + return nil, nil, errors.New("Unmatched PLMN ID length") + } - // Parse AN-Parameters - for len(anParameterField) >= 2 { - parameterType := anParameterField[0] - // The AN-parameter length field indicates the length of the AN-parameter value field. - parameterLength := anParameterField[1] + plmnField := make([]byte, 1) + plmnField = append(plmnField, parameterValue...) + // Decode PLMN using aper + ngapPLMN := new(ngapType.PLMNIdentity) + err = aper.UnmarshalWithParams(plmnField, ngapPLMN, "valueExt") + if err != nil { + ngapLog.Errorf("APER unmarshal with parameter failed: %v", err) + return nil, nil, errors.New("Unmarshal failed when decoding PLMN") + } + anParameters.SelectedPLMNID = ngapPLMN + ngapLog.Debugf("Unmarshal SelectedPLMNID: % x", plmnField) + ngapLog.Debugf("\tSelectedPLMNID: % x", anParameters.SelectedPLMNID.Value) + } else { + ngapLog.Warn("AN-Parameter PLMN field empty") + } + case ANParametersTypeRequestedNSSAI: + ngapLog.Debugf("-> Parameter type: ANParametersTypeRequestedNSSAI") + if parameterLength != 0 { + parameterValue := anParameterField[2:] - switch parameterType { - case ANParametersTypeGUAMI: - logger.NgapLog.Debugf("-> Parameter type: GUAMI") - if parameterLength != 0 { - parameterValue := anParameterField[2:] + if len(parameterValue) < int(parameterLength) { + return nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - if len(parameterValue) < int(parameterLength) { - return nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } + ngapNSSAI := new(ngapType.AllowedNSSAI) - if len(parameterValue) != ANParametersLenGUAMI { - return nil, nil, errors.New("Unmatched GUAMI length") - } + // [TS 24501 f30] 9.11.2.8 S-NSSAI + // s-nssai(LV) consists of + // len(1 byte) | SST(1) | SD(3,opt) | Mapped HPLMN SST (1,opt) | Mapped HPLMN SD (3,opt) + // The length of minimum s-nssai comprised of a length and a SST is 2 bytes. - guamiField := make([]byte, 1) - guamiField = append(guamiField, parameterValue...) - // Decode GUAMI using aper - ngapGUAMI := new(ngapType.GUAMI) - err = aper.UnmarshalWithParams(guamiField, ngapGUAMI, "valueExt") - if err != nil { - logger.NgapLog.Errorf("APER unmarshal with parameter failed: %+v", err) - return nil, nil, errors.New("Unmarshal failed when decoding GUAMI") - } - anParameters.GUAMI = ngapGUAMI - logger.NgapLog.Debugf("Unmarshal GUAMI: % x", guamiField) - logger.NgapLog.Debugf("\tGUAMI: PLMNIdentity[% x], "+ - "AMFRegionID[% x], AMFSetID[% x], AMFPointer[% x]", - anParameters.GUAMI.PLMNIdentity, anParameters.GUAMI.AMFRegionID, - anParameters.GUAMI.AMFSetID, anParameters.GUAMI.AMFPointer) - } else { - logger.NgapLog.Warn("AN-Parameter GUAMI field empty") + for len(parameterValue) >= 2 { + snssaiLength := parameterValue[0] + snssaiValue := parameterValue[1:] + + if len(snssaiValue) < int(snssaiLength) { + ngapLog.Error("SNSSAI length error") + return nil, nil, errors.New("Error formatting") } - case ANParametersTypeSelectedPLMNID: - logger.NgapLog.Debugf("-> Parameter type: ANParametersTypeSelectedPLMNID") - if parameterLength != 0 { - parameterValue := anParameterField[2:] - - if len(parameterValue) < int(parameterLength) { - return nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } + snssaiValue = snssaiValue[:snssaiLength] - if len(parameterValue) != ANParametersLenPLMNID { - return nil, nil, errors.New("Unmatched PLMN ID length") - } + ngapSNSSAIItem := ngapType.AllowedNSSAIItem{} - plmnField := make([]byte, 1) - plmnField = append(plmnField, parameterValue...) - // Decode PLMN using aper - ngapPLMN := new(ngapType.PLMNIdentity) - err = aper.UnmarshalWithParams(plmnField, ngapPLMN, "valueExt") - if err != nil { - logger.NgapLog.Errorf("APER unmarshal with parameter failed: %v", err) - return nil, nil, errors.New("Unmarshal failed when decoding PLMN") + if len(snssaiValue) == 1 { + ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ + SST: ngapType.SST{ + Value: []byte{snssaiValue[0]}, + }, + } + } else if len(snssaiValue) == 4 { + ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ + SST: ngapType.SST{ + Value: []byte{snssaiValue[0]}, + }, + SD: &ngapType.SD{ + Value: []byte{snssaiValue[1], snssaiValue[2], snssaiValue[3]}, + }, } - anParameters.SelectedPLMNID = ngapPLMN - logger.NgapLog.Debugf("Unmarshal SelectedPLMNID: % x", plmnField) - logger.NgapLog.Debugf("\tSelectedPLMNID: % x", anParameters.SelectedPLMNID.Value) } else { - logger.NgapLog.Warn("AN-Parameter PLMN field empty") + ngapLog.Error("Empty SNSSAI value") + return nil, nil, errors.New("Error formatting") } - case ANParametersTypeRequestedNSSAI: - logger.NgapLog.Debugf("-> Parameter type: ANParametersTypeRequestedNSSAI") - if parameterLength != 0 { - parameterValue := anParameterField[2:] - - if len(parameterValue) < int(parameterLength) { - return nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } - ngapNSSAI := new(ngapType.AllowedNSSAI) - - // [TS 24501 f30] 9.11.2.8 S-NSSAI - // s-nssai(LV) consists of - // len(1 byte) | SST(1) | SD(3,opt) | Mapped HPLMN SST (1,opt) | Mapped HPLMN SD (3,opt) - // The length of minimum s-nssai comprised of a length and a SST is 2 bytes. - - for len(parameterValue) >= 2 { - snssaiLength := parameterValue[0] - snssaiValue := parameterValue[1:] - - if len(snssaiValue) < int(snssaiLength) { - logger.NgapLog.Error("SNSSAI length error") - return nil, nil, errors.New("Error formatting") - } else { - snssaiValue = snssaiValue[:snssaiLength] - } - - ngapSNSSAIItem := ngapType.AllowedNSSAIItem{} - - if len(snssaiValue) == 1 { - ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ - SST: ngapType.SST{ - Value: []byte{snssaiValue[0]}, - }, - } - } else if len(snssaiValue) == 4 { - ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ - SST: ngapType.SST{ - Value: []byte{snssaiValue[0]}, - }, - SD: &ngapType.SD{ - Value: []byte{snssaiValue[1], snssaiValue[2], snssaiValue[3]}, - }, - } - } else { - logger.NgapLog.Error("Empty SNSSAI value") - return nil, nil, errors.New("Error formatting") - } - - ngapNSSAI.List = append(ngapNSSAI.List, ngapSNSSAIItem) - - logger.NgapLog.Debugf("Unmarshal SNSSAI: % x", parameterValue[:1+snssaiLength]) - logger.NgapLog.Debugf("\t\t\tSST: % x", ngapSNSSAIItem.SNSSAI.SST.Value) - sd := ngapSNSSAIItem.SNSSAI.SD - if sd == nil { - logger.NgapLog.Debugf("\t\t\tSD: nil") - } else { - logger.NgapLog.Debugf("\t\t\tSD: % x", sd.Value) - } - - // shift parameterValue for parsing next s-nssai - parameterValue = parameterValue[1+snssaiLength:] - } - anParameters.RequestedNSSAI = ngapNSSAI + ngapNSSAI.List = append(ngapNSSAI.List, ngapSNSSAIItem) + + ngapLog.Debugf("Unmarshal SNSSAI: % x", parameterValue[:1+snssaiLength]) + ngapLog.Debugf("\t\t\tSST: % x", ngapSNSSAIItem.SNSSAI.SST.Value) + sd := ngapSNSSAIItem.SNSSAI.SD + if sd == nil { + ngapLog.Debugf("\t\t\tSD: nil") } else { - logger.NgapLog.Warn("AN-Parameter NSSAI is empty") + ngapLog.Debugf("\t\t\tSD: % x", sd.Value) } - case ANParametersTypeEstablishmentCause: - logger.NgapLog.Debugf("-> Parameter type: ANParametersTypeEstablishmentCause") - if parameterLength != 0 { - parameterValue := anParameterField[2:] - - if len(parameterValue) < int(parameterLength) { - return nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } - if len(parameterValue) != ANParametersLenEstCause { - return nil, nil, errors.New("Unmatched Establishment Cause length") - } + // shift parameterValue for parsing next s-nssai + parameterValue = parameterValue[1+snssaiLength:] + } + anParameters.RequestedNSSAI = ngapNSSAI + } else { + ngapLog.Warn("AN-Parameter NSSAI is empty") + } + case ANParametersTypeEstablishmentCause: + ngapLog.Debugf("-> Parameter type: ANParametersTypeEstablishmentCause") + if parameterLength != 0 { + parameterValue := anParameterField[2:] - logger.NgapLog.Debugf("Unmarshal ANParametersTypeEstablishmentCause: % x", parameterValue) - - establishmentCause := parameterValue[0] & 0x0f - switch establishmentCause { - case EstablishmentCauseEmergency: - logger.NgapLog.Trace("AN-Parameter establishment cause: Emergency") - case EstablishmentCauseHighPriorityAccess: - logger.NgapLog.Trace("AN-Parameter establishment cause: High Priority Access") - case EstablishmentCauseMO_Signalling: - logger.NgapLog.Trace("AN-Parameter establishment cause: MO Signalling") - case EstablishmentCauseMO_Data: - logger.NgapLog.Trace("AN-Parameter establishment cause: MO Data") - case EstablishmentCauseMPS_PriorityAccess: - logger.NgapLog.Trace("AN-Parameter establishment cause: MPS Priority Access") - case EstablishmentCauseMCS_PriorityAccess: - logger.NgapLog.Trace("AN-Parameter establishment cause: MCS Priority Access") - default: - logger.NgapLog.Trace("AN-Parameter establishment cause: Unknown. Treat as mo-Data") - establishmentCause = EstablishmentCauseMO_Data - } + if len(parameterValue) < int(parameterLength) { + return nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - ngapEstablishmentCause := new(ngapType.RRCEstablishmentCause) - ngapEstablishmentCause.Value = aper.Enumerated(establishmentCause) + if len(parameterValue) != ANParametersLenEstCause { + return nil, nil, errors.New("Unmatched Establishment Cause length") + } - anParameters.EstablishmentCause = ngapEstablishmentCause - } else { - logger.NgapLog.Warn("AN-Parameter establishment cause field empty") - } + ngapLog.Debugf("Unmarshal ANParametersTypeEstablishmentCause: % x", parameterValue) + + establishmentCause := parameterValue[0] & 0x0f + switch establishmentCause { + case EstablishmentCauseEmergency: + ngapLog.Trace("AN-Parameter establishment cause: Emergency") + case EstablishmentCauseHighPriorityAccess: + ngapLog.Trace("AN-Parameter establishment cause: High Priority Access") + case EstablishmentCauseMO_Signalling: + ngapLog.Trace("AN-Parameter establishment cause: MO Signalling") + case EstablishmentCauseMO_Data: + ngapLog.Trace("AN-Parameter establishment cause: MO Data") + case EstablishmentCauseMPS_PriorityAccess: + ngapLog.Trace("AN-Parameter establishment cause: MPS Priority Access") + case EstablishmentCauseMCS_PriorityAccess: + ngapLog.Trace("AN-Parameter establishment cause: MCS Priority Access") default: - logger.NgapLog.Warn("Unsopprted AN-Parameter. Ignore.") + ngapLog.Trace("AN-Parameter establishment cause: Unknown. Treat as mo-Data") + establishmentCause = EstablishmentCauseMO_Data } - // shift anParameterField - anParameterField = anParameterField[2+parameterLength:] + ngapEstablishmentCause := new(ngapType.RRCEstablishmentCause) + ngapEstablishmentCause.Value = aper.Enumerated(establishmentCause) + + anParameters.EstablishmentCause = ngapEstablishmentCause + } else { + ngapLog.Warn("AN-Parameter establishment cause field empty") } + default: + ngapLog.Warn("Unsopprted AN-Parameter. Ignore.") } - // shift codedData - codedData = codedData[2+anParameterLength:] - } else { - logger.NgapLog.Error("No AN-Parameter type or length specified") - return nil, nil, errors.New("Error formatting") + // shift anParameterField + anParameterField = anParameterField[2+parameterLength:] } + } - if len(codedData) >= 2 { - // Length of the NASPDU field - nasPDULength := binary.BigEndian.Uint16(codedData[:2]) - logger.NgapLog.Debugf("nasPDULength: %d", nasPDULength) - - if nasPDULength != 0 { - nasPDUField := codedData[2:] - - // Bound checking - if len(nasPDUField) < int(nasPDULength) { - return nil, nil, errors.New("Error formatting") - } else { - nasPDUField = nasPDUField[:nasPDULength] - } + // shift codedData + codedData = codedData[2+anParameterLength:] - logger.NgapLog.Debugf("nasPDUField: % v", nasPDUField) + if len(codedData) > 2 { + ngapLog.Error("No NASPDU length specified") + return nil, nil, errors.New("Error formatting") + } + // Length of the NASPDU field + nasPDULength := binary.BigEndian.Uint16(codedData[:2]) + ngapLog.Debugf("nasPDULength: %d", nasPDULength) - nasPDU = append(nasPDU, nasPDUField...) - } else { - logger.NgapLog.Error("No NAS PDU included in EAP-5G packet") - return nil, nil, errors.New("No NAS PDU") - } - } else { - logger.NgapLog.Error("No NASPDU length specified") - return nil, nil, errors.New("Error formatting") - } + if nasPDULength == 0 { + ngapLog.Error("No NAS PDU included in EAP-5G packet") + return nil, nil, errors.New("No NAS PDU") + } - return anParameters, nasPDU, err + nasPDUField := codedData[2:] + // Bound checking + if len(nasPDUField) < int(nasPDULength) { + return nil, nil, errors.New("Error formatting") } else { - return nil, nil, errors.New("No data to decode") + nasPDUField = nasPDUField[:nasPDULength] } + ngapLog.Debugf("nasPDUField: % v", nasPDUField) + + nasPDU = append(nasPDU, nasPDUField...) + return anParameters, nasPDU, err } diff --git a/internal/ngap/message/build.go b/internal/ngap/message/build.go index 4e049b3f..97668fe3 100644 --- a/internal/ngap/message/build.go +++ b/internal/ngap/message/build.go @@ -65,13 +65,14 @@ func BuildNGSetupRequest() ([]byte, error) { supportedTAList := ie.Value.SupportedTAList + ngapLog := logger.NgapLog for _, supportedTAItemLocal := range n3iwfSelf.NFInfo.SupportedTAList { // SupportedTAItem in SupportedTAList supportedTAItem := ngapType.SupportedTAItem{} var err error supportedTAItem.TAC.Value, err = hex.DecodeString(supportedTAItemLocal.TAC) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } broadcastPLMNList := &supportedTAItem.BroadcastPLMNList @@ -88,14 +89,14 @@ func BuildNGSetupRequest() ([]byte, error) { sliceSupportItem := ngapType.SliceSupportItem{} sliceSupportItem.SNSSAI.SST.Value, err = hex.DecodeString(sliceSupportItemLocal.SNSSAI.SST) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } if sliceSupportItemLocal.SNSSAI.SD != "" { sliceSupportItem.SNSSAI.SD = new(ngapType.SD) sliceSupportItem.SNSSAI.SD.Value, err = hex.DecodeString(sliceSupportItemLocal.SNSSAI.SD) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } } @@ -655,6 +656,8 @@ func BuildUEContextReleaseRequest(ranUe *context.N3IWFRanUe, cause ngapType.Caus func BuildInitialUEMessage(ranUe *context.N3IWFRanUe, nasPdu []byte, allowedNSSAI *ngapType.AllowedNSSAI, ) ([]byte, error) { + ngapLog := logger.NgapLog + var pdu ngapType.NGAPPDU pdu.Present = ngapType.NGAPPDUPresentInitiatingMessage pdu.InitiatingMessage = new(ngapType.InitiatingMessage) @@ -749,7 +752,7 @@ func BuildInitialUEMessage(ranUe *context.N3IWFRanUe, nasPdu []byte, var err error fiveGSTMSI.FiveGTMSI.Value, err = hex.DecodeString(tmsi) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } initialUEMessageIEs.List = append(initialUEMessageIEs.List, ie) } @@ -1613,6 +1616,8 @@ func BuildAMFConfigurationUpdateFailure( } func BuildRANConfigurationUpdate() ([]byte, error) { + ngapLog := logger.NgapLog + var pdu ngapType.NGAPPDU pdu.Present = ngapType.NGAPPDUPresentInitiatingMessage pdu.InitiatingMessage = new(ngapType.InitiatingMessage) @@ -1658,7 +1663,7 @@ func BuildRANConfigurationUpdate() ([]byte, error) { var err error supportedTAItem.TAC.Value, err = hex.DecodeString(supportedTAItemLocal.TAC) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } broadcastPLMNList := &supportedTAItem.BroadcastPLMNList @@ -1675,14 +1680,14 @@ func BuildRANConfigurationUpdate() ([]byte, error) { sliceSupportItem := ngapType.SliceSupportItem{} sliceSupportItem.SNSSAI.SST.Value, err = hex.DecodeString(sliceSupportItemLocal.SNSSAI.SST) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } if sliceSupportItemLocal.SNSSAI.SD != "" { sliceSupportItem.SNSSAI.SD = new(ngapType.SD) sliceSupportItem.SNSSAI.SD.Value, err = hex.DecodeString(sliceSupportItemLocal.SNSSAI.SD) if err != nil { - logger.NgapLog.Errorf("DecodeString error: %+v", err) + ngapLog.Errorf("DecodeString error: %+v", err) } } diff --git a/internal/ngap/message/send.go b/internal/ngap/message/send.go index 91ebbd88..7dfddeba 100644 --- a/internal/ngap/message/send.go +++ b/internal/ngap/message/send.go @@ -10,45 +10,47 @@ import ( ) func SendToAmf(amf *context.N3IWFAMF, pkt []byte) { + ngapLog := logger.NgapLog if amf == nil { - logger.NgapLog.Errorf("[N3IWF] AMF Context is nil ") + ngapLog.Errorf("[N3IWF] AMF Context is nil ") } else { if n, err := amf.SCTPConn.Write(pkt); err != nil { - logger.NgapLog.Errorf("Write to SCTP socket failed: %+v", err) + ngapLog.Errorf("Write to SCTP socket failed: %+v", err) } else { - logger.NgapLog.Tracef("Wrote %d bytes", n) + ngapLog.Tracef("Wrote %d bytes", n) } } } func SendNGSetupRequest(conn *sctp.SCTPConn) { + ngapLog := logger.NgapLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NgapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ngapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } }() - logger.NgapLog.Infoln("[N3IWF] Send NG Setup Request") + ngapLog.Infoln("[N3IWF] Send NG Setup Request") sctpAddr := conn.RemoteAddr().String() if available, _ := context.N3IWFSelf().AMFReInitAvailableListLoad(sctpAddr); !available { - logger.NgapLog.Warnf( + ngapLog.Warnf( "[N3IWF] Please Wait at least for the indicated time before reinitiating toward same AMF[%s]", sctpAddr) return } pkt, err := BuildNGSetupRequest() if err != nil { - logger.NgapLog.Errorf("Build NGSetup Request failed: %+v\n", err) + ngapLog.Errorf("Build NGSetup Request failed: %+v\n", err) return } if n, err := conn.Write(pkt); err != nil { - logger.NgapLog.Errorf("Write to SCTP socket failed: %+v", err) + ngapLog.Errorf("Write to SCTP socket failed: %+v", err) } else { - logger.NgapLog.Tracef("Wrote %d bytes", n) + ngapLog.Tracef("Wrote %d bytes", n) } } @@ -58,11 +60,12 @@ func SendNGReset( cause ngapType.Cause, partOfNGInterface *ngapType.UEAssociatedLogicalNGConnectionList, ) { - logger.NgapLog.Infoln("[N3IWF] Send NG Reset") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send NG Reset") pkt, err := BuildNGReset(cause, partOfNGInterface) if err != nil { - logger.NgapLog.Errorf("Build NGReset failed : %s", err.Error()) + ngapLog.Errorf("Build NGReset failed : %s", err.Error()) return } @@ -74,16 +77,17 @@ func SendNGResetAcknowledge( partOfNGInterface *ngapType.UEAssociatedLogicalNGConnectionList, diagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send NG Reset Acknowledge") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send NG Reset Acknowledge") if partOfNGInterface != nil && len(partOfNGInterface.List) == 0 { - logger.NgapLog.Error("length of partOfNGInterface is 0") + ngapLog.Error("length of partOfNGInterface is 0") return } pkt, err := BuildNGResetAcknowledge(partOfNGInterface, diagnostics) if err != nil { - logger.NgapLog.Errorf("Build NGReset Acknowledge failed : %s", err.Error()) + ngapLog.Errorf("Build NGReset Acknowledge failed : %s", err.Error()) return } @@ -96,21 +100,22 @@ func SendInitialContextSetupResponse( failedList *ngapType.PDUSessionResourceFailedToSetupListCxtRes, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send Initial Context Setup Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Initial Context Setup Response") if responseList != nil && len(responseList.List) > context.MaxNumOfPDUSessions { - logger.NgapLog.Errorln("Pdu List out of range") + ngapLog.Errorln("Pdu List out of range") return } if failedList != nil && len(failedList.List) > context.MaxNumOfPDUSessions { - logger.NgapLog.Errorln("Pdu List out of range") + ngapLog.Errorln("Pdu List out of range") return } pkt, err := BuildInitialContextSetupResponse(ranUe, responseList, failedList, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build Initial Context Setup Response failed : %+v\n", err) + ngapLog.Errorf("Build Initial Context Setup Response failed : %+v\n", err) return } @@ -123,16 +128,17 @@ func SendInitialContextSetupFailure( failedList *ngapType.PDUSessionResourceFailedToSetupListCxtFail, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send Initial Context Setup Failure") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Initial Context Setup Failure") if failedList != nil && len(failedList.List) > context.MaxNumOfPDUSessions { - logger.NgapLog.Errorln("Pdu List out of range") + ngapLog.Errorln("Pdu List out of range") return } pkt, err := BuildInitialContextSetupFailure(ranUe, cause, failedList, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build Initial Context Setup Failure failed : %+v\n", err) + ngapLog.Errorf("Build Initial Context Setup Failure failed : %+v\n", err) return } @@ -143,11 +149,12 @@ func SendUEContextModificationResponse( ranUe *context.N3IWFRanUe, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send UE Context Modification Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send UE Context Modification Response") pkt, err := BuildUEContextModificationResponse(ranUe, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build UE Context Modification Response failed : %+v\n", err) + ngapLog.Errorf("Build UE Context Modification Response failed : %+v\n", err) return } @@ -159,11 +166,12 @@ func SendUEContextModificationFailure( cause ngapType.Cause, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send UE Context Modification Failure") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send UE Context Modification Failure") pkt, err := BuildUEContextModificationFailure(ranUe, cause, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build UE Context Modification Failure failed : %+v\n", err) + ngapLog.Errorf("Build UE Context Modification Failure failed : %+v\n", err) return } @@ -174,11 +182,12 @@ func SendUEContextReleaseComplete( ranUe *context.N3IWFRanUe, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send UE Context Release Complete") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send UE Context Release Complete") pkt, err := BuildUEContextReleaseComplete(ranUe, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build UE Context Release Complete failed : %+v\n", err) + ngapLog.Errorf("Build UE Context Release Complete failed : %+v\n", err) return } @@ -188,11 +197,12 @@ func SendUEContextReleaseComplete( func SendUEContextReleaseRequest( ranUe *context.N3IWFRanUe, cause ngapType.Cause, ) { - logger.NgapLog.Infoln("[N3IWF] Send UE Context Release Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send UE Context Release Request") pkt, err := BuildUEContextReleaseRequest(ranUe, cause) if err != nil { - logger.NgapLog.Errorf("Build UE Context Release Request failed : %+v\n", err) + ngapLog.Errorf("Build UE Context Release Request failed : %+v\n", err) return } @@ -202,12 +212,13 @@ func SendUEContextReleaseRequest( func SendInitialUEMessage(amf *context.N3IWFAMF, ranUe *context.N3IWFRanUe, nasPdu []byte, ) { - logger.NgapLog.Infoln("[N3IWF] Send Initial UE Message") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Initial UE Message") // Attach To AMF pkt, err := BuildInitialUEMessage(ranUe, nasPdu, nil) if err != nil { - logger.NgapLog.Errorf("Build Initial UE Message failed : %+v\n", err) + ngapLog.Errorf("Build Initial UE Message failed : %+v\n", err) return } @@ -219,16 +230,17 @@ func SendUplinkNASTransport( ranUe *context.N3IWFRanUe, nasPdu []byte, ) { - logger.NgapLog.Infoln("[N3IWF] Send Uplink NAS Transport") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Uplink NAS Transport") if len(nasPdu) == 0 { - logger.NgapLog.Errorln("NAS Pdu is nil") + ngapLog.Errorln("NAS Pdu is nil") return } pkt, err := BuildUplinkNASTransport(ranUe, nasPdu) if err != nil { - logger.NgapLog.Errorf("Build Uplink NAS Transport failed : %+v\n", err) + ngapLog.Errorf("Build Uplink NAS Transport failed : %+v\n", err) return } @@ -240,16 +252,17 @@ func SendNASNonDeliveryIndication( nasPdu []byte, cause ngapType.Cause, ) { - logger.NgapLog.Infoln("[N3IWF] Send NAS NonDelivery Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send NAS NonDelivery Indication") if len(nasPdu) == 0 { - logger.NgapLog.Errorln("NAS Pdu is nil") + ngapLog.Errorln("NAS Pdu is nil") return } pkt, err := BuildNASNonDeliveryIndication(ranUe, nasPdu, cause) if err != nil { - logger.NgapLog.Errorf("Build Uplink NAS Transport failed : %+v\n", err) + ngapLog.Errorf("Build Uplink NAS Transport failed : %+v\n", err) return } @@ -257,7 +270,8 @@ func SendNASNonDeliveryIndication( } func SendRerouteNASRequest() { - logger.NgapLog.Infoln("[N3IWF] Send Reroute NAS Request") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Reroute NAS Request") } func SendPDUSessionResourceSetupResponse( @@ -266,16 +280,17 @@ func SendPDUSessionResourceSetupResponse( failedListSURes *ngapType.PDUSessionResourceFailedToSetupListSURes, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send PDU Session Resource Setup Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send PDU Session Resource Setup Response") if ranUe == nil { - logger.NgapLog.Error("UE context is nil, this information is mandatory.") + ngapLog.Error("UE context is nil, this information is mandatory.") return } pkt, err := BuildPDUSessionResourceSetupResponse(ranUe, responseList, failedListSURes, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build PDU Session Resource Setup Response failed : %+v", err) + ngapLog.Errorf("Build PDU Session Resource Setup Response failed : %+v", err) return } @@ -288,16 +303,17 @@ func SendPDUSessionResourceModifyResponse( failedList *ngapType.PDUSessionResourceFailedToModifyListModRes, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send PDU Session Resource Modify Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send PDU Session Resource Modify Response") if ranUe == nil && criticalityDiagnostics == nil { - logger.NgapLog.Error("UE context is nil, this information is mandatory") + ngapLog.Error("UE context is nil, this information is mandatory") return } pkt, err := BuildPDUSessionResourceModifyResponse(ranUe, responseList, failedList, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build PDU Session Resource Modify Response failed : %+v", err) + ngapLog.Errorf("Build PDU Session Resource Modify Response failed : %+v", err) return } @@ -308,21 +324,22 @@ func SendPDUSessionResourceModifyIndication( ranUe *context.N3IWFRanUe, modifyList []ngapType.PDUSessionResourceModifyItemModInd, ) { - logger.NgapLog.Infoln("[N3IWF] Send PDU Session Resource Modify Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send PDU Session Resource Modify Indication") if ranUe == nil { - logger.NgapLog.Error("UE context is nil, this information is mandatory") + ngapLog.Error("UE context is nil, this information is mandatory") return } if modifyList == nil { - logger.NgapLog.Errorln( + ngapLog.Errorln( "PDU Session Resource Modify Indication List is nil. This message shall contain at least one Item") return } pkt, err := BuildPDUSessionResourceModifyIndication(ranUe, modifyList) if err != nil { - logger.NgapLog.Errorf("Build PDU Session Resource Modify Indication failed : %+v", err) + ngapLog.Errorf("Build PDU Session Resource Modify Indication failed : %+v", err) return } @@ -334,16 +351,17 @@ func SendPDUSessionResourceNotify( notiList *ngapType.PDUSessionResourceNotifyList, relList *ngapType.PDUSessionResourceReleasedListNot, ) { - logger.NgapLog.Infoln("[N3IWF] Send PDU Session Resource Notify") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send PDU Session Resource Notify") if ranUe == nil { - logger.NgapLog.Error("UE context is nil, this information is mandatory") + ngapLog.Error("UE context is nil, this information is mandatory") return } pkt, err := BuildPDUSessionResourceNotify(ranUe, notiList, relList) if err != nil { - logger.NgapLog.Errorf("Build PDUSession Resource Notify failed : %+v", err) + ngapLog.Errorf("Build PDUSession Resource Notify failed : %+v", err) return } @@ -355,21 +373,22 @@ func SendPDUSessionResourceReleaseResponse( relList ngapType.PDUSessionResourceReleasedListRelRes, diagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send PDU Session Resource Release Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send PDU Session Resource Release Response") if ranUe == nil { - logger.NgapLog.Error("UE context is nil, this information is mandatory") + ngapLog.Error("UE context is nil, this information is mandatory") return } if len(relList.List) < 1 { - logger.NgapLog.Errorln( + ngapLog.Errorln( "PDUSessionResourceReleasedListRelRes is nil. This message shall contain at least one Item") return } pkt, err := BuildPDUSessionResourceReleaseResponse(ranUe, relList, diagnostics) if err != nil { - logger.NgapLog.Errorf("Build PDU Session Resource Release Response failed : %+v", err) + ngapLog.Errorf("Build PDU Session Resource Release Response failed : %+v", err) return } @@ -383,16 +402,17 @@ func SendErrorIndication( cause *ngapType.Cause, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send Error Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Error Indication") if (cause == nil) && (criticalityDiagnostics == nil) { - logger.NgapLog.Errorln("Both cause and criticality is nil. This message shall contain at least one of them.") + ngapLog.Errorln("Both cause and criticality is nil. This message shall contain at least one of them.") return } pkt, err := BuildErrorIndication(amfUENGAPID, ranUENGAPID, cause, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build Error Indication failed : %+v\n", err) + ngapLog.Errorf("Build Error Indication failed : %+v\n", err) return } @@ -406,28 +426,30 @@ func SendErrorIndicationWithSctpConn( cause *ngapType.Cause, criticalityDiagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send Error Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Error Indication") if (cause == nil) && (criticalityDiagnostics == nil) { - logger.NgapLog.Errorln("Both cause and criticality is nil. This message shall contain at least one of them.") + ngapLog.Errorln("Both cause and criticality is nil. This message shall contain at least one of them.") return } pkt, err := BuildErrorIndication(amfUENGAPID, ranUENGAPID, cause, criticalityDiagnostics) if err != nil { - logger.NgapLog.Errorf("Build Error Indication failed : %+v\n", err) + ngapLog.Errorf("Build Error Indication failed : %+v\n", err) return } if n, err := sctpConn.Write(pkt); err != nil { - logger.NgapLog.Errorf("Write to SCTP socket failed: %+v", err) + ngapLog.Errorf("Write to SCTP socket failed: %+v", err) } else { - logger.NgapLog.Tracef("Wrote %d bytes", n) + ngapLog.Tracef("Wrote %d bytes", n) } } func SendUERadioCapabilityInfoIndication() { - logger.NgapLog.Infoln("[N3IWF] Send UE Radio Capability Info Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send UE Radio Capability Info Indication") } func SendUERadioCapabilityCheckResponse( @@ -435,11 +457,12 @@ func SendUERadioCapabilityCheckResponse( ranUe *context.N3IWFRanUe, diagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send UE Radio Capability Check Response") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send UE Radio Capability Check Response") pkt, err := BuildUERadioCapabilityCheckResponse(ranUe, diagnostics) if err != nil { - logger.NgapLog.Errorf("Build UERadio Capability Check Response failed : %+v\n", err) + ngapLog.Errorf("Build UERadio Capability Check Response failed : %+v\n", err) return } SendToAmf(ranUe.AMF, pkt) @@ -451,11 +474,12 @@ func SendAMFConfigurationUpdateAcknowledge( failList *ngapType.TNLAssociationList, diagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send AMF Configuration Update Acknowledge") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send AMF Configuration Update Acknowledge") pkt, err := BuildAMFConfigurationUpdateAcknowledge(setupList, failList, diagnostics) if err != nil { - logger.NgapLog.Errorf("Build AMF Configuration Update Acknowledge failed : %+v\n", err) + ngapLog.Errorf("Build AMF Configuration Update Acknowledge failed : %+v\n", err) return } @@ -468,10 +492,11 @@ func SendAMFConfigurationUpdateFailure( time *ngapType.TimeToWait, diagnostics *ngapType.CriticalityDiagnostics, ) { - logger.NgapLog.Infoln("[N3IWF] Send AMF Configuration Update Failure") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send AMF Configuration Update Failure") pkt, err := BuildAMFConfigurationUpdateFailure(ngCause, time, diagnostics) if err != nil { - logger.NgapLog.Errorf("Build AMF Configuration Update Failure failed : %+v\n", err) + ngapLog.Errorf("Build AMF Configuration Update Failure failed : %+v\n", err) return } @@ -479,10 +504,11 @@ func SendAMFConfigurationUpdateFailure( } func SendRANConfigurationUpdate(amf *context.N3IWFAMF) { - logger.NgapLog.Infoln("[N3IWF] Send RAN Configuration Update") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send RAN Configuration Update") if available, _ := context.N3IWFSelf().AMFReInitAvailableListLoad(amf.SCTPAddr); !available { - logger.NgapLog.Warnf( + ngapLog.Warnf( "[N3IWF] Please Wait at least for the indicated time before reinitiating toward same AMF[%s]", amf.SCTPAddr) return @@ -490,7 +516,7 @@ func SendRANConfigurationUpdate(amf *context.N3IWFAMF) { pkt, err := BuildRANConfigurationUpdate() if err != nil { - logger.NgapLog.Errorf("Build AMF Configuration Update Failure failed : %+v\n", err) + ngapLog.Errorf("Build AMF Configuration Update Failure failed : %+v\n", err) return } @@ -498,21 +524,26 @@ func SendRANConfigurationUpdate(amf *context.N3IWFAMF) { } func SendUplinkRANConfigurationTransfer() { - logger.NgapLog.Infoln("[N3IWF] Send Uplink RAN Configuration Transfer") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Uplink RAN Configuration Transfer") } func SendUplinkRANStatusTransfer() { - logger.NgapLog.Infoln("[N3IWF] Send Uplink RAN Status Transfer") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Uplink RAN Status Transfer") } func SendLocationReportingFailureIndication() { - logger.NgapLog.Infoln("[N3IWF] Send Location Reporting Failure Indication") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Location Reporting Failure Indication") } func SendLocationReport() { - logger.NgapLog.Infoln("[N3IWF] Send Location Report") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send Location Report") } func SendRRCInactiveTransitionReport() { - logger.NgapLog.Infoln("[N3IWF] Send RRC Inactive Transition Report") + ngapLog := logger.NgapLog + ngapLog.Infoln("[N3IWF] Send RRC Inactive Transition Report") } diff --git a/internal/ngap/service/service.go b/internal/ngap/service/service.go index b6b53a24..8d33a495 100644 --- a/internal/ngap/service/service.go +++ b/internal/ngap/service/service.go @@ -23,6 +23,8 @@ var ( // Run start the N3IWF SCTP process. func Run(wg *sync.WaitGroup) error { + ngapLog := logger.NgapLog + // n3iwf context n3iwfSelf := context.N3IWFSelf() // load amf SCTP address slice @@ -36,7 +38,7 @@ func Run(wg *sync.WaitGroup) error { wg.Add(1) go Receiver(localAddr, remoteAddr, errChan, n3iwfSelf.NGAPServer, wg) if err, ok := <-errChan; ok { - logger.NgapLog.Errorln(err) + ngapLog.Errorln(err) return errors.New("NGAP service run failed") } } @@ -55,12 +57,13 @@ func NewNGAPServer() *context.NGAPServer { } func server(ngapServer *context.NGAPServer, wg *sync.WaitGroup) { + ngapLog := logger.NgapLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NgapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ngapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } - logger.NgapLog.Infof("NGAP server stopped") + ngapLog.Infof("NGAP server stopped") close(ngapServer.RcvEventCh) close(ngapServer.RcvNgapPktCh) wg.Done() @@ -82,12 +85,13 @@ func server(ngapServer *context.NGAPServer, wg *sync.WaitGroup) { func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapServer *context.NGAPServer, wg *sync.WaitGroup, ) { + ngapLog := logger.NgapLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NgapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ngapLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } - logger.NgapLog.Infof("NGAP receiver stopped") + ngapLog.Infof("NGAP receiver stopped") wg.Done() }() @@ -97,16 +101,16 @@ func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapSe for i := 0; i < 3; i++ { conn, err = sctp.DialSCTP("sctp", localAddr, remoteAddr) if err != nil { - logger.NgapLog.Errorf("[SCTP] DialSCTP(): %+v", err) + ngapLog.Errorf("[SCTP] DialSCTP(): %+v", err) } else { break } if i != 2 { - logger.NgapLog.Info("Retry to connect AMF after 1 second...") + ngapLog.Info("Retry to connect AMF after 1 second...") time.Sleep(1 * time.Second) } else { - logger.NgapLog.Debugf("[SCTP] AMF SCTP address: %s", remoteAddr) + ngapLog.Debugf("[SCTP] AMF SCTP address: %s", remoteAddr) errChan <- errors.New("Failed to connect to AMF.") return } @@ -115,10 +119,10 @@ func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapSe // Set default sender SCTP information sinfo_ppid = NGAP_PPID = 60 info, err := conn.GetDefaultSentParam() if err != nil { - logger.NgapLog.Errorf("[SCTP] GetDefaultSentParam(): %+v", err) + ngapLog.Errorf("[SCTP] GetDefaultSentParam(): %+v", err) errConn := conn.Close() if errConn != nil { - logger.NgapLog.Errorf("conn close error in GetDefaultSentParam(): %+v", errConn) + ngapLog.Errorf("conn close error in GetDefaultSentParam(): %+v", errConn) } errChan <- errors.New("Get socket information failed.") return @@ -126,10 +130,10 @@ func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapSe info.PPID = lib_ngap.PPID err = conn.SetDefaultSentParam(info) if err != nil { - logger.NgapLog.Errorf("[SCTP] SetDefaultSentParam(): %+v", err) + ngapLog.Errorf("[SCTP] SetDefaultSentParam(): %+v", err) errConn := conn.Close() if errConn != nil { - logger.NgapLog.Errorf("conn close error in SetDefaultSentParam(): %+v", errConn) + ngapLog.Errorf("conn close error in SetDefaultSentParam(): %+v", errConn) } errChan <- errors.New("Set socket parameter failed.") return @@ -138,10 +142,10 @@ func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapSe // Subscribe receiver SCTP information err = conn.SubscribeEvents(sctp.SCTP_EVENT_DATA_IO) if err != nil { - logger.NgapLog.Errorf("[SCTP] SubscribeEvents(): %+v", err) + ngapLog.Errorf("[SCTP] SubscribeEvents(): %+v", err) errConn := conn.Close() if errConn != nil { - logger.NgapLog.Errorf("conn close error in SubscribeEvents(): %+v", errConn) + ngapLog.Errorf("conn close error in SubscribeEvents(): %+v", errConn) } errChan <- errors.New("Subscribe SCTP event failed.") return @@ -159,22 +163,22 @@ func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapSe n, info, _, err := conn.SCTPRead(data) if err != nil { - logger.NgapLog.Debugf("[SCTP] AMF SCTP address: %s", remoteAddr) + ngapLog.Debugf("[SCTP] AMF SCTP address: %s", remoteAddr) if err == io.EOF || err == io.ErrUnexpectedEOF { - logger.NgapLog.Warn("[SCTP] Close connection.") + ngapLog.Warn("[SCTP] Close connection.") errConn := conn.Close() if errConn != nil { - logger.NgapLog.Errorf("conn close error: %+v", errConn) + ngapLog.Errorf("conn close error: %+v", errConn) } ngapServer.RcvNgapPktCh <- context.ReceiveNGAPPacket{} return } - logger.NgapLog.Errorf("[SCTP] Read from SCTP connection failed: %+v", err) + ngapLog.Errorf("[SCTP] Read from SCTP connection failed: %+v", err) } else { - logger.NgapLog.Tracef("[SCTP] Successfully read %d bytes.", n) + ngapLog.Tracef("[SCTP] Successfully read %d bytes.", n) if info == nil || info.PPID != lib_ngap.PPID { - logger.NgapLog.Warn("Received SCTP PPID != 60") + ngapLog.Warn("Received SCTP PPID != 60") continue } @@ -190,11 +194,12 @@ func Receiver(localAddr, remoteAddr *sctp.SCTPAddr, errChan chan<- error, ngapSe } func Stop(n3iwfContext *context.N3IWFContext) { - logger.NgapLog.Infof("Close NGAP server....") + ngapLog := logger.NgapLog + ngapLog.Infof("Close NGAP server....") for _, ngapServerConn := range n3iwfContext.NGAPServer.Conn { if err := ngapServerConn.Close(); err != nil { - logger.NgapLog.Errorf("Stop ngap server error : %+v", err) + ngapLog.Errorf("Stop ngap server error : %+v", err) } } } diff --git a/internal/nwucp/service/service.go b/internal/nwucp/service/service.go index 6fb8e3b5..17915922 100644 --- a/internal/nwucp/service/service.go +++ b/internal/nwucp/service/service.go @@ -20,19 +20,20 @@ var tcpListener net.Listener // Run setup N3IWF NAS for UE to forward NAS message // to AMF func Run(wg *sync.WaitGroup) error { + nwucpLog := logger.NWuCPLog // N3IWF context n3iwfSelf := context.N3IWFSelf() tcpAddr := fmt.Sprintf("%s:%d", n3iwfSelf.IPSecGatewayAddress, n3iwfSelf.TCPPort) listener, err := net.Listen("tcp", tcpAddr) if err != nil { - logger.NWuCPLog.Errorf("Listen TCP address failed: %+v", err) + nwucpLog.Errorf("Listen TCP address failed: %+v", err) return errors.New("Listen failed") } tcpListener = listener - logger.NWuCPLog.Tracef("Successfully listen %+v", tcpAddr) + nwucpLog.Tracef("Successfully listen %+v", tcpAddr) wg.Add(1) go listenAndServe(tcpListener, wg) @@ -45,15 +46,16 @@ func Run(wg *sync.WaitGroup) error { // context, and finally, call serveConn() to serve the messages // received from the connection. func listenAndServe(listener net.Listener, wg *sync.WaitGroup) { + nwucpLog := logger.NWuCPLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NWuCPLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + nwucpLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } err := tcpListener.Close() if err != nil { - logger.NWuCPLog.Errorf("Error closing tcpListener: %+v", err) + nwucpLog.Errorf("Error closing tcpListener: %+v", err) } wg.Done() }() @@ -61,11 +63,11 @@ func listenAndServe(listener net.Listener, wg *sync.WaitGroup) { for { connection, err := listener.Accept() if err != nil { - logger.NWuCPLog.Errorf("TCP server accept failed : %+v. Close the listener...", err) + nwucpLog.Errorf("TCP server accept failed : %+v. Close the listener...", err) return } - logger.NWuCPLog.Tracef("Accepted one UE from %+v", connection.RemoteAddr()) + nwucpLog.Tracef("Accepted one UE from %+v", connection.RemoteAddr()) // Find UE context and store this connection in to it, then check if // there is any cached NAS message for this UE. If yes, send to it. @@ -74,13 +76,13 @@ func listenAndServe(listener net.Listener, wg *sync.WaitGroup) { ueIP := strings.Split(connection.RemoteAddr().String(), ":")[0] ikeUe, ok := n3iwfSelf.AllocatedUEIPAddressLoad(ueIP) if !ok { - logger.NWuCPLog.Errorf("UE context not found for peer %+v", ueIP) + nwucpLog.Errorf("UE context not found for peer %+v", ueIP) continue } ranUe, err := n3iwfSelf.RanUeLoadFromIkeSPI(ikeUe.N3IWFIKESecurityAssociation.LocalSPI) if err != nil { - logger.NWuCPLog.Errorf("RanUe context not found : %+v", err) + nwucpLog.Errorf("RanUe context not found : %+v", err) continue } // Store connection @@ -111,10 +113,11 @@ func decapNasMsgFromEnvelope(envelop []byte) []byte { } func Stop(n3iwfContext *context.N3IWFContext) { - logger.NWuCPLog.Infof("Close Nwucp server...") + nwucpLog := logger.NWuCPLog + nwucpLog.Infof("Close Nwucp server...") if err := tcpListener.Close(); err != nil { - logger.NWuCPLog.Errorf("Stop nwuup server error : %+v", err) + nwucpLog.Errorf("Stop nwuup server error : %+v", err) } n3iwfContext.RANUePool.Range( @@ -133,15 +136,16 @@ func Stop(n3iwfContext *context.N3IWFContext) { // from the connection and call forward() to forward NAS messages // to AMF func serveConn(ranUe *context.N3IWFRanUe, connection net.Conn, wg *sync.WaitGroup) { + nwucpLog := logger.NWuCPLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NWuCPLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + nwucpLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } err := connection.Close() if err != nil { - logger.NWuCPLog.Errorf("Error closing connection: %+v", err) + nwucpLog.Errorf("Error closing connection: %+v", err) } wg.Done() }() @@ -150,11 +154,11 @@ func serveConn(ranUe *context.N3IWFRanUe, connection net.Conn, wg *sync.WaitGrou for { n, err := connection.Read(data) if err != nil { - logger.NWuCPLog.Errorf("Read TCP connection failed: %+v", err) + nwucpLog.Errorf("Read TCP connection failed: %+v", err) ranUe.TCPConnection = nil return } - logger.NWuCPLog.Tracef("Get NAS PDU from UE:\nNAS length: %d\nNAS content:\n%s", n, hex.Dump(data[:n])) + nwucpLog.Tracef("Get NAS PDU from UE:\nNAS length: %d\nNAS content:\n%s", n, hex.Dump(data[:n])) // Decap Nas envelope forwardData := decapNasMsgFromEnvelope(data) @@ -167,14 +171,15 @@ func serveConn(ranUe *context.N3IWFRanUe, connection net.Conn, wg *sync.WaitGrou // forward forwards NAS messages sent from UE to the // associated AMF func forward(ranUe *context.N3IWFRanUe, packet []byte, wg *sync.WaitGroup) { + nwucpLog := logger.NWuCPLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NWuCPLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + nwucpLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } wg.Done() }() - logger.NWuCPLog.Trace("Forward NWu -> N2") + nwucpLog.Trace("Forward NWu -> N2") message.SendUplinkNASTransport(ranUe, packet) } diff --git a/internal/nwuup/service/service.go b/internal/nwuup/service/service.go index 02f1727f..0ad54aab 100644 --- a/internal/nwuup/service/service.go +++ b/internal/nwuup/service/service.go @@ -20,6 +20,7 @@ import ( // with UP_IP_ADDRESS, catching GRE encapsulated packets and forward // to N3 interface. func Run(wg *sync.WaitGroup) error { + nwuupLog := logger.NWuUPLog // Local IPSec address n3iwfSelf := context.N3IWFSelf() listenAddr := n3iwfSelf.IPSecGatewayAddress @@ -28,12 +29,12 @@ func Run(wg *sync.WaitGroup) error { // This socket will only capture GRE encapsulated packet connection, err := net.ListenPacket("ip4:gre", listenAddr) if err != nil { - logger.NWuUPLog.Errorf("Error setting listen socket on %s: %+v", listenAddr, err) + nwuupLog.Errorf("Error setting listen socket on %s: %+v", listenAddr, err) return errors.New("ListenPacket failed") } ipv4PacketConn := ipv4.NewPacketConn(connection) - if err != nil { - logger.NWuUPLog.Errorf("Error opening IPv4 packet connection socket on %s: %+v", listenAddr, err) + if ipv4PacketConn != nil { + nwuupLog.Errorf("Error opening IPv4 packet connection socket on %s", listenAddr) return errors.New("NewPacketConn failed") } @@ -48,15 +49,16 @@ func Run(wg *sync.WaitGroup) error { // listenAndServe read from socket and call forward() to // forward packet. func listenAndServe(ipv4PacketConn *ipv4.PacketConn, wg *sync.WaitGroup) { + nwuupLog := logger.NWuUPLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NWuUPLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + nwuupLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } err := ipv4PacketConn.Close() if err != nil { - logger.NWuUPLog.Errorf("Error closing raw socket: %+v", err) + nwuupLog.Errorf("Error closing raw socket: %+v", err) } wg.Done() }() @@ -64,15 +66,15 @@ func listenAndServe(ipv4PacketConn *ipv4.PacketConn, wg *sync.WaitGroup) { buffer := make([]byte, 65535) if err := ipv4PacketConn.SetControlMessage(ipv4.FlagInterface|ipv4.FlagTTL, true); err != nil { - logger.NWuUPLog.Errorf("Set control message visibility for IPv4 packet connection fail: %+v", err) + nwuupLog.Errorf("Set control message visibility for IPv4 packet connection fail: %+v", err) return } for { n, cm, src, err := ipv4PacketConn.ReadFrom(buffer) - logger.NWuUPLog.Tracef("Read %d bytes, %s", n, cm) + nwuupLog.Tracef("Read %d bytes, %s", n, cm) if err != nil { - logger.NWuUPLog.Errorf("Error read from IPv4 packet connection: %+v", err) + nwuupLog.Errorf("Error read from IPv4 packet connection: %+v", err) return } @@ -87,10 +89,11 @@ func listenAndServe(ipv4PacketConn *ipv4.PacketConn, wg *sync.WaitGroup) { // forward forwards user plane packets from NWu to UPF // with GTP header encapsulated func forward(ueInnerIP string, ifIndex int, rawData []byte, wg *sync.WaitGroup) { + nwuupLog := logger.NWuUPLog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.NWuUPLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + nwuupLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } wg.Done() }() @@ -99,13 +102,13 @@ func forward(ueInnerIP string, ifIndex int, rawData []byte, wg *sync.WaitGroup) self := context.N3IWFSelf() ikeUe, ok := self.AllocatedUEIPAddressLoad(ueInnerIP) if !ok { - logger.NWuUPLog.Error("Ike UE context not found") + nwuupLog.Error("Ike UE context not found") return } ranUe, err := self.RanUeLoadFromIkeSPI(ikeUe.N3IWFIKESecurityAssociation.LocalSPI) if err != nil { - logger.NWuUPLog.Error("ranUe not found") + nwuupLog.Error("ranUe not found") return } @@ -121,7 +124,7 @@ func forward(ueInnerIP string, ifIndex int, rawData []byte, wg *sync.WaitGroup) } if pduSession == nil { - logger.NWuUPLog.Error("This UE doesn't have any available PDU session") + nwuupLog.Error("This UE doesn't have any available PDU session") return } @@ -132,7 +135,7 @@ func forward(ueInnerIP string, ifIndex int, rawData []byte, wg *sync.WaitGroup) // Decapsulate GRE header and extract QoS Parameters if exist grePacket := gre.GREPacket{} if err := grePacket.Unmarshal(rawData); err != nil { - logger.NWuUPLog.Errorf("gre Unmarshal err: %+v", err) + nwuupLog.Errorf("gre Unmarshal err: %+v", err) return } @@ -148,31 +151,30 @@ func forward(ueInnerIP string, ifIndex int, rawData []byte, wg *sync.WaitGroup) qfi := grePacket.GetQFI() gtpPacket, err := buildQoSGTPPacket(gtpConnection.OutgoingTEID, qfi, payload) if err != nil { - logger.NWuUPLog.Errorf("buildQoSGTPPacket err: %+v", err) + nwuupLog.Errorf("buildQoSGTPPacket err: %+v", err) return } n, writeErr = userPlaneConnection.WriteTo(gtpPacket, gtpConnection.UPFUDPAddr) } else { - logger.NWuUPLog.Warnf("Receive GRE header without key field specifying QFI and RQI.") + nwuupLog.Warnf("Receive GRE header without key field specifying QFI and RQI.") n, writeErr = userPlaneConnection.WriteToGTP(gtpConnection.OutgoingTEID, payload, gtpConnection.UPFUDPAddr) } if writeErr != nil { - logger.NWuUPLog.Errorf("Write to UPF failed: %+v", writeErr) + nwuupLog.Errorf("Write to UPF failed: %+v", writeErr) if writeErr == gtpv1.ErrConnNotOpened { - logger.NWuUPLog.Error("The connection has been closed") + nwuupLog.Error("The connection has been closed") // TODO: Release the GTP resource } return - } else { - logger.NWuUPLog.Trace("Forward NWu -> N3") - logger.NWuUPLog.Tracef("Wrote %d bytes", n) - return } + nwuupLog.Trace("Forward NWu -> N3") + nwuupLog.Tracef("Wrote %d bytes", n) } func buildQoSGTPPacket(teid uint32, qfi uint8, payload []byte) ([]byte, error) { + nwuupLog := logger.NWuUPLog header := gtpMsg.NewHeader(0x34, gtpMsg.MsgTypeTPDU, teid, 0x00, payload).WithExtensionHeaders( gtpMsg.NewExtensionHeader( gtpMsg.ExtHeaderTypePDUSessionContainer, @@ -184,7 +186,7 @@ func buildQoSGTPPacket(teid uint32, qfi uint8, payload []byte) ([]byte, error) { b := make([]byte, header.MarshalLen()) if err := header.MarshalTo(b); err != nil { - logger.NWuUPLog.Errorf("go-gtp MarshalTo err: %+v", err) + nwuupLog.Errorf("go-gtp MarshalTo err: %+v", err) return nil, err } @@ -192,9 +194,10 @@ func buildQoSGTPPacket(teid uint32, qfi uint8, payload []byte) ([]byte, error) { } func Stop(n3iwfContext *context.N3IWFContext) { - logger.NWuUPLog.Infof("Close Nwuup server...") + nwuupLog := logger.NWuUPLog + nwuupLog.Infof("Close Nwuup server...") if err := n3iwfContext.NWuIPv4PacketConn.Close(); err != nil { - logger.NWuUPLog.Errorf("Stop nwuup server error : %+v", err) + nwuupLog.Errorf("Stop nwuup server error : %+v", err) } } diff --git a/pkg/ike/dispatcher.go b/pkg/ike/dispatcher.go index a75bdfc3..34c543fe 100644 --- a/pkg/ike/dispatcher.go +++ b/pkg/ike/dispatcher.go @@ -10,10 +10,11 @@ import ( ) func IkeDispatch(udpConn *net.UDPConn, localAddr, remoteAddr *net.UDPAddr, msg []byte) { + ikeLog := logger.IKELog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.IKELog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ikeLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } }() @@ -22,7 +23,7 @@ func IkeDispatch(udpConn *net.UDPConn, localAddr, remoteAddr *net.UDPAddr, msg [ if localAddr.Port == 4500 { for i := 0; i < 4; i++ { if msg[i] != 0 { - logger.IKELog.Warn( + ikeLog.Warn( "Received an IKE packet that does not prepend 4 bytes zero from UDP port 4500," + " this packet may be the UDP encapsulated ESP. The packet will not be handled.") return @@ -35,7 +36,7 @@ func IkeDispatch(udpConn *net.UDPConn, localAddr, remoteAddr *net.UDPAddr, msg [ err := ikeMessage.Decode(msg) if err != nil { - logger.IKELog.Error(err) + ikeLog.Error(err) return } @@ -49,6 +50,6 @@ func IkeDispatch(udpConn *net.UDPConn, localAddr, remoteAddr *net.UDPAddr, msg [ case ike_message.INFORMATIONAL: handler.HandleInformational(udpConn, localAddr, remoteAddr, ikeMessage) default: - logger.IKELog.Warnf("Unimplemented IKE message type, exchange type: %d", ikeMessage.ExchangeType) + ikeLog.Warnf("Unimplemented IKE message type, exchange type: %d", ikeMessage.ExchangeType) } } diff --git a/pkg/ike/handler/3gpp_types.go b/pkg/ike/handler/3gpp_types.go index 637cf853..ae272851 100644 --- a/pkg/ike/handler/3gpp_types.go +++ b/pkg/ike/handler/3gpp_types.go @@ -21,268 +21,259 @@ type ANParameters struct { } func UnmarshalEAP5GData(codedData []byte) (eap5GMessageID uint8, anParameters *ANParameters, nasPDU []byte, err error) { - if len(codedData) >= 2 { - logger.IKELog.Debug("===== Unmarshal EAP5G Data (Ref: TS24.502 Fig. 9.3.2.2.2-1) =====") + ikeLog := logger.IKELog + if len(codedData) < 2 { + return 0, nil, nil, errors.New("No data to decode") + } + ikeLog.Debug("===== Unmarshal EAP5G Data (Ref: TS24.502 Fig. 9.3.2.2.2-1) =====") + + eap5GMessageID = codedData[0] + ikeLog.Debugf("Message-Id: %d", eap5GMessageID) + if eap5GMessageID == message.EAP5GType5GStop { + return eap5GMessageID, anParameters, nasPDU, err + } + + codedData = codedData[2:] - eap5GMessageID = codedData[0] - logger.IKELog.Debugf("Message-Id: %d", eap5GMessageID) - if eap5GMessageID == message.EAP5GType5GStop { - return eap5GMessageID, anParameters, nasPDU, err + // [TS 24.502 f30] 9.3.2.2.2.3 + // AN-parameter value field in GUAMI, PLMN ID and NSSAI is coded as value part + // Therefore, IEI of AN-parameter is not needed to be included. + // anParameter = AN-parameter Type | AN-parameter Length | Value part of IE + + if len(codedData) < 2 { + ikeLog.Error("No AN-Parameter type or length specified") + return 0, nil, nil, errors.New("Error formatting") + } + + // Length of the AN-Parameter field + anParameterLength := binary.BigEndian.Uint16(codedData[:2]) + ikeLog.Debugf("AN-parameters length: %d", anParameterLength) + + if anParameterLength != 0 { + anParameterField := codedData[2:] + + // Bound checking + if len(anParameterField) < int(anParameterLength) { + ikeLog.Error("Packet contained error length of value") + return 0, nil, nil, errors.New("Error formatting") } + anParameterField = anParameterField[:anParameterLength] - codedData = codedData[2:] + ikeLog.Debugf("Parsing AN-parameters...: % v", anParameterField) - // [TS 24.502 f30] 9.3.2.2.2.3 - // AN-parameter value field in GUAMI, PLMN ID and NSSAI is coded as value part - // Therefore, IEI of AN-parameter is not needed to be included. - // anParameter = AN-parameter Type | AN-parameter Length | Value part of IE + anParameters = new(ANParameters) - if len(codedData) >= 2 { - // Length of the AN-Parameter field - anParameterLength := binary.BigEndian.Uint16(codedData[:2]) - logger.IKELog.Debugf("AN-parameters length: %d", anParameterLength) + // Parse AN-Parameters + for len(anParameterField) >= 2 { + parameterType := anParameterField[0] + // The AN-parameter length field indicates the length of the AN-parameter value field. + parameterLength := anParameterField[1] + + switch parameterType { + case message.ANParametersTypeGUAMI: + ikeLog.Debugf("-> Parameter type: GUAMI") + if parameterLength != 0 { + parameterValue := anParameterField[2:] + + if len(parameterValue) < int(parameterLength) { + return 0, nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - if anParameterLength != 0 { - anParameterField := codedData[2:] + if len(parameterValue) != message.ANParametersLenGUAMI { + return 0, nil, nil, errors.New("Unmatched GUAMI length") + } - // Bound checking - if len(anParameterField) < int(anParameterLength) { - logger.IKELog.Error("Packet contained error length of value") - return 0, nil, nil, errors.New("Error formatting") + guamiField := make([]byte, 1) + guamiField = append(guamiField, parameterValue...) + // Decode GUAMI using aper + ngapGUAMI := new(ngapType.GUAMI) + err = aper.UnmarshalWithParams(guamiField, ngapGUAMI, "valueExt") + if err != nil { + ikeLog.Errorf("APER unmarshal with parameter failed: %+v", err) + return 0, nil, nil, errors.New("Unmarshal failed when decoding GUAMI") + } + anParameters.GUAMI = ngapGUAMI + ikeLog.Debugf("Unmarshal GUAMI: % x", guamiField) + ikeLog.Debugf("\tGUAMI: PLMNIdentity[% x], "+ + "AMFRegionID[% x], AMFSetID[% x], AMFPointer[% x]", + anParameters.GUAMI.PLMNIdentity, anParameters.GUAMI.AMFRegionID, + anParameters.GUAMI.AMFSetID, anParameters.GUAMI.AMFPointer) } else { - anParameterField = anParameterField[:anParameterLength] + ikeLog.Warn("AN-Parameter GUAMI field empty") } + case message.ANParametersTypeSelectedPLMNID: + ikeLog.Debugf("-> Parameter type: ANParametersTypeSelectedPLMNID") + if parameterLength != 0 { + parameterValue := anParameterField[2:] - logger.IKELog.Debugf("Parsing AN-parameters...: % v", anParameterField) + if len(parameterValue) < int(parameterLength) { + return 0, nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - anParameters = new(ANParameters) + if len(parameterValue) != message.ANParametersLenPLMNID { + return 0, nil, nil, errors.New("Unmatched PLMN ID length") + } - // Parse AN-Parameters - for len(anParameterField) >= 2 { - parameterType := anParameterField[0] - // The AN-parameter length field indicates the length of the AN-parameter value field. - parameterLength := anParameterField[1] + plmnField := make([]byte, 1) + plmnField = append(plmnField, parameterValue...) + // Decode PLMN using aper + ngapPLMN := new(ngapType.PLMNIdentity) + err = aper.UnmarshalWithParams(plmnField, ngapPLMN, "valueExt") + if err != nil { + ikeLog.Errorf("APER unmarshal with parameter failed: %v", err) + return 0, nil, nil, errors.New("Unmarshal failed when decoding PLMN") + } + anParameters.SelectedPLMNID = ngapPLMN + ikeLog.Debugf("Unmarshal SelectedPLMNID: % x", plmnField) + ikeLog.Debugf("\tSelectedPLMNID: % x", anParameters.SelectedPLMNID.Value) + } else { + ikeLog.Warn("AN-Parameter PLMN field empty") + } + case message.ANParametersTypeRequestedNSSAI: + ikeLog.Debugf("-> Parameter type: ANParametersTypeRequestedNSSAI") + if parameterLength != 0 { + parameterValue := anParameterField[2:] - switch parameterType { - case message.ANParametersTypeGUAMI: - logger.IKELog.Debugf("-> Parameter type: GUAMI") - if parameterLength != 0 { - parameterValue := anParameterField[2:] + if len(parameterValue) < int(parameterLength) { + return 0, nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - if len(parameterValue) < int(parameterLength) { - return 0, nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } + ngapNSSAI := new(ngapType.AllowedNSSAI) - if len(parameterValue) != message.ANParametersLenGUAMI { - return 0, nil, nil, errors.New("Unmatched GUAMI length") - } + // [TS 24501 f30] 9.11.2.8 S-NSSAI + // s-nssai(LV) consists of + // len(1 byte) | SST(1) | SD(3,opt) | Mapped HPLMN SST (1,opt) | Mapped HPLMN SD (3,opt) + // The length of minimum s-nssai comprised of a length and a SST is 2 bytes. - guamiField := make([]byte, 1) - guamiField = append(guamiField, parameterValue...) - // Decode GUAMI using aper - ngapGUAMI := new(ngapType.GUAMI) - err = aper.UnmarshalWithParams(guamiField, ngapGUAMI, "valueExt") - if err != nil { - logger.IKELog.Errorf("APER unmarshal with parameter failed: %+v", err) - return 0, nil, nil, errors.New("Unmarshal failed when decoding GUAMI") - } - anParameters.GUAMI = ngapGUAMI - logger.IKELog.Debugf("Unmarshal GUAMI: % x", guamiField) - logger.IKELog.Debugf("\tGUAMI: PLMNIdentity[% x], "+ - "AMFRegionID[% x], AMFSetID[% x], AMFPointer[% x]", - anParameters.GUAMI.PLMNIdentity, anParameters.GUAMI.AMFRegionID, - anParameters.GUAMI.AMFSetID, anParameters.GUAMI.AMFPointer) - } else { - logger.IKELog.Warn("AN-Parameter GUAMI field empty") + for len(parameterValue) >= 2 { + snssaiLength := parameterValue[0] + snssaiValue := parameterValue[1:] + + if len(snssaiValue) < int(snssaiLength) { + ikeLog.Error("SNSSAI length error") + return 0, nil, nil, errors.New("Error formatting") } - case message.ANParametersTypeSelectedPLMNID: - logger.IKELog.Debugf("-> Parameter type: ANParametersTypeSelectedPLMNID") - if parameterLength != 0 { - parameterValue := anParameterField[2:] - - if len(parameterValue) < int(parameterLength) { - return 0, nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } + snssaiValue = snssaiValue[:snssaiLength] - if len(parameterValue) != message.ANParametersLenPLMNID { - return 0, nil, nil, errors.New("Unmatched PLMN ID length") - } + ngapSNSSAIItem := ngapType.AllowedNSSAIItem{} - plmnField := make([]byte, 1) - plmnField = append(plmnField, parameterValue...) - // Decode PLMN using aper - ngapPLMN := new(ngapType.PLMNIdentity) - err = aper.UnmarshalWithParams(plmnField, ngapPLMN, "valueExt") - if err != nil { - logger.IKELog.Errorf("APER unmarshal with parameter failed: %v", err) - return 0, nil, nil, errors.New("Unmarshal failed when decoding PLMN") + if len(snssaiValue) == 1 { + ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ + SST: ngapType.SST{ + Value: []byte{snssaiValue[0]}, + }, + } + } else if len(snssaiValue) == 4 { + ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ + SST: ngapType.SST{ + Value: []byte{snssaiValue[0]}, + }, + SD: &ngapType.SD{ + Value: []byte{snssaiValue[1], snssaiValue[2], snssaiValue[3]}, + }, } - anParameters.SelectedPLMNID = ngapPLMN - logger.IKELog.Debugf("Unmarshal SelectedPLMNID: % x", plmnField) - logger.IKELog.Debugf("\tSelectedPLMNID: % x", anParameters.SelectedPLMNID.Value) } else { - logger.IKELog.Warn("AN-Parameter PLMN field empty") + ikeLog.Error("Empty SNSSAI value") + return 0, nil, nil, errors.New("Error formatting") } - case message.ANParametersTypeRequestedNSSAI: - logger.IKELog.Debugf("-> Parameter type: ANParametersTypeRequestedNSSAI") - if parameterLength != 0 { - parameterValue := anParameterField[2:] - - if len(parameterValue) < int(parameterLength) { - return 0, nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } - ngapNSSAI := new(ngapType.AllowedNSSAI) - - // [TS 24501 f30] 9.11.2.8 S-NSSAI - // s-nssai(LV) consists of - // len(1 byte) | SST(1) | SD(3,opt) | Mapped HPLMN SST (1,opt) | Mapped HPLMN SD (3,opt) - // The length of minimum s-nssai comprised of a length and a SST is 2 bytes. - - for len(parameterValue) >= 2 { - snssaiLength := parameterValue[0] - snssaiValue := parameterValue[1:] - - if len(snssaiValue) < int(snssaiLength) { - logger.IKELog.Error("SNSSAI length error") - return 0, nil, nil, errors.New("Error formatting") - } else { - snssaiValue = snssaiValue[:snssaiLength] - } - - ngapSNSSAIItem := ngapType.AllowedNSSAIItem{} - - if len(snssaiValue) == 1 { - ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ - SST: ngapType.SST{ - Value: []byte{snssaiValue[0]}, - }, - } - } else if len(snssaiValue) == 4 { - ngapSNSSAIItem.SNSSAI = ngapType.SNSSAI{ - SST: ngapType.SST{ - Value: []byte{snssaiValue[0]}, - }, - SD: &ngapType.SD{ - Value: []byte{snssaiValue[1], snssaiValue[2], snssaiValue[3]}, - }, - } - } else { - logger.IKELog.Error("Empty SNSSAI value") - return 0, nil, nil, errors.New("Error formatting") - } - - ngapNSSAI.List = append(ngapNSSAI.List, ngapSNSSAIItem) - - logger.IKELog.Debugf("Unmarshal SNSSAI: % x", parameterValue[:1+snssaiLength]) - logger.IKELog.Debugf("\t\t\tSST: % x", ngapSNSSAIItem.SNSSAI.SST.Value) - sd := ngapSNSSAIItem.SNSSAI.SD - if sd == nil { - logger.IKELog.Debugf("\t\t\tSD: nil") - } else { - logger.IKELog.Debugf("\t\t\tSD: % x", sd.Value) - } - - // shift parameterValue for parsing next s-nssai - parameterValue = parameterValue[1+snssaiLength:] - } - anParameters.RequestedNSSAI = ngapNSSAI + ngapNSSAI.List = append(ngapNSSAI.List, ngapSNSSAIItem) + + ikeLog.Debugf("Unmarshal SNSSAI: % x", parameterValue[:1+snssaiLength]) + ikeLog.Debugf("\t\t\tSST: % x", ngapSNSSAIItem.SNSSAI.SST.Value) + sd := ngapSNSSAIItem.SNSSAI.SD + if sd == nil { + ikeLog.Debugf("\t\t\tSD: nil") } else { - logger.IKELog.Warn("AN-Parameter NSSAI is empty") + ikeLog.Debugf("\t\t\tSD: % x", sd.Value) } - case message.ANParametersTypeEstablishmentCause: - logger.IKELog.Debugf("-> Parameter type: ANParametersTypeEstablishmentCause") - if parameterLength != 0 { - parameterValue := anParameterField[2:] - - if len(parameterValue) < int(parameterLength) { - return 0, nil, nil, errors.New("Error formatting") - } else { - parameterValue = parameterValue[:parameterLength] - } - if len(parameterValue) != message.ANParametersLenEstCause { - return 0, nil, nil, errors.New("Unmatched Establishment Cause length") - } + // shift parameterValue for parsing next s-nssai + parameterValue = parameterValue[1+snssaiLength:] + } + anParameters.RequestedNSSAI = ngapNSSAI + } else { + ikeLog.Warn("AN-Parameter NSSAI is empty") + } + case message.ANParametersTypeEstablishmentCause: + ikeLog.Debugf("-> Parameter type: ANParametersTypeEstablishmentCause") + if parameterLength != 0 { + parameterValue := anParameterField[2:] - logger.IKELog.Debugf("Unmarshal ANParametersTypeEstablishmentCause: % x", parameterValue) - - establishmentCause := parameterValue[0] & 0x0f - switch establishmentCause { - case message.EstablishmentCauseEmergency: - logger.IKELog.Trace("AN-Parameter establishment cause: Emergency") - case message.EstablishmentCauseHighPriorityAccess: - logger.IKELog.Trace("AN-Parameter establishment cause: High Priority Access") - case message.EstablishmentCauseMO_Signalling: - logger.IKELog.Trace("AN-Parameter establishment cause: MO Signalling") - case message.EstablishmentCauseMO_Data: - logger.IKELog.Trace("AN-Parameter establishment cause: MO Data") - case message.EstablishmentCauseMPS_PriorityAccess: - logger.IKELog.Trace("AN-Parameter establishment cause: MPS Priority Access") - case message.EstablishmentCauseMCS_PriorityAccess: - logger.IKELog.Trace("AN-Parameter establishment cause: MCS Priority Access") - default: - logger.IKELog.Trace("AN-Parameter establishment cause: Unknown. Treat as mo-Data") - establishmentCause = message.EstablishmentCauseMO_Data - } + if len(parameterValue) < int(parameterLength) { + return 0, nil, nil, errors.New("Error formatting") + } + parameterValue = parameterValue[:parameterLength] - ngapEstablishmentCause := new(ngapType.RRCEstablishmentCause) - ngapEstablishmentCause.Value = aper.Enumerated(establishmentCause) + if len(parameterValue) != message.ANParametersLenEstCause { + return 0, nil, nil, errors.New("Unmatched Establishment Cause length") + } - anParameters.EstablishmentCause = ngapEstablishmentCause - } else { - logger.IKELog.Warn("AN-Parameter establishment cause field empty") - } + ikeLog.Debugf("Unmarshal ANParametersTypeEstablishmentCause: % x", parameterValue) + + establishmentCause := parameterValue[0] & 0x0f + switch establishmentCause { + case message.EstablishmentCauseEmergency: + ikeLog.Trace("AN-Parameter establishment cause: Emergency") + case message.EstablishmentCauseHighPriorityAccess: + ikeLog.Trace("AN-Parameter establishment cause: High Priority Access") + case message.EstablishmentCauseMO_Signalling: + ikeLog.Trace("AN-Parameter establishment cause: MO Signalling") + case message.EstablishmentCauseMO_Data: + ikeLog.Trace("AN-Parameter establishment cause: MO Data") + case message.EstablishmentCauseMPS_PriorityAccess: + ikeLog.Trace("AN-Parameter establishment cause: MPS Priority Access") + case message.EstablishmentCauseMCS_PriorityAccess: + ikeLog.Trace("AN-Parameter establishment cause: MCS Priority Access") default: - logger.IKELog.Warn("Unsopprted AN-Parameter. Ignore.") + ikeLog.Trace("AN-Parameter establishment cause: Unknown. Treat as mo-Data") + establishmentCause = message.EstablishmentCauseMO_Data } - // shift anParameterField - anParameterField = anParameterField[2+parameterLength:] + ngapEstablishmentCause := new(ngapType.RRCEstablishmentCause) + ngapEstablishmentCause.Value = aper.Enumerated(establishmentCause) + + anParameters.EstablishmentCause = ngapEstablishmentCause + } else { + ikeLog.Warn("AN-Parameter establishment cause field empty") } + default: + ikeLog.Warn("Unsopprted AN-Parameter. Ignore.") } - // shift codedData - codedData = codedData[2+anParameterLength:] - } else { - logger.IKELog.Error("No AN-Parameter type or length specified") - return 0, nil, nil, errors.New("Error formatting") + // shift anParameterField + anParameterField = anParameterField[2+parameterLength:] } + } - if len(codedData) >= 2 { - // Length of the NASPDU field - nasPDULength := binary.BigEndian.Uint16(codedData[:2]) - logger.IKELog.Debugf("nasPDULength: %d", nasPDULength) - - if nasPDULength != 0 { - nasPDUField := codedData[2:] + // shift codedData + codedData = codedData[2+anParameterLength:] + if len(codedData) < 2 { + ikeLog.Error("No NASPDU length specified") + return 0, nil, nil, errors.New("Error formatting") + } - // Bound checking - if len(nasPDUField) < int(nasPDULength) { - return 0, nil, nil, errors.New("Error formatting") - } else { - nasPDUField = nasPDUField[:nasPDULength] - } + // Length of the NASPDU field + nasPDULength := binary.BigEndian.Uint16(codedData[:2]) + ikeLog.Debugf("nasPDULength: %d", nasPDULength) - logger.IKELog.Debugf("nasPDUField: % v", nasPDUField) + if nasPDULength == 0 { + ikeLog.Error("No NAS PDU included in EAP-5G packet") + return 0, nil, nil, errors.New("No NAS PDU") + } - nasPDU = append(nasPDU, nasPDUField...) - } else { - logger.IKELog.Error("No NAS PDU included in EAP-5G packet") - return 0, nil, nil, errors.New("No NAS PDU") - } - } else { - logger.IKELog.Error("No NASPDU length specified") - return 0, nil, nil, errors.New("Error formatting") - } - return eap5GMessageID, anParameters, nasPDU, err - } else { - return 0, nil, nil, errors.New("No data to decode") + nasPDUField := codedData[2:] + // Bound checking + if len(nasPDUField) < int(nasPDULength) { + return 0, nil, nil, errors.New("Error formatting") } + nasPDUField = nasPDUField[:nasPDULength] + + ikeLog.Debugf("nasPDUField: % v", nasPDUField) + + nasPDU = append(nasPDU, nasPDUField...) + return eap5GMessageID, anParameters, nasPDU, err } diff --git a/pkg/ike/handler/handler.go b/pkg/ike/handler/handler.go index fc627196..a68551f0 100644 --- a/pkg/ike/handler/handler.go +++ b/pkg/ike/handler/handler.go @@ -26,7 +26,8 @@ import ( func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message *ike_message.IKEMessage, realMessage1 []byte, ) { - logger.IKELog.Infoln("Handle IKE_SA_INIT") + ikeLog := logger.IKELog + ikeLog.Infoln("Handle IKE_SA_INIT") // Used to receive value from peer var securityAssociation *ike_message.SecurityAssociation @@ -46,7 +47,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa var ueIsBehindNAT, n3iwfIsBehindNAT bool if message == nil { - logger.IKELog.Error("IKE Message is nil") + ikeLog.Error("IKE Message is nil") return } @@ -54,7 +55,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa // check major version majorVersion := ((message.Version & 0xf0) >> 4) if majorVersion > 2 { - logger.IKELog.Warn("Received an IKE message with higher major version") + ikeLog.Warn("Received an IKE message with higher major version") // send INFORMATIONAL type message with INVALID_MAJOR_VERSION Notify payload responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, ike_message.INFORMATIONAL, ike_message.ResponseBitCheck, message.MessageID) @@ -78,7 +79,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa case ike_message.TypeN: notifications = append(notifications, ikePayload.(*ike_message.Notification)) default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in IKE_SA_INIT message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -167,7 +168,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa } if len(responseSecurityAssociation.Proposals) == 0 { - logger.IKELog.Warn("No proposal chosen") + ikeLog.Warn("No proposal chosen") // Respond NO_PROPOSAL_CHOSEN to UE responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, ike_message.IKE_SA_INIT, ike_message.ResponseBitCheck, message.MessageID) @@ -179,7 +180,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa return } } else { - logger.IKELog.Error("The security association field is nil") + ikeLog.Error("The security association field is nil") // TODO: send error message to UE return } @@ -187,7 +188,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa if keyExcahge != nil { chosenDiffieHellmanGroup := diffieHellmanGroupTransform.TransformID if chosenDiffieHellmanGroup != keyExcahge.DiffieHellmanGroup { - logger.IKELog.Warn("The Diffie-Hellman group defined in key exchange payload not matches the one in chosen proposal") + ikeLog.Warn("The Diffie-Hellman group defined in key exchange payload not matches the one in chosen proposal") // send INVALID_KE_PAYLOAD to UE responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, ike_message.IKE_SA_INIT, ike_message.ResponseBitCheck, message.MessageID) @@ -209,7 +210,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa keyExcahge.KeyExchangeData, chosenDiffieHellmanGroup) responseIKEMessage.Payloads.BUildKeyExchange(chosenDiffieHellmanGroup, localPublicValue) } else { - logger.IKELog.Error("The key exchange field is nil") + ikeLog.Error("The key exchange field is nil") // TODO: send error message to UE return } @@ -220,7 +221,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa responseIKEMessage.Payloads.BuildNonce(localNonce) } else { - logger.IKELog.Error("The nonce field is nil") + ikeLog.Error("The nonce field is nil") // TODO: send error message to UE return } @@ -229,7 +230,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa for _, notification := range notifications { switch notification.NotifyMessageType { case ike_message.NAT_DETECTION_SOURCE_IP: - logger.IKELog.Trace("Received IKE Notify: NAT_DETECTION_SOURCE_IP") + ikeLog.Trace("Received IKE Notify: NAT_DETECTION_SOURCE_IP") // Calculate local NAT_DETECTION_SOURCE_IP hash // : sha1(ispi | rspi | ueip | ueport) localDetectionData := make([]byte, 22) @@ -240,7 +241,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa sha1HashFunction := sha1.New() if _, err := sha1HashFunction.Write(localDetectionData); err != nil { - logger.IKELog.Errorf("Hash function write error: %+v", err) + ikeLog.Errorf("Hash function write error: %+v", err) return } @@ -248,7 +249,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa ueIsBehindNAT = true } case ike_message.NAT_DETECTION_DESTINATION_IP: - logger.IKELog.Trace("Received IKE Notify: NAT_DETECTION_DESTINATION_IP") + ikeLog.Trace("Received IKE Notify: NAT_DETECTION_DESTINATION_IP") // Calculate local NAT_DETECTION_SOURCE_IP hash // : sha1(ispi | rspi | n3iwfip | n3iwfport) localDetectionData := make([]byte, 22) @@ -259,7 +260,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa sha1HashFunction := sha1.New() if _, err := sha1HashFunction.Write(localDetectionData); err != nil { - logger.IKELog.Errorf("Hash function write error: %+v", err) + ikeLog.Errorf("Hash function write error: %+v", err) return } @@ -290,7 +291,7 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa ikeSecurityAssociation.DiffieHellmanSharedKey = append(ikeSecurityAssociation.DiffieHellmanSharedKey, sharedKeyData...) if err := GenerateKeyForIKESA(ikeSecurityAssociation); err != nil { - logger.IKELog.Errorf("Generate key for IKE SA failed: %+v", err) + ikeLog.Errorf("Generate key for IKE SA failed: %+v", err) return } @@ -329,8 +330,8 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa // ResponderSignedOctet = RealMessage2 | NonceIData | MACedIDForR responseIKEMessageData, err := responseIKEMessage.Encode() if err != nil { - logger.IKELog.Errorln(err) - logger.IKELog.Error("Encoding IKE message failed") + ikeLog.Errorln(err) + ikeLog.Error("Encoding IKE message failed") return } ikeSecurityAssociation.ResponderSignedOctets = append(responseIKEMessageData, nonce.NonceData...) @@ -339,24 +340,24 @@ func HandleIKESAINIT(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, messa idPayload.BuildIdentificationResponder(ike_message.ID_FQDN, []byte(n3iwfSelf.FQDN)) idPayloadData, err := idPayload.Encode() if err != nil { - logger.IKELog.Errorln(err) - logger.IKELog.Error("Encode IKE payload failed.") + ikeLog.Errorln(err) + ikeLog.Error("Encode IKE payload failed.") return } pseudorandomFunction, ok := NewPseudorandomFunction(ikeSecurityAssociation.SK_pr, ikeSecurityAssociation.PseudorandomFunction.TransformID) if !ok { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return } if _, err := pseudorandomFunction.Write(idPayloadData[4:]); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return } ikeSecurityAssociation.ResponderSignedOctets = append(ikeSecurityAssociation.ResponderSignedOctets, pseudorandomFunction.Sum(nil)...) - logger.IKELog.Tracef("Local unsigned authentication data:\n%s", hex.Dump(ikeSecurityAssociation.ResponderSignedOctets)) + ikeLog.Tracef("Local unsigned authentication data:\n%s", hex.Dump(ikeSecurityAssociation.ResponderSignedOctets)) // Send response to UE SendIKEMessageToUE(udpConn, n3iwfAddr, ueAddr, responseIKEMessage) @@ -374,7 +375,8 @@ const ( ) func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message *ike_message.IKEMessage) { - logger.IKELog.Infoln("Handle IKE_AUTH") + ikeLog := logger.IKELog + ikeLog.Infoln("Handle IKE_AUTH") var encryptedPayload *ike_message.Encrypted @@ -385,7 +387,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message var responseIKEPayload ike_message.IKEPayloadContainer if message == nil { - logger.IKELog.Error("IKE Message is nil") + ikeLog.Error("IKE Message is nil") return } @@ -393,7 +395,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // check major version majorVersion := ((message.Version & 0xf0) >> 4) if majorVersion > 2 { - logger.IKELog.Warn("Received an IKE message with higher major version") + ikeLog.Warn("Received an IKE message with higher major version") // send INFORMATIONAL type message with INVALID_MAJOR_VERSION Notify payload ( OUTSIDE IKE SA ) responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, ike_message.INFORMATIONAL, ike_message.ResponseBitCheck, message.MessageID) @@ -409,7 +411,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message localSPI := message.ResponderSPI ikeSecurityAssociation, ok := n3iwfSelf.IKESALoad(localSPI) if !ok { - logger.IKELog.Warn("Unrecognized SPI") + ikeLog.Warn("Unrecognized SPI") // send INFORMATIONAL type message with INVALID_IKE_SPI Notify payload ( OUTSIDE IKE SA ) responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, 0, ike_message.INFORMATIONAL, ike_message.ResponseBitCheck, message.MessageID) @@ -426,7 +428,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message case ike_message.TypeSK: encryptedPayload = ikePayload.(*ike_message.Encrypted) default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in IKE_AUTH message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -434,7 +436,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message decryptedIKEPayload, err := DecryptProcedure(ikeSecurityAssociation, message, encryptedPayload) if err != nil { - logger.IKELog.Errorf("Decrypt IKE message failed: %+v", err) + ikeLog.Errorf("Decrypt IKE message failed: %+v", err) return } @@ -470,7 +472,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message case ike_message.TypeCP: configuration = ikePayload.(*ike_message.Configuration) default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in IKE_AUTH message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -483,7 +485,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message switch ikeSecurityAssociation.State { case PreSignalling: if initiatorID != nil { - logger.IKELog.Info("Ecoding initiator for later IKE authentication") + ikeLog.Info("Ecoding initiator for later IKE authentication") ikeSecurityAssociation.InitiatorID = initiatorID // Record maced identification for authentication @@ -492,26 +494,26 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message } idPayloadData, err := idPayload.Encode() if err != nil { - logger.IKELog.Errorln(err) - logger.IKELog.Error("Encoding ID payload message failed.") + ikeLog.Errorln(err) + ikeLog.Error("Encoding ID payload message failed.") return } pseudorandomFunction, ok1 := NewPseudorandomFunction( ikeSecurityAssociation.SK_pi, transformPseudorandomFunction.TransformID) if !ok1 { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return } if _, err := pseudorandomFunction.Write(idPayloadData[4:]); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return } ikeSecurityAssociation.InitiatorSignedOctets = append( ikeSecurityAssociation.InitiatorSignedOctets, pseudorandomFunction.Sum(nil)...) } else { - logger.IKELog.Error("The initiator identification field is nil") + ikeLog.Error("The initiator identification field is nil") // TODO: send error message to UE return } @@ -525,20 +527,20 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // can be validated up to one of the specified certification // authorities. This can be a chain of certificates. if certificateRequest != nil { - logger.IKELog.Info("UE request N3IWF certificate") + ikeLog.Info("UE request N3IWF certificate") if CompareRootCertificate(certificateRequest.CertificateEncoding, certificateRequest.CertificationAuthority) { // TODO: Complete N3IWF Certificate/Certificate Authority related procedure - logger.IKELog.Info("Certificate Request sent from UE matches N3IWF CA") + ikeLog.Info("Certificate Request sent from UE matches N3IWF CA") } } if certificate != nil { - logger.IKELog.Info("UE send its certficate") + ikeLog.Info("UE send its certficate") ikeSecurityAssociation.InitiatorCertificate = certificate } if securityAssociation != nil { - logger.IKELog.Info("Parsing security association") + ikeLog.Info("Parsing security association") responseSecurityAssociation := new(ike_message.SecurityAssociation) for _, proposal := range securityAssociation.Proposals { @@ -623,7 +625,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message } if len(responseSecurityAssociation.Proposals) == 0 { - logger.IKELog.Warn("No proposal chosen") + ikeLog.Warn("No proposal chosen") // Respond NO_PROPOSAL_CHOSEN to UE // Build IKE message responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, @@ -637,7 +639,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message responseIKEPayload.BuildNotification(ike_message.TypeNone, ike_message.NO_PROPOSAL_CHOSEN, nil, nil) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -649,25 +651,25 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message ikeSecurityAssociation.IKEAuthResponseSA = responseSecurityAssociation } else { - logger.IKELog.Error("The security association field is nil") + ikeLog.Error("The security association field is nil") // TODO: send error message to UE return } if trafficSelectorInitiator != nil { - logger.IKELog.Info("Received traffic selector initiator from UE") + ikeLog.Info("Received traffic selector initiator from UE") ikeSecurityAssociation.TrafficSelectorInitiator = trafficSelectorInitiator } else { - logger.IKELog.Error("The initiator traffic selector field is nil") + ikeLog.Error("The initiator traffic selector field is nil") // TODO: send error message to UE return } if trafficSelectorResponder != nil { - logger.IKELog.Info("Received traffic selector initiator from UE") + ikeLog.Info("Received traffic selector initiator from UE") ikeSecurityAssociation.TrafficSelectorResponder = trafficSelectorResponder } else { - logger.IKELog.Error("The initiator traffic selector field is nil") + ikeLog.Error("The initiator traffic selector field is nil") // TODO: send error message to UE return } @@ -684,16 +686,16 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message responseIKEPayload.BuildCertificate(ike_message.X509CertificateSignature, n3iwfSelf.N3IWFCertificate) // Authentication Data - logger.IKELog.Tracef("Local authentication data:\n%s", hex.Dump(ikeSecurityAssociation.ResponderSignedOctets)) + ikeLog.Tracef("Local authentication data:\n%s", hex.Dump(ikeSecurityAssociation.ResponderSignedOctets)) sha1HashFunction := sha1.New() if _, err := sha1HashFunction.Write(ikeSecurityAssociation.ResponderSignedOctets); err != nil { - logger.IKELog.Errorf("Hash function write error: %+v", err) + ikeLog.Errorf("Hash function write error: %+v", err) return } signedAuth, err := rsa.SignPKCS1v15(rand.Reader, n3iwfSelf.N3IWFPrivateKey, crypto.SHA1, sha1HashFunction.Sum(nil)) if err != nil { - logger.IKELog.Errorf("Sign authentication data failed: %+v", err) + ikeLog.Errorf("Sign authentication data failed: %+v", err) } responseIKEPayload.BuildAuthentication(ike_message.RSADigitalSignature, signedAuth) @@ -703,7 +705,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message for { identifier, err = GenerateRandomUint8() if err != nil { - logger.IKELog.Errorf("Random number failed: %+v", err) + ikeLog.Errorf("Random number failed: %+v", err) return } if identifier != ikeSecurityAssociation.LastEAPIdentifier { @@ -714,7 +716,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message responseIKEPayload.BuildEAP5GStart(identifier) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -728,11 +730,11 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // If success, N3IWF will send an UPLinkNASTransport to AMF if eap != nil { if eap.Code != ike_message.EAPCodeResponse { - logger.IKELog.Error("[EAP] Received an EAP payload with code other than response. Drop the payload.") + ikeLog.Error("[EAP] Received an EAP payload with code other than response. Drop the payload.") return } if eap.Identifier != ikeSecurityAssociation.LastEAPIdentifier { - logger.IKELog.Error("[EAP] Received an EAP payload with unmatched identifier. Drop the payload.") + ikeLog.Error("[EAP] Received an EAP payload with unmatched identifier. Drop the payload.") return } @@ -747,21 +749,21 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message case ike_message.EAPTypeExpanded: eapExpanded = eapTypeData.(*ike_message.EAPExpanded) default: - logger.IKELog.Errorf("[EAP] Received EAP packet with type other than EAP expanded type: %d", eapTypeData.Type()) + ikeLog.Errorf("[EAP] Received EAP packet with type other than EAP expanded type: %d", eapTypeData.Type()) return } if eapExpanded.VendorID != ike_message.VendorID3GPP { - logger.IKELog.Error("The peer sent EAP expended packet with wrong vendor ID. Drop the packet.") + ikeLog.Error("The peer sent EAP expended packet with wrong vendor ID. Drop the packet.") return } if eapExpanded.VendorType != ike_message.VendorTypeEAP5G { - logger.IKELog.Error("The peer sent EAP expanded packet with wrong vendor type. Drop the packet.") + ikeLog.Error("The peer sent EAP expanded packet with wrong vendor type. Drop the packet.") return } eap5GMessageID := eapExpanded.VendorData[0] - logger.IKELog.Infof("EAP5G MessageID : %+v", eap5GMessageID) + ikeLog.Infof("EAP5G MessageID : %+v", eap5GMessageID) if eap5GMessageID == ike_message.EAP5GType5GStop { // Send EAP failure @@ -773,13 +775,13 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // EAP identifier, err := GenerateRandomUint8() if err != nil { - logger.IKELog.Errorf("Generate random uint8 failed: %+v", err) + ikeLog.Errorf("Generate random uint8 failed: %+v", err) return } responseIKEPayload.BuildEAPfailure(identifier) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -809,7 +811,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message ikeSecurityAssociation.InitiatorMessageID = message.MessageID } else { - logger.IKELog.Error("EAP is nil") + ikeLog.Error("EAP is nil") } case PostSignalling: @@ -819,17 +821,17 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // Prepare pseudorandom function for calculating/verifying authentication data pseudorandomFunction, ok := NewPseudorandomFunction(ikeUE.Kn3iwf, transformPseudorandomFunction.TransformID) if !ok { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return } if _, err := pseudorandomFunction.Write([]byte("Key Pad for IKEv2")); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return } secret := pseudorandomFunction.Sum(nil) pseudorandomFunction, ok = NewPseudorandomFunction(secret, transformPseudorandomFunction.TransformID) if !ok { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return } @@ -837,14 +839,14 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // Verifying remote AUTH pseudorandomFunction.Reset() if _, err := pseudorandomFunction.Write(ikeSecurityAssociation.InitiatorSignedOctets); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return } expectedAuthenticationData := pseudorandomFunction.Sum(nil) - logger.IKELog.Tracef("Expected Authentication Data:\n%s", hex.Dump(expectedAuthenticationData)) + ikeLog.Tracef("Expected Authentication Data:\n%s", hex.Dump(expectedAuthenticationData)) if !bytes.Equal(authentication.AuthenticationData, expectedAuthenticationData) { - logger.IKELog.Warn("Peer authentication failed.") + ikeLog.Warn("Peer authentication failed.") // Inform UE the authentication has failed // Build IKE message responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, @@ -855,7 +857,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message responseIKEPayload.BuildNotification(ike_message.TypeNone, ike_message.AUTHENTICATION_FAILED, nil, nil) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -863,10 +865,10 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message SendIKEMessageToUE(udpConn, n3iwfAddr, ueAddr, responseIKEMessage) return } else { - logger.IKELog.Tracef("Peer authentication success") + ikeLog.Tracef("Peer authentication success") } } else { - logger.IKELog.Warn("Peer authentication failed.") + ikeLog.Warn("Peer authentication failed.") // Inform UE the authentication has failed // Build IKE message responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, @@ -877,7 +879,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message responseIKEPayload.BuildNotification(ike_message.TypeNone, ike_message.AUTHENTICATION_FAILED, nil, nil) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -891,7 +893,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message var addrRequest bool = false if configuration != nil { - logger.IKELog.Tracef("Received configuration payload with type: %d", configuration.ConfigurationType) + ikeLog.Tracef("Received configuration payload with type: %d", configuration.ConfigurationType) var attribute *ike_message.IndividualConfigurationAttribute for _, attribute = range configuration.ConfigurationAttribute { @@ -899,15 +901,15 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message case ike_message.INTERNAL_IP4_ADDRESS: addrRequest = true if len(attribute.Value) != 0 { - logger.IKELog.Tracef("Got client requested address: %d.%d.%d.%d", + ikeLog.Tracef("Got client requested address: %d.%d.%d.%d", attribute.Value[0], attribute.Value[1], attribute.Value[2], attribute.Value[3]) } default: - logger.IKELog.Warnf("Receive other type of configuration request: %d", attribute.Type) + ikeLog.Warnf("Receive other type of configuration request: %d", attribute.Type) } } } else { - logger.IKELog.Warn("Configuration is nil. UE did not sent any configuration request.") + ikeLog.Warn("Configuration is nil. UE did not sent any configuration request.") } // Build response IKE message @@ -918,7 +920,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message // Calculate local AUTH pseudorandomFunction.Reset() if _, err := pseudorandomFunction.Write(ikeSecurityAssociation.ResponderSignedOctets); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return } @@ -940,14 +942,14 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message ikeUE.IPSecInnerIP = ueIPAddr if ipsecInnerIPAddr, err := net.ResolveIPAddr("ip", ueIPAddr.String()); err != nil { - logger.IKELog.Errorf("Resolve UE inner IP address failed: %+v", err) + ikeLog.Errorf("Resolve UE inner IP address failed: %+v", err) return } else { ikeUE.IPSecInnerIPAddr = ipsecInnerIPAddr } - logger.IKELog.Tracef("ueIPAddr: %+v", ueIPAddr) + ikeLog.Tracef("ueIPAddr: %+v", ueIPAddr) } else { - logger.IKELog.Error("UE did not send any configuration request for its IP address.") + ikeLog.Error("UE did not send any configuration request for its IP address.") return } @@ -982,7 +984,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message binary.BigEndian.PutUint32(inboundSPIByte, inboundSPI) outboundSPI := binary.BigEndian.Uint32(ikeSecurityAssociation.IKEAuthResponseSA.Proposals[0].SPI) - logger.IKELog.Infof("Inbound SPI: %+v, Outbound SPI: %+v", inboundSPI, outboundSPI) + ikeLog.Infof("Inbound SPI: %+v, Outbound SPI: %+v", inboundSPI, outboundSPI) // SPI field of IKEAuthResponseSA is used to save outbound SPI temporarily. // After N3IWF produced its inbound SPI, the field will be overwritten with the SPI. @@ -993,21 +995,21 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message childSecurityAssociationContext, err := ikeUE.CompleteChildSA( 0x01, outboundSPI, ikeSecurityAssociation.IKEAuthResponseSA) if err != nil { - logger.IKELog.Errorf("Create child security association context failed: %+v", err) + ikeLog.Errorf("Create child security association context failed: %+v", err) return } err = parseIPAddressInformationToChildSecurityAssociation(childSecurityAssociationContext, ueAddr.IP, ikeSecurityAssociation.TrafficSelectorResponder.TrafficSelectors[0], ikeSecurityAssociation.TrafficSelectorInitiator.TrafficSelectors[0]) if err != nil { - logger.IKELog.Errorf("Parse IP address to child security association failed: %+v", err) + ikeLog.Errorf("Parse IP address to child security association failed: %+v", err) return } // Select TCP traffic childSecurityAssociationContext.SelectedIPProtocol = unix.IPPROTO_TCP if errGen := GenerateKeyForChildSA(ikeSecurityAssociation, childSecurityAssociationContext); errGen != nil { - logger.IKELog.Errorf("Generate key for child SA failed: %+v", errGen) + ikeLog.Errorf("Generate key for child SA failed: %+v", errGen) return } // NAT-T concern @@ -1024,14 +1026,14 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message responseIKEPayload.BuildNotifyNAS_TCP_PORT(n3iwfSelf.TCPPort) if errEncrypt := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); errEncrypt != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", errEncrypt) + ikeLog.Errorf("Encrypting IKE message failed: %+v", errEncrypt) return } // Aplly XFRM rules // IPsec for CP always use default XFRM interface if err = xfrm.ApplyXFRMRule(false, n3iwfSelf.XfrmIfaceId, childSecurityAssociationContext); err != nil { - logger.IKELog.Errorf("Applying XFRM rules failed: %+v", err) + ikeLog.Errorf("Applying XFRM rules failed: %+v", err) return } @@ -1040,7 +1042,7 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message ranNgapId, ok := n3iwfSelf.NgapIdLoad(ikeUE.N3IWFIKESecurityAssociation.LocalSPI) if !ok { - logger.IKELog.Errorf("Cannot get RanNgapId from SPI : %+v", ikeUE.N3IWFIKESecurityAssociation.LocalSPI) + ikeLog.Errorf("Cannot get RanNgapId from SPI : %+v", ikeUE.N3IWFIKESecurityAssociation.LocalSPI) return } @@ -1059,7 +1061,8 @@ func HandleIKEAUTH(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message } func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message *ike_message.IKEMessage) { - logger.IKELog.Infoln("Handle CREATE_CHILD_SA") + ikeLog := logger.IKELog + ikeLog.Infoln("Handle CREATE_CHILD_SA") var encryptedPayload *ike_message.Encrypted @@ -1068,7 +1071,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m responseIKEMessage := new(ike_message.IKEMessage) if message == nil { - logger.IKELog.Error("IKE Message is nil") + ikeLog.Error("IKE Message is nil") return } @@ -1076,7 +1079,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m // check major version majorVersion := ((message.Version & 0xf0) >> 4) if majorVersion > 2 { - logger.IKELog.Warn("Received an IKE message with higher major version") + ikeLog.Warn("Received an IKE message with higher major version") // send INFORMATIONAL type message with INVALID_MAJOR_VERSION Notify payload ( OUTSIDE IKE SA ) responseIKEMessage.BuildIKEHeader(message.InitiatorSPI, message.ResponderSPI, ike_message.INFORMATIONAL, ike_message.ResponseBitCheck, message.MessageID) @@ -1091,10 +1094,10 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m // Find corresponding IKE security association responderSPI := message.ResponderSPI - logger.IKELog.Warnf("CREATE_CHILD_SA responderSPI: %+v", responderSPI) + ikeLog.Warnf("CREATE_CHILD_SA responderSPI: %+v", responderSPI) ikeSecurityAssociation, ok := n3iwfSelf.IKESALoad(responderSPI) if !ok { - logger.IKELog.Warn("Unrecognized SPI") + ikeLog.Warn("Unrecognized SPI") // send INFORMATIONAL type message with INVALID_IKE_SPI Notify payload ( OUTSIDE IKE SA ) responseIKEMessage.BuildIKEHeader(0, message.ResponderSPI, ike_message.INFORMATIONAL, ike_message.ResponseBitCheck, message.MessageID) @@ -1111,7 +1114,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m case ike_message.TypeSK: encryptedPayload = ikePayload.(*ike_message.Encrypted) default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in CREATE_CHILD_SA message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -1119,7 +1122,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m decryptedIKEPayload, err := DecryptProcedure(ikeSecurityAssociation, message, encryptedPayload) if err != nil { - logger.IKELog.Errorf("Decrypt IKE message failed: %+v", err) + ikeLog.Errorf("Decrypt IKE message failed: %+v", err) return } @@ -1140,7 +1143,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m case ike_message.TypeTSr: trafficSelectorResponder = ikePayload.(*ike_message.TrafficSelectorResponder) default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in CREATE_CHILD_SA message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -1148,17 +1151,17 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m // Check received message if securityAssociation == nil { - logger.IKELog.Error("The security association field is nil") + ikeLog.Error("The security association field is nil") return } if trafficSelectorInitiator == nil { - logger.IKELog.Error("The traffic selector initiator field is nil") + ikeLog.Error("The traffic selector initiator field is nil") return } if trafficSelectorResponder == nil { - logger.IKELog.Error("The traffic selector responder field is nil") + ikeLog.Error("The traffic selector responder field is nil") return } @@ -1166,7 +1169,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m if nonce != nil { ikeSecurityAssociation.ConcatenatedNonce = append(ikeSecurityAssociation.ConcatenatedNonce, nonce.NonceData...) } else { - logger.IKELog.Error("The nonce field is nil") + ikeLog.Error("The nonce field is nil") // TODO: send error message to UE return } @@ -1179,7 +1182,7 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m ranNgapId, ok := n3iwfSelf.NgapIdLoad(ikeSecurityAssociation.LocalSPI) if !ok { - logger.IKELog.Errorf("Cannot get RanNgapID from SPI : %+v", ikeSecurityAssociation.LocalSPI) + ikeLog.Errorf("Cannot get RanNgapID from SPI : %+v", ikeSecurityAssociation.LocalSPI) return } @@ -1192,23 +1195,24 @@ func HandleCREATECHILDSA(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociation, temporaryPDUSessionSetupData *context.PDUSessionSetupTemporaryData, ) { + ikeLog := logger.IKELog n3iwfSelf := context.N3IWFSelf() // UE context ikeUe := ikeSecurityAssociation.IkeUE if ikeUe == nil { - logger.IKELog.Error("UE context is nil") + ikeLog.Error("UE context is nil") return } // PDU session information if temporaryPDUSessionSetupData == nil { - logger.IKELog.Error("No PDU session information") + ikeLog.Error("No PDU session information") return } if len(temporaryPDUSessionSetupData.UnactivatedPDUSession) == 0 { - logger.IKELog.Error("No unactivated PDU session information") + ikeLog.Error("No unactivated PDU session information") return } @@ -1222,13 +1226,13 @@ func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio childSecurityAssociationContext, err := ikeUe.CompleteChildSA( ikeSecurityAssociation.ResponderMessageID, outboundSPI, temporaryIkeMsg.SecurityAssociation) if err != nil { - logger.IKELog.Errorf("Create child security association context failed: %+v", err) + ikeLog.Errorf("Create child security association context failed: %+v", err) return } // Build TSi if there is no one in the response if len(temporaryIkeMsg.TrafficSelectorInitiator.TrafficSelectors) == 0 { - logger.IKELog.Warnf("There is no TSi in CREATE_CHILD_SA response.") + ikeLog.Warnf("There is no TSi in CREATE_CHILD_SA response.") n3iwfIPAddr := net.ParseIP(n3iwfSelf.IPSecGatewayAddress) temporaryIkeMsg.TrafficSelectorInitiator.TrafficSelectors.BuildIndividualTrafficSelector( ike_message.TS_IPV4_ADDR_RANGE, ike_message.IPProtocolAll, @@ -1237,7 +1241,7 @@ func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio // Build TSr if there is no one in the response if len(temporaryIkeMsg.TrafficSelectorResponder.TrafficSelectors) == 0 { - logger.IKELog.Warnf("There is no TSr in CREATE_CHILD_SA response.") + ikeLog.Warnf("There is no TSr in CREATE_CHILD_SA response.") ueIPAddr := ikeUe.IPSecInnerIP temporaryIkeMsg.TrafficSelectorResponder.TrafficSelectors.BuildIndividualTrafficSelector( ike_message.TS_IPV4_ADDR_RANGE, ike_message.IPProtocolAll, @@ -1249,14 +1253,14 @@ func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio temporaryIkeMsg.TrafficSelectorInitiator.TrafficSelectors[0], temporaryIkeMsg.TrafficSelectorResponder.TrafficSelectors[0]) if err != nil { - logger.IKELog.Errorf("Parse IP address to child security association failed: %+v", err) + ikeLog.Errorf("Parse IP address to child security association failed: %+v", err) return } // Select GRE traffic childSecurityAssociationContext.SelectedIPProtocol = unix.IPPROTO_GRE if errGen := GenerateKeyForChildSA(ikeSecurityAssociation, childSecurityAssociationContext); errGen != nil { - logger.IKELog.Errorf("Generate key for child SA failed: %+v", errGen) + ikeLog.Errorf("Generate key for child SA failed: %+v", errGen) return } // NAT-T concern @@ -1282,7 +1286,7 @@ func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio if linkIPSec, err = xfrm.SetupIPsecXfrmi(newXfrmiName, n3iwfSelf.XfrmParentIfaceName, newXfrmiId, n3iwfIPAddrAndSubnet); err != nil { - logger.IKELog.Errorf("Setup XFRM interface %s fail: %+v", newXfrmiName, err) + ikeLog.Errorf("Setup XFRM interface %s fail: %+v", newXfrmiName, err) return } @@ -1293,19 +1297,19 @@ func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio if linkIPSec, ok := n3iwfSelf.XfrmIfaces.Load(newXfrmiId); ok { childSecurityAssociationContext.XfrmIface = linkIPSec.(netlink.Link) } else { - logger.IKELog.Warnf("Cannot find the XFRM interface with if_id: %d", newXfrmiId) + ikeLog.Warnf("Cannot find the XFRM interface with if_id: %d", newXfrmiId) return } } // Aplly XFRM rules if err = xfrm.ApplyXFRMRule(true, newXfrmiId, childSecurityAssociationContext); err != nil { - logger.IKELog.Errorf("Applying XFRM rules failed: %+v", err) + ikeLog.Errorf("Applying XFRM rules failed: %+v", err) return } else { ranNgapId, ok := n3iwfSelf.NgapIdLoad(ikeSecurityAssociation.LocalSPI) if !ok { - logger.IKELog.Errorf("Cannot get RanNgapId from SPI : %+v", ikeSecurityAssociation.LocalSPI) + ikeLog.Errorf("Cannot get RanNgapId from SPI : %+v", ikeSecurityAssociation.LocalSPI) return } // Forward PDU Seesion Establishment Accept to UE @@ -1323,10 +1327,11 @@ func continueCreateChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio } func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, message *ike_message.IKEMessage) { - logger.IKELog.Infoln("Handle Informational") + ikeLog := logger.IKELog + ikeLog.Infoln("Handle Informational") if message == nil { - logger.IKELog.Error("IKE Message is nil") + ikeLog.Error("IKE Message is nil") return } @@ -1337,7 +1342,7 @@ func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m var encryptedPayload *ike_message.Encrypted if !ok { - logger.IKELog.Warn("Unrecognized SPI") + ikeLog.Warn("Unrecognized SPI") // send INFORMATIONAL type message with INVALID_IKE_SPI Notify payload ( OUTSIDE IKE SA ) responseIKEMessage.BuildIKEHeader(0, message.ResponderSPI, ike_message.INFORMATIONAL, ike_message.ResponseBitCheck, message.MessageID) @@ -1354,7 +1359,7 @@ func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m case ike_message.TypeSK: encryptedPayload = ikePayload.(*ike_message.Encrypted) default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in Inoformational message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -1362,7 +1367,7 @@ func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m decryptedIKEPayload, err := DecryptProcedure(ikeSecurityAssociation, message, encryptedPayload) if err != nil { - logger.IKELog.Errorf("Decrypt IKE message failed: %+v", err) + ikeLog.Errorf("Decrypt IKE message failed: %+v", err) return } @@ -1385,13 +1390,13 @@ func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m ranNgapId, ok := n3iwfSelf.NgapIdLoad(n3iwfIke.N3IWFIKESecurityAssociation.LocalSPI) if !ok { - logger.IKELog.Errorf("Cannot get RanNgapId from SPI : %+v", n3iwfIke.N3IWFIKESecurityAssociation.LocalSPI) + ikeLog.Errorf("Cannot get RanNgapId from SPI : %+v", n3iwfIke.N3IWFIKESecurityAssociation.LocalSPI) return } if deletePayload.ProtocolID == ike_message.TypeIKE { // Check if UE is response to a request that delete the ike SA if err := n3iwfIke.Remove(); err != nil { - logger.IKELog.Errorf("Delete IkeUe Context error : %+v", err) + ikeLog.Errorf("Delete IkeUe Context error : %+v", err) } n3iwfSelf.NGAPServer.RcvEventCh <- context.NewSendUEContextReleaseCompleteEvt( ranNgapId, @@ -1402,7 +1407,7 @@ func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m ) } default: - logger.IKELog.Warnf( + ikeLog.Warnf( "Get IKE payload (type %d) in Inoformational message, this payload will not be handled by IKE handler", ikePayload.Type()) } @@ -1411,7 +1416,8 @@ func HandleInformational(udpConn *net.UDPConn, n3iwfAddr, ueAddr *net.UDPAddr, m } func HandleEvent(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle IKE event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle IKE event") switch ikeEvt.Type() { case context.UnmarshalEAP5GDataResponse: @@ -1433,13 +1439,14 @@ func HandleEvent(ikeEvt context.IkeEvt) { case context.GetNGAPContextResponse: HandleGetNGAPContextResponse(ikeEvt) default: - logger.IKELog.Errorf("Undefine IKE event type : %d", ikeEvt.Type()) + ikeLog.Errorf("Undefine IKE event type : %d", ikeEvt.Type()) return } } func HandleUnmarshalEAP5GDataResponse(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle UnmarshalEAP5GDataResponse event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle UnmarshalEAP5GDataResponse event") unmarshalEAP5GDataResponseEvt := ikeEvt.(*context.UnmarshalEAP5GDataResponseEvt) localSPI := unmarshalEAP5GDataResponseEvt.LocalSPI @@ -1468,7 +1475,8 @@ func HandleUnmarshalEAP5GDataResponse(ikeEvt context.IkeEvt) { } func HandleSendEAP5GFailureMsg(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle SendEAP5GFailureMsg event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle SendEAP5GFailureMsg event") sendEAP5GFailureMsgEvt := ikeEvt.(*context.SendEAP5GFailureMsgEvt) errMsg := sendEAP5GFailureMsgEvt.ErrMsg @@ -1476,7 +1484,7 @@ func HandleSendEAP5GFailureMsg(ikeEvt context.IkeEvt) { n3iwfSelf := context.N3IWFSelf() ikeSecurityAssociation, _ := n3iwfSelf.IKESALoad(localSPI) - logger.IKELog.Warnf("EAP Failure : %s", errMsg.Error()) + ikeLog.Warnf("EAP Failure : %s", errMsg.Error()) responseIKEMessage := new(ike_message.IKEMessage) var responseIKEPayload ike_message.IKEPayloadContainer @@ -1489,13 +1497,13 @@ func HandleSendEAP5GFailureMsg(ikeEvt context.IkeEvt) { // EAP identifier, err := GenerateRandomUint8() if err != nil { - logger.IKELog.Errorf("Generate random uint8 failed: %+v", err) + ikeLog.Errorf("Generate random uint8 failed: %+v", err) return } responseIKEPayload.BuildEAPfailure(identifier) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -1506,7 +1514,8 @@ func HandleSendEAP5GFailureMsg(ikeEvt context.IkeEvt) { } func HandleSendEAPSuccessMsg(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle SendEAPSuccessMsg event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle SendEAPSuccessMsg event") sendEAPSuccessMsgEvt := ikeEvt.(*context.SendEAPSuccessMsgEvt) localSPI := sendEAPSuccessMsgEvt.LocalSPI @@ -1543,7 +1552,7 @@ func HandleSendEAPSuccessMsg(ikeEvt context.IkeEvt) { responseIKEPayload.BuildEAPSuccess(identifier) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -1556,7 +1565,8 @@ func HandleSendEAPSuccessMsg(ikeEvt context.IkeEvt) { } func HandleSendEAPNASMsg(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle SendEAPNASMsg event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle SendEAPNASMsg event") sendEAPNASMsgEvt := ikeEvt.(*context.SendEAPNASMsgEvt) localSPI := sendEAPNASMsgEvt.LocalSPI @@ -1586,7 +1596,7 @@ func HandleSendEAPNASMsg(ikeEvt context.IkeEvt) { responseIKEPayload.BuildEAP5GNAS(identifier, nasPDU) if err := EncryptProcedure(ikeSecurityAssociation, responseIKEPayload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } @@ -1597,7 +1607,8 @@ func HandleSendEAPNASMsg(ikeEvt context.IkeEvt) { } func HandleCreatePDUSession(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle CreatePDUSession event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle CreatePDUSession event") createPDUSessionEvt := ikeEvt.(*context.CreatePDUSessionEvt) localSPI := createPDUSessionEvt.LocalSPI @@ -1613,7 +1624,8 @@ func HandleCreatePDUSession(ikeEvt context.IkeEvt) { } func HandleIKEDeleteRequest(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle IKEDeleteRequest event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle IKEDeleteRequest event") ikeDeleteRequest := ikeEvt.(*context.IKEDeleteRequestEvt) localSPI := ikeDeleteRequest.LocalSPI @@ -1622,7 +1634,8 @@ func HandleIKEDeleteRequest(ikeEvt context.IkeEvt) { } func HandleSendChildSADeleteRequest(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle SendChildSADeleteRequest event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle SendChildSADeleteRequest event") sendChildSADeleteRequestEvt := ikeEvt.(*context.SendChildSADeleteRequestEvt) localSPI := sendChildSADeleteRequestEvt.LocalSPI @@ -1630,14 +1643,15 @@ func HandleSendChildSADeleteRequest(ikeEvt context.IkeEvt) { ikeUe, ok := context.N3IWFSelf().IkeUePoolLoad(localSPI) if !ok { - logger.IKELog.Errorf("Cannot get IkeUE from SPI : %+v", localSPI) + ikeLog.Errorf("Cannot get IkeUE from SPI : %+v", localSPI) return } SendChildSADeleteRequest(ikeUe, releaseIdList) } func HandleIKEContextUpdate(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle IKEContextUpdate event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle IKEContextUpdate event") ikeContextUpdateEvt := ikeEvt.(*context.IKEContextUpdateEvt) localSPI := ikeContextUpdateEvt.LocalSPI @@ -1645,7 +1659,7 @@ func HandleIKEContextUpdate(ikeEvt context.IkeEvt) { ikeUe, ok := context.N3IWFSelf().IkeUePoolLoad(localSPI) if !ok { - logger.IKELog.Errorf("Cannot get IkeUE from SPI : %+v", localSPI) + ikeLog.Errorf("Cannot get IkeUE from SPI : %+v", localSPI) return } @@ -1655,7 +1669,8 @@ func HandleIKEContextUpdate(ikeEvt context.IkeEvt) { } func HandleGetNGAPContextResponse(ikeEvt context.IkeEvt) { - logger.IKELog.Infof("Handle GetNGAPContextResponse event") + ikeLog := logger.IKELog + ikeLog.Infof("Handle GetNGAPContextResponse event") getNGAPContextRepEvt := ikeEvt.(*context.GetNGAPContextRepEvt) localSPI := getNGAPContextRepEvt.LocalSPI @@ -1672,7 +1687,7 @@ func HandleGetNGAPContextResponse(ikeEvt context.IkeEvt) { case context.CxtTempPDUSessionSetupData: tempPDUSessionSetupData = ngapCxt[i].(*context.PDUSessionSetupTemporaryData) default: - logger.IKELog.Errorf("Receive undefine NGAP Context Request number : %d", num) + ikeLog.Errorf("Receive undefine NGAP Context Request number : %d", num) } } @@ -1689,12 +1704,13 @@ func HandleGetNGAPContextResponse(ikeEvt context.IkeEvt) { func CreatePDUSessionChildSA(ikeUe *context.N3IWFIkeUe, temporaryPDUSessionSetupData *context.PDUSessionSetupTemporaryData, ) { + ikeLog := logger.IKELog n3iwfSelf := context.N3IWFSelf() ikeSecurityAssociation := ikeUe.N3IWFIKESecurityAssociation ranNgapId, ok := n3iwfSelf.NgapIdLoad(ikeUe.N3IWFIKESecurityAssociation.LocalSPI) if !ok { - logger.IKELog.Errorf("Cannot get RanNgapId from SPI : %+v", ikeUe.N3IWFIKESecurityAssociation.LocalSPI) + ikeLog.Errorf("Cannot get RanNgapId from SPI : %+v", ikeUe.N3IWFIKESecurityAssociation.LocalSPI) return } @@ -1784,7 +1800,7 @@ func CreatePDUSessionChildSA(ikeUe *context.N3IWFIkeUe, temporaryPDUSessionSetupData.Index++ if err := EncryptProcedure(ikeUe.N3IWFIKESecurityAssociation, ikePayload, ikeMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) errStr = context.ErrTransportResourceUnavailable temporaryPDUSessionSetupData.FailedErrStr = append(temporaryPDUSessionSetupData.FailedErrStr, errStr) @@ -2036,6 +2052,7 @@ func parseIPAddressInformationToChildSecurityAssociation( trafficSelectorLocal *ike_message.IndividualTrafficSelector, trafficSelectorRemote *ike_message.IndividualTrafficSelector, ) error { + ikeLog := logger.IKELog if childSecurityAssociation == nil { return errors.New("childSecurityAssociation is nil") } @@ -2043,8 +2060,8 @@ func parseIPAddressInformationToChildSecurityAssociation( childSecurityAssociation.PeerPublicIPAddr = uePublicIPAddr childSecurityAssociation.LocalPublicIPAddr = net.ParseIP(context.N3IWFSelf().IKEBindAddress) - logger.IKELog.Tracef("Local TS: %+v", trafficSelectorLocal.StartAddress) - logger.IKELog.Tracef("Remote TS: %+v", trafficSelectorRemote.StartAddress) + ikeLog.Tracef("Local TS: %+v", trafficSelectorLocal.StartAddress) + ikeLog.Tracef("Remote TS: %+v", trafficSelectorRemote.StartAddress) childSecurityAssociation.TrafficSelectorLocal = net.IPNet{ IP: trafficSelectorLocal.StartAddress, diff --git a/pkg/ike/handler/security.go b/pkg/ike/handler/security.go index 57bb2acf..a47305d7 100644 --- a/pkg/ike/handler/security.go +++ b/pkg/ike/handler/security.go @@ -35,10 +35,12 @@ func init() { func GenerateRandomNumber() *big.Int { var number *big.Int var err error + + ikeLog := logger.IKELog for { number, err = rand.Int(rand.Reader, &randomNumberMaximum) if err != nil { - logger.IKELog.Errorf("Error occurs when generate random number: %+v", err) + ikeLog.Errorf("Error occurs when generate random number: %+v", err) return nil } else { if number.Cmp(&randomNumberMinimum) == 1 { @@ -50,10 +52,11 @@ func GenerateRandomNumber() *big.Int { } func GenerateRandomUint8() (uint8, error) { + ikeLog := logger.IKELog number := make([]byte, 1) _, err := io.ReadFull(rand.Reader, number) if err != nil { - logger.IKELog.Errorf("Read random failed: %+v", err) + ikeLog.Errorf("Read random failed: %+v", err) return 0, errors.New("Read failed") } return number[0], nil @@ -93,6 +96,7 @@ const ( func CalculateDiffieHellmanMaterials(secret *big.Int, peerPublicValue []byte, diffieHellmanGroupNumber uint16, ) (localPublicValue []byte, sharedKey []byte) { + ikeLog := logger.IKELog peerPublicValueBig := new(big.Int).SetBytes(peerPublicValue) var generator, factor *big.Int var ok bool @@ -102,7 +106,7 @@ func CalculateDiffieHellmanMaterials(secret *big.Int, peerPublicValue []byte, generator = new(big.Int).SetUint64(Group2Generator) factor, ok = new(big.Int).SetString(Group2PrimeString, 16) if !ok { - logger.IKELog.Errorf( + ikeLog.Errorf( "Error occurs when setting big number \"factor\" in %d group", diffieHellmanGroupNumber) } @@ -110,12 +114,12 @@ func CalculateDiffieHellmanMaterials(secret *big.Int, peerPublicValue []byte, generator = new(big.Int).SetUint64(Group14Generator) factor, ok = new(big.Int).SetString(Group14PrimeString, 16) if !ok { - logger.IKELog.Errorf( + ikeLog.Errorf( "Error occurs when setting big number \"factor\" in %d group", diffieHellmanGroupNumber) } default: - logger.IKELog.Errorf("Unsupported Diffie-Hellman group: %d", diffieHellmanGroupNumber) + ikeLog.Errorf("Unsupported Diffie-Hellman group: %d", diffieHellmanGroupNumber) return localPublicValue, sharedKey } @@ -132,19 +136,21 @@ func CalculateDiffieHellmanMaterials(secret *big.Int, peerPublicValue []byte, // Pseudorandom Function func NewPseudorandomFunction(key []byte, algorithmType uint16) (hash.Hash, bool) { + ikeLog := logger.IKELog switch algorithmType { case message.PRF_HMAC_MD5: return hmac.New(md5.New, key), true case message.PRF_HMAC_SHA1: return hmac.New(sha1.New, key), true default: - logger.IKELog.Errorf("Unsupported pseudo random function: %d", algorithmType) + ikeLog.Errorf("Unsupported pseudo random function: %d", algorithmType) return nil, false } } // Integrity Algorithm func CalculateChecksum(key []byte, originData []byte, algorithmType uint16) ([]byte, error) { + ikeLog := logger.IKELog switch algorithmType { case message.AUTH_HMAC_MD5_96: if len(key) != 16 { @@ -152,7 +158,7 @@ func CalculateChecksum(key []byte, originData []byte, algorithmType uint16) ([]b } integrityFunction := hmac.New(md5.New, key) if _, err := integrityFunction.Write(originData); err != nil { - logger.IKELog.Errorf("Hash function write error when calculating checksum: %+v", err) + ikeLog.Errorf("Hash function write error when calculating checksum: %+v", err) return nil, errors.New("Hash function write error") } return integrityFunction.Sum(nil), nil @@ -162,17 +168,18 @@ func CalculateChecksum(key []byte, originData []byte, algorithmType uint16) ([]b } integrityFunction := hmac.New(sha1.New, key) if _, err := integrityFunction.Write(originData); err != nil { - logger.IKELog.Errorf("Hash function write error when calculating checksum: %+v", err) + ikeLog.Errorf("Hash function write error when calculating checksum: %+v", err) return nil, errors.New("Hash function write error") } return integrityFunction.Sum(nil)[:12], nil default: - logger.IKELog.Errorf("Unsupported integrity function: %d", algorithmType) + ikeLog.Errorf("Unsupported integrity function: %d", algorithmType) return nil, errors.New("Unsupported algorithm") } } func VerifyIKEChecksum(key []byte, originData []byte, checksum []byte, algorithmType uint16) (bool, error) { + ikeLog := logger.IKELog switch algorithmType { case message.AUTH_HMAC_MD5_96: if len(key) != 16 { @@ -180,12 +187,12 @@ func VerifyIKEChecksum(key []byte, originData []byte, checksum []byte, algorithm } integrityFunction := hmac.New(md5.New, key) if _, err := integrityFunction.Write(originData); err != nil { - logger.IKELog.Errorf("Hash function write error when verifying IKE checksum: %+v", err) + ikeLog.Errorf("Hash function write error when verifying IKE checksum: %+v", err) return false, errors.New("Hash function write error") } checksumOfMessage := integrityFunction.Sum(nil) - logger.IKELog.Tracef("Calculated checksum:\n%s\nReceived checksum:\n%s", + ikeLog.Tracef("Calculated checksum:\n%s\nReceived checksum:\n%s", hex.Dump(checksumOfMessage), hex.Dump(checksum)) return hmac.Equal(checksumOfMessage, checksum), nil @@ -195,23 +202,24 @@ func VerifyIKEChecksum(key []byte, originData []byte, checksum []byte, algorithm } integrityFunction := hmac.New(sha1.New, key) if _, err := integrityFunction.Write(originData); err != nil { - logger.IKELog.Errorf("Hash function write error when verifying IKE checksum: %+v", err) + ikeLog.Errorf("Hash function write error when verifying IKE checksum: %+v", err) return false, errors.New("Hash function write error") } checksumOfMessage := integrityFunction.Sum(nil)[:12] - logger.IKELog.Tracef("Calculated checksum:\n%s\nReceived checksum:\n%s", + ikeLog.Tracef("Calculated checksum:\n%s\nReceived checksum:\n%s", hex.Dump(checksumOfMessage), hex.Dump(checksum)) return hmac.Equal(checksumOfMessage, checksum), nil default: - logger.IKELog.Errorf("Unsupported integrity function: %d", algorithmType) + ikeLog.Errorf("Unsupported integrity function: %d", algorithmType) return false, errors.New("Unsupported algorithm") } } // Encryption Algorithm func EncryptMessage(key []byte, originData []byte, algorithmType uint16) ([]byte, error) { + ikeLog := logger.IKELog switch algorithmType { case message.ENCR_AES_CBC: // padding message @@ -220,7 +228,7 @@ func EncryptMessage(key []byte, originData []byte, algorithmType uint16) ([]byte block, err := aes.NewCipher(key) if err != nil { - logger.IKELog.Errorf("Error occur when create new cipher: %+v", err) + ikeLog.Errorf("Error occur when create new cipher: %+v", err) return nil, errors.New("Create cipher failed") } @@ -229,7 +237,7 @@ func EncryptMessage(key []byte, originData []byte, algorithmType uint16) ([]byte _, err = io.ReadFull(rand.Reader, initializationVector) if err != nil { - logger.IKELog.Errorf("Read random failed: %+v", err) + ikeLog.Errorf("Read random failed: %+v", err) return nil, errors.New("Read random initialization vector failed") } @@ -238,16 +246,17 @@ func EncryptMessage(key []byte, originData []byte, algorithmType uint16) ([]byte return cipherText, nil default: - logger.IKELog.Errorf("Unsupported encryption algorithm: %d", algorithmType) + ikeLog.Errorf("Unsupported encryption algorithm: %d", algorithmType) return nil, errors.New("Unsupported algorithm") } } func DecryptMessage(key []byte, cipherText []byte, algorithmType uint16) ([]byte, error) { + ikeLog := logger.IKELog switch algorithmType { case message.ENCR_AES_CBC: if len(cipherText) < aes.BlockSize { - logger.IKELog.Error("Length of cipher text is too short to decrypt") + ikeLog.Error("Length of cipher text is too short to decrypt") return nil, errors.New("Cipher text is too short") } @@ -255,7 +264,7 @@ func DecryptMessage(key []byte, cipherText []byte, algorithmType uint16) ([]byte encryptedMessage := cipherText[aes.BlockSize:] if len(encryptedMessage)%aes.BlockSize != 0 { - logger.IKELog.Error("Cipher text is not a multiple of block size") + ikeLog.Error("Cipher text is not a multiple of block size") return nil, errors.New("Cipher text length error") } @@ -263,22 +272,22 @@ func DecryptMessage(key []byte, cipherText []byte, algorithmType uint16) ([]byte block, err := aes.NewCipher(key) if err != nil { - logger.IKELog.Errorf("Error occur when create new cipher: %+v", err) + ikeLog.Errorf("Error occur when create new cipher: %+v", err) return nil, errors.New("Create cipher failed") } cbcBlockMode := cipher.NewCBCDecrypter(block, initializationVector) cbcBlockMode.CryptBlocks(plainText, encryptedMessage) - logger.IKELog.Tracef("Decrypted content:\n%s", hex.Dump(plainText)) + ikeLog.Tracef("Decrypted content:\n%s", hex.Dump(plainText)) padding := int(plainText[len(plainText)-1]) + 1 plainText = plainText[:len(plainText)-padding] - logger.IKELog.Tracef("Decrypted content with out padding:\n%s", hex.Dump(plainText)) + ikeLog.Tracef("Decrypted content with out padding:\n%s", hex.Dump(plainText)) return plainText, nil default: - logger.IKELog.Errorf("Unsupported encryption algorithm: %d", algorithmType) + ikeLog.Errorf("Unsupported encryption algorithm: %d", algorithmType) return nil, errors.New("Unsupported algorithm") } } @@ -294,15 +303,16 @@ func PKCS7Padding(plainText []byte, blockSize int) []byte { // Certificate func CompareRootCertificate(certificateEncoding uint8, requestedCertificateAuthorityHash []byte) bool { + ikeLog := logger.IKELog if certificateEncoding != message.X509CertificateSignature { - logger.IKELog.Debugf("Not support certificate type: %d. Reject.", certificateEncoding) + ikeLog.Debugf("Not support certificate type: %d. Reject.", certificateEncoding) return false } n3iwfSelf := context.N3IWFSelf() if len(n3iwfSelf.CertificateAuthority) == 0 { - logger.IKELog.Error("Certificate authority in context is empty") + ikeLog.Error("Certificate authority in context is empty") return false } @@ -311,6 +321,7 @@ func CompareRootCertificate(certificateEncoding uint8, requestedCertificateAutho // Key Gen for IKE SA func GenerateKeyForIKESA(ikeSecurityAssociation *context.IKESecurityAssociation) error { + ikeLog := logger.IKELog // Check parameters if ikeSecurityAssociation == nil { return errors.New("IKE SA is nil") @@ -349,20 +360,20 @@ func GenerateKeyForIKESA(ikeSecurityAssociation *context.IKESecurityAssociation) if length_SK_d, ok = getKeyLength(transformPseudorandomFunction.TransformType, transformPseudorandomFunction.TransformID, transformPseudorandomFunction.AttributePresent, transformPseudorandomFunction.AttributeValue); !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return errors.New("Get key length failed") } if length_SK_ai, ok = getKeyLength(transformIntegrityAlgorithm.TransformType, transformIntegrityAlgorithm.TransformID, transformIntegrityAlgorithm.AttributePresent, transformIntegrityAlgorithm.AttributeValue); !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return errors.New("Get key length failed") } length_SK_ar = length_SK_ai if length_SK_ei, ok = getKeyLength(transformEncryptionAlgorithm.TransformType, transformEncryptionAlgorithm.TransformID, transformEncryptionAlgorithm.AttributePresent, transformEncryptionAlgorithm.AttributeValue); !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return errors.New("Get key length failed") } length_SK_er = length_SK_ei @@ -374,21 +385,21 @@ func GenerateKeyForIKESA(ikeSecurityAssociation *context.IKESecurityAssociation) if pseudorandomFunction, ok = NewPseudorandomFunction(ikeSecurityAssociation.ConcatenatedNonce, transformPseudorandomFunction.TransformID); !ok { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return errors.New("New pseudorandom function failed") } - logger.IKELog.Tracef("DH shared key:\n%s", hex.Dump(ikeSecurityAssociation.DiffieHellmanSharedKey)) - logger.IKELog.Tracef("Concatenated nonce:\n%s", hex.Dump(ikeSecurityAssociation.ConcatenatedNonce)) + ikeLog.Tracef("DH shared key:\n%s", hex.Dump(ikeSecurityAssociation.DiffieHellmanSharedKey)) + ikeLog.Tracef("Concatenated nonce:\n%s", hex.Dump(ikeSecurityAssociation.ConcatenatedNonce)) if _, err := pseudorandomFunction.Write(ikeSecurityAssociation.DiffieHellmanSharedKey); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return errors.New("Pseudorandom function write failed") } SKEYSEED := pseudorandomFunction.Sum(nil) - logger.IKELog.Tracef("SKEYSEED:\n%s", hex.Dump(SKEYSEED)) + ikeLog.Tracef("SKEYSEED:\n%s", hex.Dump(SKEYSEED)) seed := concatenateNonceAndSPI(ikeSecurityAssociation.ConcatenatedNonce, ikeSecurityAssociation.RemoteSPI, ikeSecurityAssociation.LocalSPI) @@ -397,11 +408,11 @@ func GenerateKeyForIKESA(ikeSecurityAssociation *context.IKESecurityAssociation) var index byte for index = 1; len(keyStream) < totalKeyLength; index++ { if pseudorandomFunction, ok = NewPseudorandomFunction(SKEYSEED, transformPseudorandomFunction.TransformID); !ok { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return errors.New("New pseudorandom function failed") } if _, err := pseudorandomFunction.Write(append(append(generatedKeyBlock, seed...), index)); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return errors.New("Pseudorandom function write failed") } generatedKeyBlock = pseudorandomFunction.Sum(nil) @@ -424,17 +435,17 @@ func GenerateKeyForIKESA(ikeSecurityAssociation *context.IKESecurityAssociation) ikeSecurityAssociation.SK_pr = keyStream[:length_SK_pr] // keyStream = keyStream[length_SK_pr:] - logger.IKELog.Debugln("====== IKE Security Association Info =====") - logger.IKELog.Debugf("Initiator's SPI: %016x", ikeSecurityAssociation.RemoteSPI) - logger.IKELog.Debugf("Responder's SPI: %016x", ikeSecurityAssociation.LocalSPI) - logger.IKELog.Debugf("Encryption Algorithm: %d", ikeSecurityAssociation.EncryptionAlgorithm.TransformID) - logger.IKELog.Debugf("SK_ei: %x", ikeSecurityAssociation.SK_ei) - logger.IKELog.Debugf("SK_er: %x", ikeSecurityAssociation.SK_er) - logger.IKELog.Debugf("Integrity Algorithm: %d", ikeSecurityAssociation.IntegrityAlgorithm.TransformID) - logger.IKELog.Debugf("SK_ai: %x", ikeSecurityAssociation.SK_ai) - logger.IKELog.Debugf("SK_ar: %x", ikeSecurityAssociation.SK_ar) - logger.IKELog.Debugf("SK_pi: %x", ikeSecurityAssociation.SK_pi) - logger.IKELog.Debugf("SK_pr: %x", ikeSecurityAssociation.SK_pr) + ikeLog.Debugln("====== IKE Security Association Info =====") + ikeLog.Debugf("Initiator's SPI: %016x", ikeSecurityAssociation.RemoteSPI) + ikeLog.Debugf("Responder's SPI: %016x", ikeSecurityAssociation.LocalSPI) + ikeLog.Debugf("Encryption Algorithm: %d", ikeSecurityAssociation.EncryptionAlgorithm.TransformID) + ikeLog.Debugf("SK_ei: %x", ikeSecurityAssociation.SK_ei) + ikeLog.Debugf("SK_er: %x", ikeSecurityAssociation.SK_er) + ikeLog.Debugf("Integrity Algorithm: %d", ikeSecurityAssociation.IntegrityAlgorithm.TransformID) + ikeLog.Debugf("SK_ai: %x", ikeSecurityAssociation.SK_ai) + ikeLog.Debugf("SK_ar: %x", ikeSecurityAssociation.SK_ar) + ikeLog.Debugf("SK_pi: %x", ikeSecurityAssociation.SK_pi) + ikeLog.Debugf("SK_pr: %x", ikeSecurityAssociation.SK_pr) return nil } @@ -443,6 +454,7 @@ func GenerateKeyForIKESA(ikeSecurityAssociation *context.IKESecurityAssociation) func GenerateKeyForChildSA(ikeSecurityAssociation *context.IKESecurityAssociation, childSecurityAssociation *context.ChildSecurityAssociation, ) error { + ikeLog := logger.IKELog // Check parameters if ikeSecurityAssociation == nil { return errors.New("IKE SA is nil") @@ -485,7 +497,7 @@ func GenerateKeyForChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio transformEncryptionAlgorithmForIPSec.TransformID, transformEncryptionAlgorithmForIPSec.AttributePresent, transformEncryptionAlgorithmForIPSec.AttributeValue); !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return errors.New("Get key length failed") } if transformIntegrityAlgorithmForIPSec != nil { @@ -493,7 +505,7 @@ func GenerateKeyForChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio transformIntegrityAlgorithmForIPSec.TransformID, transformIntegrityAlgorithmForIPSec.AttributePresent, transformIntegrityAlgorithmForIPSec.AttributeValue); !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return errors.New("Get key length failed") } } @@ -509,11 +521,11 @@ func GenerateKeyForChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio for index = 1; len(keyStream) < totalKeyLength; index++ { if pseudorandomFunction, ok = NewPseudorandomFunction(ikeSecurityAssociation.SK_d, transformPseudorandomFunction.TransformID); !ok { - logger.IKELog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get an unsupported pseudorandom funcion. This may imply an unsupported transform is chosen.") return errors.New("New pseudorandom function failed") } if _, err := pseudorandomFunction.Write(append(append(generatedKeyBlock, seed...), index)); err != nil { - logger.IKELog.Errorf("Pseudorandom function write error: %+v", err) + ikeLog.Errorf("Pseudorandom function write error: %+v", err) return errors.New("Pseudorandom function write failed") } generatedKeyBlock = pseudorandomFunction.Sum(nil) @@ -543,6 +555,7 @@ func GenerateKeyForChildSA(ikeSecurityAssociation *context.IKESecurityAssociatio func DecryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ikeMessage *message.IKEMessage, encryptedPayload *message.Encrypted, ) (message.IKEPayloadContainer, error) { + ikeLog := logger.IKELog // Check parameters if ikeSecurityAssociation == nil { return nil, errors.New("IKE SA is nil") @@ -576,7 +589,7 @@ func DecryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ik transformIntegrityAlgorithm.TransformID, transformIntegrityAlgorithm.AttributePresent, transformIntegrityAlgorithm.AttributeValue) if !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return nil, errors.New("Get key length failed") } @@ -585,8 +598,8 @@ func DecryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ik ikeMessageData, err := ikeMessage.Encode() if err != nil { - logger.IKELog.Errorln(err) - logger.IKELog.Error("Error occur when encoding for checksum") + ikeLog.Errorln(err) + ikeLog.Error("Error occur when encoding for checksum") return nil, errors.New("Encoding IKE message failed") } @@ -594,11 +607,11 @@ func DecryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ik ikeMessageData[:len(ikeMessageData)-checksumLength], checksum, transformIntegrityAlgorithm.TransformID) if err != nil { - logger.IKELog.Errorf("Error occur when verifying checksum: %+v", err) + ikeLog.Errorf("Error occur when verifying checksum: %+v", err) return nil, errors.New("Error verify checksum") } if !ok { - logger.IKELog.Warn("Message checksum failed. Drop the message.") + ikeLog.Warn("Message checksum failed. Drop the message.") return nil, errors.New("Checksum failed, drop.") } @@ -607,14 +620,14 @@ func DecryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ik plainText, err := DecryptMessage(ikeSecurityAssociation.SK_ei, encryptedData, transformEncryptionAlgorithm.TransformID) if err != nil { - logger.IKELog.Errorf("Error occur when decrypting message: %+v", err) + ikeLog.Errorf("Error occur when decrypting message: %+v", err) return nil, errors.New("Error decrypting message") } var decryptedIKEPayload message.IKEPayloadContainer err = decryptedIKEPayload.Decode(encryptedPayload.NextPayload, plainText) if err != nil { - logger.IKELog.Errorln(err) + ikeLog.Errorln(err) return nil, errors.New("Decoding decrypted payload failed") } @@ -625,6 +638,7 @@ func DecryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ik func EncryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, ikePayload message.IKEPayloadContainer, responseIKEMessage *message.IKEMessage, ) error { + ikeLog := logger.IKELog // Check parameters if ikeSecurityAssociation == nil { return errors.New("IKE SA is nil") @@ -658,21 +672,21 @@ func EncryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, transformIntegrityAlgorithm.TransformID, transformIntegrityAlgorithm.AttributePresent, transformIntegrityAlgorithm.AttributeValue) if !ok { - logger.IKELog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") + ikeLog.Error("Get key length of an unsupported algorithm. This may imply an unsupported transform is chosen.") return errors.New("Get key length failed") } // Encrypting ikePayloadData, err := ikePayload.Encode() if err != nil { - logger.IKELog.Error(err) + ikeLog.Error(err) return errors.New("Encoding IKE payload failed.") } encryptedData, err := EncryptMessage(ikeSecurityAssociation.SK_er, ikePayloadData, transformEncryptionAlgorithm.TransformID) if err != nil { - logger.IKELog.Errorf("Encrypting data error: %+v", err) + ikeLog.Errorf("Encrypting data error: %+v", err) return errors.New("Error encrypting message") } @@ -682,14 +696,14 @@ func EncryptProcedure(ikeSecurityAssociation *context.IKESecurityAssociation, // Calculate checksum responseIKEMessageData, err := responseIKEMessage.Encode() if err != nil { - logger.IKELog.Error(err) + ikeLog.Error(err) return errors.New("Encoding IKE message error") } checksumOfMessage, err := CalculateChecksum(ikeSecurityAssociation.SK_ar, responseIKEMessageData[:len(responseIKEMessageData)-checksumLength], transformIntegrityAlgorithm.TransformID) if err != nil { - logger.IKELog.Errorf("Calculating checksum failed: %+v", err) + ikeLog.Errorf("Calculating checksum failed: %+v", err) return errors.New("Error calculating checksum") } checksumField := sk.EncryptedData[len(sk.EncryptedData)-checksumLength:] @@ -834,9 +848,15 @@ func getKeyLength(transformType uint8, transformID uint16, attributePresent bool } } -func getOutputLength(transformType uint8, transformID uint16, attributePresent bool, +func getOutputLength( + transformType uint8, + transformID uint16, + attributePresent bool, attributeValue uint16, ) (int, bool) { + _ = attributePresent + _ = attributeValue + switch transformType { case message.TypePseudorandomFunction: switch transformID { diff --git a/pkg/ike/handler/send.go b/pkg/ike/handler/send.go index 330bb26b..b6bcddd9 100644 --- a/pkg/ike/handler/send.go +++ b/pkg/ike/handler/send.go @@ -13,11 +13,12 @@ import ( ) func SendIKEMessageToUE(udpConn *net.UDPConn, srcAddr, dstAddr *net.UDPAddr, message *ike_message.IKEMessage) { - logger.IKELog.Trace("Send IKE message to UE") - logger.IKELog.Trace("Encoding...") + ikeLog := logger.IKELog + ikeLog.Trace("Send IKE message to UE") + ikeLog.Trace("Encoding...") pkt, err := message.Encode() if err != nil { - logger.IKELog.Errorln(err) + ikeLog.Errorln(err) return } // As specified in RFC 7296 section 3.1, the IKE message send from/to UDP port 4500 @@ -27,14 +28,14 @@ func SendIKEMessageToUE(udpConn *net.UDPConn, srcAddr, dstAddr *net.UDPAddr, mes pkt = append(prependZero, pkt...) } - logger.IKELog.Trace("Sending...") + ikeLog.Trace("Sending...") n, err := udpConn.WriteToUDP(pkt, dstAddr) if err != nil { - logger.IKELog.Error(err) + ikeLog.Error(err) return } if n != len(pkt) { - logger.IKELog.Errorf("Not all of the data is sent. Total length: %d. Sent: %d.", len(pkt), n) + ikeLog.Errorf("Not all of the data is sent. Total length: %d. Sent: %d.", len(pkt), n) return } } @@ -42,6 +43,7 @@ func SendIKEMessageToUE(udpConn *net.UDPConn, srcAddr, dstAddr *net.UDPAddr, mes func SendUEInformationExchange( ikeUe *context.N3IWFIkeUe, payload ike_message.IKEPayloadContainer, ) { + ikeLog := logger.IKELog ikeSecurityAssociation := ikeUe.N3IWFIKESecurityAssociation responseIKEMessage := new(ike_message.IKEMessage) @@ -51,7 +53,7 @@ func SendUEInformationExchange( ikeSecurityAssociation.ResponderMessageID) if payload != nil { // This message isn't a DPD message if err := EncryptProcedure(ikeSecurityAssociation, payload, responseIKEMessage); err != nil { - logger.IKELog.Errorf("Encrypting IKE message failed: %+v", err) + ikeLog.Errorf("Encrypting IKE message failed: %+v", err) return } } @@ -60,9 +62,10 @@ func SendUEInformationExchange( } func SendIKEDeleteRequest(localSPI uint64) { + ikeLog := logger.IKELog ikeUe, ok := context.N3IWFSelf().IkeUePoolLoad(localSPI) if !ok { - logger.IKELog.Errorf("Cannot get IkeUE from SPI : %+v", localSPI) + ikeLog.Errorf("Cannot get IkeUE from SPI : %+v", localSPI) return } @@ -72,6 +75,7 @@ func SendIKEDeleteRequest(localSPI uint64) { } func SendChildSADeleteRequest(ikeUe *context.N3IWFIkeUe, relaseList []int64) { + ikeLog := logger.IKELog var deleteSPIs []byte spiLen := uint16(0) for _, releaseItem := range relaseList { @@ -82,7 +86,7 @@ func SendChildSADeleteRequest(ikeUe *context.N3IWFIkeUe, relaseList []int64) { deleteSPIs = append(deleteSPIs, spiByte...) spiLen += 1 if err := ikeUe.DeleteChildSA(childSA); err != nil { - logger.IKELog.Errorf("Delete Child SA error : %+v", err) + ikeLog.Errorf("Delete Child SA error : %+v", err) } } } @@ -94,10 +98,11 @@ func SendChildSADeleteRequest(ikeUe *context.N3IWFIkeUe, relaseList []int64) { } func StartDPD(ikeUe *context.N3IWFIkeUe) { + ikeLog := logger.IKELog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.IKELog.Errorf("panic: %v\n%s", p, string(debug.Stack())) + ikeLog.Errorf("panic: %v\n%s", p, string(debug.Stack())) } }() @@ -120,10 +125,10 @@ func StartDPD(ikeUe *context.N3IWFIkeUe) { var DPDReqRetransTime time.Duration = 2 * time.Second ikeUe.N3IWFIKESecurityAssociation.DPDReqRetransTimer = context.NewDPDPeriodicTimer(DPDReqRetransTime, liveness.MaxRetryTimes, ikeUe.N3IWFIKESecurityAssociation, func() { - logger.IKELog.Errorf("UE is down") + ikeLog.Errorf("UE is down") ranNgapId, ok := n3iwfSelf.NgapIdLoad(ikeUe.N3IWFIKESecurityAssociation.LocalSPI) if !ok { - logger.IKELog.Infof("Cannot find ranNgapId form SPI : %+v", ikeUe.N3IWFIKESecurityAssociation.LocalSPI) + ikeLog.Infof("Cannot find ranNgapId form SPI : %+v", ikeUe.N3IWFIKESecurityAssociation.LocalSPI) return } diff --git a/pkg/ike/message/build.go b/pkg/ike/message/build.go index f6440bb0..f709324b 100644 --- a/pkg/ike/message/build.go +++ b/pkg/ike/message/build.go @@ -243,8 +243,9 @@ func (container *IKEPayloadContainer) BuildEAP5GStart(identifier uint8) { } func (container *IKEPayloadContainer) BuildEAP5GNAS(identifier uint8, nasPDU []byte) { + ikeLog := logger.IKELog if len(nasPDU) == 0 { - logger.IKELog.Error("BuildEAP5GNAS(): NASPDU is nil") + ikeLog.Error("BuildEAP5GNAS(): NASPDU is nil") return } diff --git a/pkg/ike/message/message.go b/pkg/ike/message/message.go index a541e95b..413f2a17 100644 --- a/pkg/ike/message/message.go +++ b/pkg/ike/message/message.go @@ -20,7 +20,8 @@ type IKEMessage struct { } func (ikeMessage *IKEMessage) Encode() ([]byte, error) { - logger.IKELog.Info("Encoding IKE message") + ikeLog := logger.IKELog + ikeLog.Info("Encoding IKE message") ikeMessageData := make([]byte, 28) @@ -45,8 +46,8 @@ func (ikeMessage *IKEMessage) Encode() ([]byte, error) { ikeMessageData = append(ikeMessageData, ikeMessagePayloadData...) binary.BigEndian.PutUint32(ikeMessageData[24:28], uint32(len(ikeMessageData))) - logger.IKELog.Tracef("Encoded %d bytes", len(ikeMessageData)) - logger.IKELog.Tracef("IKE message data:\n%s", hex.Dump(ikeMessageData)) + ikeLog.Tracef("Encoded %d bytes", len(ikeMessageData)) + ikeLog.Tracef("IKE message data:\n%s", hex.Dump(ikeMessageData)) return ikeMessageData, nil } @@ -54,8 +55,9 @@ func (ikeMessage *IKEMessage) Encode() ([]byte, error) { func (ikeMessage *IKEMessage) Decode(rawData []byte) error { // IKE message packet format this implementation referenced is // defined in RFC 7296, Section 3.1 - logger.IKELog.Info("Decoding IKE message") - logger.IKELog.Tracef("Received IKE message:\n%s", hex.Dump(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("Decoding IKE message") + ikeLog.Tracef("Received IKE message:\n%s", hex.Dump(rawData)) // bounds checking if len(rawData) < 28 { @@ -92,7 +94,8 @@ func (ikeMessage *IKEMessage) Decode(rawData []byte) error { type IKEPayloadContainer []IKEPayload func (container *IKEPayloadContainer) Encode() ([]byte, error) { - logger.IKELog.Info("Encoding IKE payloads") + ikeLog := logger.IKELog + ikeLog.Info("Encoding IKE payloads") ikeMessagePayloadData := make([]byte, 0) @@ -123,11 +126,12 @@ func (container *IKEPayloadContainer) Encode() ([]byte, error) { } func (container *IKEPayloadContainer) Decode(nextPayload uint8, rawData []byte) error { - logger.IKELog.Info("Decoding IKE payloads") + ikeLog := logger.IKELog + ikeLog.Info("Decoding IKE payloads") for len(rawData) > 0 { // bounds checking - logger.IKELog.Trace("DecodePayload(): Decode 1 payload") + ikeLog.Trace("DecodePayload(): Decode 1 payload") if len(rawData) < 4 { return errors.New("DecodePayload(): No sufficient bytes to decode next payload") } @@ -248,7 +252,8 @@ type Transform struct { func (securityAssociation *SecurityAssociation) Type() IKEPayloadType { return TypeSA } func (securityAssociation *SecurityAssociation) marshal() ([]byte, error) { - logger.IKELog.Info("[SecurityAssociation] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[SecurityAssociation] marshal(): Start marshalling") securityAssociationData := make([]byte, 0) @@ -333,11 +338,12 @@ func (securityAssociation *SecurityAssociation) marshal() ([]byte, error) { } func (securityAssociation *SecurityAssociation) unmarshal(rawData []byte) error { - logger.IKELog.Info("[SecurityAssociation] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[SecurityAssociation] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[SecurityAssociation] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[SecurityAssociation] unmarshal(): Payload length %d bytes", len(rawData)) for len(rawData) > 0 { - logger.IKELog.Trace("[SecurityAssociation] unmarshal(): Unmarshal 1 proposal") + ikeLog.Trace("[SecurityAssociation] unmarshal(): Unmarshal 1 proposal") // bounds checking if len(rawData) < 8 { return errors.New("Proposal: No sufficient bytes to decode next proposal") @@ -352,10 +358,10 @@ func (securityAssociation *SecurityAssociation) unmarshal(rawData []byte) error // Log whether this proposal is the last if rawData[0] == 0 { - logger.IKELog.Trace("[SecurityAssociation] This proposal is the last") + ikeLog.Trace("[SecurityAssociation] This proposal is the last") } // Log the number of transform in the proposal - logger.IKELog.Tracef("[SecurityAssociation] This proposal contained %d transform", rawData[7]) + ikeLog.Tracef("[SecurityAssociation] This proposal contained %d transform", rawData[7]) proposal := new(Proposal) var transformData []byte @@ -376,7 +382,7 @@ func (securityAssociation *SecurityAssociation) unmarshal(rawData []byte) error for len(transformData) > 0 { // bounds checking - logger.IKELog.Trace("[SecurityAssociation] unmarshal(): Unmarshal 1 transform") + ikeLog.Trace("[SecurityAssociation] unmarshal(): Unmarshal 1 transform") if len(transformData) < 8 { return errors.New("Transform: No sufficient bytes to decode next transform") } @@ -390,7 +396,7 @@ func (securityAssociation *SecurityAssociation) unmarshal(rawData []byte) error // Log whether this transform is the last if transformData[0] == 0 { - logger.IKELog.Trace("[SecurityAssociation] This transform is the last") + ikeLog.Trace("[SecurityAssociation] This transform is the last") } transform := new(Transform) @@ -451,7 +457,8 @@ type KeyExchange struct { func (keyExchange *KeyExchange) Type() IKEPayloadType { return TypeKE } func (keyExchange *KeyExchange) marshal() ([]byte, error) { - logger.IKELog.Info("[KeyExchange] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[KeyExchange] marshal(): Start marshalling") keyExchangeData := make([]byte, 4) @@ -462,11 +469,12 @@ func (keyExchange *KeyExchange) marshal() ([]byte, error) { } func (keyExchange *KeyExchange) unmarshal(rawData []byte) error { - logger.IKELog.Info("[KeyExchange] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[KeyExchange] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[KeyExchange] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[KeyExchange] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[KeyExchange] unmarshal(): Unmarshal 1 key exchange data") + ikeLog.Trace("[KeyExchange] unmarshal(): Unmarshal 1 key exchange data") // bounds checking if len(rawData) <= 4 { return errors.New("KeyExchange: No sufficient bytes to decode next key exchange data") @@ -491,7 +499,8 @@ type IdentificationInitiator struct { func (identification *IdentificationInitiator) Type() IKEPayloadType { return TypeIDi } func (identification *IdentificationInitiator) marshal() ([]byte, error) { - logger.IKELog.Info("[Identification] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Identification] marshal(): Start marshalling") identificationData := make([]byte, 4) @@ -502,11 +511,12 @@ func (identification *IdentificationInitiator) marshal() ([]byte, error) { } func (identification *IdentificationInitiator) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Identification] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Identification] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Identification] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Identification] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Identification] unmarshal(): Unmarshal 1 identification") + ikeLog.Trace("[Identification] unmarshal(): Unmarshal 1 identification") // bounds checking if len(rawData) <= 4 { return errors.New("Identification: No sufficient bytes to decode next identification") @@ -531,7 +541,8 @@ type IdentificationResponder struct { func (identification *IdentificationResponder) Type() IKEPayloadType { return TypeIDr } func (identification *IdentificationResponder) marshal() ([]byte, error) { - logger.IKELog.Info("[Identification] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Identification] marshal(): Start marshalling") identificationData := make([]byte, 4) @@ -542,11 +553,12 @@ func (identification *IdentificationResponder) marshal() ([]byte, error) { } func (identification *IdentificationResponder) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Identification] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Identification] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Identification] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Identification] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Identification] unmarshal(): Unmarshal 1 identification") + ikeLog.Trace("[Identification] unmarshal(): Unmarshal 1 identification") // bounds checking if len(rawData) <= 4 { return errors.New("Identification: No sufficient bytes to decode next identification") @@ -571,7 +583,8 @@ type Certificate struct { func (certificate *Certificate) Type() IKEPayloadType { return TypeCERT } func (certificate *Certificate) marshal() ([]byte, error) { - logger.IKELog.Info("[Certificate] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Certificate] marshal(): Start marshalling") certificateData := make([]byte, 1) @@ -582,11 +595,12 @@ func (certificate *Certificate) marshal() ([]byte, error) { } func (certificate *Certificate) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Certificate] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Certificate] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Certificate] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Certificate] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Certificate] unmarshal(): Unmarshal 1 certificate") + ikeLog.Trace("[Certificate] unmarshal(): Unmarshal 1 certificate") // bounds checking if len(rawData) <= 1 { return errors.New("Certificate: No sufficient bytes to decode next certificate") @@ -611,7 +625,8 @@ type CertificateRequest struct { func (certificateRequest *CertificateRequest) Type() IKEPayloadType { return TypeCERTreq } func (certificateRequest *CertificateRequest) marshal() ([]byte, error) { - logger.IKELog.Info("[CertificateRequest] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[CertificateRequest] marshal(): Start marshalling") certificateRequestData := make([]byte, 1) @@ -622,11 +637,12 @@ func (certificateRequest *CertificateRequest) marshal() ([]byte, error) { } func (certificateRequest *CertificateRequest) unmarshal(rawData []byte) error { - logger.IKELog.Info("[CertificateRequest] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[CertificateRequest] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[CertificateRequest] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[CertificateRequest] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[CertificateRequest] unmarshal(): Unmarshal 1 certificate request") + ikeLog.Trace("[CertificateRequest] unmarshal(): Unmarshal 1 certificate request") // bounds checking if len(rawData) <= 1 { return errors.New("CertificateRequest: No sufficient bytes to decode next certificate request") @@ -651,7 +667,8 @@ type Authentication struct { func (authentication *Authentication) Type() IKEPayloadType { return TypeAUTH } func (authentication *Authentication) marshal() ([]byte, error) { - logger.IKELog.Info("[Authentication] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Authentication] marshal(): Start marshalling") authenticationData := make([]byte, 4) @@ -662,11 +679,12 @@ func (authentication *Authentication) marshal() ([]byte, error) { } func (authentication *Authentication) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Authentication] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Authentication] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Authentication] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Authentication] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Authentication] unmarshal(): Unmarshal 1 authentication") + ikeLog.Trace("[Authentication] unmarshal(): Unmarshal 1 authentication") // bounds checking if len(rawData) <= 4 { return errors.New("Authentication: No sufficient bytes to decode next authentication") @@ -690,7 +708,8 @@ type Nonce struct { func (nonce *Nonce) Type() IKEPayloadType { return TypeNiNr } func (nonce *Nonce) marshal() ([]byte, error) { - logger.IKELog.Info("[Nonce] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Nonce] marshal(): Start marshalling") nonceData := make([]byte, 0) nonceData = append(nonceData, nonce.NonceData...) @@ -699,11 +718,12 @@ func (nonce *Nonce) marshal() ([]byte, error) { } func (nonce *Nonce) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Nonce] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Nonce] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Nonce] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Nonce] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Nonce] unmarshal(): Unmarshal 1 nonce") + ikeLog.Trace("[Nonce] unmarshal(): Unmarshal 1 nonce") nonce.NonceData = append(nonce.NonceData, rawData...) } @@ -724,7 +744,8 @@ type Notification struct { func (notification *Notification) Type() IKEPayloadType { return TypeN } func (notification *Notification) marshal() ([]byte, error) { - logger.IKELog.Info("[Notification] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Notification] marshal(): Start marshalling") notificationData := make([]byte, 4) @@ -739,11 +760,12 @@ func (notification *Notification) marshal() ([]byte, error) { } func (notification *Notification) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Notification] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Notification] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Notification] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Notification] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Notification] unmarshal(): Unmarshal 1 notification") + ikeLog.Trace("[Notification] unmarshal(): Unmarshal 1 notification") // bounds checking if len(rawData) < 4 { return errors.New("Notification: No sufficient bytes to decode next notification") @@ -777,7 +799,8 @@ type Delete struct { func (del *Delete) Type() IKEPayloadType { return TypeD } func (del *Delete) marshal() ([]byte, error) { - logger.IKELog.Info("[Delete] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Delete] marshal(): Start marshalling") if len(del.SPIs) != (int(del.SPISize) * int(del.NumberOfSPI)) { return nil, fmt.Errorf("Total bytes of all SPIs not correct") @@ -797,11 +820,12 @@ func (del *Delete) marshal() ([]byte, error) { } func (del *Delete) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Delete] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Delete] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Delete] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Delete] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Delete] unmarshal(): Unmarshal 1 delete") + ikeLog.Trace("[Delete] unmarshal(): Unmarshal 1 delete") // bounds checking if len(rawData) <= 3 { return errors.New("Delete: No sufficient bytes to decode next delete") @@ -833,16 +857,18 @@ type VendorID struct { func (vendorID *VendorID) Type() IKEPayloadType { return TypeV } func (vendorID *VendorID) marshal() ([]byte, error) { - logger.IKELog.Info("[VendorID] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[VendorID] marshal(): Start marshalling") return vendorID.VendorIDData, nil } func (vendorID *VendorID) unmarshal(rawData []byte) error { - logger.IKELog.Info("[VendorID] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[VendorID] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[VendorID] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[VendorID] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[VendorID] unmarshal(): Unmarshal 1 vendor ID") + ikeLog.Trace("[VendorID] unmarshal(): Unmarshal 1 vendor ID") vendorID.VendorIDData = append(vendorID.VendorIDData, rawData...) } @@ -871,7 +897,8 @@ type IndividualTrafficSelector struct { func (trafficSelector *TrafficSelectorInitiator) Type() IKEPayloadType { return TypeTSi } func (trafficSelector *TrafficSelectorInitiator) marshal() ([]byte, error) { - logger.IKELog.Info("[TrafficSelector] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[TrafficSelector] marshal(): Start marshalling") if len(trafficSelector.TrafficSelectors) > 0 { trafficSelectorData := make([]byte, 4) @@ -881,7 +908,7 @@ func (trafficSelector *TrafficSelectorInitiator) marshal() ([]byte, error) { if individualTrafficSelector.TSType == TS_IPV4_ADDR_RANGE { // Address length checking if len(individualTrafficSelector.StartAddress) != 4 { - logger.IKELog.Errorf("Address length %d", len(individualTrafficSelector.StartAddress)) + ikeLog.Errorf("Address length %d", len(individualTrafficSelector.StartAddress)) return nil, errors.New("TrafficSelector: Start IPv4 address length is not correct") } if len(individualTrafficSelector.EndAddress) != 4 { @@ -935,11 +962,12 @@ func (trafficSelector *TrafficSelectorInitiator) marshal() ([]byte, error) { } func (trafficSelector *TrafficSelectorInitiator) unmarshal(rawData []byte) error { - logger.IKELog.Info("[TrafficSelector] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[TrafficSelector] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[TrafficSelector] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[TrafficSelector] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[TrafficSelector] unmarshal(): Unmarshal 1 traffic selector") + ikeLog.Trace("[TrafficSelector] unmarshal(): Unmarshal 1 traffic selector") // bounds checking if len(rawData) < 4 { return errors.New("TrafficSelector: No sufficient bytes to get number of traffic selector in header") @@ -1020,7 +1048,8 @@ type TrafficSelectorResponder struct { func (trafficSelector *TrafficSelectorResponder) Type() IKEPayloadType { return TypeTSr } func (trafficSelector *TrafficSelectorResponder) marshal() ([]byte, error) { - logger.IKELog.Info("[TrafficSelector] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[TrafficSelector] marshal(): Start marshalling") if len(trafficSelector.TrafficSelectors) > 0 { trafficSelectorData := make([]byte, 4) @@ -1083,11 +1112,12 @@ func (trafficSelector *TrafficSelectorResponder) marshal() ([]byte, error) { } func (trafficSelector *TrafficSelectorResponder) unmarshal(rawData []byte) error { - logger.IKELog.Info("[TrafficSelector] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[TrafficSelector] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[TrafficSelector] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[TrafficSelector] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[TrafficSelector] unmarshal(): Unmarshal 1 traffic selector") + ikeLog.Trace("[TrafficSelector] unmarshal(): Unmarshal 1 traffic selector") // bounds checking if len(rawData) < 4 { return errors.New("TrafficSelector: No sufficient bytes to get number of traffic selector in header") @@ -1169,18 +1199,20 @@ type Encrypted struct { func (encrypted *Encrypted) Type() IKEPayloadType { return TypeSK } func (encrypted *Encrypted) marshal() ([]byte, error) { - logger.IKELog.Info("[Encrypted] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Encrypted] marshal(): Start marshalling") if len(encrypted.EncryptedData) == 0 { - logger.IKELog.Warn("[Encrypted] The encrypted data is empty") + ikeLog.Warn("[Encrypted] The encrypted data is empty") } return encrypted.EncryptedData, nil } func (encrypted *Encrypted) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Encrypted] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Encrypted] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Encrypted] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Encrypted] unmarshal(): Payload length %d bytes", len(rawData)) encrypted.EncryptedData = append(encrypted.EncryptedData, rawData...) return nil } @@ -1204,7 +1236,8 @@ type IndividualConfigurationAttribute struct { func (configuration *Configuration) Type() IKEPayloadType { return TypeCP } func (configuration *Configuration) marshal() ([]byte, error) { - logger.IKELog.Info("[Configuration] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[Configuration] marshal(): Start marshalling") configurationData := make([]byte, 4) @@ -1225,11 +1258,12 @@ func (configuration *Configuration) marshal() ([]byte, error) { } func (configuration *Configuration) unmarshal(rawData []byte) error { - logger.IKELog.Info("[Configuration] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[Configuration] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[Configuration] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[Configuration] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[Configuration] unmarshal(): Unmarshal 1 configuration") + ikeLog.Trace("[Configuration] unmarshal(): Unmarshal 1 configuration") // bounds checking if len(rawData) <= 4 { return errors.New("Configuration: No sufficient bytes to decode next configuration") @@ -1239,7 +1273,7 @@ func (configuration *Configuration) unmarshal(rawData []byte) error { configurationAttributeData := rawData[4:] for len(configurationAttributeData) > 0 { - logger.IKELog.Trace("[Configuration] unmarshal(): Unmarshal 1 configuration attribute") + ikeLog.Trace("[Configuration] unmarshal(): Unmarshal 1 configuration attribute") // bounds checking if len(configurationAttributeData) < 4 { return errors.New("ConfigurationAttribute: No sufficient bytes to decode next configuration attribute") @@ -1277,7 +1311,8 @@ type EAP struct { func (eap *EAP) Type() IKEPayloadType { return TypeEAP } func (eap *EAP) marshal() ([]byte, error) { - logger.IKELog.Info("[EAP] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[EAP] marshal(): Start marshalling") eapData := make([]byte, 4) @@ -1299,11 +1334,12 @@ func (eap *EAP) marshal() ([]byte, error) { } func (eap *EAP) unmarshal(rawData []byte) error { - logger.IKELog.Info("[EAP] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[EAP] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[EAP] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[EAP] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { - logger.IKELog.Trace("[EAP] unmarshal(): Unmarshal 1 EAP") + ikeLog.Trace("[EAP] unmarshal(): Unmarshal 1 EAP") // bounds checking if len(rawData) < 4 { return errors.New("EAP: No sufficient bytes to decode next EAP payload") @@ -1373,7 +1409,8 @@ type EAPIdentity struct { func (eapIdentity *EAPIdentity) Type() EAPType { return EAPTypeIdentity } func (eapIdentity *EAPIdentity) marshal() ([]byte, error) { - logger.IKELog.Info("[EAP][Identity] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Identity] marshal(): Start marshalling") if len(eapIdentity.IdentityData) == 0 { return nil, errors.New("EAPIdentity: EAP identity is empty") @@ -1386,8 +1423,9 @@ func (eapIdentity *EAPIdentity) marshal() ([]byte, error) { } func (eapIdentity *EAPIdentity) unmarshal(rawData []byte) error { - logger.IKELog.Info("[EAP][Identity] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[EAP][Identity] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Identity] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[EAP][Identity] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 1 { eapIdentity.IdentityData = append(eapIdentity.IdentityData, rawData[1:]...) @@ -1407,7 +1445,8 @@ type EAPNotification struct { func (eapNotification *EAPNotification) Type() EAPType { return EAPTypeNotification } func (eapNotification *EAPNotification) marshal() ([]byte, error) { - logger.IKELog.Info("[EAP][Notification] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Notification] marshal(): Start marshalling") if len(eapNotification.NotificationData) == 0 { return nil, errors.New("EAPNotification: EAP notification is empty") @@ -1420,8 +1459,9 @@ func (eapNotification *EAPNotification) marshal() ([]byte, error) { } func (eapNotification *EAPNotification) unmarshal(rawData []byte) error { - logger.IKELog.Info("[EAP][Notification] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[EAP][Notification] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Notification] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[EAP][Notification] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 1 { eapNotification.NotificationData = append(eapNotification.NotificationData, rawData[1:]...) @@ -1441,7 +1481,8 @@ type EAPNak struct { func (eapNak *EAPNak) Type() EAPType { return EAPTypeNak } func (eapNak *EAPNak) marshal() ([]byte, error) { - logger.IKELog.Info("[EAP][Nak] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Nak] marshal(): Start marshalling") if len(eapNak.NakData) == 0 { return nil, errors.New("EAPNak: EAP nak is empty") @@ -1454,8 +1495,9 @@ func (eapNak *EAPNak) marshal() ([]byte, error) { } func (eapNak *EAPNak) unmarshal(rawData []byte) error { - logger.IKELog.Info("[EAP][Nak] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[EAP][Nak] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Nak] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[EAP][Nak] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 1 { eapNak.NakData = append(eapNak.NakData, rawData[1:]...) @@ -1477,7 +1519,8 @@ type EAPExpanded struct { func (eapExpanded *EAPExpanded) Type() EAPType { return EAPTypeExpanded } func (eapExpanded *EAPExpanded) marshal() ([]byte, error) { - logger.IKELog.Info("[EAP][Expanded] marshal(): Start marshalling") + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Expanded] marshal(): Start marshalling") eapExpandedData := make([]byte, 8) @@ -1488,7 +1531,7 @@ func (eapExpanded *EAPExpanded) marshal() ([]byte, error) { binary.BigEndian.PutUint32(eapExpandedData[4:8], eapExpanded.VendorType) if len(eapExpanded.VendorData) == 0 { - logger.IKELog.Warn("[EAP][Expanded] marshal(): EAP vendor data field is empty") + ikeLog.Warn("[EAP][Expanded] marshal(): EAP vendor data field is empty") return eapExpandedData, nil } @@ -1498,8 +1541,9 @@ func (eapExpanded *EAPExpanded) marshal() ([]byte, error) { } func (eapExpanded *EAPExpanded) unmarshal(rawData []byte) error { - logger.IKELog.Info("[EAP][Expanded] unmarshal(): Start unmarshalling received bytes") - logger.IKELog.Tracef("[EAP][Expanded] unmarshal(): Payload length %d bytes", len(rawData)) + ikeLog := logger.IKELog + ikeLog.Info("[EAP][Expanded] unmarshal(): Start unmarshalling received bytes") + ikeLog.Tracef("[EAP][Expanded] unmarshal(): Payload length %d bytes", len(rawData)) if len(rawData) > 0 { if len(rawData) < 8 { diff --git a/pkg/ike/message/message_test.go b/pkg/ike/message/message_test.go index ad0526f1..614ce1b2 100644 --- a/pkg/ike/message/message_test.go +++ b/pkg/ike/message/message_test.go @@ -275,11 +275,11 @@ func TestEncodeDecode(t *testing.T) { testEAP.Code = 1 testEAP.Identifier = 123 - testEAPExpanded := new(EAPExpanded) - - testEAPExpanded.VendorID = 26838 - testEAPExpanded.VendorType = 1 - testEAPExpanded.VendorData = []byte{9, 4, 8, 7} + // testEAPExpanded := &EAPExpanded{ + // VendorID: 26838, + // VendorType: 1, + // VendorData: []byte{9, 4, 8, 7}, + // } testEAPNotification := new(EAPNotification) diff --git a/pkg/ike/service/service.go b/pkg/ike/service/service.go index dc7eeaaa..0eda9f74 100644 --- a/pkg/ike/service/service.go +++ b/pkg/ike/service/service.go @@ -18,18 +18,19 @@ var ( ) func Run(wg *sync.WaitGroup) error { + ikeLog := logger.IKELog n3iwfSelf := context.N3IWFSelf() // Resolve UDP addresses ip := n3iwfSelf.IKEBindAddress udpAddrPort500, err := net.ResolveUDPAddr("udp", ip+":500") if err != nil { - logger.IKELog.Errorf("Resolve UDP address failed: %+v", err) + ikeLog.Errorf("Resolve UDP address failed: %+v", err) return errors.New("IKE service run failed") } udpAddrPort4500, err := net.ResolveUDPAddr("udp", ip+":4500") if err != nil { - logger.IKELog.Errorf("Resolve UDP address failed: %+v", err) + ikeLog.Errorf("Resolve UDP address failed: %+v", err) return errors.New("IKE service run failed") } @@ -43,7 +44,7 @@ func Run(wg *sync.WaitGroup) error { errChan = make(chan error) go Receiver(udpAddrPort500, n3iwfSelf.IKEServer, errChan, wg) if err, ok := <-errChan; ok { - logger.IKELog.Errorln(err) + ikeLog.Errorln(err) return errors.New("IKE service run failed") } @@ -52,7 +53,7 @@ func Run(wg *sync.WaitGroup) error { errChan = make(chan error) go Receiver(udpAddrPort4500, n3iwfSelf.IKEServer, errChan, wg) if err, ok := <-errChan; ok { - logger.IKELog.Errorln(err) + ikeLog.Errorln(err) return errors.New("IKE service run failed") } @@ -72,12 +73,13 @@ func NewIKEServer() *context.IkeServer { } func server(ikeServer *context.IkeServer, wg *sync.WaitGroup) { + ikeLog := logger.IKELog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.IKELog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ikeLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } - logger.IKELog.Infof("Ike server stopped") + ikeLog.Infof("Ike server stopped") close(ikeServer.RcvIkePktCh) close(ikeServer.StopServer) wg.Done() @@ -86,7 +88,7 @@ func server(ikeServer *context.IkeServer, wg *sync.WaitGroup) { for { select { case rcvPkt := <-ikeServer.RcvIkePktCh: - logger.IKELog.Tracef("Receive IKE packet") + ikeLog.Tracef("Receive IKE packet") ike.IkeDispatch(&rcvPkt.Listener, &rcvPkt.LocalAddr, &rcvPkt.RemoteAddr, rcvPkt.Msg) case rcvIkeEvent := <-ikeServer.RcvEventCh: handler.HandleEvent(rcvIkeEvent) @@ -97,18 +99,19 @@ func server(ikeServer *context.IkeServer, wg *sync.WaitGroup) { } func Receiver(localAddr *net.UDPAddr, ikeServer *context.IkeServer, errChan chan<- error, wg *sync.WaitGroup) { + ikeLog := logger.IKELog defer func() { if p := recover(); p != nil { // Print stack for panic to log. Fatalf() will let program exit. - logger.IKELog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) + ikeLog.Fatalf("panic: %v\n%s", p, string(debug.Stack())) } - logger.IKELog.Infof("Ike receiver stopped") + ikeLog.Infof("Ike receiver stopped") wg.Done() }() listener, err := net.ListenUDP("udp", localAddr) if err != nil { - logger.IKELog.Errorf("Listen UDP failed: %+v", err) + ikeLog.Errorf("Listen UDP failed: %+v", err) errChan <- errors.New("listenAndServe failed") return } @@ -122,7 +125,7 @@ func Receiver(localAddr *net.UDPAddr, ikeServer *context.IkeServer, errChan chan for { n, remoteAddr, err := listener.ReadFromUDP(data) if err != nil { - logger.IKELog.Errorf("ReadFromUDP failed: %+v", err) + ikeLog.Errorf("ReadFromUDP failed: %+v", err) return } @@ -138,11 +141,12 @@ func Receiver(localAddr *net.UDPAddr, ikeServer *context.IkeServer, errChan chan } func Stop(n3iwfContext *context.N3IWFContext) { - logger.IKELog.Infof("Close Ike server...") + ikeLog := logger.IKELog + ikeLog.Infof("Close Ike server...") for _, ikeServerListener := range n3iwfContext.IKEServer.Listener { if err := ikeServerListener.Close(); err != nil { - logger.IKELog.Errorf("Stop ike server : %s error : %+v", err, ikeServerListener.LocalAddr().String()) + ikeLog.Errorf("Stop ike server : %s error : %+v", err, ikeServerListener.LocalAddr().String()) } } diff --git a/pkg/ike/xfrm/xfrm.go b/pkg/ike/xfrm/xfrm.go index a596d210..c36f45ad 100644 --- a/pkg/ike/xfrm/xfrm.go +++ b/pkg/ike/xfrm/xfrm.go @@ -53,6 +53,7 @@ func (xfrmIntegrityAlgorithmType XFRMIntegrityAlgorithmType) String() string { func ApplyXFRMRule(n3iwf_is_initiator bool, xfrmiId uint32, childSecurityAssociation *context.ChildSecurityAssociation, ) error { + ikeLog := logger.IKELog // Build XFRM information data structure for incoming traffic. // Direction: {private_network} -> this_server @@ -105,7 +106,7 @@ func ApplyXFRMRule(n3iwf_is_initiator bool, xfrmiId uint32, // Commit xfrm state to netlink var err error if err = netlink.XfrmStateAdd(xfrmState); err != nil { - logger.IKELog.Errorf("Set XFRM rules failed: %+v", err) + ikeLog.Errorf("Set XFRM rules failed: %+v", err) return errors.New("Set XFRM state rule failed") } @@ -133,7 +134,7 @@ func ApplyXFRMRule(n3iwf_is_initiator bool, xfrmiId uint32, // Commit xfrm policy to netlink if err = netlink.XfrmPolicyAdd(xfrmPolicy); err != nil { - logger.IKELog.Errorf("Set XFRM rules failed: %+v", err) + ikeLog.Errorf("Set XFRM rules failed: %+v", err) return errors.New("Set XFRM policy rule failed") } @@ -161,7 +162,7 @@ func ApplyXFRMRule(n3iwf_is_initiator bool, xfrmiId uint32, // Commit xfrm state to netlink if err = netlink.XfrmStateAdd(xfrmState); err != nil { - logger.IKELog.Errorf("Set XFRM rules failed: %+v", err) + ikeLog.Errorf("Set XFRM rules failed: %+v", err) return errors.New("Set XFRM state rule failed") } @@ -179,7 +180,7 @@ func ApplyXFRMRule(n3iwf_is_initiator bool, xfrmiId uint32, // Commit xfrm policy to netlink if err = netlink.XfrmPolicyAdd(xfrmPolicy); err != nil { - logger.IKELog.Errorf("Set XFRM rules failed: %+v", err) + ikeLog.Errorf("Set XFRM rules failed: %+v", err) return errors.New("Set XFRM policy rule failed") } @@ -191,6 +192,7 @@ func ApplyXFRMRule(n3iwf_is_initiator bool, xfrmiId uint32, } func printSAInfo(n3iwf_is_initiator bool, xfrmiId uint32, childSecurityAssociation *context.ChildSecurityAssociation) { + ikeLog := logger.IKELog var InboundEncryptionKey, InboundIntegrityKey, OutboundEncryptionKey, OutboundIntegrityKey []byte if n3iwf_is_initiator { @@ -204,31 +206,32 @@ func printSAInfo(n3iwf_is_initiator bool, xfrmiId uint32, childSecurityAssociati OutboundEncryptionKey = childSecurityAssociation.ResponderToInitiatorEncryptionKey OutboundIntegrityKey = childSecurityAssociation.ResponderToInitiatorIntegrityKey } - logger.IKELog.Debug("====== IPSec/Child SA Info ======") + ikeLog.Debug("====== IPSec/Child SA Info ======") // ====== Inbound ====== - logger.IKELog.Debugf("XFRM interface if_id: %d", xfrmiId) - logger.IKELog.Debugf("IPSec Inbound SPI: 0x%016x", childSecurityAssociation.InboundSPI) - logger.IKELog.Debugf("[UE:%+v] -> [N3IWF:%+v]", + ikeLog.Debugf("XFRM interface if_id: %d", xfrmiId) + ikeLog.Debugf("IPSec Inbound SPI: 0x%016x", childSecurityAssociation.InboundSPI) + ikeLog.Debugf("[UE:%+v] -> [N3IWF:%+v]", childSecurityAssociation.PeerPublicIPAddr, childSecurityAssociation.LocalPublicIPAddr) - logger.IKELog.Debugf("IPSec Encryption Algorithm: %d", childSecurityAssociation.EncryptionAlgorithm) - logger.IKELog.Debugf("IPSec Encryption Key: 0x%x", InboundEncryptionKey) - logger.IKELog.Debugf("IPSec Integrity Algorithm: %d", childSecurityAssociation.IntegrityAlgorithm) - logger.IKELog.Debugf("IPSec Integrity Key: 0x%x", InboundIntegrityKey) - logger.IKELog.Debug("====== IPSec/Child SA Info ======") + ikeLog.Debugf("IPSec Encryption Algorithm: %d", childSecurityAssociation.EncryptionAlgorithm) + ikeLog.Debugf("IPSec Encryption Key: 0x%x", InboundEncryptionKey) + ikeLog.Debugf("IPSec Integrity Algorithm: %d", childSecurityAssociation.IntegrityAlgorithm) + ikeLog.Debugf("IPSec Integrity Key: 0x%x", InboundIntegrityKey) + ikeLog.Debug("====== IPSec/Child SA Info ======") // ====== Outbound ====== - logger.IKELog.Debugf("XFRM interface if_id: %d", xfrmiId) - logger.IKELog.Debugf("IPSec Outbound SPI: 0x%016x", childSecurityAssociation.OutboundSPI) - logger.IKELog.Debugf("[N3IWF:%+v] -> [UE:%+v]", + ikeLog.Debugf("XFRM interface if_id: %d", xfrmiId) + ikeLog.Debugf("IPSec Outbound SPI: 0x%016x", childSecurityAssociation.OutboundSPI) + ikeLog.Debugf("[N3IWF:%+v] -> [UE:%+v]", childSecurityAssociation.LocalPublicIPAddr, childSecurityAssociation.PeerPublicIPAddr) - logger.IKELog.Debugf("IPSec Encryption Algorithm: %d", childSecurityAssociation.EncryptionAlgorithm) - logger.IKELog.Debugf("IPSec Encryption Key: 0x%x", OutboundEncryptionKey) - logger.IKELog.Debugf("IPSec Integrity Algorithm: %d", childSecurityAssociation.IntegrityAlgorithm) - logger.IKELog.Debugf("IPSec Integrity Key: 0x%x", OutboundIntegrityKey) + ikeLog.Debugf("IPSec Encryption Algorithm: %d", childSecurityAssociation.EncryptionAlgorithm) + ikeLog.Debugf("IPSec Encryption Key: 0x%x", OutboundEncryptionKey) + ikeLog.Debugf("IPSec Integrity Algorithm: %d", childSecurityAssociation.IntegrityAlgorithm) + ikeLog.Debugf("IPSec Integrity Key: 0x%x", OutboundIntegrityKey) } func SetupIPsecXfrmi(xfrmIfaceName, parentIfaceName string, xfrmIfaceId uint32, xfrmIfaceAddr net.IPNet, ) (netlink.Link, error) { + ikeLog := logger.IKELog var ( xfrmi, parent netlink.Link err error @@ -255,7 +258,7 @@ func SetupIPsecXfrmi(xfrmIfaceName, parentIfaceName string, xfrmIfaceId uint32, return nil, err } - logger.IKELog.Debugf("XFRM interface %s index is %d", xfrmIfaceName, xfrmi.Attrs().Index) + ikeLog.Debugf("XFRM interface %s index is %d", xfrmIfaceName, xfrmi.Attrs().Index) // ip addr add xfrmIfaceAddr dev linkIPSecAddr := &netlink.Addr{