jrouter/router/router.go

68 lines
2 KiB
Go
Raw Normal View History

2024-04-19 14:57:25 +10: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.
*/
package router
import (
2024-04-23 09:50:17 +10:00
"context"
2024-05-03 16:13:59 +10:00
"fmt"
2024-04-23 09:50:17 +10:00
2024-04-19 14:57:25 +10:00
"github.com/sfiera/multitalk/pkg/ddp"
)
type Router struct {
2024-05-03 16:13:59 +10:00
Config *Config
RouteTable *RouteTable
ZoneTable *ZoneTable
2024-04-23 09:50:17 +10:00
}
2024-05-03 16:13:59 +10:00
// Forward routes a packet towards the right destination.
// It increments the hop count, then looks up the best route for the network,
// then transmits the packet according to the route.
func (rtr *Router) Forward(ctx context.Context, ddpkt *ddp.ExtPacket) error {
// Check and adjust the Hop Count
// Note the ddp package doesn't make this simple
hopCount := (ddpkt.Size & 0x3C00) >> 10
if hopCount >= 15 {
return fmt.Errorf("hop count exceeded (%d >= 15)", hopCount)
2024-04-23 09:50:17 +10:00
}
2024-05-03 16:13:59 +10:00
hopCount++
ddpkt.Size &^= 0x3C00
ddpkt.Size |= hopCount << 10
2024-04-23 09:50:17 +10:00
2024-05-03 16:13:59 +10:00
switch route := rtr.RouteTable.LookupRoute(ddpkt.DstNet); {
case route == nil:
return fmt.Errorf("no route for packet (dstnet %d); dropping packet", ddpkt.DstNet)
2024-04-23 09:50:17 +10:00
2024-05-03 16:13:59 +10:00
case route.AURPPeer != nil:
// log.Printf("Forwarding packet to AURP peer %v", route.AURPPeer.RemoteAddr)
return route.AURPPeer.Forward(ddpkt)
2024-04-21 17:47:58 +10:00
2024-05-03 16:13:59 +10:00
case route.EtherTalkPeer != nil:
// log.Printf("Forwarding to EtherTalk peer %v", route.EtherTalkPeer.PeerAddr)
// Note: resolving AARP can block
return route.EtherTalkPeer.Forward(ctx, ddpkt)
case route.EtherTalkDirect != nil:
// log.Printf("Outputting to EtherTalk directly")
// Note: resolving AARP can block
return route.EtherTalkDirect.SendEtherTalkDDP(ctx, ddpkt)
default:
return fmt.Errorf("no forwarding mechanism for route! %+v", route)
2024-04-21 17:47:58 +10:00
}
}