ooni-probe-cli/internal/engine/experiment/webconnectivity/dnslookup.go
Simone Basso 273b70bacc
refactor: interfaces and data types into the model package (#642)
## Checklist

- [x] I have read the [contribution guidelines](https://github.com/ooni/probe-cli/blob/master/CONTRIBUTING.md)
- [x] reference issue for this pull request: https://github.com/ooni/probe/issues/1885
- [x] related ooni/spec pull request: N/A

Location of the issue tracker: https://github.com/ooni/probe

## Description

This PR contains a set of changes to move important interfaces and data types into the `./internal/model` package.

The criteria for including an interface or data type in here is roughly that the type should be important and used by several packages. We are especially interested to move more interfaces here to increase modularity.

An additional side effect is that, by reading this package, one should be able to understand more quickly how different parts of the codebase interact with each other.

This is what I want to move in `internal/model`:

- [x] most important interfaces from `internal/netxlite`
- [x] everything that was previously part of `internal/engine/model`
- [x] mocks from `internal/netxlite/mocks` should also be moved in here as a subpackage
2022-01-03 13:53:23 +01:00

64 lines
1.5 KiB
Go

package webconnectivity
import (
"context"
"fmt"
"net/url"
"sort"
"time"
"github.com/ooni/probe-cli/v3/internal/engine/experiment/urlgetter"
"github.com/ooni/probe-cli/v3/internal/model"
)
// DNSLookupConfig contains settings for the DNS lookup.
type DNSLookupConfig struct {
Begin time.Time
Session model.ExperimentSession
URL *url.URL
}
// DNSLookupResult contains the result of the DNS lookup.
type DNSLookupResult struct {
Addrs map[string]int64
Failure *string
TestKeys urlgetter.TestKeys
}
// DNSLookup performs the DNS lookup part of Web Connectivity.
func DNSLookup(ctx context.Context, config DNSLookupConfig) (out DNSLookupResult) {
target := fmt.Sprintf("dnslookup://%s", config.URL.Hostname())
config.Session.Logger().Infof("%s...", target)
result, err := urlgetter.Getter{
Begin: config.Begin, Session: config.Session, Target: target}.Get(ctx)
out.Addrs = make(map[string]int64)
for _, query := range result.Queries {
for _, answer := range query.Answers {
if answer.IPv4 != "" {
out.Addrs[answer.IPv4] = answer.ASN
continue
}
if answer.IPv6 != "" {
out.Addrs[answer.IPv6] = answer.ASN
continue
}
}
}
config.Session.Logger().Infof("%s... %+v", target, err)
out.Failure = result.Failure
out.TestKeys = result
return
}
// Addresses returns the IP addresses in the DNSLookupResult
func (r DNSLookupResult) Addresses() (out []string) {
out = []string{}
for addr := range r.Addrs {
out = append(out, addr)
}
sort.Slice(out, func(i, j int) bool {
return out[i] < out[j]
})
return
}