From 4966c054b3f462f6eaf24591c4ab1a945e72bb6f Mon Sep 17 00:00:00 2001 From: sotech117 Date: Sun, 8 Oct 2023 23:05:53 -0400 Subject: fix heiarchy. rewrite routing table code --- .idea/.gitignore | 8 + .idea/iptcp-jailpt2.iml | 9 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + cmd/example/main.go | 28 +++ go.mod | 2 +- pkg/ipstack/ipstack.go | 298 +++++++++++++++++++++++++++++++ pkg/lnxconfig.go | 365 -------------------------------------- pkg/lnxconfig/lnxconfig.go | 366 +++++++++++++++++++++++++++++++++++++++ pkg/protocol.go | 299 -------------------------------- pkg/routingTable.go | 71 -------- pkg/routingtable/routingtable.go | 81 +++++++++ 12 files changed, 805 insertions(+), 736 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/iptcp-jailpt2.iml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 cmd/example/main.go create mode 100644 pkg/ipstack/ipstack.go delete mode 100644 pkg/lnxconfig.go create mode 100644 pkg/lnxconfig/lnxconfig.go delete mode 100644 pkg/protocol.go delete mode 100644 pkg/routingTable.go create mode 100644 pkg/routingtable/routingtable.go diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/iptcp-jailpt2.iml b/.idea/iptcp-jailpt2.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/iptcp-jailpt2.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..6ae4065 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/cmd/example/main.go b/cmd/example/main.go new file mode 100644 index 0000000..5b6ae61 --- /dev/null +++ b/cmd/example/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "iptcp-jailpt2/pkg/lnxconfig" + "net/netip" + "os" +) + +func main() { + if len(os.Args) != 2 { + fmt.Printf("Usage: %s \n", os.Args[0]) + os.Exit(1) + } + fileName := os.Args[1] + + // Parse the file + lnxConfig, err := lnxconfig.ParseConfig(fileName) + if err != nil { + panic(err) + } + + // Demo: print out the IP for each interface in this config + for _, iface := range lnxConfig.Interfaces { + prefixForm := netip.PrefixFrom(iface.AssignedIP, iface.AssignedPrefix.Bits()) + fmt.Printf("%s has IP %s\n", iface.Name, prefixForm.String()) + } +} diff --git a/go.mod b/go.mod index 9654e0e..b7e6cbe 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module golang-sockets +module iptcp go 1.20 diff --git a/pkg/ipstack/ipstack.go b/pkg/ipstack/ipstack.go new file mode 100644 index 0000000..770fd17 --- /dev/null +++ b/pkg/ipstack/ipstack.go @@ -0,0 +1,298 @@ +package ipstack + +import ( + "fmt" + ipv4header "github.com/brown-csci1680/iptcp-headers" + "github.com/google/netstack/tcpip/header" + "github.com/pkg/errors" + "../../pkg/lnxconfig" + "log" + "net" + "net/netip" + "os" +) + +const ( + MAX_IP_PACKET_SIZE = 1400 +) + +type Interface struct { + Name string + AssignedIP netip.Addr + AssignedPrefix netip.Prefix + + UDPAddr netip.AddrPort + State bool + neighbors map[netip.AddrPort]netip.AddrPort +} + +// type Host struct { +// Interface Interface +// Neighbors []Neighbor +// } + +// type Router struct { +// Interfaces []Interface +// Neighbors []Neighbor +// RIPNeighbors []Neighbor +// } + + +type Neighbor struct{ + DestAddr netip.Addr + UDPAddr netip.AddrPort + + InterfaceName string +} + +type RIPMessage struct { + command uint8_t; + numEntries uint8_t; + entries []RIPEntry; +} + +type RIPEntry struct { + addr netip.Addr; + cost uint16_t; + mask netip.Prefix; +} + +myInterfaces := make([]Interface); +myNeighbors := make(map[string]Neighbor) +myRIPNeighbors := make(map[string]Neighbor) +protocolHandlers := make(map[uint16]HandlerFunc) +// routingTable := make(map[Address]Routing) + +func Initialize(config IpConfig) (error) { + if len(os.Args) != 2 { + fmt.Printf("Usage: %s \n", os.Args[0]) + os.Exit(1) + } + fileName := os.Args[1] + + // Parse the file + lnxConfig, err := lnxconfig.ParseConfig(fileName) + if err != nil { + panic(err) + } + + // populate routing table??? + for _, iface := range lnxConfig.Interfaces { + myInterfaces = append(myInterfaces, Interface{iface.Name, iface.AssignedIP, iface.AssignedPrefix, iface.UDPAddr, 0}) + } + + for _, neighbor := range lnxConfig.Neighbors { + myNeighbors[neighbor.DestAddr.String()] = Neighbor{neighbor.DestAddr, neighbor.UDPAddr, neighbor.InterfaceName} + } + + // add RIP neighbors + for _, neighbor := range lnxConfig.RipNeighbors { + myRIPNeighbors[neighbor.DestAddr.String()] = Neighbor{neighbor.DestAddr, neighbor.UDPAddr, neighbor.InterfaceName} + } +} + +func ListerToInterfaces() { + for _, iface := range myInterfaces { + go RecvIp(iface) + } +} + +func RecvIp(iface Interface) (error) { + for { + buffer := make([]byte, MAX_IP_PACKET_SIZE) + _, sourceAddr, err := iface.udp.ReadFrom(buffer) + if err != nil { + log.Panicln("Error reading from UDP socket ", err) + } + + hdr, err := ipv4header.ParseHeader(buffer) + + if err != nil { + fmt.Println("Error parsing header", err) + continue + } + + headerSize := hdr.Len + headerBytes := buffer[:headerSize] + + checksumFromHeader := uint16(hdr.Checksum) + computedChecksum := ValidateChecksum(headerBytes, checksumFromHeader) + + var checksumState string + if computedChecksum == checksumFromHeader { + checksumState = "OK" + } else { + checksumState = "FAIL" + continue + } + + // check ttl + ttl := data[8] + if ttl == 0 { + fmt.Println("TTL is 0") + continue + } + + + destAddr := netip.AddrFrom(data[16:20]) + protocolNum := data[9] + + if destAddr == iface.addr { + // send to handler + protocolHandlers[protocolNum](data) + // message := buffer[headerSize:] + + // fmt.Printf("Received IP packet from %s\nHeader: %v\nChecksum: %s\nMessage: %s\n", + // sourceAddr.String(), hdr, checksumState, string(message)) + } else { + // decrement ttl and update checksum + data[8] = ttl - 1 + data[10] = 0 + data[11] = 0 + newChecksum := int(ComputeChecksum(data[:headerSize])) + data[10] = newChecksum >> 8 + data[11] = newChecksum & 0xff + + // check neighbors + for _, neighbor := range iface.neighbors { + if neighbor == destAddr { + // send to neighbor + // SendIp(destAddr, protocolNum, data) + } + } + + // check forwarding table + + } + + } +} + +func ValidateChecksum(b []byte, fromHeader uint16) uint16 { + checksum := header.Checksum(b, fromHeader) + + return checksum +} + +func SendIp(dst netip.Addr, port uint16, protocolNum uint16, data []byte, iface Interface) (error) { + bindLocalAddr, err := net.ResolveUDPAddr("udp4", iface.UDPAddr.String()) + if err != nil { + log.Panicln("Error resolving address: ", err) + } + + addrString := fmt.Sprintf("%s:%s", dst, port) + remoteAddr, err := net.ResolveUDPAddr("udp4", addrString) + if err != nil { + log.Panicln("Error resolving address: ", err) + } + + fmt.Printf("Sending to %s:%d\n", + remoteAddr.IP.String(), remoteAddr.Port) + + // Bind on the local UDP port: this sets the source port + // and creates a conn + conn, err := net.ListenUDP("udp4", bindLocalAddr) + if err != nil { + log.Panicln("Dial: ", err) + } + + // Start filling in the header + message := data[20:] + hdr := ipv4header.IPv4Header{ + Version: data[0] >> 4, + Len: 20, // Header length is always 20 when no IP options + TOS: data[1], + TotalLen: ipv4header.HeaderLen + len(message), + ID: data[4], + Flags: data[6] >> 5, + FragOff: data[6] & 0x1f, + TTL: data[8], + Protocol: data[9], + Checksum: 0, // Should be 0 until checksum is computed + Src: netip.MustParseAddr(iface.addr.String()), + Dst: netip.MustParseAddr(dst.String()), + Options: []byte{}, + } + + // Assemble the header into a byte array + headerBytes, err := hdr.Marshal() + if err != nil { + log.Fatalln("Error marshalling header: ", err) + } + + // Compute the checksum (see below) + // Cast back to an int, which is what the Header structure expects + hdr.Checksum = int(ComputeChecksum(headerBytes)) + + headerBytes, err = hdr.Marshal() + if err != nil { + log.Fatalln("Error marshalling header: ", err) + } + + bytesToSend := make([]byte, 0, len(headerBytes)+len(message)) + bytesToSend = append(bytesToSend, headerBytes...) + bytesToSend = append(bytesToSend, []byte(message)...) + + // Send the message to the "link-layer" addr:port on UDP + bytesWritten, err := conn.WriteToUDP(bytesToSend, remoteAddr) + if err != nil { + log.Panicln("Error writing to socket: ", err) + } + fmt.Printf("Sent %d bytes\n", bytesWritten) +} + +func ComputeChecksum(b []byte) uint16 { + checksum := header.Checksum(b, 0) + checksumInv := checksum ^ 0xffff + + return checksumInv +} + +func ForwardIP(data []byte) (error) { +} + +type HandlerFunc = func help(*Packet, []interface{}) (error) { + + // do smth with packet +} + +func AddRecvHandler(protocolNum uint8, callbackFunc HandlerFunc) (error) { + if protocolHandlers[protocolNum] != nil { + fmt.Printf("Warning: Handler for protocol %d already exists", protocolNum) + } + protocolHandlers[protocolNum] = callbackFunc + return nil +} + +func RemoveRecvHandler(protocolNum uint8) (error) { + // consider error + if protocolHandlers[protocolNum] == nil { + return errors.Errorf("No handler for protocol %d", protocolNum) + } + delete(protocolHandlers, protocolNum) + return nil +} + +// func routeRip(data []byte) (error) { +// // deconstruct packet +// newRIPMessage := RIPMessage{} +// newRIPMessage.command = data[0] +// newRIPMessage.numEntries = data[1] +// newRIPMessage.entries = make([]RIPEntry, newRIPMessage.numEntries) +// } + +func PrintNeighbors() { + for _, iface := range myNeighbors { + fmt.Printf("%s\n", iface.addr.String()) + } +} + +func PrintInterfaces() { + for _, iface := range myInterfaces { + fmt.Printf("%s\n", iface.addr.String()) + } +} +func GetNeighbors() ([]netip.Addr) { + return myNeighbors +} + diff --git a/pkg/lnxconfig.go b/pkg/lnxconfig.go deleted file mode 100644 index 36b1b56..0000000 --- a/pkg/lnxconfig.go +++ /dev/null @@ -1,365 +0,0 @@ -package lnxconfig - -import ( - "bufio" - "fmt" - "net/netip" - "os" - "strings" -) - -type RoutingMode int - -const ( - RoutingTypeNone RoutingMode = 0 - RoutingTypeStatic RoutingMode = 1 - RoutingTypeRIP RoutingMode = 2 -) - -/* - * NOTE: These data structures only represent structure of a - * configuration file. In your implementation, you will still need to - * build your own data structures that store relevant information - * about your links, interfaces, etc. at runtime. - * - * These structs only represent the things in the config file--you - * will probably only parse these at startup in order to set up your own - * data structures. - * - */ -type IPConfig struct { - Interfaces []InterfaceConfig - Neighbors []NeighborConfig - - OriginatingPrefixes []netip.Prefix // Unused in F23, ignore. - - RoutingMode RoutingMode - - // ROUTERS ONLY: Neighbors to send RIP packets - RipNeighbors []netip.Addr - - // Manually-added routes ("route" directive, usually just for default on hosts) - StaticRoutes map[netip.Prefix]netip.Addr -} - -type InterfaceConfig struct { - Name string - AssignedIP netip.Addr - AssignedPrefix netip.Prefix - - UDPAddr netip.AddrPort -} - -type NeighborConfig struct { - DestAddr netip.Addr - UDPAddr netip.AddrPort - - InterfaceName string -} - -// Static config for testing -var LnxConfig = IPConfig{ - Interfaces: []InterfaceConfig{ - { - Name: "if0", - AssignedIP: netip.MustParseAddr("10.1.0.1"), - AssignedPrefix: netip.MustParsePrefix("10.1.0.1/24"), - UDPAddr: netip.MustParseAddrPort("127.0.0.1:5000"), - }, - { - Name: "if1", - AssignedIP: netip.MustParseAddr("10.10.1.1"), - AssignedPrefix: netip.MustParsePrefix("10.10.1.1/24"), - UDPAddr: netip.MustParseAddrPort("127.0.0.1:5001"), - }, - }, - - Neighbors: []NeighborConfig{ - { - DestAddr: netip.MustParseAddr("10.1.0.10"), - UDPAddr: netip.MustParseAddrPort("127.0.0.1:6001"), - InterfaceName: "if0", - }, - { - DestAddr: netip.MustParseAddr("10.10.1.2"), - UDPAddr: netip.MustParseAddrPort("127.0.0.1:5100"), - InterfaceName: "if1", - }, - }, - - OriginatingPrefixes: []netip.Prefix{ - netip.MustParsePrefix("10.1.0.1/24"), - }, - - RoutingMode: RoutingTypeStatic, - - RipNeighbors: []netip.Addr{ - netip.MustParseAddr("10.10.1.2"), - }, -} - -// ******************** END PUBLIC INTERFACE ********************************************* -// (You shouldn't need to worry about what's below, unless you want to modify the parser.) - -type ParseFunc func(int, string, *IPConfig) error - -var parseCommands = map[string]ParseFunc{ - "interface": parseInterface, - "neighbor": parseNeighbor, - "routing": parseRouting, - "route": parseRoute, - "rip": parseRip, -} - -func parseRip(ln int, line string, config *IPConfig) error { - tokens := strings.Split(line, " ") - - if len(tokens) < 2 { - return newErrString(ln, "Usage: rip [cmd] ...") - } - cmd := tokens[1] - ripTokens := tokens[2:] - - switch cmd { - case "originate": - if len(ripTokens) < 2 && ripTokens[0] != "prefix" { - return newErrString(ln, "Usage: rip originate prefix ") - } - ripPrefix, err := netip.ParsePrefix(ripTokens[1]) - if err != nil { - return newErr(ln, err) - } - ripPrefix = ripPrefix.Masked() - - // Check if prefix is in config - err = addOriginatingPrefix(config, ripPrefix) - if err != nil { - return err - } - case "advertise-to": - if len(ripTokens) < 1 { - return newErrString(ln, "Usage: rip advertise-to ") - } - addr, err := netip.ParseAddr(ripTokens[0]) - if err != nil { - return newErr(ln, err) - } - err = addRipNeighbor(config, addr) - if err != nil { - return err - } - default: - return newErrString(ln, "Unrecognized RIP command %s", cmd) - } - - return nil -} - -func addOriginatingPrefix(config *IPConfig, prefix netip.Prefix) error { - for _, iface := range config.Interfaces { - if iface.AssignedPrefix == prefix { - config.OriginatingPrefixes = append(config.OriginatingPrefixes, prefix) - return nil - } - } - - return errors.Errorf("No matching prefix %s in config", prefix.String()) -} - -func addRipNeighbor(config *IPConfig, neighbor netip.Addr) error { - for _, iface := range config.Neighbors { - if iface.DestAddr == neighbor { - config.RipNeighbors = append(config.RipNeighbors, neighbor) - return nil - } - } - - return errors.Errorf("RIP neighbor %s is not a neighbor IP", neighbor.String()) -} - -func parseRouting(ln int, line string, config *IPConfig) error { - tokens := strings.Split(line, " ") - - if len(tokens) < 2 { - return newErrString(ln, "routing directive must have format: routing ") - } - rt := tokens[1] - - switch rt { - case "static": - config.RoutingMode = RoutingTypeStatic - case "rip": - config.RoutingMode = RoutingTypeRIP - default: - return newErrString(ln, "Invalid routing type: %s", rt) - } - - return nil -} - -func parseRoute(ln int, line string, config *IPConfig) error { - var sPrefix, sAddr string - - format := "route via " - r := strings.NewReader(line) - n, err := fmt.Fscanf(r, "route %s via %s", &sPrefix, &sAddr) - - if err != nil { - return err - } - - if n != 2 { - return newErrString(ln, "route directive must have format %s", format) - } - - prefix, err := netip.ParsePrefix(sPrefix) - if err != nil { - return err - } - - addr, err := netip.ParseAddr(sAddr) - if err != nil { - return err - } - - config.StaticRoutes[prefix] = addr - return nil -} - -func parseInterface(ln int, line string, config *IPConfig) error { - var sName, sPrefix, sBindAddr string - - format := "interface " - - r := strings.NewReader(line) - n, err := fmt.Fscanf(r, "interface %s %s %s", - &sName, &sPrefix, &sBindAddr) - - if err != nil { - return err - } - - if n != 3 { - return newErrString(ln, "interface directive must have format: %s", format) - } - - // Check prefix format first - prefix, err := netip.ParsePrefix(sPrefix) - if err != nil { - return err - } - - addr := prefix.Addr() // Get addr part - prefix = prefix.Masked() // Clear add bits for prefix - - addrPort, err := netip.ParseAddrPort(sBindAddr) - if err != nil { - return err - } - - iface := InterfaceConfig{ - Name: sName, - AssignedIP: addr, - AssignedPrefix: prefix, - UDPAddr: addrPort, - } - - config.Interfaces = append(config.Interfaces, iface) - return nil -} - -func parseNeighbor(ln int, line string, config *IPConfig) error { - var sDestAddr, sUDPAddr, sIfName string - - format := "neighbor at via " - - r := strings.NewReader(line) - n, err := fmt.Fscanf(r, "neighbor %s at %s via %s", - &sDestAddr, &sUDPAddr, &sIfName) - - if err != nil { - return err - } - - if n != 3 { - newErrString(ln, "neighbor directive must have format: %s", format) - } - - destAddr, err := netip.ParseAddr(sDestAddr) - if err != nil { - return err - } - - udpAddr, err := netip.ParseAddrPort(sUDPAddr) - if err != nil { - return err - } - - neighbor := NeighborConfig{ - DestAddr: destAddr, - UDPAddr: udpAddr, - InterfaceName: sIfName, - } - - config.Neighbors = append(config.Neighbors, neighbor) - - return nil -} - -func newErrString(line int, msg string, args ...any) error { - _msg := fmt.Sprintf(msg, args...) - return errors.New(fmt.Sprintf("Parse error on line %d: %s", line, _msg)) -} - -func newErr(line int, err error) error { - return errors.New(fmt.Sprintf("Parse error on line %d: %s", line, err.Error())) - -} - -// Parse a configuration file -func ParseConfig(configFile string) (*IPConfig, error) { - fd, err := os.Open(configFile) - if err != nil { - return nil, errors.New("Unable to open file") - } - defer fd.Close() - - config := &IPConfig{ - Interfaces: make([]InterfaceConfig, 0, 1), - Neighbors: make([]NeighborConfig, 0, 1), - OriginatingPrefixes: make([]netip.Prefix, 0, 1), - - RipNeighbors: make([]netip.Addr, 0), - StaticRoutes: make(map[netip.Prefix]netip.Addr, 0), - } - - scanner := bufio.NewScanner(fd) - ln := 0 - for scanner.Scan() { - ln++ - - line := scanner.Text() - tokens := strings.Split(line, " ") - - if len(tokens) == 0 { - continue - } - - // Skip comments - head := tokens[0] - if len(head) == 0 || head == "#" || head[0] == '#' { - continue - } - - pf, found := parseCommands[head] - if !found { - return nil, newErrString(ln, "Unrecognized token %s", head) - } - err = pf(ln, line, config) - if err != nil { - return nil, newErr(ln, err) - } - } - - return config, nil -} \ No newline at end of file diff --git a/pkg/lnxconfig/lnxconfig.go b/pkg/lnxconfig/lnxconfig.go new file mode 100644 index 0000000..d0699f9 --- /dev/null +++ b/pkg/lnxconfig/lnxconfig.go @@ -0,0 +1,366 @@ +package lnxconfig + +import ( + "bufio" + "fmt" + "github.com/pkg/errors" + "net/netip" + "os" + "strings" +) + +type RoutingMode int + +const ( + RoutingTypeNone RoutingMode = 0 + RoutingTypeStatic RoutingMode = 1 + RoutingTypeRIP RoutingMode = 2 +) + +/* + * NOTE: These data structures only represent structure of a + * configuration file. In your implementation, you will still need to + * build your own data structures that store relevant information + * about your links, interfaces, etc. at runtime. + * + * These structs only represent the things in the config file--you + * will probably only parse these at startup in order to set up your own + * data structures. + * + */ +type IPConfig struct { + Interfaces []InterfaceConfig + Neighbors []NeighborConfig + + OriginatingPrefixes []netip.Prefix // Unused in F23, ignore. + + RoutingMode RoutingMode + + // ROUTERS ONLY: Neighbors to send RIP packets + RipNeighbors []netip.Addr + + // Manually-added routes ("route" directive, usually just for default on hosts) + StaticRoutes map[netip.Prefix]netip.Addr +} + +type InterfaceConfig struct { + Name string + AssignedIP netip.Addr + AssignedPrefix netip.Prefix + + UDPAddr netip.AddrPort +} + +type NeighborConfig struct { + DestAddr netip.Addr + UDPAddr netip.AddrPort + + InterfaceName string +} + +// Static config for testing +var LnxConfig = IPConfig{ + Interfaces: []InterfaceConfig{ + { + Name: "if0", + AssignedIP: netip.MustParseAddr("10.1.0.1"), + AssignedPrefix: netip.MustParsePrefix("10.1.0.1/24"), + UDPAddr: netip.MustParseAddrPort("127.0.0.1:5000"), + }, + { + Name: "if1", + AssignedIP: netip.MustParseAddr("10.10.1.1"), + AssignedPrefix: netip.MustParsePrefix("10.10.1.1/24"), + UDPAddr: netip.MustParseAddrPort("127.0.0.1:5001"), + }, + }, + + Neighbors: []NeighborConfig{ + { + DestAddr: netip.MustParseAddr("10.1.0.10"), + UDPAddr: netip.MustParseAddrPort("127.0.0.1:6001"), + InterfaceName: "if0", + }, + { + DestAddr: netip.MustParseAddr("10.10.1.2"), + UDPAddr: netip.MustParseAddrPort("127.0.0.1:5100"), + InterfaceName: "if1", + }, + }, + + OriginatingPrefixes: []netip.Prefix{ + netip.MustParsePrefix("10.1.0.1/24"), + }, + + RoutingMode: RoutingTypeStatic, + + RipNeighbors: []netip.Addr{ + netip.MustParseAddr("10.10.1.2"), + }, +} + +// ******************** END PUBLIC INTERFACE ********************************************* +// (You shouldn't need to worry about what's below, unless you want to modify the parser.) + +type ParseFunc func(int, string, *IPConfig) error + +var parseCommands = map[string]ParseFunc{ + "interface": parseInterface, + "neighbor": parseNeighbor, + "routing": parseRouting, + "route": parseRoute, + "rip": parseRip, +} + +func parseRip(ln int, line string, config *IPConfig) error { + tokens := strings.Split(line, " ") + + if len(tokens) < 2 { + return newErrString(ln, "Usage: rip [cmd] ...") + } + cmd := tokens[1] + ripTokens := tokens[2:] + + switch cmd { + case "originate": + if len(ripTokens) < 2 && ripTokens[0] != "prefix" { + return newErrString(ln, "Usage: rip originate prefix ") + } + ripPrefix, err := netip.ParsePrefix(ripTokens[1]) + if err != nil { + return newErr(ln, err) + } + ripPrefix = ripPrefix.Masked() + + // Check if prefix is in config + err = addOriginatingPrefix(config, ripPrefix) + if err != nil { + return err + } + case "advertise-to": + if len(ripTokens) < 1 { + return newErrString(ln, "Usage: rip advertise-to ") + } + addr, err := netip.ParseAddr(ripTokens[0]) + if err != nil { + return newErr(ln, err) + } + err = addRipNeighbor(config, addr) + if err != nil { + return err + } + default: + return newErrString(ln, "Unrecognized RIP command %s", cmd) + } + + return nil +} + +func addOriginatingPrefix(config *IPConfig, prefix netip.Prefix) error { + for _, iface := range config.Interfaces { + if iface.AssignedPrefix == prefix { + config.OriginatingPrefixes = append(config.OriginatingPrefixes, prefix) + return nil + } + } + + return errors.Errorf("No matching prefix %s in config", prefix.String()) +} + +func addRipNeighbor(config *IPConfig, neighbor netip.Addr) error { + for _, iface := range config.Neighbors { + if iface.DestAddr == neighbor { + config.RipNeighbors = append(config.RipNeighbors, neighbor) + return nil + } + } + + return errors.Errorf("RIP neighbor %s is not a neighbor IP", neighbor.String()) +} + +func parseRouting(ln int, line string, config *IPConfig) error { + tokens := strings.Split(line, " ") + + if len(tokens) < 2 { + return newErrString(ln, "routing directive must have format: routing ") + } + rt := tokens[1] + + switch rt { + case "static": + config.RoutingMode = RoutingTypeStatic + case "rip": + config.RoutingMode = RoutingTypeRIP + default: + return newErrString(ln, "Invalid routing type: %s", rt) + } + + return nil +} + +func parseRoute(ln int, line string, config *IPConfig) error { + var sPrefix, sAddr string + + format := "route via " + r := strings.NewReader(line) + n, err := fmt.Fscanf(r, "route %s via %s", &sPrefix, &sAddr) + + if err != nil { + return err + } + + if n != 2 { + return newErrString(ln, "route directive must have format %s", format) + } + + prefix, err := netip.ParsePrefix(sPrefix) + if err != nil { + return err + } + + addr, err := netip.ParseAddr(sAddr) + if err != nil { + return err + } + + config.StaticRoutes[prefix] = addr + return nil +} + +func parseInterface(ln int, line string, config *IPConfig) error { + var sName, sPrefix, sBindAddr string + + format := "interface " + + r := strings.NewReader(line) + n, err := fmt.Fscanf(r, "interface %s %s %s", + &sName, &sPrefix, &sBindAddr) + + if err != nil { + return err + } + + if n != 3 { + return newErrString(ln, "interface directive must have format: %s", format) + } + + // Check prefix format first + prefix, err := netip.ParsePrefix(sPrefix) + if err != nil { + return err + } + + addr := prefix.Addr() // Get addr part + prefix = prefix.Masked() // Clear add bits for prefix + + addrPort, err := netip.ParseAddrPort(sBindAddr) + if err != nil { + return err + } + + iface := InterfaceConfig{ + Name: sName, + AssignedIP: addr, + AssignedPrefix: prefix, + UDPAddr: addrPort, + } + + config.Interfaces = append(config.Interfaces, iface) + return nil +} + +func parseNeighbor(ln int, line string, config *IPConfig) error { + var sDestAddr, sUDPAddr, sIfName string + + format := "neighbor at via " + + r := strings.NewReader(line) + n, err := fmt.Fscanf(r, "neighbor %s at %s via %s", + &sDestAddr, &sUDPAddr, &sIfName) + + if err != nil { + return err + } + + if n != 3 { + newErrString(ln, "neighbor directive must have format: %s", format) + } + + destAddr, err := netip.ParseAddr(sDestAddr) + if err != nil { + return err + } + + udpAddr, err := netip.ParseAddrPort(sUDPAddr) + if err != nil { + return err + } + + neighbor := NeighborConfig{ + DestAddr: destAddr, + UDPAddr: udpAddr, + InterfaceName: sIfName, + } + + config.Neighbors = append(config.Neighbors, neighbor) + + return nil +} + +func newErrString(line int, msg string, args ...any) error { + _msg := fmt.Sprintf(msg, args...) + return errors.New(fmt.Sprintf("Parse error on line %d: %s", line, _msg)) +} + +func newErr(line int, err error) error { + return errors.New(fmt.Sprintf("Parse error on line %d: %s", line, err.Error())) + +} + +// Parse a configuration file +func ParseConfig(configFile string) (*IPConfig, error) { + fd, err := os.Open(configFile) + if err != nil { + return nil, errors.New("Unable to open file") + } + defer fd.Close() + + config := &IPConfig{ + Interfaces: make([]InterfaceConfig, 0, 1), + Neighbors: make([]NeighborConfig, 0, 1), + OriginatingPrefixes: make([]netip.Prefix, 0, 1), + + RipNeighbors: make([]netip.Addr, 0), + StaticRoutes: make(map[netip.Prefix]netip.Addr, 0), + } + + scanner := bufio.NewScanner(fd) + ln := 0 + for scanner.Scan() { + ln++ + + line := scanner.Text() + tokens := strings.Split(line, " ") + + if len(tokens) == 0 { + continue + } + + // Skip comments + head := tokens[0] + if len(head) == 0 || head == "#" || head[0] == '#' { + continue + } + + pf, found := parseCommands[head] + if !found { + return nil, newErrString(ln, "Unrecognized token %s", head) + } + err = pf(ln, line, config) + if err != nil { + return nil, newErr(ln, err) + } + } + + return config, nil +} diff --git a/pkg/protocol.go b/pkg/protocol.go deleted file mode 100644 index 9358099..0000000 --- a/pkg/protocol.go +++ /dev/null @@ -1,299 +0,0 @@ -package protocol - -import ( - "net" - "net/netip" - "fmt" - "os" - "bufio" - "time" - "github.com/pkg/errors" - ipv4header "github.com/brown-csci1680/iptcp-headers" - "github.com/google/netstack/tcpip/header" - "github.com/brown-csci1680/ipstack-utils" -) - -const ( - MAX_IP_PACKET_SIZE = 1400 -) - -type Interface struct { - Name string - AssignedIP netip.Addr - AssignedPrefix netip.Prefix - - UDPAddr netip.AddrPort - State uint8_t - neighbors map[netip.AddrPort]netip.AddrPort -} - -// type Host struct { -// Interface Interface -// Neighbors []Neighbor -// } - -// type Router struct { -// Interfaces []Interface -// Neighbors []Neighbor -// RIPNeighbors []Neighbor -// } - - -type Neighbor struct{ - DestAddr netip.Addr - UDPAddr netip.AddrPort - - InterfaceName string -} - -type RIPMessage struct { - command uint8_t; - numEntries uint8_t; - entries []RIPEntry; -} - -type RIPEntry struct { - addr netip.Addr; - cost uint16_t; - mask netip.Prefix; -} - -myInterfaces := make([]Interface); -myNeighbors := make(map[string]Neighbor) -myRIPNeighbors := make(map[string]Neighbor) -protocolHandlers := make(map[uint16]HandlerFunc) -// routingTable := make(map[Address]Routing) - -func Initialize(config IpConfig) (error) { - if len(os.Args) != 2 { - fmt.Printf("Usage: %s \n", os.Args[0]) - os.Exit(1) - } - fileName := os.Args[1] - - // Parse the file - lnxConfig, err := lnxconfig.ParseConfig(fileName) - if err != nil { - panic(err) - } - - // populate routing table??? - for _, iface := range lnxConfig.Interfaces { - myInterfaces = append(myInterfaces, Interface{iface.Name, iface.AssignedIP, iface.AssignedPrefix, iface.UDPAddr, 0}) - } - - for _, neighbor := range lnxConfig.Neighbors { - myNeighbors[neighbor.DestAddr.String()] = Neighbor{neighbor.DestAddr, neighbor.UDPAddr, neighbor.InterfaceName} - } - - // add RIP neighbors - for _, neighbor := range lnxConfig.RipNeighbors { - myRIPNeighbors[neighbor.DestAddr.String()] = Neighbor{neighbor.DestAddr, neighbor.UDPAddr, neighbor.InterfaceName} - } -} - -func ListerToInterfaces() { - for _, iface := range myInterfaces { - go RecvIp(iface) - } -} - -func RecvIp(iface Interface) (error) { - for { - buffer := make([]byte, MAX_IP_PACKET_SIZE) - _, sourceAddr, err := iface.udp.ReadFrom(buffer) - if err != nil { - log.Panicln("Error reading from UDP socket ", err) - } - - hdr, err := ipv4header.ParseHeader(buffer) - - if err != nil { - fmt.Println("Error parsing header", err) - continue - } - - headerSize := hdr.Len - headerBytes := buffer[:headerSize] - - checksumFromHeader := uint16(hdr.Checksum) - computedChecksum := ValidateChecksum(headerBytes, checksumFromHeader) - - var checksumState string - if computedChecksum == checksumFromHeader { - checksumState = "OK" - } else { - checksumState = "FAIL" - continue - } - - // check ttl - ttl := data[8] - if ttl == 0 { - fmt.Println("TTL is 0") - continue - } - - - destAddr := netip.AddrFrom(data[16:20]) - protocolNum := data[9] - - if destAddr == iface.addr { - // send to handler - protocolHandlers[protocolNum](data) - // message := buffer[headerSize:] - - // fmt.Printf("Received IP packet from %s\nHeader: %v\nChecksum: %s\nMessage: %s\n", - // sourceAddr.String(), hdr, checksumState, string(message)) - } else { - // decrement ttl and update checksum - data[8] = ttl - 1 - data[10] = 0 - data[11] = 0 - newChecksum := int(ComputeChecksum(data[:headerSize])) - data[10] = newChecksum >> 8 - data[11] = newChecksum & 0xff - - // check neighbors - for _, neighbor := range iface.neighbors { - if neighbor == destAddr { - // send to neighbor - // SendIp(destAddr, protocolNum, data) - } - } - - // check forwarding table - - } - - } -} - -func ValidateChecksum(b []byte, fromHeader uint16) uint16 { - checksum := header.Checksum(b, fromHeader) - - return checksum -} - -func SendIp(dst netip.Addr, port uint16, protocolNum uint16, data []byte, iface Interface) (error) { - bindLocalAddr, err := net.ResolveUDPAddr("udp4", iface.UDPAddr.String()) - if err != nil { - log.Panicln("Error resolving address: ", err) - } - - addrString := fmt.Sprintf("%s:%s", dst, port) - remoteAddr, err := net.ResolveUDPAddr("udp4", addrString) - if err != nil { - log.Panicln("Error resolving address: ", err) - } - - fmt.Printf("Sending to %s:%d\n", - remoteAddr.IP.String(), remoteAddr.Port) - - // Bind on the local UDP port: this sets the source port - // and creates a conn - conn, err := net.ListenUDP("udp4", bindLocalAddr) - if err != nil { - log.Panicln("Dial: ", err) - } - - // Start filling in the header - message := data[20:] - hdr := ipv4header.IPv4Header{ - Version: data[0] >> 4, - Len: 20, // Header length is always 20 when no IP options - TOS: data[1], - TotalLen: ipv4header.HeaderLen + len(message), - ID: data[4], - Flags: data[6] >> 5, - FragOff: data[6] & 0x1f, - TTL: data[8], - Protocol: data[9], - Checksum: 0, // Should be 0 until checksum is computed - Src: netip.MustParseAddr(iface.addr.String()), - Dst: netip.MustParseAddr(dst.String()), - Options: []byte{}, - } - - // Assemble the header into a byte array - headerBytes, err := hdr.Marshal() - if err != nil { - log.Fatalln("Error marshalling header: ", err) - } - - // Compute the checksum (see below) - // Cast back to an int, which is what the Header structure expects - hdr.Checksum = int(ComputeChecksum(headerBytes)) - - headerBytes, err = hdr.Marshal() - if err != nil { - log.Fatalln("Error marshalling header: ", err) - } - - bytesToSend := make([]byte, 0, len(headerBytes)+len(message)) - bytesToSend = append(bytesToSend, headerBytes...) - bytesToSend = append(bytesToSend, []byte(message)...) - - // Send the message to the "link-layer" addr:port on UDP - bytesWritten, err := conn.WriteToUDP(bytesToSend, remoteAddr) - if err != nil { - log.Panicln("Error writing to socket: ", err) - } - fmt.Printf("Sent %d bytes\n", bytesWritten) -} - -func ComputeChecksum(b []byte) uint16 { - checksum := header.Checksum(b, 0) - checksumInv := checksum ^ 0xffff - - return checksumInv -} - -func ForwardIP(data []byte) (error) { -} - -type HandlerFunc = func help(*Packet, []interface{}) (error) { - - // do smth with packet -} - -func AddRecvHandler(protocolNum uint8, callbackFunc HandlerFunc) (error) { - if protocolHandlers[protocolNum] != nil { - fmt.Printf("Warning: Handler for protocol %d already exists", protocolNum) - } - protocolHandlers[protocolNum] = callbackFunc - return nil -} - -func RemoveRecvHandler(protocolNum uint8) (error) { - // consider error - if protocolHandlers[protocolNum] == nil { - return errors.Errorf("No handler for protocol %d", protocolNum) - } - delete(protocolHandlers, protocolNum) - return nil -} - -// func routeRip(data []byte) (error) { -// // deconstruct packet -// newRIPMessage := RIPMessage{} -// newRIPMessage.command = data[0] -// newRIPMessage.numEntries = data[1] -// newRIPMessage.entries = make([]RIPEntry, newRIPMessage.numEntries) -// } - -func PrintNeighbors() { - for _, iface := range myNeighbors { - fmt.Printf("%s\n", iface.addr.String()) - } -} - -func PrintInterfaces() { - for _, iface := range myInterfaces { - fmt.Printf("%s\n", iface.addr.String()) - } -} -func GetNeighbors() ([]netip.Addr) { - return myNeighbors -} - diff --git a/pkg/routingTable.go b/pkg/routingTable.go deleted file mode 100644 index bda4524..0000000 --- a/pkg/routingTable.go +++ /dev/null @@ -1,71 +0,0 @@ -package routingTable - -import ( - "fmt" - "net" - "net/netip" - "os" - "bufio" -) - -type Address struct { - addr netip.Addr; - prefix netip.Prefix; -} - -type Routing struct { - dest Address; - cost uint16_t; - mask netip.Prefix; -} - -routingTable := make(map[Address]Routing) - -func Initialize(config IpConfig) (error) { - if len(os.Args) != 2 { - fmt.Printf("Usage: %s \n", os.Args[0]) - os.Exit(1) - } - fileName := os.Args[1] - - lnxConfig, err := lnxconfig.ParseConfig(fileName) - if err != nil { - panic(err) - } - - // populate routing table - for _, iface := range lnxConfig.Interfaces { - routingTable[Address{iface.AssignedIP, iface.AssignedPrefix}] = Routing{Address{iface.AssignedIP, iface.AssignedPrefix}, 0, iface.AssignedPrefix} - } - -} - -func AddRoute(dest Address, cost uint16_t, mask netip.Prefix) (error) { - if _, ok := routingTable[dest]; ok { - return newErrString(ln, "Route already exists") - } - routingTable[dest] = Routing{dest, cost, mask} -} - -func RemoveRoute(dest Address) (error) { - if _, ok := routingTable[dest]; !ok { - return newErrString(ln, "Route does not exist") - } - delete(routingTable, dest) -} - -func GetRoute(dest Address) (Routing, error) { - // get the most specific route - for key, value := range routingTable { - if key.prefix.Contains(dest.addr) { - return value, nil - } - } - return nil, newErrString(ln, "Route does not exist") -} - -func PrintRoutingTable() { - for key, value := range routingTable { - fmt.Printf("%s/%d\t%d\n", key.addr, key.prefix.Bits(), value.cost) - } -} \ No newline at end of file diff --git a/pkg/routingtable/routingtable.go b/pkg/routingtable/routingtable.go new file mode 100644 index 0000000..7f7e2b2 --- /dev/null +++ b/pkg/routingtable/routingtable.go @@ -0,0 +1,81 @@ +package routingtable + +import ( + "fmt" + "github.com/pkg/errors" + "net/netip" +) + +type Address struct { + addr netip.Addr + prefix netip.Prefix +} + +type Route struct { + dest Address + cost uint32 + mask netip.Prefix +} + +var table map[Address]Route + +//func Initialize(config lnxconfig.IPConfig) error { +// if len(os.Args) != 2 { +// fmt.Printf("Usage: %s \n", os.Args[0]) +// os.Exit(1) +// } +// fileName := os.Args[1] +// +// lnxConfig, err := lnxconfig.ParseConfig(fileName) +// if err != nil { +// panic(err) +// } +// +// // make and populate routing table +// table = make(map[Address]Route) +// for _, iface := range lnxConfig.Interfaces { +// var address = Address{iface.AssignedIP, iface.AssignedPrefix} +// var route = Route{Address{iface.AssignedIP, iface.AssignedPrefix}, 0, iface.AssignedPrefix} +// table[address] = route +// } +// +// +//} + +func AddRoute(dest Address, cost uint32, mask netip.Prefix) error { + if _, ok := table[dest]; ok { + return errors.New("Route already exists") + } + + table[dest] = Route{dest, cost, mask} + return nil +} + +func RemoveRoute(dest Address) error { + if _, ok := table[dest]; !ok { + return errors.New("Route doesn't exist") + } + + delete(table, dest) + return nil +} + +// TODO: implement this with most specific prefix matching +func GetRoute(dest Address) (Route, error) { + // get the most specific route + for key, value := range table { + if key.prefix.Contains(dest.addr) { + return value, nil + } + } + return Route{}, errors.New("Route doesn't exist") +} + +func SprintRoutingTable() string { + message := "" + for address, route := range table { + message += fmt.Sprintf("%s/%d\t%d\n", address.addr, address.prefix, route.cost) + } + + return message +} -- cgit v1.2.3-70-g09d2