1
0

inside.go 19 KB

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