github.com/DataDog/datadog-agent/pkg/security/secl@v0.55.0-devel.0.20240517055856-10c4965fea94/model/utils.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the Apache License Version 2.0.
     3  // This product includes software developed at Datadog (https://www.datadoghq.com/).
     4  // Copyright 2016-present Datadog, Inc.
     5  
     6  // Package model holds model related files
     7  package model
     8  
     9  import (
    10  	"bytes"
    11  	"encoding/binary"
    12  )
    13  
    14  // SliceToArray copy src bytes to dst. Destination should have enough space
    15  func SliceToArray(src []byte, dst []byte) {
    16  	if len(src) != len(dst) {
    17  		panic("different len in SliceToArray")
    18  	}
    19  
    20  	copy(dst, src)
    21  }
    22  
    23  // UnmarshalStringArray extract array of string for array of byte
    24  func UnmarshalStringArray(data []byte) ([]string, error) {
    25  	var result []string
    26  	length := uint32(len(data))
    27  
    28  	for i := uint32(0); i < length; {
    29  		if i+4 >= length {
    30  			return result, ErrStringArrayOverflow
    31  		}
    32  		// size of arg
    33  		n := binary.NativeEndian.Uint32(data[i : i+4])
    34  		if n == 0 {
    35  			return result, nil
    36  		}
    37  		i += 4
    38  
    39  		if i+n > length {
    40  			// truncated
    41  			arg := NullTerminatedString(data[i:length])
    42  			return append(result, arg), ErrStringArrayOverflow
    43  		}
    44  
    45  		arg := NullTerminatedString(data[i : i+n])
    46  		i += n
    47  
    48  		result = append(result, arg)
    49  	}
    50  
    51  	return result, nil
    52  }
    53  
    54  // UnmarshalString unmarshal string
    55  func UnmarshalString(data []byte, size int) (string, error) {
    56  	if len(data) < size {
    57  		return "", ErrNotEnoughData
    58  	}
    59  
    60  	return NullTerminatedString(data[:size]), nil
    61  }
    62  
    63  // NullTerminatedString returns null-terminated string
    64  func NullTerminatedString(d []byte) string {
    65  	idx := bytes.IndexByte(d, 0)
    66  	if idx == -1 {
    67  		return string(d)
    68  	}
    69  	return string(d[:idx])
    70  }
    71  
    72  // UnmarshalPrintableString unmarshal printable string
    73  func UnmarshalPrintableString(data []byte, size int) (string, error) {
    74  	if len(data) < size {
    75  		return "", ErrNotEnoughData
    76  	}
    77  
    78  	str, err := UnmarshalString(data, size)
    79  	if err != nil {
    80  		return "", err
    81  	}
    82  	if !IsPrintable(str) {
    83  		return "", ErrNonPrintable
    84  	}
    85  
    86  	return str, nil
    87  }