diff --git a/bootstrap/client.go b/bootstrap/client.go index ffda363..3dabdb9 100644 --- a/bootstrap/client.go +++ b/bootstrap/client.go @@ -110,6 +110,7 @@ import ( "io" "net/http" "net/url" + "sync" "time" "github.com/openrdap/rdap/bootstrap/cache" @@ -162,6 +163,11 @@ type Client struct { Verbose func(text string) registries map[RegistryType]Registry + + // mu guards registries, the Cache and lazy initialisation, so one Client + // can be shared by many goroutines. It is never held across network I/O + // or while calling Verbose. + mu sync.Mutex } // A Registry implements bootstrap lookups. @@ -187,6 +193,10 @@ func (c *Client) init() { if c.BaseURL == nil { c.BaseURL, _ = url.Parse(DefaultBaseURL) } + + if c.Verbose == nil { + c.Verbose = func(text string) {} + } } // Download downloads a single bootstrap registry file. @@ -200,18 +210,24 @@ func (c *Client) Download(registry RegistryType) error { // // On success, the relevant Registry is refreshed. Use the matching accessor (ASN(), DNS(), IPv4(), or IPv6()) to access it. func (c *Client) DownloadWithContext(ctx context.Context, registry RegistryType) error { + c.mu.Lock() c.init() + c.mu.Unlock() + return c.downloadAndStore(ctx, registry) +} - var json []byte - var s Registry - +// downloadAndStore fetches a registry file without holding mu, so a slow +// download never blocks other callers, then stores it under mu. +func (c *Client) downloadAndStore(ctx context.Context, registry RegistryType) error { json, s, err := c.download(ctx, registry) if err != nil { return err } - err = c.Cache.Save(c.filenameFor(registry), json) - if err != nil { + c.mu.Lock() + defer c.mu.Unlock() + + if err := c.Cache.Save(c.filenameFor(registry), json); err != nil { return err } @@ -319,62 +335,92 @@ func newRegistry(registry RegistryType, json []byte) (Registry, error) { } // Lookup returns the RDAP base URLs for the bootstrap question |question|. +// +// Verbose messages go to c.Verbose. Lookup is safe for concurrent use. func (c *Client) Lookup(question *Question) (*Answer, error) { + return c.LookupVerbose(question, nil) +} + +// LookupVerbose is Lookup with verbose messages sent to verbose. A nil verbose +// falls back to c.Verbose. Verbose is never called with a lock held, so it may +// call the registry accessors such as DNS(). Unlike writing c.Verbose, it does +// not modify the Client, so one Client may serve several callers at once. +func (c *Client) LookupVerbose(question *Question, verbose func(text string)) (*Answer, error) { + c.mu.Lock() c.init() - if c.Verbose == nil { - c.Verbose = func(text string) {} + if verbose == nil { + verbose = c.Verbose } + c.mu.Unlock() - c.Verbose(" bootstrap: Looking up...") - c.Verbose(fmt.Sprintf(" bootstrap: Question type : %s", question.RegistryType)) - c.Verbose(fmt.Sprintf(" bootstrap: Question query: %s", question.Query)) + verbose(" bootstrap: Looking up...") + verbose(fmt.Sprintf(" bootstrap: Question type : %s", question.RegistryType)) + verbose(fmt.Sprintf(" bootstrap: Question query: %s", question.Query)) registry := question.RegistryType - state := c.Cache.State(c.filenameFor(registry)) - c.Verbose(fmt.Sprintf(" bootstrap: Cache state: %s: %s", c.filenameFor(registry), state)) + c.mu.Lock() + filename := c.filenameFor(registry) + state := c.Cache.State(filename) + c.mu.Unlock() + verbose(fmt.Sprintf(" bootstrap: Cache state: %s: %s", filename, state)) // An expired file is refreshed even if it's already parsed into memory. forceDownload := state == cache.Expired + c.mu.Lock() + var loadErr error if c.shouldLoadFromCache(registry, state) { - if err := c.reloadFromCache(registry); err != nil { + if loadErr = c.reloadFromCache(registry); loadErr != nil { forceDownload = true - - c.Verbose(fmt.Sprintf(" bootstrap: Cache load error (%s), downloading...", err)) } } + c.mu.Unlock() + if loadErr != nil { + verbose(fmt.Sprintf(" bootstrap: Cache load error (%s), downloading...", loadErr)) + } - if c.registries[registry] == nil || forceDownload { - c.Verbose(fmt.Sprintf(" bootstrap: Downloading %s", registry.Filename())) + c.mu.Lock() + needDownload := c.registries[registry] == nil || forceDownload + c.mu.Unlock() - if err := c.DownloadWithContext(question.Context(), registry); err != nil { + if needDownload { + verbose(fmt.Sprintf(" bootstrap: Downloading %s", registry.Filename())) + + if err := c.downloadAndStore(question.Context(), registry); err != nil { // Service Registry files change rarely, so an expired copy still // answers most queries. Prefer one to failing the lookup. + c.mu.Lock() if c.registries[registry] == nil { if cacheErr := c.reloadFromCache(registry); cacheErr != nil { + c.mu.Unlock() return nil, err } } + c.mu.Unlock() - c.Verbose(fmt.Sprintf(" bootstrap: Download failed (%s), using expired Service Registry file", err)) + verbose(fmt.Sprintf(" bootstrap: Download failed (%s), using expired Service Registry file", err)) } } else { - c.Verbose(" bootstrap: Using cached Service Registry file") + verbose(" bootstrap: Using cached Service Registry file") } - answer, err := c.registries[registry].Lookup(question) + c.mu.Lock() + reg := c.registries[registry] + c.mu.Unlock() + + answer, err := reg.Lookup(question) if answer != nil { - c.Verbose(fmt.Sprintf(" bootstrap: Looked up '%s'", answer.Query)) + verbose(fmt.Sprintf(" bootstrap: Looked up '%s'", answer.Query)) if answer.Entry != "" { - c.Verbose(fmt.Sprintf(" bootstrap: Matching entry '%s'", answer.Entry)) + verbose(fmt.Sprintf(" bootstrap: Matching entry '%s'", answer.Entry)) } else { - c.Verbose(" bootstrap: No match") + verbose(" bootstrap: No match") } for i, url := range answer.URLs { - c.Verbose(fmt.Sprintf(" bootstrap: Service URL #%d: '%s'", i+1, url)) + verbose(fmt.Sprintf(" bootstrap: Service URL #%d: '%s'", i+1, url)) } } @@ -385,6 +431,8 @@ func (c *Client) Lookup(question *Question) (*Answer, error) { // // This function never initiates a network transfer. func (c *Client) ASN() *ASNRegistry { + c.mu.Lock() + defer c.mu.Unlock() c.init() c.freshenFromCache(ASN) @@ -396,6 +444,8 @@ func (c *Client) ASN() *ASNRegistry { // // This function never initiates a network transfer. func (c *Client) DNS() *DNSRegistry { + c.mu.Lock() + defer c.mu.Unlock() c.init() c.freshenFromCache(DNS) @@ -407,6 +457,8 @@ func (c *Client) DNS() *DNSRegistry { // // This function never initiates a network transfer. func (c *Client) IPv4() *NetRegistry { + c.mu.Lock() + defer c.mu.Unlock() c.init() c.freshenFromCache(IPv4) @@ -418,6 +470,8 @@ func (c *Client) IPv4() *NetRegistry { // // This function never initiates a network transfer. func (c *Client) IPv6() *NetRegistry { + c.mu.Lock() + defer c.mu.Unlock() c.init() c.freshenFromCache(IPv6) @@ -429,6 +483,8 @@ func (c *Client) IPv6() *NetRegistry { // // This function never initiates a network transfer. func (c *Client) ServiceProvider() *ServiceProviderRegistry { + c.mu.Lock() + defer c.mu.Unlock() c.init() c.freshenFromCache(ServiceProvider) diff --git a/bootstrap/concurrency_test.go b/bootstrap/concurrency_test.go new file mode 100644 index 0000000..9e8468d --- /dev/null +++ b/bootstrap/concurrency_test.go @@ -0,0 +1,68 @@ +package bootstrap + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" +) + +func newDNSServer(t *testing.T) *url.URL { + t.Helper() + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/dns.json") { + fmt.Fprintf(w, `{"version":"1.0","publication":"2024-01-01T00:00:00Z","services":[[["com"],["%s/rdap/"]]]}`, srv.URL) + return + } + http.NotFound(w, r) + })) + t.Cleanup(srv.Close) + base, _ := url.Parse(srv.URL + "/") + return base +} + +// Verbose may call back into the client. Before, Lookup held the lock while +// calling Verbose, so this deadlocked. +func TestLookupVerboseMayCallAccessors(t *testing.T) { + base := newDNSServer(t) + b := &Client{BaseURL: base} + + var calls int + answer, err := b.LookupVerbose(&Question{RegistryType: DNS, Query: "example.com"}, func(string) { + calls++ + _ = b.DNS() + }) + if err != nil { + t.Fatal(err) + } + if answer == nil || len(answer.URLs) == 0 { + t.Fatalf("no answer: %#v", answer) + } + if calls == 0 { + t.Fatal("verbose was not called") + } +} + +// Concurrent lookups with their own verbose callbacks share one client. Run +// with -race. +func TestLookupVerboseSharedClient(t *testing.T) { + base := newDNSServer(t) + b := &Client{BaseURL: base} + + var wg sync.WaitGroup + for i := range 16 { + wg.Add(1) + go func(i int) { + defer wg.Done() + _, err := b.LookupVerbose(&Question{RegistryType: DNS, Query: "example.com"}, func(string) {}) + if err != nil { + t.Errorf("lookup %d: %v", i, err) + } + }(i) + } + wg.Wait() +} diff --git a/client.go b/client.go index 9c422af..6a4b2cd 100644 --- a/client.go +++ b/client.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "strings" + "sync" "time" "github.com/openrdap/rdap/bootstrap" @@ -84,6 +85,10 @@ type Client struct { // Service Provider support is now always enabled. // This field is ignored. ServiceProviderExperiment bool + + // mu guards lazy initialisation, so one Client can be shared by many + // goroutines. It is never held across network I/O. + mu sync.Mutex } // Do runs the RDAP request req and returns its Response. @@ -104,6 +109,7 @@ func (c *Client) Do(req *Request) (*Response, error) { } } + c.mu.Lock() // Init HTTP client? if c.HTTP == nil { c.HTTP = &http.Client{} @@ -118,6 +124,7 @@ func (c *Client) Do(req *Request) (*Response, error) { if c.Verbose == nil { c.Verbose = func(text string) {} } + c.mu.Unlock() c.Verbose("") c.Verbose("client: Running...") @@ -145,12 +152,6 @@ func (c *Client) Do(req *Request) (*Response, error) { } } - origBootstrapVerbose := c.Bootstrap.Verbose - c.Bootstrap.Verbose = c.Verbose - defer func() { - c.Bootstrap.Verbose = origBootstrapVerbose - }() - question := &bootstrap.Question{ RegistryType: *bootstrapType, Query: req.Query, @@ -160,7 +161,10 @@ func (c *Client) Do(req *Request) (*Response, error) { var answer *bootstrap.Answer var err error - answer, err = c.Bootstrap.Lookup(question) + // Verbose is passed per call rather than set on the bootstrap client, + // which may be shared with other Clients. The lookup runs without mu, + // so a slow registry download does not block other requests. + answer, err = c.Bootstrap.LookupVerbose(question, c.Verbose) resp.BootstrapAnswer = answer if err != nil { diff --git a/client_concurrency_test.go b/client_concurrency_test.go new file mode 100644 index 0000000..07f012b --- /dev/null +++ b/client_concurrency_test.go @@ -0,0 +1,157 @@ +package rdap + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/openrdap/rdap/bootstrap" +) + +// Do must be safe for concurrent use on a shared Client. Run with -race. +func TestClientDoConcurrent(t *testing.T) { + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/dns.json"): + fmt.Fprintf(w, `{"version":"1.0","publication":"2024-01-01T00:00:00Z","services":[[["com"],["%s/rdap/"]]]}`, srv.URL) + case strings.HasPrefix(r.URL.Path, "/rdap/domain/"): + w.Header().Set("Content-Type", "application/rdap+json") + fmt.Fprintf(w, `{"objectClassName":"domain","ldhName":"%s"}`, strings.TrimPrefix(r.URL.Path, "/rdap/domain/")) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + + base, _ := url.Parse(srv.URL + "/") + client := &Client{Bootstrap: &bootstrap.Client{BaseURL: base}} + + var wg sync.WaitGroup + errs := make(chan error, 32) + for i := range 32 { + wg.Add(1) + go func(i int) { + defer wg.Done() + resp, err := client.Do(NewDomainRequest(fmt.Sprintf("example%d.com", i))) + if err != nil { + errs <- err + return + } + if d, ok := resp.Object.(*Domain); !ok || d.LDHName != fmt.Sprintf("example%d.com", i) { + errs <- fmt.Errorf("unexpected object %#v", resp.Object) + } + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } +} + +func TestRequestURLKeepsServer(t *testing.T) { + server, _ := url.Parse("https://rdap.example/base/?key=1#frag") + req := &Request{Type: DomainRequest, Query: "example.com", Server: server} + got := req.URL().String() + if server.RawQuery != "key=1" || server.Fragment != "frag" { + t.Fatalf("URL() modified the Server URL: %s", server) + } + if want := "https://rdap.example/base/domain/example.com?key=1#frag"; got != want { + t.Fatalf("URL() = %s, want %s", got, want) + } +} + +// A stalled bootstrap download must not block requests that carry their own +// server, because the bootstrap lookup holds no client lock. +func TestStalledBootstrapDoesNotBlockExplicitServer(t *testing.T) { + hold := make(chan struct{}) + reached := make(chan struct{}) + var reachedOnce sync.Once + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/dns.json"): + reachedOnce.Do(func() { close(reached) }) + <-hold + fmt.Fprintf(w, `{"version":"1.0","publication":"2024-01-01T00:00:00Z","services":[[["com"],["%s/rdap/"]]]}`, srv.URL) + case strings.HasPrefix(r.URL.Path, "/rdap/domain/"): + w.Header().Set("Content-Type", "application/rdap+json") + fmt.Fprintf(w, `{"objectClassName":"domain","ldhName":"%s"}`, strings.TrimPrefix(r.URL.Path, "/rdap/domain/")) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(hold) }) // runs first, so the stalled handler can return + + base, _ := url.Parse(srv.URL + "/") + client := &Client{Bootstrap: &bootstrap.Client{BaseURL: base}} + + stalled := make(chan error, 1) + go func() { + _, err := client.Do(NewDomainRequest("example.com")) + stalled <- err + }() + + select { + case <-reached: + case <-time.After(5 * time.Second): + t.Fatal("bootstrap download never started") + } + + explicit := NewDomainRequest("example.net") + explicit.Server, _ = url.Parse(srv.URL + "/rdap/") + done := make(chan error, 1) + go func() { + _, err := client.Do(explicit) + done <- err + }() + + select { + case err := <-done: + if err != nil { + t.Fatalf("explicit-server request failed: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("explicit-server request blocked behind a stalled bootstrap download") + } +} + +// Two clients sharing one bootstrap client must not race on its Verbose field. +func TestSharedBootstrapClientAcrossClients(t *testing.T) { + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/dns.json"): + fmt.Fprintf(w, `{"version":"1.0","publication":"2024-01-01T00:00:00Z","services":[[["com"],["%s/rdap/"]]]}`, srv.URL) + case strings.HasPrefix(r.URL.Path, "/rdap/domain/"): + w.Header().Set("Content-Type", "application/rdap+json") + fmt.Fprintf(w, `{"objectClassName":"domain","ldhName":"%s"}`, strings.TrimPrefix(r.URL.Path, "/rdap/domain/")) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + + base, _ := url.Parse(srv.URL + "/") + shared := &bootstrap.Client{BaseURL: base} + + var wg sync.WaitGroup + for i := range 16 { + wg.Add(1) + go func(i int) { + defer wg.Done() + c := &Client{Bootstrap: shared, Verbose: func(string) {}} + if _, err := c.Do(NewDomainRequest(fmt.Sprintf("example%d.com", i))); err != nil { + t.Errorf("client %d: %v", i, err) + } + }(i) + } + wg.Wait() +} diff --git a/request.go b/request.go index decad0b..5c9aabb 100644 --- a/request.go +++ b/request.go @@ -263,7 +263,9 @@ func (r *Request) URL() *url.URL { resultURL = new(url.URL) *resultURL = *r.Server } else { - tempURL := r.Server + // Copy: r.Server is shared (bootstrap answers, callers' URLs) and + // must not be modified. + tempURL := *r.Server tempURL.RawQuery = "" tempURL.Fragment = "" tempURLString := tempURL.String()