2021-08-17 11:23:53 +02:00
|
|
|
package webconnectivity
|
2021-02-02 12:05:47 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/ooni/probe-cli/v3/internal/engine/experiment/webconnectivity"
|
2021-09-28 12:42:01 +02:00
|
|
|
"github.com/ooni/probe-cli/v3/internal/netxlite"
|
2021-02-02 12:05:47 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// CtrlHTTPResponse is the result of the HTTP check performed by
|
|
|
|
// the Web Connectivity test helper.
|
|
|
|
type CtrlHTTPResponse = webconnectivity.ControlHTTPRequestResult
|
|
|
|
|
|
|
|
// HTTPConfig configures the HTTP check.
|
|
|
|
type HTTPConfig struct {
|
|
|
|
Client *http.Client
|
|
|
|
Headers map[string][]string
|
|
|
|
MaxAcceptableBody int64
|
|
|
|
Out chan CtrlHTTPResponse
|
|
|
|
URL string
|
|
|
|
Wg *sync.WaitGroup
|
|
|
|
}
|
|
|
|
|
|
|
|
// HTTPDo performs the HTTP check.
|
|
|
|
func HTTPDo(ctx context.Context, config *HTTPConfig) {
|
|
|
|
defer config.Wg.Done()
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", config.URL, nil)
|
|
|
|
if err != nil {
|
2021-09-27 08:13:30 +02:00
|
|
|
config.Out <- CtrlHTTPResponse{ // fix: emit -1 like the old test helper does
|
|
|
|
BodyLength: -1,
|
|
|
|
Failure: newfailure(err),
|
|
|
|
StatusCode: -1,
|
2021-10-13 13:27:09 +02:00
|
|
|
Headers: map[string]string{},
|
2021-09-27 08:13:30 +02:00
|
|
|
}
|
2021-02-02 12:05:47 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// The original test helper failed with extra headers while here
|
|
|
|
// we're implementing (for now?) a more liberal approach.
|
|
|
|
for k, vs := range config.Headers {
|
|
|
|
switch strings.ToLower(k) {
|
2021-08-17 10:29:06 +02:00
|
|
|
case "user-agent", "accept", "accept-language":
|
2021-02-02 12:05:47 +01:00
|
|
|
for _, v := range vs {
|
|
|
|
req.Header.Add(k, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
resp, err := config.Client.Do(req)
|
|
|
|
if err != nil {
|
2021-09-27 08:13:30 +02:00
|
|
|
config.Out <- CtrlHTTPResponse{ // fix: emit -1 like old test helper does
|
|
|
|
BodyLength: -1,
|
|
|
|
Failure: newfailure(err),
|
|
|
|
StatusCode: -1,
|
2021-10-13 13:27:09 +02:00
|
|
|
Headers: map[string]string{},
|
2021-09-27 08:13:30 +02:00
|
|
|
}
|
2021-02-02 12:05:47 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
headers := make(map[string]string)
|
|
|
|
for k := range resp.Header {
|
|
|
|
headers[k] = resp.Header.Get(k)
|
|
|
|
}
|
|
|
|
reader := &io.LimitedReader{R: resp.Body, N: config.MaxAcceptableBody}
|
2021-09-28 12:42:01 +02:00
|
|
|
data, err := netxlite.ReadAllContext(ctx, reader)
|
2021-02-02 12:05:47 +01:00
|
|
|
config.Out <- CtrlHTTPResponse{
|
|
|
|
BodyLength: int64(len(data)),
|
|
|
|
Failure: newfailure(err),
|
|
|
|
StatusCode: int64(resp.StatusCode),
|
|
|
|
Headers: headers,
|
|
|
|
Title: webconnectivity.GetTitle(string(data)),
|
|
|
|
}
|
|
|
|
}
|