jrouter/main.go

464 lines
13 KiB
Go
Raw Normal View History

2024-03-31 09:31:50 +11:00
/*
Copyright 2024 Josh Deprez
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2024-03-10 11:57:03 +11:00
package main
2024-03-15 15:17:21 +11:00
import (
2024-03-30 14:13:34 +11:00
"context"
"errors"
2024-03-22 16:14:55 +11:00
"flag"
2024-04-17 12:14:33 +10:00
"fmt"
2024-04-07 13:11:06 +10:00
"io"
2024-03-15 15:17:21 +11:00
"log"
2024-04-05 10:43:29 +11:00
"math/rand/v2"
2024-03-15 15:17:21 +11:00
"net"
2024-03-30 14:24:16 +11:00
"os"
"os/signal"
2024-03-24 18:01:24 +11:00
"regexp"
2024-03-30 14:49:18 +11:00
"sync"
"time"
2024-03-15 15:17:21 +11:00
"gitea.drjosh.dev/josh/jrouter/aurp"
2024-04-07 13:08:15 +10:00
"github.com/google/gopacket/pcap"
2024-04-05 14:31:36 +11:00
"github.com/sfiera/multitalk/pkg/ddp"
2024-04-06 16:02:30 +11:00
"github.com/sfiera/multitalk/pkg/ethernet"
2024-04-05 14:07:16 +11:00
"github.com/sfiera/multitalk/pkg/ethertalk"
2024-03-15 15:17:21 +11:00
)
2024-03-24 18:01:24 +11:00
var hasPortRE = regexp.MustCompile(`:\d+$`)
var configFilePath = flag.String("config", "jrouter.yaml", "Path to configuration file to use")
2024-03-10 11:57:03 +11:00
func main() {
2024-03-22 16:14:55 +11:00
flag.Parse()
2024-03-15 15:17:21 +11:00
log.Println("jrouter")
2024-03-24 18:01:24 +11:00
cfg, err := loadConfig(*configFilePath)
if err != nil {
log.Fatalf("Couldn't load configuration file: %v", err)
}
localIP := net.ParseIP(cfg.LocalIP).To4()
2024-03-22 16:14:55 +11:00
if localIP == nil {
iaddrs, err := net.InterfaceAddrs()
if err != nil {
log.Fatalf("Couldn't read network interface addresses: %v", err)
}
for _, iaddr := range iaddrs {
inet, ok := iaddr.(*net.IPNet)
if !ok {
continue
}
if !inet.IP.IsGlobalUnicast() {
continue
}
localIP = inet.IP.To4()
if localIP != nil {
break
}
}
if localIP == nil {
2024-03-24 18:01:24 +11:00
log.Fatalf("No global unicast IPv4 addresses on any network interfaces, and no valid local_ip address in configuration")
2024-03-22 16:14:55 +11:00
}
}
2024-03-24 21:10:24 +11:00
localDI := aurp.IPDomainIdentifier(localIP)
2024-03-22 16:14:55 +11:00
log.Printf("Using %v as local domain identifier", localIP)
2024-03-30 20:47:18 +11:00
log.Printf("EtherTalk configuration: %+v", cfg.EtherTalk)
2024-03-24 18:01:24 +11:00
peers := make(map[udpAddr]*peer)
2024-04-05 10:43:29 +11:00
var nextConnID uint16
for nextConnID == 0 {
nextConnID = uint16(rand.IntN(0x10000))
}
2024-03-22 16:14:55 +11:00
2024-03-24 18:01:24 +11:00
ln, err := net.ListenUDP("udp4", &net.UDPAddr{Port: int(cfg.ListenPort)})
2024-03-15 15:17:21 +11:00
if err != nil {
log.Fatalf("Couldn't listen on udp4:387: %v", err)
}
2024-03-24 18:01:24 +11:00
log.Printf("Listening on %v", ln.LocalAddr())
2024-03-30 14:24:16 +11:00
log.Println("Press ^C or send SIGINT to stop the router gracefully")
2024-03-30 14:37:41 +11:00
cctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx, _ := signal.NotifyContext(cctx, os.Interrupt)
2024-03-30 14:49:18 +11:00
2024-04-07 12:56:51 +10:00
// Open PCAP session
2024-04-17 12:14:33 +10:00
// First check the interface
2024-04-07 12:56:51 +10:00
iface, err := net.InterfaceByName(cfg.EtherTalk.Device)
if err != nil {
log.Fatalf("Couldn't find interface named %q: %v", cfg.EtherTalk.Device, err)
}
myHWAddr := ethernet.Addr(iface.HardwareAddr)
2024-04-17 12:14:33 +10:00
if cfg.EtherTalk.EthAddr != "" {
// Override myHWAddr with the configured address
netHWAddr, err := net.ParseMAC(cfg.EtherTalk.EthAddr)
if err != nil {
log.Fatalf("Couldn't parse ethertalk.ethernet_addr value %q: %v", cfg.EtherTalk.EthAddr, err)
}
myHWAddr = ethernet.Addr(netHWAddr)
}
2024-04-07 12:56:51 +10:00
2024-04-17 12:14:33 +10:00
pcapHandle, err := pcap.OpenLive(cfg.EtherTalk.Device, 4096, true, 100*time.Millisecond)
2024-04-07 12:56:51 +10:00
if err != nil {
2024-04-17 12:14:33 +10:00
log.Fatalf("Couldn't open %q for packet capture: %v", cfg.EtherTalk.Device, err)
}
bpfFilter := fmt.Sprintf("(atalk or aarp) and (ether multicast or ether dst %s)", myHWAddr)
if err := pcapHandle.SetBPFFilter(bpfFilter); err != nil {
pcapHandle.Close()
log.Fatalf("Couldn't set BPF filter on packet capture: %v", err)
2024-04-07 12:56:51 +10:00
}
defer pcapHandle.Close()
2024-03-30 14:49:18 +11:00
// Wait until all peer handlers have finished before closing the port
var handlersWG sync.WaitGroup
defer func() {
2024-03-30 17:04:27 +11:00
log.Print("Waiting for handlers to return...")
2024-03-30 14:49:18 +11:00
handlersWG.Wait()
2024-03-30 14:30:58 +11:00
ln.Close()
}()
2024-04-07 12:56:51 +10:00
goPeerHandler := func(p *peer) {
2024-03-30 14:49:18 +11:00
handlersWG.Add(1)
go func() {
defer handlersWG.Done()
p.handle(ctx)
}()
}
2024-03-30 14:24:16 +11:00
2024-04-14 18:29:29 +10:00
// -------------------------------- Tables --------------------------------
2024-04-14 17:13:12 +10:00
routing := NewRoutingTable()
2024-04-14 18:29:29 +10:00
zones := NewZoneTable()
zones.Upsert(cfg.EtherTalk.NetStart, cfg.EtherTalk.ZoneName, true)
2024-04-14 13:44:35 +10:00
2024-04-12 16:14:27 +10:00
// ------------------------- Configured peer setup ------------------------
2024-03-24 18:01:24 +11:00
for _, peerStr := range cfg.Peers {
if !hasPortRE.MatchString(peerStr) {
peerStr += ":387"
}
raddr, err := net.ResolveUDPAddr("udp4", peerStr)
if err != nil {
log.Fatalf("Invalid UDP address: %v", err)
}
log.Printf("resolved %q to %v", peerStr, raddr)
peer := &peer{
2024-03-30 20:27:24 +11:00
cfg: cfg,
tr: &aurp.Transport{
LocalDI: localDI,
RemoteDI: aurp.IPDomainIdentifier(raddr.IP),
LocalConnID: nextConnID,
},
2024-04-14 13:44:35 +10:00
conn: ln,
raddr: raddr,
recv: make(chan aurp.Packet, 1024),
routingTable: routing,
2024-04-14 18:29:29 +10:00
zoneTable: zones,
2024-03-24 18:01:24 +11:00
}
2024-04-05 10:43:29 +11:00
aurp.Inc(&nextConnID)
2024-03-24 18:01:24 +11:00
peers[udpAddrFromNet(raddr)] = peer
2024-04-07 12:56:51 +10:00
goPeerHandler(peer)
2024-03-24 18:01:24 +11:00
}
2024-03-15 15:17:21 +11:00
2024-04-12 16:14:27 +10:00
// --------------------------------- AARP ---------------------------------
2024-04-06 20:11:15 +11:00
aarpMachine := NewAARPMachine(cfg, pcapHandle, myHWAddr)
2024-04-06 17:46:00 +11:00
aarpCh := make(chan *ethertalk.Packet, 1024)
go aarpMachine.Run(ctx, aarpCh)
2024-04-06 16:02:30 +11:00
2024-04-12 16:14:27 +10:00
// --------------------------------- RTMP ---------------------------------
2024-04-07 15:14:54 +10:00
rtmpMachine := &RTMPMachine{
2024-04-14 13:44:35 +10:00
aarp: aarpMachine,
cfg: cfg,
pcapHandle: pcapHandle,
routingTable: routing,
2024-04-07 15:14:54 +10:00
}
2024-04-07 15:41:27 +10:00
rtmpCh := make(chan *ddp.ExtPacket, 1024)
go rtmpMachine.Run(ctx, rtmpCh)
2024-04-07 15:14:54 +10:00
2024-04-12 16:14:27 +10:00
// ---------------------- Raw AppleTalk/AARP inbound ----------------------
2024-04-06 17:46:00 +11:00
go func() {
2024-04-05 13:18:22 +11:00
for {
2024-04-07 13:08:15 +10:00
if ctx.Err() != nil {
return
}
2024-04-06 17:46:00 +11:00
rawPkt, _, err := pcapHandle.ReadPacketData()
2024-04-07 13:08:15 +10:00
if errors.Is(err, pcap.NextErrorTimeoutExpired) {
continue
}
2024-04-07 13:11:06 +10:00
if errors.Is(err, io.EOF) || errors.Is(err, pcap.NextErrorNoMorePackets) {
return
}
2024-04-05 13:18:22 +11:00
if err != nil {
2024-04-07 13:11:06 +10:00
log.Printf("Couldn't read AppleTalk / AARP packet data: %v", err)
return
2024-04-05 14:07:16 +11:00
}
2024-04-06 17:46:00 +11:00
ethFrame := new(ethertalk.Packet)
if err := ethertalk.Unmarshal(rawPkt, ethFrame); err != nil {
2024-04-05 14:07:16 +11:00
log.Printf("Couldn't unmarshal EtherTalk frame: %v", err)
continue
2024-04-05 13:18:22 +11:00
}
2024-04-05 14:07:16 +11:00
2024-04-06 17:46:00 +11:00
// Ignore if sent by me
if ethFrame.Src == myHWAddr {
2024-04-05 14:07:16 +11:00
continue
}
2024-04-15 20:48:40 +10:00
// TODO: filter ethFrame.Dst to myHWAddr, the broadcast address,
// or the relevant zone multicast address
2024-04-05 18:03:26 +11:00
switch ethFrame.SNAPProto {
2024-04-05 14:31:36 +11:00
case ethertalk.AARPProto:
2024-04-07 15:25:30 +10:00
// log.Print("Got an AARP frame")
2024-04-06 17:46:00 +11:00
aarpCh <- ethFrame
2024-04-05 14:31:36 +11:00
case ethertalk.AppleTalkProto:
2024-04-07 15:25:30 +10:00
// log.Print("Got an AppleTalk frame")
2024-04-12 13:10:04 +10:00
ddpkt := new(ddp.ExtPacket)
if err := ddp.ExtUnmarshal(ethFrame.Payload, ddpkt); err != nil {
2024-04-05 14:31:36 +11:00
log.Printf("Couldn't unmarshal DDP packet: %v", err)
continue
}
2024-04-05 21:09:55 +11:00
log.Printf("DDP: src (%d.%d s %d) dst (%d.%d s %d) proto %d data len %d",
ddpkt.SrcNet, ddpkt.SrcNode, ddpkt.SrcSocket,
ddpkt.DstNet, ddpkt.DstNode, ddpkt.DstSocket,
ddpkt.Proto, len(ddpkt.Data))
2024-04-13 15:27:41 +10:00
2024-04-05 18:03:26 +11:00
// Glean address info for AMT
srcAddr := ddp.Addr{Network: ddpkt.SrcNet, Node: ddpkt.SrcNode}
2024-04-06 17:46:00 +11:00
aarpMachine.Learn(srcAddr, ethFrame.Src)
2024-04-14 13:32:49 +10:00
// log.Printf("DDP: Gleaned that %d.%d -> %v", srcAddr.Network, srcAddr.Node, ethFrame.Src)
2024-04-05 14:38:27 +11:00
2024-04-07 15:41:27 +10:00
// Packet for us? First, who am I?
myAddr, ok := aarpMachine.Address()
if !ok {
continue
}
// Our network?
// "The network number 0 is reserved to mean unknown; by default
// it specifies the local network to which the node is
// connected. Packets whose destination network number is 0 are
// addressed to a node on the local network."
2024-04-12 16:14:27 +10:00
if ddpkt.DstNet != 0 && (ddpkt.DstNet < cfg.EtherTalk.NetStart || ddpkt.DstNet > cfg.EtherTalk.NetEnd) {
// Is it for a network in the routing table?
2024-04-14 17:13:12 +10:00
rt := routing.LookupRoute(ddpkt.DstNet)
2024-04-12 16:14:27 +10:00
if rt == nil {
2024-04-13 15:27:41 +10:00
log.Printf("DDP: no route for network %d", ddpkt.DstNet)
2024-04-12 16:14:27 +10:00
continue
}
// Encap ethPacket.Payload into an AURP packet
2024-04-14 17:13:12 +10:00
log.Printf("DDP: forwarding to AURP peer %v", rt.Peer.tr.RemoteDI)
if _, err := rt.Peer.send(rt.Peer.tr.NewAppleTalkPacket(ethFrame.Payload)); err != nil {
2024-04-12 16:14:27 +10:00
log.Printf("DDP: Couldn't forward packet to AURP peer: %v", err)
}
2024-04-07 15:41:27 +10:00
continue
}
// To me?
// "Node ID 0 indicates any router on the network"- I'm a router
// "node ID $FF indicates either a network-wide or zone-specific
// broadcast"- that's relevant
if ddpkt.DstNode != 0 && ddpkt.DstNode != 0xff && ddpkt.DstNode != myAddr.Proto.Node {
continue
}
switch ddpkt.DstSocket {
case 1: // The RTMP socket
2024-04-12 13:10:04 +10:00
rtmpCh <- ddpkt
2024-04-07 17:01:26 +10:00
2024-04-13 17:36:55 +10:00
case 2: // The NIS (name information socket / NBP socket)
2024-04-15 18:09:15 +10:00
if err := handleNBP(pcapHandle, myHWAddr, ethFrame.Src, myAddr, zones, routing, cfg, ddpkt); err != nil {
2024-04-14 14:08:51 +10:00
log.Printf("NBP: Couldn't handle: %v", err)
2024-04-13 15:33:48 +10:00
}
2024-04-12 13:09:04 +10:00
2024-04-07 17:01:26 +10:00
case 4: // The AEP socket
2024-04-12 13:10:04 +10:00
if err := handleAEP(pcapHandle, myHWAddr, ethFrame.Src, ddpkt); err != nil {
2024-04-07 17:01:26 +10:00
log.Printf("AEP: Couldn't handle: %v", err)
}
2024-04-13 17:36:55 +10:00
case 6: // The ZIS (zone information socket / ZIP socket)
2024-04-14 18:29:29 +10:00
if err := handleZIP(pcapHandle, ethFrame.Src, myHWAddr, myAddr, cfg, zones, ddpkt); err != nil {
2024-04-14 13:53:55 +10:00
log.Printf("ZIP: couldn't handle: %v", err)
2024-04-13 17:36:55 +10:00
}
2024-04-07 15:41:27 +10:00
default:
log.Printf("DDP: No handler for socket %d", ddpkt.DstSocket)
}
2024-04-05 14:38:27 +11:00
default:
2024-04-05 18:03:26 +11:00
log.Printf("Read unknown packet %s -> %s with payload %x", ethFrame.Src, ethFrame.Dst, ethFrame.Payload)
2024-04-05 14:31:36 +11:00
}
2024-04-05 13:18:22 +11:00
}
}()
2024-04-12 16:14:27 +10:00
// ----------------------------- AURP inbound -----------------------------
2024-03-15 15:17:21 +11:00
for {
2024-03-30 14:56:04 +11:00
if ctx.Err() != nil {
return
}
ln.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
2024-04-05 14:07:16 +11:00
pktbuf := make([]byte, 4096)
2024-03-30 14:24:16 +11:00
pktlen, raddr, readErr := ln.ReadFromUDP(pktbuf)
var operr *net.OpError
if errors.As(readErr, &operr) && operr.Timeout() {
continue
}
2024-03-15 16:15:24 +11:00
2024-04-15 09:26:23 +10:00
// log.Printf("AURP: Received packet of length %d from %v", pktlen, raddr)
2024-03-24 18:01:24 +11:00
2024-03-30 14:24:16 +11:00
dh, pkt, parseErr := aurp.ParsePacket(pktbuf[:pktlen])
2024-03-15 16:15:24 +11:00
if parseErr != nil {
2024-04-06 16:02:30 +11:00
log.Printf("AURP: Failed to parse packet: %v", parseErr)
2024-04-13 15:36:24 +10:00
continue
2024-03-15 15:17:21 +11:00
}
2024-03-15 16:15:24 +11:00
if readErr != nil {
2024-04-06 16:02:30 +11:00
log.Printf("AURP: Failed to read packet: %v", readErr)
2024-03-30 14:30:58 +11:00
return
2024-03-15 15:17:21 +11:00
}
2024-03-22 16:14:55 +11:00
2024-04-06 10:34:54 +11:00
if apkt, ok := pkt.(*aurp.AppleTalkPacket); ok {
2024-04-12 14:26:12 +10:00
ddpkt := new(ddp.ExtPacket)
if err := ddp.ExtUnmarshal(apkt.Data, ddpkt); err != nil {
2024-04-06 10:34:54 +11:00
log.Printf("AURP: Couldn't unmarshal encapsulated DDP packet: %v", err)
continue
}
2024-04-15 09:26:23 +10:00
log.Printf("DDP/AURP: Got %d.%d.%d -> %d.%d.%d proto %d data len %d",
2024-04-06 10:34:54 +11:00
ddpkt.SrcNet, ddpkt.SrcNode, ddpkt.SrcSocket,
ddpkt.DstNet, ddpkt.DstNode, ddpkt.DstSocket,
ddpkt.Proto, len(ddpkt.Data))
2024-04-12 14:26:12 +10:00
// "Route" the packet
// Since for now there's only one local network, the routing
// decision is pretty easy
// TODO: Fix this to support other AppleTalk routers
if ddpkt.DstNet < cfg.EtherTalk.NetStart || ddpkt.DstNet > cfg.EtherTalk.NetEnd {
log.Print("DDP/AURP: dropping packet not addressed to our EtherTalk range")
continue
}
// Check and adjust the Hop Count
// Note the ddp package doesn't make this simple
hopCount := (ddpkt.Size & 0x3C00) >> 10
if hopCount >= 15 {
log.Printf("DDP/AURP: hop count exceeded (%d >= 15)", hopCount)
continue
}
hopCount++
ddpkt.Size &^= 0x3C00
ddpkt.Size |= hopCount << 10
// Is it addressed to me? Is it NBP?
if ddpkt.DstNode == 0 { // Node 0 = the router for the network
if ddpkt.DstSocket != 2 {
// Something else?? TODO
log.Printf("DDP/AURP: I don't have anything 'listening' on socket %d", ddpkt.DstSocket)
continue
}
// It's NBP
if err := handleNBPInAURP(pcapHandle, myHWAddr, ddpkt); err != nil {
log.Printf("NBP/DDP/AURP: %v", err)
}
continue
}
// Note: resolving AARP can block
dstEth, err := aarpMachine.Resolve(ctx, ddp.Addr{Network: ddpkt.DstNet, Node: ddpkt.DstNode})
if err != nil {
log.Printf("DDP/AURP: couldn't resolve DDP dest %d.%d to an Ethernet address", ddpkt.DstNet, ddpkt.DstNode)
continue
}
outFrame, err := ethertalk.AppleTalk(myHWAddr, *ddpkt)
if err != nil {
log.Printf("DDP/AURP: couldn't create output frame: %v", err)
continue
}
outFrame.Dst = dstEth
outFrameRaw, err := ethertalk.Marshal(*outFrame)
if err != nil {
log.Printf("DDP/AURP: couldn't marshal output frame: %v", err)
continue
}
if err := pcapHandle.WritePacketData(outFrameRaw); err != nil {
log.Printf("DDP/AURP: couldn't write output frame to device: %v", err)
}
2024-04-06 10:34:54 +11:00
continue
2024-03-30 16:14:18 +11:00
}
2024-04-15 09:26:23 +10:00
log.Printf("AURP: Got %T", pkt)
2024-03-22 16:14:55 +11:00
// Existing peer?
2024-03-24 18:01:24 +11:00
ra := udpAddrFromNet(raddr)
pr := peers[ra]
if pr == nil {
2024-03-22 16:14:55 +11:00
// New peer!
2024-03-24 18:01:24 +11:00
pr = &peer{
2024-03-30 20:27:24 +11:00
cfg: cfg,
2024-03-24 18:01:24 +11:00
tr: &aurp.Transport{
2024-03-24 21:10:24 +11:00
LocalDI: localDI,
2024-03-24 18:01:24 +11:00
RemoteDI: dh.SourceDI, // platinum rule
LocalConnID: nextConnID,
},
2024-04-14 13:44:35 +10:00
conn: ln,
raddr: raddr,
recv: make(chan aurp.Packet, 1024),
routingTable: routing,
2024-04-14 18:29:29 +10:00
zoneTable: zones,
2024-03-24 18:01:24 +11:00
}
2024-04-05 10:43:29 +11:00
aurp.Inc(&nextConnID)
2024-03-24 18:01:24 +11:00
peers[ra] = pr
2024-04-07 12:56:51 +10:00
goPeerHandler(pr)
2024-03-22 16:14:55 +11:00
}
2024-03-24 21:10:24 +11:00
// Pass the packet to the goroutine in charge of this peer.
2024-03-30 14:30:58 +11:00
select {
case pr.recv <- pkt:
// That's it for us.
case <-ctx.Done():
return
}
2024-03-24 21:10:24 +11:00
}
}
2024-03-24 18:01:24 +11:00
// Hashable net.UDPAddr
type udpAddr struct {
ipv4 [4]byte
port uint16
}
func udpAddrFromNet(a *net.UDPAddr) udpAddr {
return udpAddr{
ipv4: [4]byte(a.IP.To4()),
port: uint16(a.Port),
}
}
func (u udpAddr) toNet() *net.UDPAddr {
return &net.UDPAddr{
IP: u.ipv4[:],
Port: int(u.port),
}
}