2021-08-17 11:23:53 +02:00
|
|
|
package webconnectivity
|
2021-02-02 12:05:47 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/ooni/probe-cli/v3/internal/engine/netx"
|
2021-09-05 14:49:38 +02:00
|
|
|
"github.com/ooni/probe-cli/v3/internal/netxlite/iox"
|
2021-08-17 10:29:06 +02:00
|
|
|
"github.com/ooni/probe-cli/v3/internal/runtimex"
|
2021-02-04 11:00:27 +01:00
|
|
|
"github.com/ooni/probe-cli/v3/internal/version"
|
2021-02-02 12:05:47 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// Handler implements the Web Connectivity test helper HTTP API.
|
|
|
|
type Handler struct {
|
|
|
|
Client *http.Client
|
|
|
|
Dialer netx.Dialer
|
|
|
|
MaxAcceptableBody int64
|
|
|
|
Resolver netx.Resolver
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
|
|
w.Header().Add("Server", fmt.Sprintf(
|
|
|
|
"oohelperd/%s ooniprobe-engine/%s", version.Version, version.Version,
|
|
|
|
))
|
|
|
|
if req.Method != "POST" {
|
|
|
|
w.WriteHeader(400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reader := &io.LimitedReader{R: req.Body, N: h.MaxAcceptableBody}
|
2021-06-15 11:57:40 +02:00
|
|
|
data, err := iox.ReadAllContext(req.Context(), reader)
|
2021-02-02 12:05:47 +01:00
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var creq CtrlRequest
|
|
|
|
if err := json.Unmarshal(data, &creq); err != nil {
|
|
|
|
w.WriteHeader(400)
|
|
|
|
return
|
|
|
|
}
|
2021-06-15 11:57:40 +02:00
|
|
|
measureConfig := MeasureConfig(h)
|
2021-02-02 12:05:47 +01:00
|
|
|
cresp, err := Measure(req.Context(), measureConfig, &creq)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// We assume that the following call cannot fail because it's a
|
|
|
|
// clearly serializable data structure.
|
2021-08-17 10:29:06 +02:00
|
|
|
data, err = json.Marshal(cresp)
|
|
|
|
runtimex.PanicOnError(err, "json.Marshal failed")
|
2021-02-02 12:05:47 +01:00
|
|
|
w.Header().Add("Content-Type", "application/json")
|
|
|
|
w.Write(data)
|
|
|
|
}
|