message.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build darwin || dragonfly || freebsd || netbsd || openbsd
  5. // +build darwin dragonfly freebsd netbsd openbsd
  6. package route
  7. // A Message represents a routing message.
  8. type Message interface {
  9. // Sys returns operating system-specific information.
  10. Sys() []Sys
  11. }
  12. // A Sys reprensents operating system-specific information.
  13. type Sys interface {
  14. // SysType returns a type of operating system-specific
  15. // information.
  16. SysType() SysType
  17. }
  18. // A SysType represents a type of operating system-specific
  19. // information.
  20. type SysType int
  21. const (
  22. SysMetrics SysType = iota
  23. SysStats
  24. )
  25. // ParseRIB parses b as a routing information base and returns a list
  26. // of routing messages.
  27. func ParseRIB(typ RIBType, b []byte) ([]Message, error) {
  28. if !typ.parseable() {
  29. return nil, errUnsupportedMessage
  30. }
  31. var msgs []Message
  32. nmsgs, nskips := 0, 0
  33. for len(b) > 4 {
  34. nmsgs++
  35. l := int(nativeEndian.Uint16(b[:2]))
  36. if l == 0 {
  37. return nil, errInvalidMessage
  38. }
  39. if len(b) < l {
  40. return nil, errMessageTooShort
  41. }
  42. if b[2] != rtmVersion {
  43. b = b[l:]
  44. continue
  45. }
  46. if w, ok := wireFormats[int(b[3])]; !ok {
  47. nskips++
  48. } else {
  49. m, err := w.parse(typ, b[:l])
  50. if err != nil {
  51. return nil, err
  52. }
  53. if m == nil {
  54. nskips++
  55. } else {
  56. msgs = append(msgs, m)
  57. }
  58. }
  59. b = b[l:]
  60. }
  61. // We failed to parse any of the messages - version mismatch?
  62. if nmsgs != len(msgs)+nskips {
  63. return nil, errMessageMismatch
  64. }
  65. return msgs, nil
  66. }