Use Redis for blocked servers list

This commit is contained in:
Jacob Gunther
2023-02-24 19:41:54 -06:00
parent d5f7c669b7
commit b2ffb03e1d
9 changed files with 130 additions and 107 deletions

View File

@@ -5,68 +5,18 @@ import (
_ "embed"
"encoding/hex"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
)
var (
//go:embed icon.png
defaultIconBytes []byte
blockedServers *MutexArray[string] = nil
ipAddressRegExp *regexp.Regexp = regexp.MustCompile(`^\d{1,3}(\.\d{1,3}){3}$`)
defaultIcon []byte
ipAddressRegExp *regexp.Regexp = regexp.MustCompile(`^\d{1,3}(\.\d{1,3}){3}$`)
)
type MutexArray[K comparable] struct {
List []K
Mutex *sync.Mutex
}
func (m *MutexArray[K]) Has(value K) bool {
m.Mutex.Lock()
defer m.Mutex.Unlock()
for _, v := range m.List {
if v == value {
return true
}
}
return false
}
func GetBlockedServerList() error {
resp, err := http.Get("https://sessionserver.mojang.com/blockedservers")
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
blockedServers = &MutexArray[string]{
List: strings.Split(string(body), "\n"),
Mutex: &sync.Mutex{},
}
return nil
}
func IsBlockedAddress(address string) bool {
func IsBlockedAddress(address string) (bool, error) {
split := strings.Split(strings.ToLower(address), ".")
isIPAddress := ipAddressRegExp.MatchString(address)
@@ -94,14 +44,19 @@ func IsBlockedAddress(address string) bool {
}
newAddressBytes := sha1.Sum([]byte(newAddress))
newAddressHash := hex.EncodeToString(newAddressBytes[:])
if blockedServers.Has(newAddressHash) {
return true
exists, err := r.Exists(fmt.Sprintf("blocked:%s", hex.EncodeToString(newAddressBytes[:])))
if err != nil {
return false, err
}
if exists {
return true, nil
}
}
return false
return false, nil
}
func ParseAddress(address string, defaultPort uint16) (string, uint16, error) {