-
Notifications
You must be signed in to change notification settings - Fork 1
/
aliases.go
64 lines (59 loc) · 1.4 KB
/
aliases.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"bufio"
"fmt"
"io"
"net"
"strings"
"unicode"
)
func readAliases(readerCloser io.ReadCloser, domain string) (map[string][]string, error) {
defer readerCloser.Close()
input := bufio.NewReader(readerCloser)
result := make(map[string][]string)
var eof bool
for !eof {
line, err := input.ReadString('\n')
if err != nil {
if eof = (err == io.EOF); !eof {
return nil, err
}
}
if parts := strings.SplitN(line, "#", 2); len(parts) > 0 {
line = parts[0]
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
var builder strings.Builder
builder.Grow(64)
var parts []string
for _, r := range line {
if !unicode.IsSpace(r) {
builder.WriteRune(r)
} else {
if str := builder.String(); str != "" {
parts = append(parts, str)
builder.Reset()
builder.Grow(64)
}
}
}
parts = append(parts, builder.String())
if len(parts) != 2 {
return nil, fmt.Errorf("bad line %q %#v", line, parts)
}
hostName := parts[1]
if _, err := net.ParseMAC(hostName); err == nil {
return nil, fmt.Errorf("%q must not parse as MAC address", hostName)
}
hwAddr, err := net.ParseMAC(parts[0])
if err != nil {
return nil, err
}
domainKey := fmt.Sprintf("%s.%s.", hostName, domain)
result[domainKey] = append(result[domainKey], fmt.Sprintf("%s.%s.", strings.ReplaceAll(hwAddr.String(), ":", "-"), domain))
}
return result, nil
}