forked from client9/ipcat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare.go
67 lines (55 loc) · 1.36 KB
/
cloudflare.go
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
package ipcat
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
)
var (
cloudflareDownload = []string{
"https://www.cloudflare.com/ips-v4",
"https://www.cloudflare.com/ips-v6",
}
)
// DownloadCloudflare downloads the latest Cloudflare IP ranges list
func DownloadCloudflare() ([]byte, error) {
readers := make([]io.Reader, 0, len(cloudflareDownload))
defer func() {
for _, reader := range readers {
reader.(io.ReadCloser).Close()
}
}()
for _, uri := range cloudflareDownload {
resp, err := http.Get(uri)
if err != nil {
return nil, err
}
readers = append(readers, resp.Body)
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Failed to download Cloudflare ranges: status code %s", resp.Status)
}
}
body, err := ioutil.ReadAll(io.MultiReader(readers...))
if err != nil {
return nil, err
}
return bytes.TrimSpace(body), nil
}
// UpdateCloudflare parses the Cloudflare IP text file and updates the interval set
func UpdateCloudflare(ipmap *IntervalSet, body []byte) error {
const (
cloudflareName = "Cloudflare Inc"
cloudflareURL = "https://www.cloudflare.com/"
)
// delete all existing records
ipmap.DeleteByName(cloudflareName)
// and add back
for _, cidr := range bytes.Split(body, []byte("\n")) {
err := ipmap.AddCIDR(string(cidr), cloudflareName, cloudflareURL)
if err != nil {
return err
}
}
return nil
}