Copy latest code to master
[ric-plt/resource-status-manager.git] / RSM / converters / x2apPdu_asn1_unpacker.go
1 //
2 // Copyright 2019 AT&T Intellectual Property
3 // Copyright 2019 Nokia
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //      http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 //  This source code is part of the near-RT RIC (RAN Intelligent Controller)
18 //  platform project (RICP).
19
20
21 package converters
22
23 // #cgo CFLAGS: -I../3rdparty/asn1codec/inc/ -I../3rdparty/asn1codec/e2ap_engine/
24 // #cgo LDFLAGS: -L ../3rdparty/asn1codec/lib/ -L../3rdparty/asn1codec/e2ap_engine/ -le2ap_codec -lasncodec
25 // #include <asn1codec_utils.h>
26 import "C"
27 import (
28         "fmt"
29         "github.com/pkg/errors"
30         "rsm/logger"
31         "unsafe"
32 )
33
34 type X2apPduUnpacker struct {
35         logger               *logger.Logger
36         maxMessageBufferSize int
37 }
38
39 func NewX2apPduUnpacker(logger *logger.Logger, maxMessageBufferSize int) X2apPduUnpacker {
40         return X2apPduUnpacker{logger: logger, maxMessageBufferSize: maxMessageBufferSize}
41 }
42
43 func (r X2apPduUnpacker) UnpackX2apPdu(packedBuf []byte) (*C.E2AP_PDU_t, error) {
44         pdu := C.new_pdu()
45
46         if pdu == nil {
47                 return nil, errors.New("allocation failure (pdu)")
48         }
49
50         errBuf := make([]C.char, r.maxMessageBufferSize)
51         if !C.per_unpack_pdu(pdu, C.ulong(len(packedBuf)), (*C.uchar)(unsafe.Pointer(&packedBuf[0])), C.ulong(len(errBuf)), &errBuf[0]) {
52                 return nil, errors.New(fmt.Sprintf("unpacking error: %s", C.GoString(&errBuf[0])))
53         }
54
55         if r.logger.DebugEnabled() {
56                 C.asn1_pdu_printer(pdu, C.size_t(len(errBuf)), &errBuf[0])
57                 r.logger.Debugf("#x2apPdu_asn1_unpacker.UnpackX2apPdu - PDU: %v  packed size:%d", C.GoString(&errBuf[0]), len(packedBuf))
58         }
59
60         return pdu, nil
61 }
62
63 func (r X2apPduUnpacker) UnpackX2apPduAsString(packedBuf []byte, maxMessageBufferSize int) (string, error) {
64         pdu, err := r.UnpackX2apPdu(packedBuf)
65         if err != nil {
66                 return "", err
67         }
68
69         defer C.delete_pdu(pdu)
70
71         buf := make([]C.char, 16*maxMessageBufferSize)
72         C.asn1_pdu_printer(pdu, C.size_t(len(buf)), &buf[0])
73         return C.GoString(&buf[0]), nil
74 }