1 | package main |
||
2 | |||
3 | import ( |
||
4 | "net" |
||
5 | "os" |
||
6 | "github.com/mattn/go-isatty" |
||
7 | "path/filepath" |
||
8 | "errors" |
||
9 | "strings" |
||
10 | "net/url" |
||
11 | ) |
||
12 | |||
13 | func FatalCheck(err error) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
14 | if err != nil { |
||
15 | Errorf("%v", err) |
||
16 | panic(err) |
||
17 | } |
||
18 | } |
||
19 | |||
20 | func FilterIPV4(ips []net.IP) []string { |
||
0 ignored issues
–
show
|
|||
21 | var ret = make([]string, 0) |
||
22 | for _, ip := range ips { |
||
23 | if ip.To4() != nil { |
||
24 | ret = append(ret, ip.String()) |
||
25 | } |
||
26 | } |
||
27 | return ret |
||
28 | } |
||
29 | |||
30 | func MkdirIfNotExist(folder string) error { |
||
0 ignored issues
–
show
|
|||
31 | if _, err := os.Stat(folder); err != nil { |
||
32 | if err = os.MkdirAll(folder, 0700); err != nil { |
||
33 | return err |
||
34 | } |
||
35 | } |
||
36 | return nil |
||
37 | } |
||
38 | |||
39 | func ExistDir(folder string) bool { |
||
0 ignored issues
–
show
|
|||
40 | _, err := os.Stat(folder) |
||
41 | return err == nil |
||
42 | } |
||
43 | |||
44 | func DisplayProgressBar() bool { |
||
0 ignored issues
–
show
|
|||
45 | return isatty.IsTerminal(os.Stdout.Fd()) && displayProgress |
||
46 | } |
||
47 | |||
48 | func FolderOf(url string) string { |
||
0 ignored issues
–
show
|
|||
49 | safePath := filepath.Join(os.Getenv("HOME"), dataFolder) |
||
50 | fullQualifyPath, err := filepath.Abs(filepath.Join(os.Getenv("HOME"), dataFolder, filepath.Base(url))) |
||
51 | FatalCheck(err) |
||
52 | |||
53 | //must ensure full qualify path is CHILD of safe path |
||
54 | //to prevent directory traversal attack |
||
55 | //using Rel function to get relative between parent and child |
||
56 | //if relative join base == child, then child path MUST BE real child |
||
57 | relative, err := filepath.Rel(safePath, fullQualifyPath) |
||
58 | FatalCheck(err) |
||
59 | |||
60 | if strings.Contains(relative, "..") { |
||
61 | FatalCheck(errors.New("you may be a victim of directory traversal path attack\n")) |
||
0 ignored issues
–
show
|
|||
62 | return "" //return is redundant be cause in fatal check we have panic, but compiler does not able to check |
||
63 | } else { |
||
0 ignored issues
–
show
|
|||
64 | return fullQualifyPath |
||
65 | } |
||
66 | } |
||
67 | |||
68 | func TaskFromUrl(url string) string { |
||
0 ignored issues
–
show
|
|||
69 | //task is just download file name |
||
70 | //so we get download file name on url |
||
71 | filename := filepath.Base(url) |
||
72 | return filename |
||
73 | } |
||
74 | |||
75 | func IsUrl(s string) bool { |
||
0 ignored issues
–
show
|
|||
76 | _, err := url.Parse(s) |
||
77 | return err == nil |
||
78 | } |
||
79 |