github.com/crowdsecurity/crowdsec@v1.6.1/pkg/cwhub/leakybucket.go (about)

     1  package cwhub
     2  
     3  // Resolve a symlink to find the hub item it points to.
     4  // This file is used only by pkg/leakybucket
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  )
    12  
    13  // itemKey extracts the map key of an item (i.e. author/name) from its pathname. Follows a symlink if necessary.
    14  func itemKey(itemPath string) (string, error) {
    15  	f, err := os.Lstat(itemPath)
    16  	if err != nil {
    17  		return "", fmt.Errorf("while performing lstat on %s: %w", itemPath, err)
    18  	}
    19  
    20  	if f.Mode()&os.ModeSymlink == 0 {
    21  		// it's not a symlink, so the filename itsef should be the key
    22  		return filepath.Base(itemPath), nil
    23  	}
    24  
    25  	// resolve the symlink to hub file
    26  	pathInHub, err := os.Readlink(itemPath)
    27  	if err != nil {
    28  		return "", fmt.Errorf("while reading symlink of %s: %w", itemPath, err)
    29  	}
    30  
    31  	author := filepath.Base(filepath.Dir(pathInHub))
    32  
    33  	fname := filepath.Base(pathInHub)
    34  	fname = strings.TrimSuffix(fname, ".yaml")
    35  	fname = strings.TrimSuffix(fname, ".yml")
    36  
    37  	return fmt.Sprintf("%s/%s", author, fname), nil
    38  }
    39  
    40  // GetItemByPath retrieves an item from the hub index based on its local path.
    41  func (h *Hub) GetItemByPath(itemType string, itemPath string) (*Item, error) {
    42  	itemKey, err := itemKey(itemPath)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	item := h.GetItem(itemType, itemKey)
    48  	if item == nil {
    49  		return nil, fmt.Errorf("%s not found in %s", itemKey, itemType)
    50  	}
    51  
    52  	return item, nil
    53  }