This repository has been archived on 2024-03-03. You can view files and clone it, but cannot push or open issues or pull requests.
adlin/token-validator/ip.go

90 lines
2.0 KiB
Go

package main
import (
"fmt"
"net"
"strconv"
"github.com/julienschmidt/httprouter"
"git.nemunai.re/srs/adlin/libadlin"
)
func init() {
router.GET("/api/ips", apiHandler(showIPs))
router.GET("/api/students/:sid/ips", apiHandler(studentHandler(func(student *adlin.Student, body []byte) (interface{}, error) {
return getStudentIPs(student), nil
})))
}
func IPSuffix(s *adlin.Student, network net.IPNet) net.IP {
ipshift := s.Id*4 + 7
myIP := make(net.IP, len(network.IP))
copy(myIP, network.IP)
if ipshift > 254 {
myIP[len(myIP)-2] += byte(ipshift / 254)
ipshift = ipshift % 254
}
myIP[len(myIP)-1] += byte(ipshift)
return myIP
}
func showIPs(_ httprouter.Params, body []byte) (interface{}, error) {
r := make(map[string]map[string]string)
students, err := adlin.GetStudents()
if err != nil {
return nil, err
}
for _, std := range students {
sid := fmt.Sprintf("%d", std.Id)
r[sid] = getStudentIPs(std)
if std.MAC == nil {
continue
}
r[sid]["mac"] = *std.MAC
}
return r, nil
}
func GetStudentTunnelIPs(student *adlin.Student) (ips []string) {
if ts, err := student.GetActivesTunnels(); err != nil || len(ts) == 0 || ts[0].SuffixIP == 0 {
ips = append(ips, adlin.StudentIP(student.Id, 0).String()+"1")
} else {
for _, t := range ts {
ips = append(ips, t.GetStudentIP())
}
}
return
}
func getStudentIPs(student *adlin.Student) (r map[string]string) {
r = make(map[string]string)
r["vlan0"] = IPSuffix(student, net.IPNet{IP: net.ParseIP("172.23.12.0"), Mask: net.CIDRMask(17, 32)}).String()
r["wg0"] = IPSuffix(student, net.IPNet{IP: net.ParseIP("172.17.12.0"), Mask: net.CIDRMask(16, 32)}).String()
r["vlan7"] = IPSuffix(student, net.IPNet{IP: net.ParseIP("172.23.142.0"), Mask: net.CIDRMask(23, 32)}).String()
for d, ip := range GetStudentTunnelIPs(student) {
key := "wg"
if d > 0 {
key += strconv.Itoa(d)
}
r[key] = ip
}
r["adn"] = student.MyAssociatedDomain()
r["ddn"] = student.MyDelegatedDomain()
return
}