← Back to blog

Forwarding packets in both directions

With a TUN device and a UDP transport working on their own, the next step was to connect them. That’s the first pull request in the project, and the first version where a ping goes from one namespace to the other through the tunnel. Nothing is encrypted yet.

Two loops

Forwarding has two independent directions:

  • Outbound: read a packet from the TUN device, send it to the peer over UDP.
  • Inbound: receive a datagram from the peer, write it to the TUN device.

Both block while they wait for data, so each needs its own goroutine. The inbound loop runs in a new goroutine and the outbound loop runs on the main one. Each has its own buffer, since sharing one between two goroutines would be a data race.

recvBuf := make([]byte, 1500)
wg.Add(1)
go func() {
	defer wg.Done()
	for {
		nRecv, err := t.Recv(recvBuf)
		if err != nil {
			if ctx.Err() != nil {
				return
			}
			fmt.Fprintf(os.Stderr, "Error while reading UDP payload\n")
			continue
		}
		dev.Write(recvBuf[:nRecv])
	}
}()

The outbound loop is the mirror image: dev.Read, then t.Send.

Stopping cleanly

The harder part was stopping. Both loops are stuck inside blocking calls, and there’s no way to tell a blocked Read to give up through a context. What does work is closing the underlying file or socket: the blocked call returns with an error.

So shutdown is three pieces:

  1. signal.NotifyContext gives me a context that’s cancelled on SIGINT or SIGTERM.
  2. A small goroutine waits for that, then closes the TUN device and the socket.
  3. Each loop treats an error after cancellation as “time to exit”, not as a failure. The main loop then waits on the WaitGroup so the inbound goroutine is done before run returns.
go func() {
	<-ctx.Done()
	dev.Close()
	t.Close()
}()

Checking ctx.Err() is what tells an expected error apart from a real one. Without it, every Ctrl+C would print a pile of “use of closed file” errors.

Why run exists

All of this lives in a run function that returns an error, and main only parses flags and calls it. The reason is log.Fatal: it calls os.Exit, which skips deferred calls. If main did the work and hit a fatal error, the defer dev.Close() would never run. With run, every deferred cleanup runs and main decides how to exit.

The same PR added the -peer and -port flags, parsed with flag.TextVar straight into a netip.AddrPort, so an invalid address fails before anything is created.

What’s next

Testing still means opening four terminals and running the namespace lab by hand. I want a single command that starts two peers and lets me ping across, which sounds like a job for Docker Compose.