File: deviceid.go

package info (click to toggle)
syncthing 1.29.5~ds1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 22,848 kB
  • sloc: javascript: 37,288; sh: 1,838; xml: 1,115; makefile: 66
file content (230 lines) | stat: -rw-r--r-- 4,989 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package protocol

import (
	"bytes"
	"crypto/sha256"
	"encoding/base32"
	"encoding/binary"
	"errors"
	"fmt"
	"strings"
)

const (
	DeviceIDLength = 32
	// keep consistent with shortIDStringLength in gui/default/syncthing/app.js
	ShortIDStringLength = 7
)

type (
	DeviceID [DeviceIDLength]byte
	ShortID  uint64
)

var (
	LocalDeviceID  = repeatedDeviceID(0xff)
	GlobalDeviceID = repeatedDeviceID(0xf8)
	EmptyDeviceID  = DeviceID{ /* all zeroes */ }
)

func repeatedDeviceID(v byte) (d DeviceID) {
	for i := range d {
		d[i] = v
	}
	return
}

// NewDeviceID generates a new device ID from SHA256 hash of the given piece
// of data (usually raw certificate bytes).
func NewDeviceID(rawCert []byte) DeviceID {
	return DeviceID(sha256.Sum256(rawCert))
}

// DeviceIDFromString parses a device ID from a string. The string is expected
// to be in the canonical format, with check digits.
func DeviceIDFromString(s string) (DeviceID, error) {
	var n DeviceID
	err := n.UnmarshalText([]byte(s))
	return n, err
}

// DeviceIDFromBytes converts a 32 byte slice to a DeviceID. A slice of the
// wrong length results in an error.
func DeviceIDFromBytes(bs []byte) (DeviceID, error) {
	var n DeviceID
	if len(bs) != len(n) {
		return n, errors.New("incorrect length of byte slice representing device ID")
	}
	copy(n[:], bs)
	return n, nil
}

// String returns the canonical string representation of the device ID
func (n DeviceID) String() string {
	if n == EmptyDeviceID {
		return ""
	}
	id := base32.StdEncoding.EncodeToString(n[:])
	id = strings.Trim(id, "=")
	id, err := luhnify(id)
	if err != nil {
		// Should never happen
		panic(err)
	}
	id = chunkify(id)
	return id
}

func (n DeviceID) GoString() string {
	return n.String()
}

func (n DeviceID) Compare(other DeviceID) int {
	return bytes.Compare(n[:], other[:])
}

func (n DeviceID) Equals(other DeviceID) bool {
	return bytes.Equal(n[:], other[:])
}

// Short returns an integer representing bits 0-63 of the device ID.
func (n DeviceID) Short() ShortID {
	return ShortID(binary.BigEndian.Uint64(n[:]))
}

func (n DeviceID) MarshalText() ([]byte, error) {
	return []byte(n.String()), nil
}

func (s ShortID) String() string {
	if s == 0 {
		return ""
	}
	var bs [8]byte
	binary.BigEndian.PutUint64(bs[:], uint64(s))
	return base32.StdEncoding.EncodeToString(bs[:])[:ShortIDStringLength]
}

func (n *DeviceID) UnmarshalText(bs []byte) error {
	id := string(bs)
	id = strings.Trim(id, "=")
	id = strings.ToUpper(id)
	id = untypeoify(id)
	id = unchunkify(id)

	var err error
	switch len(id) {
	case 0:
		*n = EmptyDeviceID
		return nil
	case 56:
		// New style, with check digits
		id, err = unluhnify(id)
		if err != nil {
			return err
		}
		fallthrough
	case 52:
		// Old style, no check digits
		dec, err := base32.StdEncoding.DecodeString(id + "====")
		if err != nil {
			return err
		}
		copy(n[:], dec)
		return nil
	default:
		return fmt.Errorf("%q: device ID invalid: incorrect length", bs)
	}
}

func (*DeviceID) ProtoSize() int {
	// Used by protobuf marshaller.
	return DeviceIDLength
}

func (n *DeviceID) MarshalTo(bs []byte) (int, error) {
	// Used by protobuf marshaller.
	if len(bs) < DeviceIDLength {
		return 0, errors.New("destination too short")
	}
	copy(bs, (*n)[:])
	return DeviceIDLength, nil
}

func (n *DeviceID) Unmarshal(bs []byte) error {
	// Used by protobuf marshaller.
	if len(bs) < DeviceIDLength {
		return fmt.Errorf("%q: not enough data", bs)
	}
	copy((*n)[:], bs)
	return nil
}

func luhnify(s string) (string, error) {
	if len(s) != 52 {
		panic("unsupported string length")
	}

	res := make([]byte, 4*(13+1))
	for i := 0; i < 4; i++ {
		p := s[i*13 : (i+1)*13]
		copy(res[i*(13+1):], p)
		l, err := luhn32(p)
		if err != nil {
			return "", err
		}
		res[(i+1)*(13)+i] = byte(l)
	}
	return string(res), nil
}

func unluhnify(s string) (string, error) {
	if len(s) != 56 {
		return "", fmt.Errorf("%q: unsupported string length %d", s, len(s))
	}

	res := make([]byte, 52)
	for i := 0; i < 4; i++ {
		p := s[i*(13+1) : (i+1)*(13+1)-1]
		copy(res[i*13:], p)
		l, err := luhn32(p)
		if err != nil {
			return "", err
		}
		if s[(i+1)*14-1] != byte(l) {
			return "", fmt.Errorf("%q: check digit incorrect", s)
		}
	}
	return string(res), nil
}

func chunkify(s string) string {
	chunks := len(s) / 7
	res := make([]byte, chunks*(7+1)-1)
	for i := 0; i < chunks; i++ {
		if i > 0 {
			res[i*(7+1)-1] = '-'
		}
		copy(res[i*(7+1):], s[i*7:(i+1)*7])
	}
	return string(res)
}

func unchunkify(s string) string {
	s = strings.ReplaceAll(s, "-", "")
	s = strings.ReplaceAll(s, " ", "")
	return s
}

func untypeoify(s string) string {
	s = strings.ReplaceAll(s, "0", "O")
	s = strings.ReplaceAll(s, "1", "I")
	s = strings.ReplaceAll(s, "8", "B")
	return s
}