inside.go 20 KB

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