-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (71 loc) · 1.55 KB
/
main.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"strings"
"golang.org/x/net/idna"
)
var ErrOutOfScope = errors.New("domain is out of scope")
type stringSlice []string
func (s *stringSlice) Set(value string) error {
*s = append(*s, value)
return nil
}
func (s *stringSlice) String() string {
return strings.Join(*s, ",")
}
func main() {
var (
scope stringSlice
outOfScope stringSlice
silent bool
)
flag.Var(&scope, "scope", "Suffix for domain in scope")
flag.Var(&outOfScope, "out-of-scope", "Suffix for domain out of scope")
flag.BoolVar(&silent, "silent", false, "Silent errors (do not print to stderr)")
flag.Parse()
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
domain := s.Text()
ascii, err := ToASCII(domain, scope, outOfScope)
if err == nil {
fmt.Println(ascii)
continue
}
if !silent {
fmt.Fprintf(os.Stderr, "Error converting %q: %v\n", domain, err)
}
}
}
func ToASCII(domain string, scope, outOfScope []string) (string, error) {
if domain == "" {
return "", errors.New("domain is empty")
}
if domain == "." {
return "", errors.New("domain is root")
}
if domain[len(domain)-1] == '.' {
domain = domain[:len(domain)-1]
}
result, err := idna.Lookup.ToASCII(domain)
if err != nil {
return "", err
}
for _, suffix := range outOfScope {
if strings.HasSuffix(domain, suffix) {
return "", ErrOutOfScope
}
}
if len(scope) == 0 {
return result, nil
}
for _, suffix := range scope {
if strings.HasSuffix(domain, suffix) {
return result, nil
}
}
return "", ErrOutOfScope
}