2020-01-13 05:13:26 +00:00
|
|
|
// +build !windows
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"os"
|
2020-05-21 07:10:35 +00:00
|
|
|
"os/exec"
|
2020-07-09 18:19:31 +00:00
|
|
|
"regexp"
|
2020-06-03 17:40:35 +00:00
|
|
|
"strconv"
|
2020-05-21 07:10:35 +00:00
|
|
|
"strings"
|
2020-05-23 07:18:06 +00:00
|
|
|
"syscall"
|
2020-01-13 05:13:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func DirWritable(path string) (bool, error) {
|
|
|
|
info, err := os.Stat(path)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.New("path doesn't exist")
|
|
|
|
}
|
|
|
|
|
|
|
|
if !info.IsDir() {
|
|
|
|
return false, errors.New("path isn't a directory")
|
|
|
|
}
|
|
|
|
|
|
|
|
if info.Mode().Perm()&(1<<(uint(7))) == 0 {
|
|
|
|
return false, errors.New("write permission bit is not set on this file for user")
|
|
|
|
}
|
|
|
|
|
2020-05-23 07:18:06 +00:00
|
|
|
var stat syscall.Stat_t
|
|
|
|
if err = syscall.Stat(path, &stat); err != nil {
|
|
|
|
return false, errors.New("unable to get stat")
|
|
|
|
}
|
|
|
|
|
|
|
|
if uint32(os.Geteuid()) != stat.Uid {
|
|
|
|
return false, errors.New("user doesn't have permission to write to this directory")
|
|
|
|
}
|
2020-05-21 07:10:35 +00:00
|
|
|
return true, nil
|
|
|
|
}
|
2020-01-13 05:13:26 +00:00
|
|
|
|
2020-07-09 18:19:31 +00:00
|
|
|
func Ping(address string, secondsTimeout int) (int64, error) {
|
2020-05-21 07:10:35 +00:00
|
|
|
ping, err := exec.LookPath("ping")
|
|
|
|
if err != nil {
|
2020-07-09 18:19:31 +00:00
|
|
|
return 0, err
|
2020-01-13 05:13:26 +00:00
|
|
|
}
|
2020-06-03 17:40:35 +00:00
|
|
|
out, _, err := Command(ping, address, "-c", "1", "-W", strconv.Itoa(secondsTimeout))
|
2020-05-21 07:10:35 +00:00
|
|
|
if err != nil {
|
2020-07-09 18:19:31 +00:00
|
|
|
return 0, err
|
2020-05-21 07:10:35 +00:00
|
|
|
}
|
2020-05-23 07:18:06 +00:00
|
|
|
if strings.Contains(out, "Unknown host") {
|
2020-07-09 18:19:31 +00:00
|
|
|
return 0, errors.New("unknown host")
|
2020-05-23 07:18:06 +00:00
|
|
|
}
|
|
|
|
if strings.Contains(out, "100.0% packet loss") {
|
2020-07-09 18:19:31 +00:00
|
|
|
return 0, errors.New("destination host unreachable")
|
2020-05-21 07:10:35 +00:00
|
|
|
}
|
2020-07-09 18:19:31 +00:00
|
|
|
|
|
|
|
r := regexp.MustCompile(`time=(.*) ms`)
|
|
|
|
strs := r.FindStringSubmatch(out)
|
|
|
|
if len(strs) < 2 {
|
|
|
|
return 0, errors.New("could not parse ping duration")
|
|
|
|
}
|
|
|
|
f, _ := strconv.ParseFloat(strs[1], 64)
|
|
|
|
return int64(f * 1000), nil
|
2020-01-13 05:13:26 +00:00
|
|
|
}
|