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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
|
// OpenRDAP
// Copyright 2017 Tom Harwood
// MIT License, see the LICENSE file.
package rdap
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/openrdap/rdap/bootstrap"
)
// Client implements an RDAP client.
//
// This client executes RDAP requests, and returns the responses as Go values.
//
// Quick usage:
// client := &rdap.Client{}
// domain, err := client.QueryDomain("example.cz")
//
// if err == nil {
// fmt.Printf("Handle=%s Domain=%s\n", domain.Handle, domain.LDHName)
// }
// The QueryDomain(), QueryAutnum(), and QueryIP() methods all provide full contact information, and timeout after 30s.
//
// Normal usage:
// // Query example.cz.
// req := &rdap.Request{
// Type: rdap.DomainRequest,
// Query: "example.cz",
// }
//
// client := &rdap.Client{}
// resp, err := client.Do(req)
//
// if domain, ok := resp.Object.(*rdap.Domain); ok {
// fmt.Printf("Handle=%s Domain=%s\n", domain.Handle, domain.LDHName)
// }
//
// Advanced usage:
//
// This demonstrates custom FetchRoles, a custom Context, a custom HTTP client,
// a custom Bootstrapper, and a custom timeout.
// // Nameserver query on rdap.nic.cz.
// server, _ := url.Parse("https://rdap.nic.cz")
// req := &rdap.Request{
// Type: rdap.NameserverRequest,
// Query: "a.ns.nic.cz",
// FetchRoles: []string{"all"},
// Timeout: time.Second * 45, // Custom timeout.
//
// Server: server,
// }
//
// req = req.WithContext(ctx) // Custom context (see https://blog.golang.org/context).
//
// client := &rdap.Client{}
// client.HTTP = &http.Client{} // Custom HTTP client.
// client.Bootstrap = &bootstrap.Client{} // Custom bootstapper.
//
// resp, err := client.Do(req)
//
// if ns, ok := resp.Object.(*rdap.Nameserver); ok {
// fmt.Printf("Handle=%s Domain=%s\n", ns.Handle, ns.LDHName)
// }
type Client struct {
HTTP *http.Client
Bootstrap *bootstrap.Client
// Optional callback function for verbose messages.
Verbose func(text string)
ServiceProviderExperiment bool
UserAgent string
}
func (c *Client) Do(req *Request) (*Response, error) {
// Response struct.
resp := &Response{}
// Bad query?
if req == nil {
return nil, &ClientError{
Type: InputError,
Text: "nil Request",
}
}
// Init HTTP client?
if c.HTTP == nil {
c.HTTP = &http.Client{}
}
// Init Bootstrap client?
if c.Bootstrap == nil {
c.Bootstrap = &bootstrap.Client{}
}
// Init Verbose callback?
if c.Verbose == nil {
c.Verbose = func(text string) {}
}
c.Verbose("")
c.Verbose(fmt.Sprintf("client: Running..."))
c.Verbose(fmt.Sprintf("client: Request type : %s", req.Type))
c.Verbose(fmt.Sprintf("client: Request query : %s", req.Query))
var reqs []*Request
// Need to bootstrap the query?
if req.Server != nil {
c.Verbose(fmt.Sprintf("client: Request URL : %s", req.URL()))
reqs = []*Request{req}
} else if req.Server == nil {
c.Verbose("client: Request URL : TBD, bootstrap required")
var bootstrapType *bootstrap.RegistryType = bootstrapTypeFor(req)
if bootstrapType == nil || (*bootstrapType == bootstrap.ServiceProvider && !c.ServiceProviderExperiment) {
return nil, &ClientError{
Type: BootstrapNotSupported,
Text: fmt.Sprintf("Cannot run query type '%s' without a server URL, "+
"the server must be specified",
req.Type),
}
}
origBootstrapVerbose := c.Bootstrap.Verbose
c.Bootstrap.Verbose = c.Verbose
defer func() {
c.Bootstrap.Verbose = origBootstrapVerbose
}()
question := &bootstrap.Question{
RegistryType: *bootstrapType,
Query: req.Query,
}
question = question.WithContext(req.Context())
var answer *bootstrap.Answer
var err error
answer, err = c.Bootstrap.Lookup(question)
resp.BootstrapAnswer = answer
if err != nil {
return resp, err
}
// No URLs to query?
if len(answer.URLs) == 0 {
return resp, &ClientError{
Type: BootstrapNoMatch,
Text: fmt.Sprintf("No RDAP servers found for '%s'", question.Query),
}
}
for _, u := range answer.URLs {
reqs = append(reqs, req.WithServer(u))
}
}
for i, r := range reqs {
c.Verbose(fmt.Sprintf("client: RDAP URL #%d is %s", i, r.URL()))
}
for _, r := range reqs {
c.Verbose(fmt.Sprintf("client: GET %s", r.URL()))
httpResponse := c.get(r)
resp.HTTP = append(resp.HTTP, httpResponse)
if httpResponse.Error != nil {
c.Verbose(fmt.Sprintf("client: error: %s",
httpResponse.Error))
if r.Context().Err() == context.DeadlineExceeded {
return resp, httpResponse.Error
}
// Continues to the next RDAP server.
} else {
hrr := httpResponse.Response
c.Verbose(fmt.Sprintf("client: status-code=%d, content-type=%s, length=%d bytes, duration=%s",
hrr.StatusCode,
hrr.Header.Get("Content-Type"),
len(httpResponse.Body),
httpResponse.Duration))
if len(httpResponse.Body) > 0 && hrr.StatusCode >= 200 && hrr.StatusCode <= 299 {
// Decode the response.
decoder := NewDecoder(httpResponse.Body)
resp.Object, httpResponse.Error = decoder.Decode()
if httpResponse.Error != nil {
c.Verbose(fmt.Sprintf("client: Error decoding response: %s",
httpResponse.Error))
continue
}
c.Verbose("client: Successfully decoded response")
// Implement additional fetches here.
return resp, nil
} else if hrr.StatusCode == 404 {
return resp, &ClientError{
Type: ObjectDoesNotExist,
Text: fmt.Sprintf("RDAP server returned 404, object does not exist."),
}
}
}
}
return resp, &ClientError{
Type: NoWorkingServers,
Text: fmt.Sprintf("No RDAP servers responded successfully (tried %d server(s))",
len(reqs)),
}
}
func (c *Client) get(rdapReq *Request) *HTTPResponse {
// HTTPResponse stores the URL, http.Response, response body...
httpResponse := &HTTPResponse{
URL: rdapReq.URL().String(),
}
start := time.Now()
// Setup the HTTP request.
req, err := http.NewRequest("GET", httpResponse.URL, nil)
if err != nil {
httpResponse.Error = err
httpResponse.Duration = time.Since(start)
return httpResponse
}
// Optionally add User-Agent header.
if c.UserAgent != "" {
req.Header.Add("User-Agent", c.UserAgent)
}
// HTTP Accept header.
req.Header.Add("Accept", "application/rdap+json, application/json")
// Add context for timeout.
req = req.WithContext(rdapReq.Context())
// Make the HTTP request.
resp, err := c.HTTP.Do(req)
httpResponse.Response = resp
// Handle errors such as "remote doesn't speak HTTP"...
if err != nil {
httpResponse.Error = err
httpResponse.Duration = time.Since(start)
return httpResponse
}
defer resp.Body.Close()
httpResponse.Body, httpResponse.Error = ioutil.ReadAll(resp.Body)
httpResponse.Duration = time.Since(start)
return httpResponse
}
// QueryDomain makes an RDAP request for the |domain|.
//
// Full contact information (where available) is provided. The timeout is 30s.
func (c *Client) QueryDomain(domain string) (*Domain, error) {
req := &Request{
Type: DomainRequest,
Query: domain,
}
resp, err := c.doQuickRequest(req)
if err != nil {
return nil, err
}
if domain, ok := resp.Object.(*Domain); ok {
return domain, nil
} else if respError, ok := resp.Object.(*Error); ok {
return nil, clientErrorFromRDAPError(respError)
}
return nil, &ClientError{
Type: WrongResponseType,
Text: "The server returned a non-Domain RDAP response",
}
}
func (c *Client) doQuickRequest(req *Request) (*Response, error) {
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*30)
defer cancelFunc()
req = req.WithContext(ctx)
resp, err := c.Do(req)
return resp, err
}
// QueryAutnum makes an RDAP request for the Autonomous System Number (ASN) |autnum|.
//
// |autnum| is an ASN string, e.g. "AS2856" or "5400".
//
// Full contact information (where available) is provided. The timeout is 30s.
func (c *Client) QueryAutnum(autnum string) (*Autnum, error) {
req := &Request{
Type: AutnumRequest,
Query: autnum,
}
resp, err := c.doQuickRequest(req)
if err != nil {
return nil, err
}
if autnum, ok := resp.Object.(*Autnum); ok {
return autnum, nil
} else if respError, ok := resp.Object.(*Error); ok {
return nil, clientErrorFromRDAPError(respError)
}
return nil, &ClientError{
Type: WrongResponseType,
Text: "The server returned a non-Autnum RDAP response",
}
}
// QueryIP makes an RDAP request for the IPv4/6 address |ip|, e.g. "192.0.2.0" or "2001:db8::".
//
// Full contact information (where available) is provided. The timeout is 30s.
func (c *Client) QueryIP(ip string) (*IPNetwork, error) {
req := &Request{
Type: IPRequest,
Query: ip,
}
resp, err := c.doQuickRequest(req)
if err != nil {
return nil, err
}
if ipNet, ok := resp.Object.(*IPNetwork); ok {
return ipNet, nil
} else if respError, ok := resp.Object.(*Error); ok {
return nil, clientErrorFromRDAPError(respError)
}
return nil, &ClientError{
Type: WrongResponseType,
Text: "The server returned a non-IPNetwork RDAP response",
}
}
func bootstrapTypeFor(req *Request) *bootstrap.RegistryType {
b := new(bootstrap.RegistryType)
switch req.Type {
case DomainRequest:
*b = bootstrap.DNS
case AutnumRequest:
*b = bootstrap.ASN
case EntityRequest:
*b = bootstrap.ServiceProvider
case IPRequest:
if strings.Contains(req.Query, ":") {
*b = bootstrap.IPv6
} else {
*b = bootstrap.IPv4
}
default:
b = nil
}
return b
}
|