1
0

commands.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. package nebula
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "log/slog"
  8. "maps"
  9. "net/netip"
  10. "sort"
  11. "strings"
  12. "github.com/slackhq/nebula/commands"
  13. "github.com/slackhq/nebula/config"
  14. "github.com/slackhq/nebula/logging"
  15. )
  16. // The commands nebula serves. attachCommands builds the one registry every surface
  17. // reads. See the commands package for what a Command is.
  18. type listHostMapFlags struct {
  19. Json bool
  20. Pretty bool
  21. ByIndex bool
  22. }
  23. // listHostMapFlagSet is the flag set list-hostmap and list-pending-hostmap share.
  24. func listHostMapFlagSet() (*flag.FlagSet, any) {
  25. fl := flag.NewFlagSet("", flag.ContinueOnError)
  26. s := listHostMapFlags{}
  27. fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
  28. fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
  29. fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
  30. return fl, &s
  31. }
  32. type printCertFlags struct {
  33. Json bool
  34. Pretty bool
  35. Raw bool
  36. }
  37. type printTunnelFlags struct {
  38. Pretty bool
  39. }
  40. type changeRemoteFlags struct {
  41. Address string
  42. }
  43. type closeTunnelFlags struct {
  44. LocalOnly bool
  45. }
  46. type createTunnelFlags struct {
  47. Address string
  48. }
  49. type deviceInfoFlags struct {
  50. Json bool
  51. Pretty bool
  52. }
  53. func attachCommands(l *slog.Logger, c *config.C, reg *commands.Registry, f *Interface) {
  54. reg.Register(&commands.Command{
  55. Name: commands.ListHostmap,
  56. ShortDescription: "List all known previously connected hosts",
  57. Flags: listHostMapFlagSet,
  58. Callback: func(fs any, a []string, w commands.StringWriter) error {
  59. return listHostMapCommand(f.hostMap, fs, w)
  60. },
  61. })
  62. reg.Register(&commands.Command{
  63. Name: commands.ListPendingHostmap,
  64. ShortDescription: "List all handshaking hosts",
  65. Flags: listHostMapFlagSet,
  66. Callback: func(fs any, a []string, w commands.StringWriter) error {
  67. return listHostMapCommand(f.handshakeManager, fs, w)
  68. },
  69. })
  70. reg.Register(&commands.Command{
  71. Name: commands.ListLighthouseAddrmap,
  72. ShortDescription: "List all lighthouse map entries",
  73. Flags: func() (*flag.FlagSet, any) {
  74. fl := flag.NewFlagSet("", flag.ContinueOnError)
  75. s := listHostMapFlags{}
  76. fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
  77. fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
  78. return fl, &s
  79. },
  80. Callback: func(fs any, a []string, w commands.StringWriter) error {
  81. return listLighthouseAddrmapCommand(f.lightHouse, fs, w)
  82. },
  83. })
  84. reg.Register(&commands.Command{
  85. Name: commands.Reload,
  86. ShortDescription: "Reloads configuration from disk, same as sending HUP to the process",
  87. Callback: func(fs any, a []string, w commands.StringWriter) error {
  88. return reloadCommand(l, c, w)
  89. },
  90. })
  91. reg.Register(&commands.Command{
  92. Name: commands.LogLevel,
  93. ShortDescription: "Gets or sets the current log level",
  94. Callback: func(fs any, a []string, w commands.StringWriter) error {
  95. return logLevelCommand(l, fs, a, w)
  96. },
  97. })
  98. reg.Register(&commands.Command{
  99. Name: commands.LogFormat,
  100. ShortDescription: "Gets or sets the current log format",
  101. Callback: func(fs any, a []string, w commands.StringWriter) error {
  102. return logFormatCommand(l, fs, a, w)
  103. },
  104. })
  105. reg.Register(&commands.Command{
  106. Name: commands.Version,
  107. ShortDescription: "Prints the currently running version of nebula",
  108. Callback: func(fs any, a []string, w commands.StringWriter) error {
  109. return versionCommand(f, fs, a, w)
  110. },
  111. })
  112. reg.Register(&commands.Command{
  113. Name: commands.DeviceInfo,
  114. ShortDescription: "Prints information about the network device.",
  115. Flags: func() (*flag.FlagSet, any) {
  116. fl := flag.NewFlagSet("", flag.ContinueOnError)
  117. s := deviceInfoFlags{}
  118. fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
  119. fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
  120. return fl, &s
  121. },
  122. Callback: func(fs any, a []string, w commands.StringWriter) error {
  123. return deviceInfoCommand(f, fs, w)
  124. },
  125. })
  126. reg.Register(&commands.Command{
  127. Name: commands.PrintCert,
  128. ShortDescription: "Prints the current certificate being used or the certificate for the provided vpn addr",
  129. Flags: func() (*flag.FlagSet, any) {
  130. fl := flag.NewFlagSet("", flag.ContinueOnError)
  131. s := printCertFlags{}
  132. fl.BoolVar(&s.Json, "json", false, "outputs as json")
  133. fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
  134. fl.BoolVar(&s.Raw, "raw", false, "raw prints the PEM encoded certificate, not compatible with -json or -pretty")
  135. return fl, &s
  136. },
  137. Callback: func(fs any, a []string, w commands.StringWriter) error {
  138. return printCertCommand(f, fs, a, w)
  139. },
  140. })
  141. reg.Register(&commands.Command{
  142. Name: commands.PrintTunnel,
  143. ShortDescription: "Prints json details about a tunnel for the provided vpn addr",
  144. Flags: func() (*flag.FlagSet, any) {
  145. fl := flag.NewFlagSet("", flag.ContinueOnError)
  146. s := printTunnelFlags{}
  147. fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
  148. return fl, &s
  149. },
  150. Callback: func(fs any, a []string, w commands.StringWriter) error {
  151. return printTunnelCommand(f, fs, a, w)
  152. },
  153. })
  154. reg.Register(&commands.Command{
  155. Name: commands.PrintRelays,
  156. ShortDescription: "Prints json details about all relay info",
  157. Flags: func() (*flag.FlagSet, any) {
  158. fl := flag.NewFlagSet("", flag.ContinueOnError)
  159. s := printTunnelFlags{}
  160. fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
  161. return fl, &s
  162. },
  163. Callback: func(fs any, a []string, w commands.StringWriter) error {
  164. return printRelaysCommand(f, fs, a, w)
  165. },
  166. })
  167. reg.Register(&commands.Command{
  168. Name: commands.ChangeRemote,
  169. ShortDescription: "Changes the remote address used in the tunnel for the provided vpn addr",
  170. Flags: func() (*flag.FlagSet, any) {
  171. fl := flag.NewFlagSet("", flag.ContinueOnError)
  172. s := changeRemoteFlags{}
  173. fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
  174. return fl, &s
  175. },
  176. Callback: func(fs any, a []string, w commands.StringWriter) error {
  177. return changeRemoteCommand(f, fs, a, w)
  178. },
  179. })
  180. reg.Register(&commands.Command{
  181. Name: commands.CloseTunnel,
  182. ShortDescription: "Closes a tunnel for the provided vpn addr",
  183. Flags: func() (*flag.FlagSet, any) {
  184. fl := flag.NewFlagSet("", flag.ContinueOnError)
  185. s := closeTunnelFlags{}
  186. fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
  187. return fl, &s
  188. },
  189. Callback: func(fs any, a []string, w commands.StringWriter) error {
  190. return closeTunnelCommand(f, fs, a, w)
  191. },
  192. })
  193. reg.Register(&commands.Command{
  194. Name: commands.CreateTunnel,
  195. ShortDescription: "Creates a tunnel for the provided vpn address",
  196. Help: "The lighthouses will be queried for real addresses but you can provide one as well.",
  197. Flags: func() (*flag.FlagSet, any) {
  198. fl := flag.NewFlagSet("", flag.ContinueOnError)
  199. s := createTunnelFlags{}
  200. fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
  201. return fl, &s
  202. },
  203. Callback: func(fs any, a []string, w commands.StringWriter) error {
  204. return createTunnelCommand(f, fs, a, w)
  205. },
  206. })
  207. reg.Register(&commands.Command{
  208. Name: commands.QueryLighthouse,
  209. ShortDescription: "Query the lighthouses for the provided vpn address",
  210. Help: "This command is asynchronous. Only currently known udp addresses will be printed.",
  211. Callback: func(fs any, a []string, w commands.StringWriter) error {
  212. return queryLighthouseCommand(f, fs, a, w)
  213. },
  214. })
  215. }
  216. func listHostMapCommand(hl controlHostLister, a any, w commands.StringWriter) error {
  217. fs, ok := a.(*listHostMapFlags)
  218. if !ok {
  219. return fmt.Errorf("internal error: expected *listHostMapFlags but was %T", a)
  220. }
  221. var hm []ControlHostInfo
  222. if fs.ByIndex {
  223. hm = listHostMapIndexes(hl)
  224. } else {
  225. hm = listHostMapHosts(hl)
  226. }
  227. sort.Slice(hm, func(i, j int) bool {
  228. return hm[i].VpnAddrs[0].Compare(hm[j].VpnAddrs[0]) < 0
  229. })
  230. if fs.Json || fs.Pretty {
  231. js := json.NewEncoder(w.GetWriter())
  232. if fs.Pretty {
  233. js.SetIndent("", " ")
  234. }
  235. if err := js.Encode(hm); err != nil {
  236. return err
  237. }
  238. } else {
  239. for _, v := range hm {
  240. err := w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddrs, v.RemoteAddrs))
  241. if err != nil {
  242. return err
  243. }
  244. }
  245. }
  246. return nil
  247. }
  248. func listLighthouseAddrmapCommand(lightHouse *LightHouse, a any, w commands.StringWriter) error {
  249. fs, ok := a.(*listHostMapFlags)
  250. if !ok {
  251. return fmt.Errorf("internal error: expected *listHostMapFlags but was %T", a)
  252. }
  253. type lighthouseInfo struct {
  254. VpnAddr string `json:"vpnAddr"`
  255. Addrs *CacheMap `json:"addrs"`
  256. }
  257. lightHouse.RLock()
  258. addrMap := make([]lighthouseInfo, len(lightHouse.addrMap))
  259. x := 0
  260. for k, v := range lightHouse.addrMap {
  261. addrMap[x] = lighthouseInfo{
  262. VpnAddr: k.String(),
  263. Addrs: v.CopyCache(),
  264. }
  265. x++
  266. }
  267. lightHouse.RUnlock()
  268. sort.Slice(addrMap, func(i, j int) bool {
  269. return strings.Compare(addrMap[i].VpnAddr, addrMap[j].VpnAddr) < 0
  270. })
  271. if fs.Json || fs.Pretty {
  272. js := json.NewEncoder(w.GetWriter())
  273. if fs.Pretty {
  274. js.SetIndent("", " ")
  275. }
  276. if err := js.Encode(addrMap); err != nil {
  277. return err
  278. }
  279. } else {
  280. for _, v := range addrMap {
  281. b, err := json.Marshal(v.Addrs)
  282. if err != nil {
  283. return err
  284. }
  285. err = w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddr, string(b)))
  286. if err != nil {
  287. return err
  288. }
  289. }
  290. }
  291. return nil
  292. }
  293. // parseVpnAddr parses the vpn address a command takes as its first operand, failing to w
  294. // when there is none or it does not parse. noun is how the command's messages name it,
  295. // "vpn address" or "vpn addr", which the output golden pins per command.
  296. func parseVpnAddr(a []string, noun string, w commands.StringWriter) (netip.Addr, error) {
  297. if len(a) == 0 {
  298. return netip.Addr{}, commands.Fail(w, "No vpn address was provided")
  299. }
  300. vpnAddr, err := netip.ParseAddr(a[0])
  301. if err != nil {
  302. return netip.Addr{}, commands.Fail(w, fmt.Sprintf("The provided %s could not be parsed: %s", noun, a[0]))
  303. }
  304. return vpnAddr, nil
  305. }
  306. func versionCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  307. return w.WriteLine(ifce.version)
  308. }
  309. func queryLighthouseCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  310. vpnAddr, err := parseVpnAddr(a, "vpn address", w)
  311. if err != nil {
  312. return err
  313. }
  314. var cm *CacheMap
  315. rl := ifce.lightHouse.Query(vpnAddr)
  316. if rl != nil {
  317. cm = rl.CopyCache()
  318. }
  319. return json.NewEncoder(w.GetWriter()).Encode(cm)
  320. }
  321. func closeTunnelCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  322. flags, ok := fs.(*closeTunnelFlags)
  323. if !ok {
  324. return fmt.Errorf("internal error: expected *closeTunnelFlags but was %T", fs)
  325. }
  326. vpnAddr, err := parseVpnAddr(a, "vpn address", w)
  327. if err != nil {
  328. return err
  329. }
  330. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  331. if hostInfo == nil {
  332. return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
  333. }
  334. if !flags.LocalOnly {
  335. ifce.sendCloseTunnel(hostInfo)
  336. }
  337. ifce.closeTunnel(hostInfo)
  338. return w.WriteLine("Closed")
  339. }
  340. func createTunnelCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  341. flags, ok := fs.(*createTunnelFlags)
  342. if !ok {
  343. return fmt.Errorf("internal error: expected *createTunnelFlags but was %T", fs)
  344. }
  345. vpnAddr, err := parseVpnAddr(a, "vpn address", w)
  346. if err != nil {
  347. return err
  348. }
  349. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  350. if hostInfo != nil {
  351. return commands.Fail(w, "Tunnel already exists")
  352. }
  353. hostInfo = ifce.handshakeManager.QueryVpnAddr(vpnAddr)
  354. if hostInfo != nil {
  355. return commands.Fail(w, "Tunnel already handshaking")
  356. }
  357. var addr netip.AddrPort
  358. if flags.Address != "" {
  359. addr, err = netip.ParseAddrPort(flags.Address)
  360. if err != nil {
  361. return commands.Fail(w, "Address could not be parsed")
  362. }
  363. }
  364. // Set the remote from the callback, which StartHandshake runs under the handshake manager lock
  365. // before the hostinfo reaches the handshake loop or the static-host trigger, so the address is
  366. // in the RemoteList before the first handshake is sent.
  367. ifce.handshakeManager.StartHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  368. if addr.IsValid() {
  369. hh.hostinfo.SetRemote(addr)
  370. }
  371. })
  372. return w.WriteLine("Created")
  373. }
  374. func changeRemoteCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  375. flags, ok := fs.(*changeRemoteFlags)
  376. if !ok {
  377. return fmt.Errorf("internal error: expected *changeRemoteFlags but was %T", fs)
  378. }
  379. vpnAddr, err := parseVpnAddr(a, "vpn address", w)
  380. if err != nil {
  381. return err
  382. }
  383. if flags.Address == "" {
  384. return commands.Fail(w, "No address was provided")
  385. }
  386. addr, err := netip.ParseAddrPort(flags.Address)
  387. if err != nil {
  388. return commands.Fail(w, "Address could not be parsed")
  389. }
  390. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  391. if hostInfo == nil {
  392. return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
  393. }
  394. hostInfo.SetRemote(addr)
  395. return w.WriteLine("Changed")
  396. }
  397. func logLevelCommand(l *slog.Logger, fs any, a []string, w commands.StringWriter) error {
  398. ctrl, ok := l.Handler().(interface {
  399. GetLevel() slog.Level
  400. SetLevel(slog.Level)
  401. })
  402. if !ok {
  403. return commands.Fail(w, "Log level is not reconfigurable on this logger")
  404. }
  405. if len(a) == 0 {
  406. return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
  407. }
  408. level, err := logging.ParseLevel(strings.ToLower(a[0]))
  409. if err != nil {
  410. return commands.Fail(w, fmt.Sprintf("Unknown log level %s. Possible log levels: trace, debug, info, warn, error", a))
  411. }
  412. ctrl.SetLevel(level)
  413. return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
  414. }
  415. func logFormatCommand(l *slog.Logger, fs any, a []string, w commands.StringWriter) error {
  416. ctrl, ok := l.Handler().(interface {
  417. GetFormat() string
  418. SetFormat(string) error
  419. })
  420. if !ok {
  421. return commands.Fail(w, "Log format is not reconfigurable on this logger")
  422. }
  423. if len(a) == 0 {
  424. return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
  425. }
  426. if err := ctrl.SetFormat(strings.ToLower(a[0])); err != nil {
  427. return commands.Fail(w, fmt.Sprintf("Unable to set log format: %s", err))
  428. }
  429. return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
  430. }
  431. func printCertCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  432. args, ok := fs.(*printCertFlags)
  433. if !ok {
  434. return fmt.Errorf("internal error: expected *printCertFlags but was %T", fs)
  435. }
  436. cert := ifce.pki.getCertState().GetDefaultCertificate()
  437. if len(a) > 0 {
  438. vpnAddr, err := parseVpnAddr(a, "vpn addr", w)
  439. if err != nil {
  440. return err
  441. }
  442. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  443. if hostInfo == nil {
  444. return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
  445. }
  446. cert = hostInfo.GetCert().Certificate
  447. }
  448. if args.Json || args.Pretty {
  449. b, err := cert.MarshalJSON()
  450. if err != nil {
  451. return commands.Fail(w, fmt.Sprintf("Unable to marshal the certificate: %s", err))
  452. }
  453. if args.Pretty {
  454. buf := new(bytes.Buffer)
  455. if err := json.Indent(buf, b, "", " "); err != nil {
  456. return commands.Fail(w, fmt.Sprintf("Unable to marshal the certificate: %s", err))
  457. }
  458. b = buf.Bytes()
  459. }
  460. return w.WriteBytes(b)
  461. }
  462. if args.Raw {
  463. b, err := cert.MarshalPEM()
  464. if err != nil {
  465. return commands.Fail(w, fmt.Sprintf("Unable to marshal the certificate: %s", err))
  466. }
  467. return w.WriteBytes(b)
  468. }
  469. return w.WriteLine(cert.String())
  470. }
  471. func printRelaysCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  472. args, ok := fs.(*printTunnelFlags)
  473. if !ok {
  474. return fmt.Errorf("internal error: expected *printTunnelFlags but was %T", fs)
  475. }
  476. ifce.hostMap.RLock()
  477. relays := maps.Clone(ifce.hostMap.Relays)
  478. ifce.hostMap.RUnlock()
  479. type RelayFor struct {
  480. Error string `json:",omitempty"`
  481. Type string
  482. State string
  483. PeerAddr netip.Addr
  484. LocalIndex uint32
  485. RemoteIndex uint32
  486. RelayedThrough []netip.Addr
  487. }
  488. type RelayOutput struct {
  489. NebulaAddr netip.Addr
  490. RelayForAddrs []RelayFor
  491. }
  492. type CmdOutput struct {
  493. Relays []*RelayOutput
  494. }
  495. co := CmdOutput{}
  496. enc := json.NewEncoder(w.GetWriter())
  497. if args.Pretty {
  498. enc.SetIndent("", " ")
  499. }
  500. for k, v := range relays {
  501. ro := RelayOutput{NebulaAddr: v.vpnAddrs[0]}
  502. co.Relays = append(co.Relays, &ro)
  503. relayHI := ifce.hostMap.QueryVpnAddr(v.vpnAddrs[0])
  504. if relayHI == nil {
  505. ro.RelayForAddrs = append(ro.RelayForAddrs, RelayFor{Error: "could not find hostinfo"})
  506. continue
  507. }
  508. for _, vpnAddr := range relayHI.relayState.CopyRelayForIps() {
  509. rf := RelayFor{}
  510. r, ok := relayHI.relayState.GetRelayForByAddr(vpnAddr)
  511. if ok {
  512. t := ""
  513. switch r.Type {
  514. case ForwardingType:
  515. t = "forwarding"
  516. case TerminalType:
  517. t = "terminal"
  518. default:
  519. t = "unknown"
  520. }
  521. s := ""
  522. switch r.State {
  523. case Requested:
  524. s = "requested"
  525. case Established:
  526. s = "established"
  527. default:
  528. s = "unknown"
  529. }
  530. rf.LocalIndex = r.LocalIndex
  531. rf.RemoteIndex = r.RemoteIndex
  532. rf.PeerAddr = r.PeerAddr
  533. rf.Type = t
  534. rf.State = s
  535. if rf.LocalIndex != k {
  536. rf.Error = fmt.Sprintf("hostmap LocalIndex '%v' does not match RelayState LocalIndex", k)
  537. }
  538. }
  539. relayedHI := ifce.hostMap.QueryVpnAddr(vpnAddr)
  540. if relayedHI != nil {
  541. rf.RelayedThrough = append(rf.RelayedThrough, relayedHI.relayState.CopyRelayIps()...)
  542. }
  543. ro.RelayForAddrs = append(ro.RelayForAddrs, rf)
  544. }
  545. }
  546. return enc.Encode(co)
  547. }
  548. func printTunnelCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
  549. args, ok := fs.(*printTunnelFlags)
  550. if !ok {
  551. return fmt.Errorf("internal error: expected *printTunnelFlags but was %T", fs)
  552. }
  553. vpnAddr, err := parseVpnAddr(a, "vpn addr", w)
  554. if err != nil {
  555. return err
  556. }
  557. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  558. if hostInfo == nil {
  559. return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
  560. }
  561. enc := json.NewEncoder(w.GetWriter())
  562. if args.Pretty {
  563. enc.SetIndent("", " ")
  564. }
  565. return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges()))
  566. }
  567. func deviceInfoCommand(ifce *Interface, fs any, w commands.StringWriter) error {
  568. flags, ok := fs.(*deviceInfoFlags)
  569. if !ok {
  570. return fmt.Errorf("internal error: expected flags to be deviceInfoFlags but was %+v", fs)
  571. }
  572. data := struct {
  573. Name string `json:"name"`
  574. Cidr []netip.Prefix `json:"cidr"`
  575. }{
  576. Name: ifce.inside.Name(),
  577. Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
  578. }
  579. copy(data.Cidr, ifce.inside.Networks())
  580. if flags.Json || flags.Pretty {
  581. js := json.NewEncoder(w.GetWriter())
  582. if flags.Pretty {
  583. js.SetIndent("", " ")
  584. }
  585. return js.Encode(data)
  586. } else {
  587. return w.WriteLine(fmt.Sprintf("name=%v cidr=%v", data.Name, data.Cidr))
  588. }
  589. }
  590. // reloadCommand reloads the config and writes the result to the client. It reloads even if the client has gone away
  591. func reloadCommand(l *slog.Logger, c *config.C, w commands.StringWriter) error {
  592. writeErr := w.WriteLine("Reloading config")
  593. res := c.ReloadConfig()
  594. res.Log(l)
  595. if err := w.WriteLine(res.String()); writeErr == nil {
  596. writeErr = err
  597. }
  598. if writeErr != nil {
  599. return writeErr
  600. }
  601. if res.Err != nil || res.Failed {
  602. return &commands.Failure{Msg: res.String()}
  603. }
  604. return nil
  605. }