deviceid.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "encoding/base32"
  6. "encoding/binary"
  7. "errors"
  8. "fmt"
  9. "strings"
  10. "github.com/calmh/luhn"
  11. "github.com/syncthing/syncthing/lib/sha256"
  12. )
  13. const DeviceIDLength = 32
  14. type DeviceID [DeviceIDLength]byte
  15. type ShortID uint64
  16. var (
  17. LocalDeviceID = DeviceID{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  18. EmptyDeviceID = DeviceID{ /* all zeroes */ }
  19. )
  20. // NewDeviceID generates a new device ID from the raw bytes of a certificate
  21. func NewDeviceID(rawCert []byte) DeviceID {
  22. var n DeviceID
  23. hf := sha256.New()
  24. hf.Write(rawCert)
  25. hf.Sum(n[:0])
  26. return n
  27. }
  28. func DeviceIDFromString(s string) (DeviceID, error) {
  29. var n DeviceID
  30. err := n.UnmarshalText([]byte(s))
  31. return n, err
  32. }
  33. func DeviceIDFromBytes(bs []byte) DeviceID {
  34. var n DeviceID
  35. if len(bs) != len(n) {
  36. panic("incorrect length of byte slice representing device ID")
  37. }
  38. copy(n[:], bs)
  39. return n
  40. }
  41. // String returns the canonical string representation of the device ID
  42. func (n DeviceID) String() string {
  43. if n == EmptyDeviceID {
  44. return ""
  45. }
  46. id := base32.StdEncoding.EncodeToString(n[:])
  47. id = strings.Trim(id, "=")
  48. id, err := luhnify(id)
  49. if err != nil {
  50. // Should never happen
  51. panic(err)
  52. }
  53. id = chunkify(id)
  54. return id
  55. }
  56. func (n DeviceID) GoString() string {
  57. return n.String()
  58. }
  59. func (n DeviceID) Compare(other DeviceID) int {
  60. return bytes.Compare(n[:], other[:])
  61. }
  62. func (n DeviceID) Equals(other DeviceID) bool {
  63. return bytes.Equal(n[:], other[:])
  64. }
  65. // Short returns an integer representing bits 0-63 of the device ID.
  66. func (n DeviceID) Short() ShortID {
  67. return ShortID(binary.BigEndian.Uint64(n[:]))
  68. }
  69. func (n *DeviceID) MarshalText() ([]byte, error) {
  70. return []byte(n.String()), nil
  71. }
  72. func (s ShortID) String() string {
  73. if s == 0 {
  74. return ""
  75. }
  76. var bs [8]byte
  77. binary.BigEndian.PutUint64(bs[:], uint64(s))
  78. return base32.StdEncoding.EncodeToString(bs[:])[:7]
  79. }
  80. func (n *DeviceID) UnmarshalText(bs []byte) error {
  81. id := string(bs)
  82. id = strings.Trim(id, "=")
  83. id = strings.ToUpper(id)
  84. id = untypeoify(id)
  85. id = unchunkify(id)
  86. var err error
  87. switch len(id) {
  88. case 0:
  89. *n = EmptyDeviceID
  90. return nil
  91. case 56:
  92. // New style, with check digits
  93. id, err = unluhnify(id)
  94. if err != nil {
  95. return err
  96. }
  97. fallthrough
  98. case 52:
  99. // Old style, no check digits
  100. dec, err := base32.StdEncoding.DecodeString(id + "====")
  101. if err != nil {
  102. return err
  103. }
  104. copy(n[:], dec)
  105. return nil
  106. default:
  107. return fmt.Errorf("%q: device ID invalid: incorrect length", bs)
  108. }
  109. }
  110. func (n *DeviceID) ProtoSize() int {
  111. // Used by protobuf marshaller.
  112. return DeviceIDLength
  113. }
  114. func (n *DeviceID) MarshalTo(bs []byte) (int, error) {
  115. // Used by protobuf marshaller.
  116. if len(bs) < DeviceIDLength {
  117. return 0, errors.New("destination too short")
  118. }
  119. copy(bs, (*n)[:])
  120. return DeviceIDLength, nil
  121. }
  122. func (n *DeviceID) Unmarshal(bs []byte) error {
  123. // Used by protobuf marshaller.
  124. if len(bs) < DeviceIDLength {
  125. return fmt.Errorf("%q: not enough data", bs)
  126. }
  127. copy((*n)[:], bs)
  128. return nil
  129. }
  130. func luhnify(s string) (string, error) {
  131. if len(s) != 52 {
  132. panic("unsupported string length")
  133. }
  134. res := make([]byte, 4*(13+1))
  135. for i := 0; i < 4; i++ {
  136. p := s[i*13 : (i+1)*13]
  137. copy(res[i*(13+1):], p)
  138. l, err := luhn.Base32.Generate(p)
  139. if err != nil {
  140. return "", err
  141. }
  142. res[(i+1)*(13)+i] = byte(l)
  143. }
  144. return string(res), nil
  145. }
  146. func unluhnify(s string) (string, error) {
  147. if len(s) != 56 {
  148. return "", fmt.Errorf("%q: unsupported string length %d", s, len(s))
  149. }
  150. res := make([]byte, 52)
  151. for i := 0; i < 4; i++ {
  152. p := s[i*(13+1) : (i+1)*(13+1)-1]
  153. copy(res[i*13:], p)
  154. l, err := luhn.Base32.Generate(p)
  155. if err != nil {
  156. return "", err
  157. }
  158. if s[(i+1)*14-1] != byte(l) {
  159. return "", fmt.Errorf("%q: check digit incorrect", s)
  160. }
  161. }
  162. return string(res), nil
  163. }
  164. func chunkify(s string) string {
  165. chunks := len(s) / 7
  166. res := make([]byte, chunks*(7+1)-1)
  167. for i := 0; i < chunks; i++ {
  168. if i > 0 {
  169. res[i*(7+1)-1] = '-'
  170. }
  171. copy(res[i*(7+1):], s[i*7:(i+1)*7])
  172. }
  173. return string(res)
  174. }
  175. func unchunkify(s string) string {
  176. s = strings.Replace(s, "-", "", -1)
  177. s = strings.Replace(s, " ", "", -1)
  178. return s
  179. }
  180. func untypeoify(s string) string {
  181. s = strings.Replace(s, "0", "O", -1)
  182. s = strings.Replace(s, "1", "I", -1)
  183. s = strings.Replace(s, "8", "B", -1)
  184. return s
  185. }
  186. // DeviceIDs is a sortable slice of DeviceID
  187. type DeviceIDs []DeviceID
  188. func (l DeviceIDs) Len() int {
  189. return len(l)
  190. }
  191. func (l DeviceIDs) Less(a, b int) bool {
  192. return l[a].Compare(l[b]) == -1
  193. }
  194. func (l DeviceIDs) Swap(a, b int) {
  195. l[a], l[b] = l[b], l[a]
  196. }