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. if !hostinfo.remote.IsValid() {
  132. // Slow path: relay fallback. Reuse rejectBuf as the ciphertext
  133. // scratch; sendNoMetrics arranges header space for SendVia.
  134. // Segment any superpacket so each segment is sized to fit a
  135. // single relay encap.
  136. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  137. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, seg, nb, rejectBuf, q)
  138. return nil
  139. })
  140. if err != nil {
  141. hostinfo.logger(f.l).Error("Failed to segment superpacket for relay send",
  142. "error", err,
  143. )
  144. }
  145. return
  146. }
  147. if hostinfo.lastRebindCount != f.rebindCount {
  148. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  149. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  150. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  151. hostinfo.lastRebindCount = f.rebindCount
  152. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  153. hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind counter",
  154. "vpnAddrs", hostinfo.vpnAddrs,
  155. )
  156. }
  157. }
  158. ecnEnabled := f.ecnEnabled.Load()
  159. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  160. // header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
  161. scratch := sendBatch.Reserve(header.Len + len(seg) + 16)
  162. if noiseutil.EncryptLockNeeded {
  163. ci.writeLock.Lock()
  164. }
  165. c := ci.messageCounter.Add(1)
  166. out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  167. f.connectionManager.Out(hostinfo)
  168. out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
  169. if noiseutil.EncryptLockNeeded {
  170. ci.writeLock.Unlock()
  171. }
  172. if encErr != nil {
  173. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  174. "error", encErr,
  175. "udpAddr", hostinfo.remote,
  176. "counter", c,
  177. )
  178. // Skip this segment; the rest of the superpacket can still
  179. // go out — TCP will retransmit anything we drop here.
  180. return nil
  181. }
  182. var ecn byte
  183. if ecnEnabled {
  184. ecn = innerECN(seg)
  185. }
  186. sendBatch.Commit(out, hostinfo.remote, ecn)
  187. return nil
  188. })
  189. if err != nil {
  190. hostinfo.logger(f.l).Error("Failed to segment superpacket for send",
  191. "error", err,
  192. )
  193. }
  194. }
  195. // innerECN returns the 2-bit IP-level ECN codepoint of an inner IPv4 or IPv6
  196. // packet, or 0 if pkt is too short or its IP version is unrecognized. Used at
  197. // encap to copy the inner codepoint onto the outer carrier per RFC 6040.
  198. func innerECN(pkt []byte) byte {
  199. if len(pkt) < 2 {
  200. return 0
  201. }
  202. switch pkt[0] >> 4 {
  203. case 4:
  204. return pkt[1] & 0x03
  205. case 6:
  206. return (pkt[1] >> 4) & 0x03
  207. }
  208. return 0
  209. }
  210. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  211. if !f.firewall.InSendReject {
  212. return
  213. }
  214. out = iputil.CreateRejectPacket(packet, out)
  215. if len(out) == 0 {
  216. return
  217. }
  218. _, err := f.readers[q].Write(out)
  219. if err != nil {
  220. f.l.Error("Failed to write to tun", "error", err)
  221. }
  222. }
  223. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  224. if !f.firewall.OutSendReject {
  225. return
  226. }
  227. out = iputil.CreateRejectPacket(packet, out)
  228. if len(out) == 0 {
  229. return
  230. }
  231. if len(out) > iputil.MaxRejectPacketSize {
  232. if f.l.Enabled(context.Background(), slog.LevelInfo) {
  233. f.l.Info("rejectOutside: packet too big, not sending",
  234. "packet", packet,
  235. "outPacket", out,
  236. )
  237. }
  238. return
  239. }
  240. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
  241. }
  242. // 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
  243. // it does not check if it is within our vpn networks!
  244. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  245. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  246. }
  247. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  248. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  249. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  250. if f.myVpnNetworksTable.Contains(vpnAddr) {
  251. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  252. }
  253. return nil, false
  254. }
  255. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  256. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  257. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  258. destinationAddr := fwPacket.RemoteAddr
  259. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  260. // Host is inside the mesh, no routing required
  261. if hostinfo != nil {
  262. return hostinfo, ready
  263. }
  264. gateways := f.inside.RoutesFor(destinationAddr)
  265. switch len(gateways) {
  266. case 0:
  267. return nil, false
  268. case 1:
  269. // Single gateway route
  270. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  271. default:
  272. // Multi gateway route, perform ECMP categorization
  273. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  274. if !balancingOk {
  275. // This happens if the gateway buckets were not calculated, this _should_ never happen
  276. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  277. }
  278. var handshakeInfoForChosenGateway *HandshakeHostInfo
  279. var hhReceiver = func(hh *HandshakeHostInfo) {
  280. handshakeInfoForChosenGateway = hh
  281. }
  282. // Store the handshakeHostInfo for later.
  283. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  284. // cache the packet for this gateway.
  285. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  286. return hostinfo, true
  287. }
  288. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  289. // The current implementation breaks ECMP but that seems better than no connectivity.
  290. // If ECMP is also required when a gateway is down then connectivity status
  291. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  292. // This would also need to interact with unsafe_route updates through reloading the config or
  293. // use of the use_system_route_table option
  294. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  295. f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
  296. "destination", destinationAddr,
  297. "originalGateway", gatewayAddr,
  298. )
  299. }
  300. for i := range gateways {
  301. // Skip the gateway that failed previously
  302. if gateways[i].Addr() == gatewayAddr {
  303. continue
  304. }
  305. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  306. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  307. return hostinfo, true
  308. }
  309. }
  310. // No gateways reachable, cache the packet in the originally chosen gateway
  311. cacheCallback(handshakeInfoForChosenGateway)
  312. return hostinfo, false
  313. }
  314. }
  315. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  316. fp := &firewall.Packet{}
  317. err := newPacket(p, false, fp)
  318. if err != nil {
  319. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  320. return
  321. }
  322. // check if packet is in outbound fw rules
  323. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  324. if dropReason != nil {
  325. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  326. f.l.Debug("dropping cached packet",
  327. "fwPacket", fp,
  328. "reason", dropReason,
  329. )
  330. }
  331. return
  332. }
  333. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  334. }
  335. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  336. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  337. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  338. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  339. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  340. })
  341. if hostInfo == nil {
  342. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  343. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  344. "vpnAddr", vpnAddr,
  345. )
  346. }
  347. return
  348. }
  349. if !ready {
  350. return
  351. }
  352. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  353. }
  354. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  355. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  356. }
  357. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  358. f.messageMetrics.Tx(t, st, 1)
  359. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  360. }
  361. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  362. f.messageMetrics.Tx(t, st, 1)
  363. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  364. }
  365. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  366. // to the payload for the ultimate target host, making this a useful method for sending
  367. // handshake messages to peers through relay tunnels.
  368. // via is the HostInfo through which the message is relayed.
  369. // ad is the plaintext data to authenticate, but not encrypt
  370. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  371. // out is a buffer used to store the result of the Encrypt operation
  372. // q indicates which writer to use to send the packet.
  373. func (f *Interface) SendVia(via *HostInfo,
  374. relay *Relay,
  375. ad,
  376. nb,
  377. out []byte,
  378. nocopy bool,
  379. ) {
  380. if noiseutil.EncryptLockNeeded {
  381. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  382. via.ConnectionState.writeLock.Lock()
  383. }
  384. c := via.ConnectionState.messageCounter.Add(1)
  385. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  386. f.connectionManager.Out(via)
  387. // Authenticate the header and payload, but do not encrypt for this message type.
  388. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  389. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  390. if noiseutil.EncryptLockNeeded {
  391. via.ConnectionState.writeLock.Unlock()
  392. }
  393. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  394. "outCap", cap(out),
  395. "payloadLen", len(ad),
  396. "headerLen", len(out),
  397. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  398. )
  399. return
  400. }
  401. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  402. offset := len(out)
  403. out = out[:offset+len(ad)]
  404. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  405. // be copied into 'out'.
  406. if !nocopy {
  407. copy(out[offset:], ad)
  408. }
  409. var err error
  410. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  411. if noiseutil.EncryptLockNeeded {
  412. via.ConnectionState.writeLock.Unlock()
  413. }
  414. if err != nil {
  415. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  416. return
  417. }
  418. err = f.writers[0].WriteTo(out, via.remote)
  419. if err != nil {
  420. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  421. }
  422. f.connectionManager.RelayUsed(relay.LocalIndex)
  423. }
  424. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  425. if ci.eKey == nil {
  426. return
  427. }
  428. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  429. fullOut := out
  430. if useRelay {
  431. if len(out) < header.Len {
  432. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  433. // Grow it to make sure the next operation works.
  434. out = out[:header.Len]
  435. }
  436. // Save a header's worth of data at the front of the 'out' buffer.
  437. out = out[header.Len:]
  438. }
  439. if noiseutil.EncryptLockNeeded {
  440. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  441. ci.writeLock.Lock()
  442. }
  443. c := ci.messageCounter.Add(1)
  444. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  445. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  446. f.connectionManager.Out(hostinfo)
  447. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  448. // all our addrs and enable a faster roaming.
  449. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  450. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  451. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  452. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  453. hostinfo.lastRebindCount = f.rebindCount
  454. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  455. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  456. "vpnAddrs", hostinfo.vpnAddrs,
  457. )
  458. }
  459. }
  460. var err error
  461. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  462. if noiseutil.EncryptLockNeeded {
  463. ci.writeLock.Unlock()
  464. }
  465. if err != nil {
  466. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  467. "error", err,
  468. "udpAddr", remote,
  469. "counter", c,
  470. "attemptedCounter", 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 hostinfo.remote.IsValid() {
  483. err = f.writers[q].WriteTo(out, hostinfo.remote)
  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. }