~bigbes/core-go

deb699c9d01acf127800ce7eedc8d40826b11e98 — Robin Jarry 1 year, 7 months ago 0ad8eb8
config: add global internal-ipnet setting

Add support for a general [sr.ht]internal-ipnet list of networks that
can be considered OK for internal operations.

The default is loopback addresses (127.0.0.0/8 and ::1/128) and private
routable unicast addresses (192.168.0.0/16, 10.0.0.0/8 and fc00::/7)

Since parsing IP networks and addresses can be costly, store the result
of [sr.ht]internal-ipnet into a global list of net.IPNet and
a convenience IsInternalIP() function to be called by services.

Signed-off-by: Robin Jarry <robin@jarry.cc>
1 files changed, 29 insertions(+), 2 deletions(-)

M config/config.go
M config/config.go => config/config.go +29 -2
@@ 3,9 3,11 @@ package config
import (
	"fmt"
	"log"
	"net"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"git.sr.ht/~sircmpwn/getopt"
	"github.com/vaughan0/go-ini"


@@ 14,8 16,9 @@ import (
)

var (
	Debug bool
	Addr  string
	Debug         bool
	Addr          string
	InternalIPNet []net.IPNet
)

// Just loads the config files


@@ 79,6 82,19 @@ func LoadConfig(defaultAddr string) ini.File {

	config := LoadFiles()
	crypto.InitCrypto(config)

	nets, ok := config.Get("sr.ht", "internal-ipnet")
	if !ok {
		nets = "127.0.0.0/8,192.168.0.0/16,10.0.0.0/8,::1/128,fc00::/7"
	}
	for _, n := range strings.Split(nets, ",") {
		_, net, err := net.ParseCIDR(n)
		if err != nil {
			panic(fmt.Errorf("[sr.ht]internal-ipnet: %w", err))
		}
		InternalIPNet = append(InternalIPNet, *net)
	}

	return config
}



@@ 110,3 126,14 @@ func GetInt(conf ini.File, section, name string, defValue int) int {
	}
	return value
}

// Returns true if the given IP address is part of the internal networks as
// per the configuration of [sr.ht]internal-ipnet.
func IsInternalIP(ip net.IP) bool {
	for _, net := range InternalIPNet {
		if net.Contains(ip) {
			return true
		}
	}
	return false
}