summaryrefslogtreecommitdiffstats
path: root/src/go/plugin/go.d/modules/whoisquery/provider.go
blob: f6164da7ca60c79078158a5f6dc55c53567c0f96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// SPDX-License-Identifier: GPL-3.0-or-later

package whoisquery

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/araddon/dateparse"
	"github.com/likexian/whois"
	whoisparser "github.com/likexian/whois-parser"
)

type provider interface {
	remainingTime() (float64, error)
}

type whoisClient struct {
	domainAddress string
	client        *whois.Client
}

func newProvider(config Config) (provider, error) {
	domain := config.Source
	client := whois.NewClient()
	client.SetTimeout(config.Timeout.Duration())

	return &whoisClient{
		domainAddress: domain,
		client:        client,
	}, nil
}

func (c *whoisClient) remainingTime() (float64, error) {
	info, err := c.queryWhoisInfo()
	if err != nil {
		return 0, err
	}

	if info.Domain.ExpirationDate == "" {
		if !strings.HasPrefix(c.domainAddress, "=") {
			// some servers support requesting extended data
			// https://github.com/netdata/netdata/issues/17907#issuecomment-2171758380
			c.domainAddress = fmt.Sprintf("= %s", c.domainAddress)
			return c.remainingTime()
		}
	}

	return parseWhoisInfoExpirationDate(info)
}

func (c *whoisClient) queryWhoisInfo() (*whoisparser.WhoisInfo, error) {
	resp, err := c.client.Whois(c.domainAddress)
	if err != nil {
		return nil, err
	}

	info, err := whoisparser.Parse(resp)
	if err != nil {
		return nil, err
	}

	return &info, nil
}

func parseWhoisInfoExpirationDate(info *whoisparser.WhoisInfo) (float64, error) {
	if info == nil || info.Domain == nil {
		return 0, errors.New("nil Whois Info")
	}

	if info.Domain.ExpirationDateInTime != nil {
		return time.Until(*info.Domain.ExpirationDateInTime).Seconds(), nil
	}

	date := info.Domain.ExpirationDate
	if date == "" {
		return 0, errors.New("no expiration date")
	}

	if strings.Contains(date, " ") {
		// https://community.netdata.cloud/t/whois-query-monitor-cannot-parse-expiration-time/3485
		if v, err := time.Parse("2006.01.02 15:04:05", date); err == nil {
			return time.Until(v).Seconds(), nil
		}
	}

	expire, err := dateparse.ParseAny(date)
	if err != nil {
		return 0, err
	}

	return time.Until(expire).Seconds(), nil
}