deviceid.go 4.9 KB

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