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

     1  package cwhub
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"path/filepath"
     7  	"sort"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/crowdsecurity/go-cs-lib/version"
    12  )
    13  
    14  // hubTransport wraps a Transport to set a custom User-Agent.
    15  type hubTransport struct {
    16  	http.RoundTripper
    17  }
    18  
    19  func (t *hubTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    20  	req.Header.Set("User-Agent", "crowdsec/"+version.String())
    21  	return t.RoundTripper.RoundTrip(req)
    22  }
    23  
    24  // hubClient is the HTTP client used to communicate with the CrowdSec Hub.
    25  var hubClient = &http.Client{
    26  	Timeout: 120 * time.Second,
    27  	Transport: &hubTransport{http.DefaultTransport},
    28  }
    29  
    30  // safePath returns a joined path and ensures that it does not escape the base directory.
    31  func safePath(dir, filePath string) (string, error) {
    32  	absBaseDir, err := filepath.Abs(filepath.Clean(dir))
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  
    37  	absFilePath, err := filepath.Abs(filepath.Join(dir, filePath))
    38  	if err != nil {
    39  		return "", err
    40  	}
    41  
    42  	if !strings.HasPrefix(absFilePath, absBaseDir) {
    43  		return "", fmt.Errorf("path %s escapes base directory %s", filePath, dir)
    44  	}
    45  
    46  	return absFilePath, nil
    47  }
    48  
    49  // SortItemSlice sorts a slice of items by name, case insensitive.
    50  func SortItemSlice(items []*Item) {
    51  	sort.Slice(items, func(i, j int) bool {
    52  		return strings.ToLower(items[i].Name) < strings.ToLower(items[j].Name)
    53  	})
    54  }