aboutsummaryrefslogtreecommitdiff
path: root/pkg/ipstack/ipstack.go
blob: fb1816182112ad6bc763cc0b5d316ede9e9b2bf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package ipstack

import (
	"fmt"
	"github.com/pkg/errors"
	"iptcp/pkg/lnxconfig"
	"net"
	"net/netip"
	"time"
)

const (
	MAX_IP_PACKET_SIZE        = 1400
	LOCAL_COST         uint32 = 0
	STATIC_COST        uint32 = 4294967295 // 2^32 - 1
)

// STRUCTS ---------------------------------------------------------------------
type Interface struct {
	Name     string
	IpPrefix netip.Prefix

	RecvSocket    net.Conn
	SocketChannel chan bool
	State         bool
}

type Neighbor struct {
	VipAddr netip.Addr
	UdpAddr netip.AddrPort

	SendSocket    net.Conn
	SocketChannel chan bool
}

type RIPMessage struct {
	command    uint8
	numEntries uint8
	entries    []RIPEntry
}

type RIPEntry struct {
	addr netip.Addr
	cost uint32
	mask netip.Prefix
}

type Hop struct {
	Cost     uint32
	VipAsStr string
}

// GLOBAL VARIABLES (data structures) ------------------------------------------
var myInterfaces []*Interface
var myNeighbors = make(map[string][]*Neighbor)

// var myRIPNeighbors = make(map[string]Neighbor)
type HandlerFunc func(int, string, *[]byte) error

var protocolHandlers = make(map[uint16]HandlerFunc)

// var routingTable = routingtable.New()
var routingTable = make(map[netip.Prefix]Hop)

// reference: https://github.com/brown-csci1680/lecture-examples/blob/main/ip-demo/cmd/udp-ip-recv/main.go
func createUDPConn(UdpAddr netip.AddrPort, conn *net.Conn) error {
	listenString := UdpAddr.String()
	listenAddr, err := net.ResolveUDPAddr("udp4", listenString)
	if err != nil {
		return errors.WithMessage(err, "Error resolving address->\t"+listenString)
	}
	tmpConn, err := net.ListenUDP("udp4", listenAddr)
	if err != nil {
		return errors.WithMessage(err, "Could not bind to UDP port->\t"+listenString)
	}
	*conn = tmpConn

	return nil
}

func Initialize(lnxFilePath string) error {
	//if len(os.Args) != 2 {
	//	fmt.Printf("Usage:  %s <configFile>\n", os.Args[0])
	//	os.Exit(1)
	//}
	//lnxFilePath := os.Args[1]

	// Parse the file
	lnxConfig, err := lnxconfig.ParseConfig(lnxFilePath)
	if err != nil {
		return errors.WithMessage(err, "Error parsing config file->\t"+lnxFilePath)
	}

	// 1) initialize the interfaces on this node here and into the routing table
	static := false
	for _, iface := range lnxConfig.Interfaces {
		prefix := netip.PrefixFrom(iface.AssignedIP, iface.AssignedPrefix.Bits())
		i := &Interface{
			Name:          iface.Name,
			IpPrefix:      prefix,
			RecvSocket:    nil,
			SocketChannel: nil,
			State:         false,
		}
		err := createUDPConn(iface.UDPAddr, &i.RecvSocket)
		if err != nil {
			return errors.WithMessage(err, "Error creating UDP socket for interface->\t"+iface.Name)
		}
		myInterfaces = append(myInterfaces, i)

		// TODO: (FOR HOSTS ONLY)
		// add STATIC to routing table
		if !static {
			ifacePrefix := netip.MustParsePrefix("0.0.0.0/0")
			routingTable[ifacePrefix] = Hop{STATIC_COST, iface.Name}
			static = true
		}
	}

	// 2) initialize the neighbors connected to the node and into the routing table
	for _, neighbor := range lnxConfig.Neighbors {
		n := &Neighbor{
			VipAddr:    neighbor.DestAddr,
			UdpAddr:    neighbor.UDPAddr,
			SendSocket: nil,
		}
		err := createUDPConn(neighbor.UDPAddr, &n.SendSocket)
		if err != nil {
			return errors.WithMessage(err, "Error creating UDP socket for neighbor->\t"+neighbor.DestAddr.String())
		}
		myNeighbors[neighbor.InterfaceName] = append(myNeighbors[neighbor.InterfaceName], n)

		// add to routing table
		neighborPrefix := netip.PrefixFrom(neighbor.DestAddr, 24)
		routingTable[neighborPrefix] = Hop{LOCAL_COST, neighbor.InterfaceName}
	}

	return nil
}

func InterfaceListenerRoutine(iface Interface, signal <-chan bool) {
	isDown := false
	for {
		select {
		case open, sig := <-signal:
			if !open {
				fmt.Println("channel closed, exiting")
				return
			}
			fmt.Println("received SIGNAL with value", sig)
			if sig {
				isDown = <-signal
			}
		default:
			if isDown {
				continue
			}
			fmt.Println("no activity, actively listening on", iface.Name)
			// TODO: remove these training wheels
			time.Sleep(1 * time.Millisecond)
		}
	}
}

// When an interface goes up, we need to start it's go routine that listens
func InterfaceUp(iface *Interface) {
	iface.SocketChannel = make(chan bool)
	iface.State = true
	go func() {
		InterfaceListenerRoutine(*iface, iface.SocketChannel)
	}()
}

func InterfaceDown(iface *Interface) {
	iface.SocketChannel <- true
	iface.State = false
}

/*

func ListerToInterfaces() {
	for _, iface := range myInterfaces {
		go RecvIp(iface)
	}
}
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 {
}

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 GetNeighbors() []netip.Addr {
	return myNeighbors
}
*/

func GetInterfaceByName(ifaceName string) (*Interface, error) {
	for _, iface := range myInterfaces {
		if iface.Name == ifaceName {
			return iface, nil
		}
	}

	return nil, errors.Errorf("No interface with name %s", ifaceName)
}

func SprintInterfaces() string {
	buf := ""
	for _, iface := range myInterfaces {
		buf += fmt.Sprintf("%s\t%s\t%t\n", iface.Name, iface.IpPrefix.String(), iface.State)
	}
	return buf
}

func SprintNeighbors() string {
	buf := ""
	for ifaceName, neighbor := range myNeighbors {
		for _, n := range neighbor {
			buf += fmt.Sprintf("%s\t%s\t%s\n", ifaceName, n.UdpAddr.String(), n.VipAddr.String())
		}
	}
	return buf
}

func SprintRoutingTable() string {
	buf := ""
	for prefix, hop := range routingTable {
		buf += fmt.Sprintf("%s\t%s\t%d\n", prefix.String(), hop.VipAsStr, hop.Cost)
	}
	return buf
}

func DebugNeighbors() {
	for ifaceName, neighbor := range myNeighbors {
		for _, n := range neighbor {
			fmt.Printf("%s\t%s\t%s\t%s\n", ifaceName, n.UdpAddr.String(), n.VipAddr.String(), n.SendSocket)
		}
	}
}

func CleanUp() {
	fmt.Print("Cleaning up...\n")
	// go through the interfaces, pop thread & close the UDP FDs
	for _, iface := range myInterfaces {
		if iface.SocketChannel != nil {
			close(iface.SocketChannel)
		}
		iface.RecvSocket.Close()
	}

	// go through the neighbors, pop thread & close the UDP FDs
	for _, neighbor := range myNeighbors {
		for _, n := range neighbor {
			if n.SocketChannel != nil {
				close(n.SocketChannel)
			}
			n.SendSocket.Close()
		}
	}
}