summaryrefslogtreecommitdiff
path: root/internal/engine/healthcheck.go
blob: a856608374b2b33c4c5408555be4814b7f9d94bb (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
package engine

import (
	"io"
	"net/http"
	"strings"
	"time"

	"vpnem/internal/config"
)

const DefaultBlockedSiteProbeURL = "https://rutracker.org"

func ModeRequiresExitIP(mode config.Mode) bool {
	return mode.Final == "proxy"
}

func CheckExitIP(localProxyPort int) string {
	client, err := HTTPClientViaSOCKS5(config.LocalProxyHost, localProxyPort, 5*time.Second)
	if err != nil {
		return ""
	}
	resp, err := client.Get("http://ifconfig.me/ip")
	if err != nil {
		return ""
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(io.LimitReader(resp.Body, 64))
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(body))
}

func ProbeBlockedSite(localProxyPort int, rawURL string, timeout time.Duration) (int, error) {
	client, err := HTTPClientViaSOCKS5(config.LocalProxyHost, localProxyPort, timeout)
	if err != nil {
		return 0, err
	}

	req, err := http.NewRequest(http.MethodGet, rawURL, nil)
	if err != nil {
		return 0, err
	}
	req.Header.Set("User-Agent", "vpnem-health/1.0")

	resp, err := client.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 256))
	return resp.StatusCode, nil
}

func DeepCheckRequiresRestart(mode config.Mode, exitIP string, probeErr error) bool {
	if ModeRequiresExitIP(mode) {
		return exitIP == ""
	}
	return probeErr != nil
}