-
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathrdap.go
More file actions
84 lines (73 loc) · 2.14 KB
/
rdap.go
File metadata and controls
84 lines (73 loc) · 2.14 KB
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
package registry
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strings"
"github.com/openrdap/rdap"
)
// queryRDAP performs an RDAP lookup using github.com/openrdap/rdap.
// When opts.RDAPServer or a non-IANA RIR is set, the server URL is supplied
// directly on the request, bypassing bootstrap.
func queryRDAP(ctx context.Context, opts Options) (string, error) {
kind := Classify(opts.Target)
req, err := buildRDAPRequest(kind, opts.Target)
if err != nil {
return "", err
}
base := opts.RDAPServer
if base == "" {
base = rirRDAPBase(opts.RIR)
}
if base != "" {
serverURL, err := url.Parse(base)
if err != nil {
return "", fmt.Errorf("registry: parse rdap server %q: %w", base, err)
}
req = req.WithServer(serverURL)
}
req = req.WithContext(ctx)
req.Timeout = opts.Timeout
client := &rdap.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("registry: rdap: %w", err)
}
if resp == nil || resp.Object == nil {
return "", fmt.Errorf("registry: rdap: empty response")
}
return formatRDAP(resp, opts.Format)
}
func buildRDAPRequest(kind Kind, target string) (*rdap.Request, error) {
switch kind {
case KindDomain:
return &rdap.Request{Type: rdap.DomainRequest, Query: target}, nil
case KindIPv4, KindIPv6:
return &rdap.Request{Type: rdap.IPRequest, Query: target}, nil
case KindASN:
num := strings.TrimPrefix(strings.ToUpper(target), "AS")
return &rdap.Request{Type: rdap.AutnumRequest, Query: num}, nil
case KindNICHandle:
return &rdap.Request{Type: rdap.EntityRequest, Query: target}, nil
}
return nil, fmt.Errorf("registry: cannot classify rdap target %q", target)
}
func formatRDAP(resp *rdap.Response, format string) (string, error) {
switch strings.ToLower(format) {
case "json", "raw":
b, err := json.MarshalIndent(resp.Object, "", " ")
if err != nil {
return "", fmt.Errorf("registry: marshal rdap: %w", err)
}
return string(b), nil
}
if pretty := formatRDAPPretty(resp); pretty != "" {
return pretty, nil
}
b, err := json.MarshalIndent(resp.Object, "", " ")
if err != nil {
return "", fmt.Errorf("registry: marshal rdap: %w", err)
}
return string(b), nil
}