Skip to content

Commit

Permalink
Reduced the complexity of handlePgpass (#1101)
Browse files Browse the repository at this point in the history
  • Loading branch information
JCPrice0024 authored Jan 24, 2023
1 parent 133ac67 commit 3a6282f
Showing 1 changed file with 40 additions and 34 deletions.
74 changes: 40 additions & 34 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,46 +261,52 @@ func (cn *conn) handlePgpass(o values) {
}
defer file.Close()
scanner := bufio.NewScanner(io.Reader(file))
// From: https://github.com/tg/pgpass/blob/master/reader.go
for scanner.Scan() {
scanText(scanner.Text(), o)
}
}

// GetFields is a helper function for scanText.
func getFields(s string) []string {
fs := make([]string, 0, 5)
f := make([]rune, 0, len(s))

var esc bool
for _, c := range s {
switch {
case esc:
f = append(f, c)
esc = false
case c == '\\':
esc = true
case c == ':':
fs = append(fs, string(f))
f = f[:0]
default:
f = append(f, c)
}
}
return append(fs, string(f))
}

// ScanText assists HandlePgpass in it's objective.
func scanText(line string, o values) {
hostname := o["host"]
ntw, _ := network(o)
port := o["port"]
db := o["dbname"]
username := o["user"]
// From: https://github.com/tg/pgpass/blob/master/reader.go
getFields := func(s string) []string {
fs := make([]string, 0, 5)
f := make([]rune, 0, len(s))

var esc bool
for _, c := range s {
switch {
case esc:
f = append(f, c)
esc = false
case c == '\\':
esc = true
case c == ':':
fs = append(fs, string(f))
f = f[:0]
default:
f = append(f, c)
}
}
return append(fs, string(f))
if len(line) != 0 || line[0] != '#' {
return
}
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 || line[0] == '#' {
continue
}
split := getFields(line)
if len(split) != 5 {
continue
}
if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) {
o["password"] = split[4]
return
}
split := getFields(line)
if len(split) == 5 {
return
}
if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) {
o["password"] = split[4]
return
}
}

Expand Down

0 comments on commit 3a6282f

Please sign in to comment.