k8s.io/kubernetes@v1.29.3/pkg/util/iptables/save_restore.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package iptables
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  )
    23  
    24  // MakeChainLine return an iptables-save/restore formatted chain line given a Chain
    25  func MakeChainLine(chain Chain) string {
    26  	return fmt.Sprintf(":%s - [0:0]", chain)
    27  }
    28  
    29  // GetChainsFromTable parses iptables-save data to find the chains that are defined. It
    30  // assumes that save contains a single table's data, and returns a map with keys for every
    31  // chain defined in that table.
    32  func GetChainsFromTable(save []byte) map[Chain]struct{} {
    33  	chainsMap := make(map[Chain]struct{})
    34  
    35  	for {
    36  		i := bytes.Index(save, []byte("\n:"))
    37  		if i == -1 {
    38  			break
    39  		}
    40  		start := i + 2
    41  		save = save[start:]
    42  		end := bytes.Index(save, []byte(" "))
    43  		if i == -1 {
    44  			// shouldn't happen, but...
    45  			break
    46  		}
    47  		chain := Chain(save[:end])
    48  		chainsMap[chain] = struct{}{}
    49  		save = save[end:]
    50  	}
    51  	return chainsMap
    52  }