refactor(stunreachability): input required and must be an URL (#630)

Here we're refactoring stunreachability to not provide internally a
default input and to take in input an URL rather than a string.

The related ooni/spec change is https://github.com/ooni/spec/pull/227.

This diff has been extracted from https://github.com/ooni/probe-cli/pull/539.

Because the original diff was large, I'm splitting it in a set of
more easily manageable diffs.

The reference issue is https://github.com/ooni/probe/issues/1814, which
is complex enough to require us to proceed incrementally.

This diff WILL need to be backported to release/3.11.
This commit is contained in:
Simone Basso 2021-12-03 14:27:04 +01:00 committed by GitHub
commit cba72d1ca3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 127 additions and 90 deletions

View file

@ -5,8 +5,10 @@ package stunreachability
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"time"
"github.com/ooni/probe-cli/v3/internal/engine/legacy/errorsx"
@ -20,7 +22,7 @@ import (
const (
testName = "stunreachability"
testVersion = "0.2.0"
testVersion = "0.3.0"
)
// Config contains the experiment config.
@ -64,6 +66,15 @@ func wrap(err error) error {
}.MaybeBuild()
}
// errStunMissingInput means that the user did not provide any input
var errStunMissingInput = errors.New("stun: missing input")
// errStunMissingPortInURL means the URL is missing the port
var errStunMissingPortInURL = errors.New("stun: missing port in URL")
// errUnsupportedURLScheme means we don't support the URL scheme
var errUnsupportedURLScheme = errors.New("stun: unsupported URL scheme")
// Run implements ExperimentMeasurer.Run.
func (m *Measurer) Run(
ctx context.Context, sess model.ExperimentSession,
@ -72,7 +83,21 @@ func (m *Measurer) Run(
tk := new(TestKeys)
measurement.TestKeys = tk
registerExtensions(measurement)
if err := wrap(tk.run(ctx, m.config, sess, measurement, callbacks)); err != nil {
input := string(measurement.Input)
if input == "" {
return errStunMissingInput
}
URL, err := url.Parse(input)
if err != nil {
return err
}
if URL.Port() == "" {
return errStunMissingPortInURL
}
if URL.Scheme != "stun" {
return errUnsupportedURLScheme
}
if err := wrap(tk.run(ctx, m.config, sess, measurement, callbacks, URL.Host)); err != nil {
s := err.Error()
tk.Failure = &s
return err
@ -83,12 +108,8 @@ func (m *Measurer) Run(
func (tk *TestKeys) run(
ctx context.Context, config Config, sess model.ExperimentSession,
measurement *model.Measurement, callbacks model.ExperimentCallbacks,
endpoint string,
) error {
const defaultAddress = "stun.l.google.com:19302"
endpoint := string(measurement.Input)
if endpoint == "" {
endpoint = defaultAddress
}
callbacks.OnProgress(0, fmt.Sprintf("stunreachability: measuring: %s...", endpoint))
defer callbacks.OnProgress(
1, fmt.Sprintf("stunreachability: measuring: %s... done", endpoint))