talos

Форк
0
/
safepath.go 
40 строк · 1.5 Кб
1
// This Source Code Form is subject to the terms of the Mozilla Public
2
// License, v. 2.0. If a copy of the MPL was not distributed with this
3
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4

5
// Package safepath provides a set of functions to make paths safe for use with.
6
package safepath
7

8
import (
9
	"os"
10
	"path/filepath"
11
)
12

13
// CleanPath makes a path safe for use with filepath.Join. This is done by not
14
// only cleaning the path, but also (if the path is relative) adding a leading
15
// '/' and cleaning it (then removing the leading '/'). This ensures that a
16
// path resulting from prepending another path will always resolve to lexically
17
// be a subdirectory of the prefixed path. This is all done lexically, so paths
18
// that include symlinks won't be safe as a result of using CleanPath.
19
func CleanPath(path string) string {
20
	// Deal with empty strings nicely.
21
	if path == "" {
22
		return ""
23
	}
24

25
	// Ensure that all paths are cleaned (especially problematic ones like
26
	// "/../../../../../" which can cause lots of issues).
27
	path = filepath.Clean(path)
28

29
	// If the path isn't absolute, we need to do more processing to fix paths
30
	// such as "../../../../<etc>/some/path". We also shouldn't convert absolute
31
	// paths to relative ones.
32
	if !filepath.IsAbs(path) {
33
		path = filepath.Clean(string(os.PathSeparator) + path)
34
		// This can't fail, as (by definition) all paths are relative to root.
35
		path, _ = filepath.Rel(string(os.PathSeparator), path) //nolint:errcheck
36
	}
37

38
	// Clean the path again for good measure.
39
	return filepath.Clean(path)
40
}
41

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.