inside.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package nebula
  2. import (
  3. "context"
  4. "log/slog"
  5. "net/netip"
  6. "github.com/slackhq/nebula/firewall"
  7. "github.com/slackhq/nebula/header"
  8. "github.com/slackhq/nebula/iputil"
  9. "github.com/slackhq/nebula/noiseutil"
  10. "github.com/slackhq/nebula/overlay/batch"
  11. "github.com/slackhq/nebula/overlay/tio"
  12. "github.com/slackhq/nebula/routing"
  13. )
  14. func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Packet, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
  15. // borrowed: pkt.Bytes is owned by the originating tio.Queue and is
  16. // only valid until the next Read on that queue. Every consumer below
  17. // (parse, self-forward, handshake cache, sendInsideMessage) reads it
  18. // synchronously; do not retain pkt outside this call. If a future
  19. // caller needs to keep the packet, use pkt.Clone() to detach it from
  20. // the borrow.
  21. //
  22. // pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
  23. // superpacket. In both cases the L3+L4 headers at the start describe
  24. // the same 5-tuple every segment will share, so a single newPacket /
  25. // firewall check covers the whole superpacket.
  26. packet := pkt.Bytes
  27. err := newPacket(packet, false, fwPacket)
  28. if err != nil {
  29. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  30. f.l.Debug("Error while validating outbound packet",
  31. "packet", packet,
  32. "error", err,
  33. )
  34. }
  35. return
  36. }
  37. // Ignore local broadcast packets
  38. if f.dropLocalBroadcast {
  39. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  40. return
  41. }
  42. }
  43. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  44. // Immediately forward packets from self to self.
  45. // This should only happen on Darwin-based and FreeBSD hosts, which
  46. // routes packets from the Nebula addr to the Nebula addr through the Nebula
  47. // TUN device.
  48. if immediatelyForwardToSelf {
  49. // Write copies into the kernel queue synchronously, so seg's lifetime ends at return.
  50. // A self-forwarded superpacket would be re-handed to the
  51. // kernel as one giant blob; segment first so the loopback
  52. // path sees one IP datagram per Write.
  53. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  54. _, werr := f.readers[q].Write(seg)
  55. return werr
  56. })
  57. if err != nil {
  58. f.l.Error("Failed to forward to tun", "error", err)
  59. }
  60. }
  61. // Otherwise, drop. On linux, we should never see these packets - Linux
  62. // routes packets from the nebula addr to the nebula addr through the loopback device.
  63. return
  64. }
  65. // Ignore multicast packets
  66. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  67. return
  68. }
  69. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  70. // borrowed: SegmentSuperpacket builds each segment in the kernel-supplied pkt
  71. // bytes underneath. cachePacket explicitly copies its argument (handshake_manager.go cachePacket),
  72. // so retaining segments past the loop is safe.
  73. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  74. hh.cachePacket(f.l, header.Message, 0, seg, f.sendMessageNow, f.cachedPacketMetrics)
  75. return nil
  76. })
  77. if err != nil && f.l.Enabled(context.Background(), slog.LevelDebug) {
  78. f.l.Debug("Failed to segment superpacket for handshake cache",
  79. "error", err,
  80. "vpnAddr", fwPacket.RemoteAddr,
  81. )
  82. }
  83. })
  84. if hostinfo == nil {
  85. f.rejectInside(packet, rejectBuf, q)
  86. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  87. f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
  88. "vpnAddr", fwPacket.RemoteAddr,
  89. "fwPacket", fwPacket,
  90. )
  91. }
  92. return
  93. }
  94. if !ready {
  95. return
  96. }
  97. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  98. if dropReason == nil {
  99. f.sendInsideMessage(hostinfo, pkt, nb, sendBatch, rejectBuf, q)
  100. } else {
  101. f.rejectInside(packet, rejectBuf, q)
  102. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  103. hostinfo.logger(f.l).Debug("dropping outbound packet",
  104. "fwPacket", fwPacket,
  105. "reason", dropReason,
  106. )
  107. }
  108. }
  109. }
  110. // sendInsideMessage encrypts a firewall-approved inside packet (or every
  111. // segment of a TSO/USO superpacket) into the caller's batch slot for
  112. // later sendmmsg flush. Segmentation is fused with encryption here so the
  113. // kernel-supplied superpacket bytes never get written into a separate
  114. // scratch arena: SegmentSuperpacket builds each segment's plaintext in
  115. // segScratch[:segLen] in turn, and we encrypt directly into a fresh
  116. // SendBatch slot.
  117. //
  118. // When hostinfo.remote is not valid we fall through to the relay slow
  119. // path via the unbatched sendNoMetrics so relay behavior is unchanged;
  120. // each segment of a superpacket goes through that path independently.
  121. // sendInsideMessage takes a borrowed pkt: pkt.Bytes is only valid until the
  122. // next Read on the originating tio.Queue. Each segment is encrypted into a
  123. // fresh sendBatch slot (Reserve returns owned scratch), so the borrow ends
  124. // inside the SegmentSuperpacket callback below. Do not retain pkt or any
  125. // seg slice past the callback's return.
  126. func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int) {
  127. ci := hostinfo.ConnectionState
  128. if ci.eKey == nil {
  129. return
  130. }
  131. remote := hostinfo.GetRemote()
  132. if !remote.IsValid() {
  133. // Slow path: relay fallback. Reuse rejectBuf as the ciphertext
  134. // scratch; sendNoMetrics arranges header space for SendVia.
  135. // Segment any superpacket so each segment is sized to fit a
  136. // single relay encap.
  137. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  138. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, seg, nb, rejectBuf, q)
  139. return nil
  140. })
  141. if err != nil {
  142. hostinfo.logger(f.l).Error("Failed to segment superpacket for relay send",
  143. "error", err,
  144. )
  145. }
  146. return
  147. }
  148. if hostinfo.lastRebindCount != f.rebindCount {
  149. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  150. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  151. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  152. hostinfo.lastRebindCount = f.rebindCount
  153. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  154. hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind counter",
  155. "vpnAddrs", hostinfo.vpnAddrs,
  156. )
  157. }
  158. }
  159. ecnEnabled := f.ecnEnabled.Load()
  160. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  161. // header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
  162. scratch := sendBatch.Reserve(header.Len + len(seg) + 16)
  163. if noiseutil.EncryptLockNeeded {
  164. ci.writeLock.Lock()
  165. }
  166. c := ci.messageCounter.Add(1)
  167. out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  168. f.connectionManager.Out(hostinfo)
  169. out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
  170. if noiseutil.EncryptLockNeeded {
  171. ci.writeLock.Unlock()
  172. }
  173. if encErr != nil {
  174. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  175. "error", encErr,
  176. "udpAddr", remote,
  177. "counter", c,
  178. )
  179. // Skip this segment; the rest of the superpacket can still
  180. // go out — TCP will retransmit anything we drop here.
  181. return nil
  182. }
  183. var ecn byte
  184. if ecnEnabled {
  185. ecn = innerECN(seg)
  186. }
  187. sendBatch.Commit(out, remote, ecn)
  188. return nil
  189. })
  190. if err != nil {
  191. hostinfo.logger(f.l).Error("Failed to segment superpacket for send",
  192. "error", err,
  193. )
  194. }
  195. }
  196. // innerECN returns the 2-bit IP-level ECN codepoint of an inner IPv4 or IPv6
  197. // packet, or 0 if pkt is too short or its IP version is unrecognized. Used at
  198. // encap to copy the inner codepoint onto the outer carrier per RFC 6040.
  199. func innerECN(pkt []byte) byte {
  200. if len(pkt) < 2 {
  201. return 0
  202. }
  203. switch pkt[0] >> 4 {
  204. case 4:
  205. return pkt[1] & 0x03
  206. case 6:
  207. return (pkt[1] >> 4) & 0x03
  208. }
  209. return 0
  210. }
  211. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  212. if !f.firewall.OutboundSendReject {
  213. return
  214. }
  215. out = iputil.CreateRejectPacket(packet, out)
  216. if len(out) == 0 {
  217. return
  218. }
  219. _, err := f.readers[q].Write(out)
  220. if err != nil {
  221. f.l.Error("Failed to write to tun", "error", err)
  222. }
  223. }
  224. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  225. if !f.firewall.InboundSendReject {
  226. return
  227. }
  228. out = iputil.CreateRejectPacket(packet, out)
  229. if len(out) == 0 {
  230. return
  231. }
  232. if len(out) > iputil.MaxRejectPacketSize {
  233. if f.l.Enabled(context.Background(), slog.LevelInfo) {
  234. f.l.Info("rejectOutside: packet too big, not sending",
  235. "packet", packet,
  236. "outPacket", out,
  237. )
  238. }
  239. return
  240. }
  241. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
  242. }
  243. // Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
  244. // it does not check if it is within our vpn networks!
  245. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  246. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  247. }
  248. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  249. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  250. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  251. if f.myVpnNetworksTable.Contains(vpnAddr) {
  252. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  253. }
  254. return nil, false
  255. }
  256. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  257. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  258. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  259. destinationAddr := fwPacket.RemoteAddr
  260. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  261. // Host is inside the mesh, no routing required
  262. if hostinfo != nil {
  263. return hostinfo, ready
  264. }
  265. gateways := f.inside.RoutesFor(destinationAddr)
  266. switch len(gateways) {
  267. case 0:
  268. return nil, false
  269. case 1:
  270. // Single gateway route
  271. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  272. default:
  273. // Multi gateway route, perform ECMP categorization
  274. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  275. if !balancingOk {
  276. // This happens if the gateway buckets were not calculated, this _should_ never happen
  277. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  278. }
  279. var handshakeInfoForChosenGateway *HandshakeHostInfo
  280. var hhReceiver = func(hh *HandshakeHostInfo) {
  281. handshakeInfoForChosenGateway = hh
  282. }
  283. // Store the handshakeHostInfo for later.
  284. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  285. // cache the packet for this gateway.
  286. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  287. return hostinfo, true
  288. }
  289. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  290. // The current implementation breaks ECMP but that seems better than no connectivity.
  291. // If ECMP is also required when a gateway is down then connectivity status
  292. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  293. // This would also need to interact with unsafe_route updates through reloading the config or
  294. // use of the use_system_route_table option
  295. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  296. f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
  297. "destination", destinationAddr,
  298. "originalGateway", gatewayAddr,
  299. )
  300. }
  301. for i := range gateways {
  302. // Skip the gateway that failed previously
  303. if gateways[i].Addr() == gatewayAddr {
  304. continue
  305. }
  306. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  307. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  308. return hostinfo, true
  309. }
  310. }
  311. // No gateways reachable, cache the packet in the originally chosen gateway
  312. cacheCallback(handshakeInfoForChosenGateway)
  313. return hostinfo, false
  314. }
  315. }
  316. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  317. fp := &firewall.Packet{}
  318. err := newPacket(p, false, fp)
  319. if err != nil {
  320. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  321. return
  322. }
  323. // check if packet is in outbound fw rules
  324. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  325. if dropReason != nil {
  326. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  327. f.l.Debug("dropping cached packet",
  328. "fwPacket", fp,
  329. "reason", dropReason,
  330. )
  331. }
  332. return
  333. }
  334. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  335. }
  336. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  337. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  338. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  339. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  340. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  341. })
  342. if hostInfo == nil {
  343. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  344. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  345. "vpnAddr", vpnAddr,
  346. )
  347. }
  348. return
  349. }
  350. if !ready {
  351. return
  352. }
  353. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  354. }
  355. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  356. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  357. }
  358. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  359. f.messageMetrics.Tx(t, st, 1)
  360. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  361. }
  362. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  363. f.messageMetrics.Tx(t, st, 1)
  364. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  365. }
  366. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  367. // to the payload for the ultimate target host, making this a useful method for sending
  368. // handshake messages to peers through relay tunnels.
  369. // via is the HostInfo through which the message is relayed.
  370. // ad is the plaintext data to authenticate, but not encrypt
  371. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  372. // out is a buffer used to store the result of the Encrypt operation
  373. // q indicates which writer to use to send the packet.
  374. func (f *Interface) SendVia(via *HostInfo,
  375. relay *Relay,
  376. ad,
  377. nb,
  378. out []byte,
  379. nocopy bool,
  380. ) {
  381. if noiseutil.EncryptLockNeeded {
  382. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  383. via.ConnectionState.writeLock.Lock()
  384. }
  385. c := via.ConnectionState.messageCounter.Add(1)
  386. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  387. f.connectionManager.Out(via)
  388. // Authenticate the header and payload, but do not encrypt for this message type.
  389. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  390. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  391. if noiseutil.EncryptLockNeeded {
  392. via.ConnectionState.writeLock.Unlock()
  393. }
  394. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  395. "outCap", cap(out),
  396. "payloadLen", len(ad),
  397. "headerLen", len(out),
  398. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  399. )
  400. return
  401. }
  402. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  403. offset := len(out)
  404. out = out[:offset+len(ad)]
  405. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  406. // be copied into 'out'.
  407. if !nocopy {
  408. copy(out[offset:], ad)
  409. }
  410. var err error
  411. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  412. if noiseutil.EncryptLockNeeded {
  413. via.ConnectionState.writeLock.Unlock()
  414. }
  415. if err != nil {
  416. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  417. return
  418. }
  419. err = f.writers[0].WriteTo(out, via.GetRemote())
  420. if err != nil {
  421. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  422. }
  423. f.connectionManager.RelayUsed(relay.LocalIndex)
  424. }
  425. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  426. if ci.eKey == nil {
  427. return
  428. }
  429. useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
  430. fullOut := out
  431. if useRelay {
  432. if len(out) < header.Len {
  433. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  434. // Grow it to make sure the next operation works.
  435. out = out[:header.Len]
  436. }
  437. // Save a header's worth of data at the front of the 'out' buffer.
  438. out = out[header.Len:]
  439. }
  440. if noiseutil.EncryptLockNeeded {
  441. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  442. ci.writeLock.Lock()
  443. }
  444. c := ci.messageCounter.Add(1)
  445. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  446. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  447. f.connectionManager.Out(hostinfo)
  448. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  449. // all our addrs and enable a faster roaming.
  450. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  451. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  452. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  453. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  454. hostinfo.lastRebindCount = f.rebindCount
  455. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  456. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  457. "vpnAddrs", hostinfo.vpnAddrs,
  458. )
  459. }
  460. }
  461. var err error
  462. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  463. if noiseutil.EncryptLockNeeded {
  464. ci.writeLock.Unlock()
  465. }
  466. if err != nil {
  467. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  468. "error", err,
  469. "udpAddr", remote,
  470. "counter", c,
  471. )
  472. return
  473. }
  474. if remote.IsValid() {
  475. err = f.writers[q].WriteTo(out, remote)
  476. if err != nil {
  477. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  478. "error", err,
  479. "udpAddr", remote,
  480. )
  481. }
  482. } else if hr := hostinfo.GetRemote(); hr.IsValid() {
  483. err = f.writers[q].WriteTo(out, hr)
  484. if err != nil {
  485. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  486. "error", err,
  487. "udpAddr", remote,
  488. )
  489. }
  490. } else {
  491. // Try to send via a relay
  492. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  493. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  494. if err != nil {
  495. hostinfo.relayState.DeleteRelay(relayIP)
  496. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  497. "relay", relayIP,
  498. "error", err,
  499. )
  500. continue
  501. }
  502. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  503. break
  504. }
  505. }
  506. }