| 1 |
package routing |
| 2 |
|
| 3 |
import ( |
| 4 |
"net/netip" |
| 5 |
|
| 6 |
"github.com/slackhq/nebula/firewall" |
| 7 |
) |
| 8 |
|
| 9 |
// Hashes the packet source and destination port and always returns a positive integer |
| 10 |
// Based on 'Prospecting for Hash Functions' |
| 11 |
// - https://nullprogram.com/blog/2018/07/31/ |
| 12 |
// - https://github.com/skeeto/hash-prospector |
| 13 |
// [16 21f0aaad 15 d35a2d97 15] = 0.10760229515479501 |
| 14 |
func hashPacket(p *firewall.Packet) int { |
| 15 |
x := (uint32(p.LocalPort) << 16) | uint32(p.RemotePort) |
| 16 |
x ^= x >> 16 |
| 17 |
x *= 0x21f0aaad |
| 18 |
x ^= x >> 15 |
| 19 |
x *= 0xd35a2d97 |
| 20 |
x ^= x >> 15 |
| 21 |
|
| 22 |
return int(x) & 0x7FFFFFFF |
| 23 |
} |
| 24 |
|
| 25 |
// For this function to work correctly it requires that the buckets for the gateways have been calculated |
| 26 |
// If the contract is violated balancing will not work properly and the second return value will return false |
| 27 |
func BalancePacket(fwPacket *firewall.Packet, gateways []Gateway) (netip.Addr, bool) { |
| 28 |
hash := hashPacket(fwPacket) |
| 29 |
|
| 30 |
for i := range gateways { |
| 31 |
if hash <= gateways[i].BucketUpperBound() { |
| 32 |
return gateways[i].Addr(), true |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
// If you land here then the buckets for the gateways are not properly calculated |
| 37 |
// Fallback to random routing and let the caller know |
| 38 |
return gateways[hash%len(gateways)].Addr(), false |
| 39 |
} |