package check import ( "bytes" "context" "crypto/tls" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "strconv" "strings" "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" ) // HTTPConfig configures an HTTP(S) check. type HTTPConfig struct { Method string `json:"method"` // ExpectStatus lists accepted codes or classes such as "2xx" or "301". ExpectStatus []string `json:"expect_status"` // Keyword must appear in the body, or must not if KeywordAbsent is set. Keyword string `json:"keyword,omitempty"` KeywordAbsent bool `json:"keyword_absent,omitempty"` FollowRedirects bool `json:"follow_redirects"` VerifyTLS bool `json:"verify_tls"` Headers map[string]string `json:"headers,omitempty"` } // maxBody bounds how much of a response is searched for the keyword. const maxBody = 1 << 20 type httpCheck struct{} func (httpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { u, err := url.Parse(target) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil { return nil, invalid("invalid_target") } c := HTTPConfig{Method: http.MethodGet, ExpectStatus: []string{"2xx", "3xx"}, FollowRedirects: true, VerifyTLS: true} if err := json.Unmarshal(config, &c); err != nil { return nil, invalid("invalid_config") } c.Method = strings.ToUpper(c.Method) if c.Method != http.MethodGet && c.Method != http.MethodHead { return nil, invalid("invalid_method") } if c.Method == http.MethodHead && c.Keyword != "" { return nil, invalid("keyword_needs_get") } if len(c.ExpectStatus) == 0 || len(c.ExpectStatus) > 20 { return nil, invalid("invalid_expect_status") } for _, p := range c.ExpectStatus { if !validStatusPattern(p) { return nil, invalid("invalid_expect_status") } } if len(c.Keyword) > 500 || len(c.Headers) > 20 { return nil, invalid("invalid_config") } for k, v := range c.Headers { if k == "" || strings.ContainsAny(k+v, "\r\n") || strings.EqualFold(k, "Host") { return nil, invalid("invalid_header") } } return encode(c), nil } func validStatusPattern(p string) bool { if len(p) == 3 && p[1:] == "xx" { return p[0] >= '1' && p[0] <= '5' } n, err := strconv.Atoi(p) return err == nil && n >= 100 && n <= 599 } func statusMatches(code int, patterns []string) bool { s := strconv.Itoa(code) for _, p := range patterns { if p == s || (strings.HasSuffix(p, "xx") && p[0] == s[0]) { return true } } return false } func (httpCheck) run(ctx context.Context, s Spec) Outcome { c, err := decode[HTTPConfig](s.Config) if err != nil { return Outcome{Error: "invalid configuration"} } d := netguard.Dialer(s.AllowPrivate, s.Timeout) tr := &http.Transport{ DialContext: d.DialContext, TLSClientConfig: &tls.Config{InsecureSkipVerify: !c.VerifyTLS}, //nolint:gosec // opt-out chosen by the customer per monitor DisableKeepAlives: true, TLSHandshakeTimeout: s.Timeout, ForceAttemptHTTP2: true, } defer tr.CloseIdleConnections() client := &http.Client{Transport: tr} if !c.FollowRedirects { client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } } req, err := http.NewRequestWithContext(ctx, c.Method, s.Target, nil) if err != nil { return Outcome{Error: "invalid target"} } req.Header.Set("User-Agent", "uptimesebi-checker") for k, v := range c.Headers { req.Header.Set(k, v) } resp, err := client.Do(req) if err != nil { return Outcome{Error: describeNetErr(err)} } defer func() { _ = resp.Body.Close() }() o := Outcome{StatusCode: resp.StatusCode} if !statusMatches(resp.StatusCode, c.ExpectStatus) { o.Error = fmt.Sprintf("unexpected status %d", resp.StatusCode) return o } if c.Keyword != "" { body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody)) if err != nil { o.Error = describeNetErr(err) return o } found := bytes.Contains(body, []byte(c.Keyword)) switch { case found && c.KeywordAbsent: o.Error = "keyword present" return o case !found && !c.KeywordAbsent: o.Error = "keyword not found" return o } } o.OK = true return o } // describeNetErr turns transport errors into short, stable messages. func describeNetErr(err error) string { var dnsErr *net.DNSError var certErr *tls.CertificateVerificationError var opErr *net.OpError switch { case errors.Is(err, netguard.ErrForbiddenAddress): return "target resolves to a non-public address" case errors.Is(err, context.DeadlineExceeded): return "timeout" case errors.As(err, &dnsErr): if dnsErr.IsNotFound { return "host not found" } return "dns lookup failed" case errors.As(err, &certErr): return "tls certificate invalid: " + certErr.Err.Error() case errors.As(err, &opErr): if opErr.Op == "dial" { return "connection failed: " + opErr.Err.Error() } return opErr.Op + " failed: " + opErr.Err.Error() } return err.Error() }