github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/upath/safejoin.go (about)

     1  // Copyright 2021 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build !windows
     6  // +build !windows
     7  
     8  package upath
     9  
    10  import (
    11  	"fmt"
    12  	"path/filepath"
    13  	"strings"
    14  )
    15  
    16  // SafeFilepathJoin safely joins two paths path1+path2. The resulting path will
    17  // always be contained within path1 even if path2 tries to escape with "../".
    18  // If that path is not possible, an error is returned. The resulting path is
    19  // cleaned.
    20  func SafeFilepathJoin(path1, path2 string) (string, error) {
    21  	relPath, err := filepath.Rel(".", path2)
    22  	if err != nil || strings.HasPrefix(relPath, "..") {
    23  		return "", fmt.Errorf("(zipslip) filepath is unsafe %q: %v", path2, err)
    24  	}
    25  	if path1 == "" {
    26  		path1 = "."
    27  	}
    28  	return filepath.Join(path1, filepath.Join("/", relPath)), nil
    29  }