Debian Codegraph @

pkg/utils/utils.go

raw symbols SCIP
1 // Copyright 2016 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package utils
16
17 import (
18 "crypto/sha512"
19 "fmt"
20 )
21
22 const (
23 maxChainLength = 28
24 chainPrefix = "CNI-"
25 )
26
27 // FormatChainName generates a chain name to be used
28 // with iptables. Ensures that the generated chain
29 // name is exactly maxChainLength chars in length.
30 func FormatChainName(name string, id string) string {
31 return MustFormatChainNameWithPrefix(name, id, "")
32 }
33
34 // MustFormatChainNameWithPrefix generates a chain name similar
35 // to FormatChainName, but adds a custom prefix between
36 // chainPrefix and unique identifier. Ensures that the
37 // generated chain name is exactly maxChainLength chars in length.
38 // Panics if the given prefix is too long.
39 func MustFormatChainNameWithPrefix(name string, id string, prefix string) string {
40 return MustFormatHashWithPrefix(maxChainLength, chainPrefix+prefix, name+id)
41 }
42
43 // FormatComment returns a comment used for easier
44 // rule identification within iptables.
45 func FormatComment(name string, id string) string {
46 return fmt.Sprintf("name: %q id: %q", name, id)
47 }
48
49 const MaxHashLen = sha512.Size * 2
50
51 // MustFormatHashWithPrefix returns a string of given length that begins with the
52 // given prefix. It is filled with entropy based on the given string toHash.
53 func MustFormatHashWithPrefix(length int, prefix string, toHash string) string {
54 if len(prefix) >= length || length > MaxHashLen {
55 panic("invalid length")
56 }
57
58 output := sha512.Sum512([]byte(toHash))
59 return fmt.Sprintf("%s%x", prefix, output)[:length]
60 }