Skip to content
This repository has been archived by the owner on Aug 22, 2024. It is now read-only.

Commit

Permalink
Extend check of network addresses for its locality.
Browse files Browse the repository at this point in the history
  • Loading branch information
lesovsky committed Aug 25, 2021
1 parent 455146e commit 8e7097f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
25 changes: 24 additions & 1 deletion internal/collector/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/weaponry/pgscv/internal/log"
"github.com/weaponry/pgscv/internal/model"
"github.com/weaponry/pgscv/internal/store"
"net"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -154,9 +155,31 @@ func newPostgresServiceConfig(connStr string) (postgresServiceConfig, error) {

// isAddressLocal return true if passed address is local, and return false otherwise.
func isAddressLocal(addr string) bool {
if strings.HasPrefix(addr, "/") || strings.HasPrefix(addr, "127.") || addr == "localhost" {
if addr == "" {
return false
}

if strings.HasPrefix(addr, "/") {
return true
}

if addr == "localhost" || strings.HasPrefix(addr, "127.") || addr == "::1" {
return true
}

addresses, err := net.InterfaceAddrs()
if err != nil {
// Consider error as the passed host address is not local
log.Warnf("check network address '%s' failed: %s; consider it as remote", addr, err)
return false
}

for _, a := range addresses {
if strings.HasPrefix(a.String(), addr) {
return true
}
}

return false
}

Expand Down
5 changes: 4 additions & 1 deletion internal/collector/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,15 @@ func Test_isAddressLocal(t *testing.T) {
addr string
want bool
}{
{addr: "", want: false},
{addr: "127.0.0.1", want: true},
{addr: "127.1.2.3", want: true},
{addr: "/", want: true},
{addr: "/var/run/postgresql", want: true},
{addr: "localhost", want: true},
{addr: "", want: false},
{addr: "example", want: false},
{addr: "1.2.3.4", want: false},
{addr: "::1", want: true},
}

for _, tc := range testcases {
Expand Down

0 comments on commit 8e7097f

Please sign in to comment.