-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathIP.go
66 lines (53 loc) · 1.58 KB
/
IP.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
/*
File Name: IP.go
Copyright: 2020 Kleissner Investments s.r.o.
Author: Peter Kleissner
*/
package ip2tor
import (
"net"
"net/http"
"time"
)
var torIPs map[string]struct{}
// Init starts the download daemon and optionally reads the cache file, if specified
// Mode: 0 = disabled (no IP check), 1 = active (ban exit nodes only), 2 = active (ban all nodes), 3 = active, no fetching (only use file cache)
func Init(mode int, waitTime time.Duration, filename string) {
if mode == 0 { // disabled?
torIPs = make(map[string]struct{})
return
}
var useCache bool
torIPs, useCache = readCacheFile(filename)
if mode == 3 { // only use file cache?
startFileCacheFetcher(waitTime, filename)
return
}
startDownloadDaemon(mode == 1, waitTime, filename, !useCache)
}
// IsTor checks if an IP address is listed as Tor IP
func IsTor(IP net.IP) bool {
if IP == nil { // invalid input?
return false
}
_, ok := torIPs[IP.String()]
return ok
}
// BlockTorMiddleware returns a middleware function to be used with mux.Router.Use(). Tor IPs will be denied access.
func BlockTorMiddleware(BanStatusCode int, BanPayload []byte) func(http.Handler) http.Handler {
return (func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// parse IP:port
host, _, _ := net.SplitHostPort(r.RemoteAddr)
hostIP := net.ParseIP(host)
// Is Tor?
if IsTor(hostIP) {
w.WriteHeader(BanStatusCode)
w.Write(BanPayload)
return
}
next.ServeHTTP(w, r)
return
})
})
}