57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
"net"
|
|
"encoding/base32"
|
|
"strings"
|
|
"flag"
|
|
)
|
|
|
|
// define tld
|
|
var tld = flag.String("tld", "mesh.cat", "The top level domain for our network")
|
|
|
|
// domainFromIP derives a meshname subdomain for the authoritative DNS server address
|
|
func domainFromIP(target net.IP) string {
|
|
host := strings.ToLower(base32.StdEncoding.EncodeToString(target)[0:26])
|
|
domain := strings.Join([]string{host, ".", *tld, "\n"}, "")
|
|
return domain
|
|
}
|
|
|
|
// handle HTTP requests
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
// get client's ip address
|
|
ip, port, err := net.SplitHostPort(r.RemoteAddr)
|
|
_, _ = port, err
|
|
// check if we're behind a reverse proxy
|
|
xForwardedFor := r.Header.Get("X-Forwarded-For")
|
|
if xForwardedFor != "" {
|
|
ip = xForwardedFor
|
|
}
|
|
parsedIP := net.ParseIP(ip)
|
|
// return domain for IPv6 only
|
|
if parsedIP.To4() == nil {
|
|
w.Write([]byte(domainFromIP(parsedIP)))
|
|
} else {
|
|
// set the response status code to 422
|
|
w.WriteHeader(http.StatusUnprocessableEntity)
|
|
w.Write([]byte("ipv4 not supported\n"))
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
// define path
|
|
http.HandleFunc("/", handler)
|
|
// define ip address
|
|
address := flag.String("address", "[::0]", "The interface address to listen on")
|
|
// define port
|
|
port := flag.String("port", "8008", "The port to listen on")
|
|
// parse the command-line arguments
|
|
flag.Parse()
|
|
// construct listening address
|
|
listenAddr := strings.Join([]string{*address, ":", *port}, "")
|
|
print("Listening on address: ", listenAddr, "\n")
|
|
// start server
|
|
http.ListenAndServe(listenAddr, nil)
|
|
}
|