Test Setup Failed
Push — master ( f94c9e...f6e4d0 )
by Abouzar
02:21
created
Severity
1
package main
2
3
import (
4
	"errors"
5
	"github.com/mattn/go-isatty"
6
	"net"
7
	"net/url"
8
	"os"
9
	"path/filepath"
10
	"strings"
11
)
12
13
// FatalCheck panics if err is not nil.
14
func FatalCheck(err error) {
15
	if err != nil {
16
		Errorf("%v", err)
17
		panic(err)
18
	}
19
}
20
21
// FilterIPV4 returns parsed ipv4 string.
22
func FilterIPV4(ips []net.IP) []string {
23
	var ret = make([]string, 0)
24
	for _, ip := range ips {
25
		if ip.To4() != nil {
26
			ret = append(ret, ip.String())
27
		}
28
	}
29
	return ret
30
}
31
32
// MkdirIfNotExist creates `folder` directory if not available
33
func MkdirIfNotExist(folder string) error {
34
	if _, err := os.Stat(folder); err != nil {
35
		if err = os.MkdirAll(folder, 0700); err != nil {
36
			return err
37
		}
38
	}
39
	return nil
40
}
41
42
// ExistDir checks if `folder` is available
43
func ExistDir(folder string) bool {
44
	_, err := os.Stat(folder)
45
	return err == nil
46
}
47
48
// DisplayProgressBar shows a fancy progress bar
49
func DisplayProgressBar() bool {
50
	return isatty.IsTerminal(os.Stdout.Fd()) && displayProgress
51
}
52
53
// FolderOf makes sure you won't get LFI
54
func FolderOf(url string) string {
55
	safePath := filepath.Join(os.Getenv("HOME"), dataFolder)
56
	fullQualifyPath, err := filepath.Abs(filepath.Join(os.Getenv("HOME"), dataFolder, filepath.Base(url)))
57
	FatalCheck(err)
58
59
	//must ensure full qualify path is CHILD of safe path
60
	//to prevent directory traversal attack
61
	//using Rel function to get relative between parent and child
62
	//if relative join base == child, then child path MUST BE real child
63
	relative, err := filepath.Rel(safePath, fullQualifyPath)
64
	FatalCheck(err)
65
66
	if strings.Contains(relative, "..") {
67
		FatalCheck(errors.New("you may be a victim of directory traversal path attack"))
68
		return "" //return is redundant be cause in fatal check we have panic, but compiler does not able to check
69
	} else {
0 ignored issues
show
if block ends with a return statement, so drop this else and outdent its block
Loading history...
70
		return fullQualifyPath
71
	}
72
}
73
74
// TaskFromUrl runs when you want to download a single url
75
func TaskFromUrl(url string) string {
0 ignored issues
show
func TaskFromUrl should be TaskFromURL
Loading history...
76
	//task is just download file name
77
	//so we get download file name on url
78
	filename := filepath.Base(url)
79
	return filename
80
}
81
82
// IsUrl checks if `s` is actually a parsable URL.
83
func IsUrl(s string) bool {
0 ignored issues
show
func IsUrl should be IsURL
Loading history...
84
	_, err := url.Parse(s)
85
	return err == nil
86
}
87