router.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. //go:build e2e_testing
  2. // +build e2e_testing
  3. package router
  4. import (
  5. "context"
  6. "fmt"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "testing"
  15. "time"
  16. "github.com/google/gopacket"
  17. "github.com/google/gopacket/layers"
  18. "github.com/slackhq/nebula"
  19. "github.com/slackhq/nebula/header"
  20. "github.com/slackhq/nebula/iputil"
  21. "github.com/slackhq/nebula/udp"
  22. )
  23. type R struct {
  24. // Simple map of the ip:port registered on a control to the control
  25. // Basically a router, right?
  26. controls map[string]*nebula.Control
  27. // A map for inbound packets for a control that doesn't know about this address
  28. inNat map[string]*nebula.Control
  29. // A last used map, if an inbound packet hit the inNat map then
  30. // all return packets should use the same last used inbound address for the outbound sender
  31. // map[from address + ":" + to address] => ip:port to rewrite in the udp packet to receiver
  32. outNat map[string]net.UDPAddr
  33. // A map of vpn ip to the nebula control it belongs to
  34. vpnControls map[iputil.VpnIp]*nebula.Control
  35. ignoreFlows []ignoreFlow
  36. flow []flowEntry
  37. // A set of additional mermaid graphs to draw in the flow log markdown file
  38. // Currently consisting only of hostmap renders
  39. additionalGraphs []mermaidGraph
  40. // All interactions are locked to help serialize behavior
  41. sync.Mutex
  42. fn string
  43. cancelRender context.CancelFunc
  44. t testing.TB
  45. }
  46. type ignoreFlow struct {
  47. tun NullBool
  48. messageType header.MessageType
  49. subType header.MessageSubType
  50. //from
  51. //to
  52. }
  53. type mermaidGraph struct {
  54. title string
  55. content string
  56. }
  57. type NullBool struct {
  58. HasValue bool
  59. IsTrue bool
  60. }
  61. type flowEntry struct {
  62. note string
  63. packet *packet
  64. }
  65. type packet struct {
  66. from *nebula.Control
  67. to *nebula.Control
  68. packet *udp.Packet
  69. tun bool // a packet pulled off a tun device
  70. rx bool // the packet was received by a udp device
  71. }
  72. func (p *packet) WasReceived() {
  73. if p != nil {
  74. p.rx = true
  75. }
  76. }
  77. type ExitType int
  78. const (
  79. // KeepRouting the function will get called again on the next packet
  80. KeepRouting ExitType = 0
  81. // ExitNow does not route this packet and exits immediately
  82. ExitNow ExitType = 1
  83. // RouteAndExit routes this packet and exits immediately afterwards
  84. RouteAndExit ExitType = 2
  85. )
  86. type ExitFunc func(packet *udp.Packet, receiver *nebula.Control) ExitType
  87. // NewR creates a new router to pass packets in a controlled fashion between the provided controllers.
  88. // The packet flow will be recorded in a file within the mermaid directory under the same name as the test.
  89. // Renders will occur automatically, roughly every 100ms, until a call to RenderFlow() is made
  90. func NewR(t testing.TB, controls ...*nebula.Control) *R {
  91. ctx, cancel := context.WithCancel(context.Background())
  92. if err := os.MkdirAll("mermaid", 0755); err != nil {
  93. panic(err)
  94. }
  95. r := &R{
  96. controls: make(map[string]*nebula.Control),
  97. vpnControls: make(map[iputil.VpnIp]*nebula.Control),
  98. inNat: make(map[string]*nebula.Control),
  99. outNat: make(map[string]net.UDPAddr),
  100. flow: []flowEntry{},
  101. ignoreFlows: []ignoreFlow{},
  102. fn: filepath.Join("mermaid", fmt.Sprintf("%s.md", t.Name())),
  103. t: t,
  104. cancelRender: cancel,
  105. }
  106. // Try to remove our render file
  107. os.Remove(r.fn)
  108. for _, c := range controls {
  109. addr := c.GetUDPAddr()
  110. if _, ok := r.controls[addr]; ok {
  111. panic("Duplicate listen address: " + addr)
  112. }
  113. r.vpnControls[c.GetVpnIp()] = c
  114. r.controls[addr] = c
  115. }
  116. // Spin the renderer in case we go nuts and the test never completes
  117. go func() {
  118. clockSource := time.NewTicker(time.Millisecond * 100)
  119. defer clockSource.Stop()
  120. for {
  121. select {
  122. case <-ctx.Done():
  123. return
  124. case <-clockSource.C:
  125. r.renderFlow()
  126. }
  127. }
  128. }()
  129. return r
  130. }
  131. // AddRoute will place the nebula controller at the ip and port specified.
  132. // It does not look at the addr attached to the instance.
  133. // If a route is used, this will behave like a NAT for the return path.
  134. // Rewriting the source ip:port to what was last sent to from the origin
  135. func (r *R) AddRoute(ip net.IP, port uint16, c *nebula.Control) {
  136. r.Lock()
  137. defer r.Unlock()
  138. inAddr := net.JoinHostPort(ip.String(), fmt.Sprintf("%v", port))
  139. if _, ok := r.inNat[inAddr]; ok {
  140. panic("Duplicate listen address inNat: " + inAddr)
  141. }
  142. r.inNat[inAddr] = c
  143. }
  144. // RenderFlow renders the packet flow seen up until now and stops further automatic renders from happening.
  145. func (r *R) RenderFlow() {
  146. r.cancelRender()
  147. r.renderFlow()
  148. }
  149. // CancelFlowLogs stops flow logs from being tracked and destroys any logs already collected
  150. func (r *R) CancelFlowLogs() {
  151. r.cancelRender()
  152. r.flow = nil
  153. }
  154. func (r *R) renderFlow() {
  155. if r.flow == nil {
  156. return
  157. }
  158. f, err := os.OpenFile(r.fn, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
  159. if err != nil {
  160. panic(err)
  161. }
  162. var participants = map[string]struct{}{}
  163. var participantsVals []string
  164. fmt.Fprintln(f, "```mermaid")
  165. fmt.Fprintln(f, "sequenceDiagram")
  166. // Assemble participants
  167. for _, e := range r.flow {
  168. if e.packet == nil {
  169. continue
  170. }
  171. addr := e.packet.from.GetUDPAddr()
  172. if _, ok := participants[addr]; ok {
  173. continue
  174. }
  175. participants[addr] = struct{}{}
  176. sanAddr := strings.Replace(addr, ":", "#58;", 1)
  177. participantsVals = append(participantsVals, sanAddr)
  178. fmt.Fprintf(
  179. f, " participant %s as Nebula: %s<br/>UDP: %s\n",
  180. sanAddr, e.packet.from.GetVpnIp(), sanAddr,
  181. )
  182. }
  183. // Print packets
  184. h := &header.H{}
  185. for _, e := range r.flow {
  186. if e.packet == nil {
  187. fmt.Fprintf(f, " note over %s: %s\n", strings.Join(participantsVals, ", "), e.note)
  188. continue
  189. }
  190. p := e.packet
  191. if p.tun {
  192. fmt.Fprintln(f, r.formatUdpPacket(p))
  193. } else {
  194. if err := h.Parse(p.packet.Data); err != nil {
  195. panic(err)
  196. }
  197. line := "--x"
  198. if p.rx {
  199. line = "->>"
  200. }
  201. fmt.Fprintf(f,
  202. " %s%s%s: %s(%s), index %v, counter: %v\n",
  203. strings.Replace(p.from.GetUDPAddr(), ":", "#58;", 1),
  204. line,
  205. strings.Replace(p.to.GetUDPAddr(), ":", "#58;", 1),
  206. h.TypeName(), h.SubTypeName(), h.RemoteIndex, h.MessageCounter,
  207. )
  208. }
  209. }
  210. fmt.Fprintln(f, "```")
  211. for _, g := range r.additionalGraphs {
  212. fmt.Fprintf(f, "## %s\n", g.title)
  213. fmt.Fprintln(f, "```mermaid")
  214. fmt.Fprintln(f, g.content)
  215. fmt.Fprintln(f, "```")
  216. }
  217. }
  218. // IgnoreFlow tells the router to stop recording future flows that matches the provided criteria.
  219. // messageType and subType will target nebula underlay packets while tun will target nebula overlay packets
  220. // NOTE: This is a very broad system, if you set tun to true then no more tun traffic will be rendered
  221. func (r *R) IgnoreFlow(messageType header.MessageType, subType header.MessageSubType, tun NullBool) {
  222. r.Lock()
  223. defer r.Unlock()
  224. r.ignoreFlows = append(r.ignoreFlows, ignoreFlow{
  225. tun,
  226. messageType,
  227. subType,
  228. })
  229. }
  230. func (r *R) RenderHostmaps(title string, controls ...*nebula.Control) {
  231. r.Lock()
  232. defer r.Unlock()
  233. s := renderHostmaps(controls...)
  234. if len(r.additionalGraphs) > 0 {
  235. lastGraph := r.additionalGraphs[len(r.additionalGraphs)-1]
  236. if lastGraph.content == s && lastGraph.title == title {
  237. // Ignore this rendering if it matches the last rendering added
  238. // This is useful if you want to track rendering changes
  239. return
  240. }
  241. }
  242. r.additionalGraphs = append(r.additionalGraphs, mermaidGraph{
  243. title: title,
  244. content: s,
  245. })
  246. }
  247. // InjectFlow can be used to record packet flow if the test is handling the routing on its own.
  248. // The packet is assumed to have been received
  249. func (r *R) InjectFlow(from, to *nebula.Control, p *udp.Packet) {
  250. r.Lock()
  251. defer r.Unlock()
  252. r.unlockedInjectFlow(from, to, p, false)
  253. }
  254. func (r *R) Log(arg ...any) {
  255. if r.flow == nil {
  256. return
  257. }
  258. r.Lock()
  259. r.flow = append(r.flow, flowEntry{note: fmt.Sprint(arg...)})
  260. r.t.Log(arg...)
  261. r.Unlock()
  262. }
  263. func (r *R) Logf(format string, arg ...any) {
  264. if r.flow == nil {
  265. return
  266. }
  267. r.Lock()
  268. r.flow = append(r.flow, flowEntry{note: fmt.Sprintf(format, arg...)})
  269. r.t.Logf(format, arg...)
  270. r.Unlock()
  271. }
  272. // unlockedInjectFlow is used by the router to record a packet has been transmitted, the packet is returned and
  273. // should be marked as received AFTER it has been placed on the receivers channel.
  274. // If flow logs have been disabled this function will return nil
  275. func (r *R) unlockedInjectFlow(from, to *nebula.Control, p *udp.Packet, tun bool) *packet {
  276. if r.flow == nil {
  277. return nil
  278. }
  279. if len(r.ignoreFlows) > 0 {
  280. var h header.H
  281. err := h.Parse(p.Data)
  282. if err != nil {
  283. panic(err)
  284. }
  285. for _, i := range r.ignoreFlows {
  286. if !tun {
  287. if i.messageType == h.Type && i.subType == h.Subtype {
  288. return nil
  289. }
  290. } else if i.tun.HasValue && i.tun.IsTrue {
  291. return nil
  292. }
  293. }
  294. }
  295. fp := &packet{
  296. from: from,
  297. to: to,
  298. packet: p.Copy(),
  299. tun: tun,
  300. }
  301. r.flow = append(r.flow, flowEntry{packet: fp})
  302. return fp
  303. }
  304. // OnceFrom will route a single packet from sender then return
  305. // If the router doesn't have the nebula controller for that address, we panic
  306. func (r *R) OnceFrom(sender *nebula.Control) {
  307. r.RouteExitFunc(sender, func(*udp.Packet, *nebula.Control) ExitType {
  308. return RouteAndExit
  309. })
  310. }
  311. // RouteUntilTxTun will route for sender and return when a packet is seen on receivers tun
  312. // If the router doesn't have the nebula controller for that address, we panic
  313. func (r *R) RouteUntilTxTun(sender *nebula.Control, receiver *nebula.Control) []byte {
  314. tunTx := receiver.GetTunTxChan()
  315. udpTx := sender.GetUDPTxChan()
  316. for {
  317. select {
  318. // Maybe we already have something on the tun for us
  319. case b := <-tunTx:
  320. r.Lock()
  321. np := udp.Packet{Data: make([]byte, len(b))}
  322. copy(np.Data, b)
  323. r.unlockedInjectFlow(receiver, receiver, &np, true)
  324. r.Unlock()
  325. return b
  326. // Nope, lets push the sender along
  327. case p := <-udpTx:
  328. outAddr := sender.GetUDPAddr()
  329. r.Lock()
  330. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  331. c := r.getControl(outAddr, inAddr, p)
  332. if c == nil {
  333. r.Unlock()
  334. panic("No control for udp tx")
  335. }
  336. fp := r.unlockedInjectFlow(sender, c, p, false)
  337. c.InjectUDPPacket(p)
  338. fp.WasReceived()
  339. r.Unlock()
  340. }
  341. }
  342. }
  343. // RouteForAllUntilTxTun will route for everyone and return when a packet is seen on receivers tun
  344. // If the router doesn't have the nebula controller for that address, we panic
  345. func (r *R) RouteForAllUntilTxTun(receiver *nebula.Control) []byte {
  346. sc := make([]reflect.SelectCase, len(r.controls)+1)
  347. cm := make([]*nebula.Control, len(r.controls)+1)
  348. i := 0
  349. sc[i] = reflect.SelectCase{
  350. Dir: reflect.SelectRecv,
  351. Chan: reflect.ValueOf(receiver.GetTunTxChan()),
  352. Send: reflect.Value{},
  353. }
  354. cm[i] = receiver
  355. i++
  356. for _, c := range r.controls {
  357. sc[i] = reflect.SelectCase{
  358. Dir: reflect.SelectRecv,
  359. Chan: reflect.ValueOf(c.GetUDPTxChan()),
  360. Send: reflect.Value{},
  361. }
  362. cm[i] = c
  363. i++
  364. }
  365. for {
  366. x, rx, _ := reflect.Select(sc)
  367. r.Lock()
  368. if x == 0 {
  369. // we are the tun tx, we can exit
  370. p := rx.Interface().([]byte)
  371. np := udp.Packet{Data: make([]byte, len(p))}
  372. copy(np.Data, p)
  373. r.unlockedInjectFlow(cm[x], cm[x], &np, true)
  374. r.Unlock()
  375. return p
  376. } else {
  377. // we are a udp tx, route and continue
  378. p := rx.Interface().(*udp.Packet)
  379. outAddr := cm[x].GetUDPAddr()
  380. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  381. c := r.getControl(outAddr, inAddr, p)
  382. if c == nil {
  383. r.Unlock()
  384. panic("No control for udp tx")
  385. }
  386. fp := r.unlockedInjectFlow(cm[x], c, p, false)
  387. c.InjectUDPPacket(p)
  388. fp.WasReceived()
  389. }
  390. r.Unlock()
  391. }
  392. }
  393. // RouteExitFunc will call the whatDo func with each udp packet from sender.
  394. // whatDo can return:
  395. // - exitNow: the packet will not be routed and this call will return immediately
  396. // - routeAndExit: this call will return immediately after routing the last packet from sender
  397. // - keepRouting: the packet will be routed and whatDo will be called again on the next packet from sender
  398. func (r *R) RouteExitFunc(sender *nebula.Control, whatDo ExitFunc) {
  399. h := &header.H{}
  400. for {
  401. p := sender.GetFromUDP(true)
  402. r.Lock()
  403. if err := h.Parse(p.Data); err != nil {
  404. panic(err)
  405. }
  406. outAddr := sender.GetUDPAddr()
  407. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  408. receiver := r.getControl(outAddr, inAddr, p)
  409. if receiver == nil {
  410. r.Unlock()
  411. panic("Can't route for host: " + inAddr)
  412. }
  413. e := whatDo(p, receiver)
  414. switch e {
  415. case ExitNow:
  416. r.Unlock()
  417. return
  418. case RouteAndExit:
  419. fp := r.unlockedInjectFlow(sender, receiver, p, false)
  420. receiver.InjectUDPPacket(p)
  421. fp.WasReceived()
  422. r.Unlock()
  423. return
  424. case KeepRouting:
  425. fp := r.unlockedInjectFlow(sender, receiver, p, false)
  426. receiver.InjectUDPPacket(p)
  427. fp.WasReceived()
  428. default:
  429. panic(fmt.Sprintf("Unknown exitFunc return: %v", e))
  430. }
  431. r.Unlock()
  432. }
  433. }
  434. // RouteUntilAfterMsgType will route for sender until a message type is seen and sent from sender
  435. // If the router doesn't have the nebula controller for that address, we panic
  436. func (r *R) RouteUntilAfterMsgType(sender *nebula.Control, msgType header.MessageType, subType header.MessageSubType) {
  437. h := &header.H{}
  438. r.RouteExitFunc(sender, func(p *udp.Packet, r *nebula.Control) ExitType {
  439. if err := h.Parse(p.Data); err != nil {
  440. panic(err)
  441. }
  442. if h.Type == msgType && h.Subtype == subType {
  443. return RouteAndExit
  444. }
  445. return KeepRouting
  446. })
  447. }
  448. func (r *R) RouteForAllUntilAfterMsgTypeTo(receiver *nebula.Control, msgType header.MessageType, subType header.MessageSubType) {
  449. h := &header.H{}
  450. r.RouteForAllExitFunc(func(p *udp.Packet, r *nebula.Control) ExitType {
  451. if r != receiver {
  452. return KeepRouting
  453. }
  454. if err := h.Parse(p.Data); err != nil {
  455. panic(err)
  456. }
  457. if h.Type == msgType && h.Subtype == subType {
  458. return RouteAndExit
  459. }
  460. return KeepRouting
  461. })
  462. }
  463. func (r *R) InjectUDPPacket(sender, receiver *nebula.Control, packet *udp.Packet) {
  464. r.Lock()
  465. defer r.Unlock()
  466. fp := r.unlockedInjectFlow(sender, receiver, packet, false)
  467. receiver.InjectUDPPacket(packet)
  468. fp.WasReceived()
  469. }
  470. // RouteForUntilAfterToAddr will route for sender and return only after it sees and sends a packet destined for toAddr
  471. // finish can be any of the exitType values except `keepRouting`, the default value is `routeAndExit`
  472. // If the router doesn't have the nebula controller for that address, we panic
  473. func (r *R) RouteForUntilAfterToAddr(sender *nebula.Control, toAddr *net.UDPAddr, finish ExitType) {
  474. if finish == KeepRouting {
  475. finish = RouteAndExit
  476. }
  477. r.RouteExitFunc(sender, func(p *udp.Packet, r *nebula.Control) ExitType {
  478. if p.ToIp.Equal(toAddr.IP) && p.ToPort == uint16(toAddr.Port) {
  479. return finish
  480. }
  481. return KeepRouting
  482. })
  483. }
  484. // RouteForAllExitFunc will route for every registered controller and calls the whatDo func with each udp packet from
  485. // whatDo can return:
  486. // - exitNow: the packet will not be routed and this call will return immediately
  487. // - routeAndExit: this call will return immediately after routing the last packet from sender
  488. // - keepRouting: the packet will be routed and whatDo will be called again on the next packet from sender
  489. func (r *R) RouteForAllExitFunc(whatDo ExitFunc) {
  490. sc := make([]reflect.SelectCase, len(r.controls))
  491. cm := make([]*nebula.Control, len(r.controls))
  492. i := 0
  493. for _, c := range r.controls {
  494. sc[i] = reflect.SelectCase{
  495. Dir: reflect.SelectRecv,
  496. Chan: reflect.ValueOf(c.GetUDPTxChan()),
  497. Send: reflect.Value{},
  498. }
  499. cm[i] = c
  500. i++
  501. }
  502. for {
  503. x, rx, _ := reflect.Select(sc)
  504. r.Lock()
  505. p := rx.Interface().(*udp.Packet)
  506. outAddr := cm[x].GetUDPAddr()
  507. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  508. receiver := r.getControl(outAddr, inAddr, p)
  509. if receiver == nil {
  510. r.Unlock()
  511. panic("Can't route for host: " + inAddr)
  512. }
  513. e := whatDo(p, receiver)
  514. switch e {
  515. case ExitNow:
  516. r.Unlock()
  517. return
  518. case RouteAndExit:
  519. fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
  520. receiver.InjectUDPPacket(p)
  521. fp.WasReceived()
  522. r.Unlock()
  523. return
  524. case KeepRouting:
  525. fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
  526. receiver.InjectUDPPacket(p)
  527. fp.WasReceived()
  528. default:
  529. panic(fmt.Sprintf("Unknown exitFunc return: %v", e))
  530. }
  531. r.Unlock()
  532. }
  533. }
  534. // FlushAll will route for every registered controller, exiting once there are no packets left to route
  535. func (r *R) FlushAll() {
  536. sc := make([]reflect.SelectCase, len(r.controls))
  537. cm := make([]*nebula.Control, len(r.controls))
  538. i := 0
  539. for _, c := range r.controls {
  540. sc[i] = reflect.SelectCase{
  541. Dir: reflect.SelectRecv,
  542. Chan: reflect.ValueOf(c.GetUDPTxChan()),
  543. Send: reflect.Value{},
  544. }
  545. cm[i] = c
  546. i++
  547. }
  548. // Add a default case to exit when nothing is left to send
  549. sc = append(sc, reflect.SelectCase{
  550. Dir: reflect.SelectDefault,
  551. Chan: reflect.Value{},
  552. Send: reflect.Value{},
  553. })
  554. for {
  555. x, rx, ok := reflect.Select(sc)
  556. if !ok {
  557. return
  558. }
  559. r.Lock()
  560. p := rx.Interface().(*udp.Packet)
  561. outAddr := cm[x].GetUDPAddr()
  562. inAddr := net.JoinHostPort(p.ToIp.String(), fmt.Sprintf("%v", p.ToPort))
  563. receiver := r.getControl(outAddr, inAddr, p)
  564. if receiver == nil {
  565. r.Unlock()
  566. panic("Can't route for host: " + inAddr)
  567. }
  568. r.Unlock()
  569. }
  570. }
  571. // getControl performs or seeds NAT translation and returns the control for toAddr, p from fields may change
  572. // This is an internal router function, the caller must hold the lock
  573. func (r *R) getControl(fromAddr, toAddr string, p *udp.Packet) *nebula.Control {
  574. if newAddr, ok := r.outNat[fromAddr+":"+toAddr]; ok {
  575. p.FromIp = newAddr.IP
  576. p.FromPort = uint16(newAddr.Port)
  577. }
  578. c, ok := r.inNat[toAddr]
  579. if ok {
  580. sHost, sPort, err := net.SplitHostPort(toAddr)
  581. if err != nil {
  582. panic(err)
  583. }
  584. port, err := strconv.Atoi(sPort)
  585. if err != nil {
  586. panic(err)
  587. }
  588. r.outNat[c.GetUDPAddr()+":"+fromAddr] = net.UDPAddr{
  589. IP: net.ParseIP(sHost),
  590. Port: port,
  591. }
  592. return c
  593. }
  594. return r.controls[toAddr]
  595. }
  596. func (r *R) formatUdpPacket(p *packet) string {
  597. packet := gopacket.NewPacket(p.packet.Data, layers.LayerTypeIPv4, gopacket.Lazy)
  598. v4 := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
  599. if v4 == nil {
  600. panic("not an ipv4 packet")
  601. }
  602. from := "unknown"
  603. if c, ok := r.vpnControls[iputil.Ip2VpnIp(v4.SrcIP)]; ok {
  604. from = c.GetUDPAddr()
  605. }
  606. udp := packet.Layer(layers.LayerTypeUDP).(*layers.UDP)
  607. if udp == nil {
  608. panic("not a udp packet")
  609. }
  610. data := packet.ApplicationLayer()
  611. return fmt.Sprintf(
  612. " %s-->>%s: src port: %v<br/>dest port: %v<br/>data: \"%v\"\n",
  613. strings.Replace(from, ":", "#58;", 1),
  614. strings.Replace(p.to.GetUDPAddr(), ":", "#58;", 1),
  615. udp.SrcPort,
  616. udp.DstPort,
  617. string(data.Payload()),
  618. )
  619. }