-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathzeroconf.go
More file actions
313 lines (254 loc) · 8.16 KB
/
zeroconf.go
File metadata and controls
313 lines (254 loc) · 8.16 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package zeroconf
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"net"
"net/http"
"sync"
librespot "github.com/devgianlu/go-librespot"
"github.com/devgianlu/go-librespot/dh"
devicespb "github.com/devgianlu/go-librespot/proto/spotify/connectstate/devices"
"github.com/devgianlu/go-librespot/zeroconf/discovery"
log "github.com/sirupsen/logrus"
)
type Zeroconf struct {
log librespot.Logger
deviceName string
deviceId string
deviceType devicespb.DeviceType
listener net.Listener
discovery discovery.Service
dh *dh.DiffieHellman
reqsChan chan NewUserRequest
authenticatingUser string
currentUser string
userLock sync.RWMutex
}
type NewUserRequest struct {
Username string
AuthBlob []byte
DeviceName string
result chan bool
}
type Options struct {
Log librespot.Logger
Port int
DeviceName string
DeviceId string
DeviceType devicespb.DeviceType
DiscoveryImplementation string
InterfacesToAdvertise []string
}
func NewZeroconf(opts Options) (_ *Zeroconf, err error) {
z := &Zeroconf{log: opts.Log, deviceId: opts.DeviceId, deviceName: opts.DeviceName, deviceType: opts.DeviceType}
z.reqsChan = make(chan NewUserRequest)
z.dh, err = dh.NewDiffieHellman()
if err != nil {
return nil, fmt.Errorf("failed initializing diffiehellman: %w", err)
}
z.listener, err = net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", opts.Port))
if err != nil {
return nil, fmt.Errorf("failed starting zeroconf listener: %w", err)
}
listenPort := z.listener.Addr().(*net.TCPAddr).Port
log.Infof("zeroconf server listening on port %d", listenPort)
var ifaces []net.Interface
for _, ifaceName := range opts.InterfacesToAdvertise {
liface, err := net.InterfaceByName(ifaceName)
if err != nil {
return nil, fmt.Errorf("failed to get info for network interface %s: %w", ifaceName, err)
}
ifaces = append(ifaces, *liface)
log.Info(fmt.Sprintf("advertising on network interface %s", ifaceName))
}
discoveryImpl := opts.DiscoveryImplementation
if discoveryImpl == "" {
discoveryImpl = "builtin"
}
z.discovery = discovery.GetService(discoveryImpl)
if z.discovery == nil {
return nil, fmt.Errorf("unknown discovery implementation: %s", discoveryImpl)
}
if err := z.discovery.Register(z.deviceName, "_spotify-connect._tcp", "local.", listenPort, []string{"CPath=/", "VERSION=1.0", "Stack=SP"}, ifaces); err != nil {
return nil, fmt.Errorf("failed registering zeroconf service: %w", err)
}
return z, nil
}
func (z *Zeroconf) SetCurrentUser(username string) {
z.userLock.Lock()
z.currentUser = username
z.userLock.Unlock()
}
// Close stops the zeroconf responder and HTTP listener,
// but does not close the last opened session.
func (z *Zeroconf) Close() {
z.discovery.Shutdown()
_ = z.listener.Close()
}
func (z *Zeroconf) handleGetInfo(writer http.ResponseWriter, _ *http.Request) error {
writer.WriteHeader(http.StatusOK)
// get current username holding the client
z.userLock.RLock()
currentUsername := z.currentUser
z.userLock.RUnlock()
return json.NewEncoder(writer).Encode(GetInfoResponse{
Status: 101,
StatusString: "OK",
SpotifyError: 0,
Version: "2.7.1",
LibraryVersion: librespot.VersionNumberString(),
AccountReq: "PREMIUM",
BrandDisplayName: "devgianlu",
ModelDisplayName: "go-librespot",
VoiceSupport: "NO",
Availability: "",
ProductID: 0,
TokenType: "default",
GroupStatus: "NONE",
ResolverVersion: "0",
Scope: "streaming,client-authorization-universal",
DeviceID: z.deviceId,
RemoteName: z.deviceName,
PublicKey: base64.StdEncoding.EncodeToString(z.dh.PublicKeyBytes()),
DeviceType: z.deviceType.String(),
ActiveUser: currentUsername,
})
}
func (z *Zeroconf) handleAddUser(writer http.ResponseWriter, request *http.Request) error {
username, blobStr, clientKeyStr, deviceName := request.Form.Get("userName"), request.Form.Get("blob"), request.Form.Get("clientKey"), request.Form.Get("deviceName")
if len(username) == 0 {
return fmt.Errorf("missing username")
} else if len(blobStr) == 0 {
return fmt.Errorf("missing blob")
} else if len(clientKeyStr) == 0 {
return fmt.Errorf("missing client key")
} else if len(deviceName) == 0 {
return fmt.Errorf("missing device name")
}
blob, err := base64.StdEncoding.DecodeString(blobStr)
if err != nil {
return fmt.Errorf("invalid blob: %w", err)
}
clientKey, err := base64.StdEncoding.DecodeString(clientKeyStr)
if err != nil {
return fmt.Errorf("invalid client key: %w", err)
}
// start handshake and decrypting of blob
sharedSecret := z.dh.Exchange(clientKey)
baseKey := func() []byte { sum := sha1.Sum(sharedSecret); return sum[:16] }()
iv, encrypted, checksum := blob[:16], blob[16:len(blob)-20], blob[len(blob)-20:]
mac := hmac.New(sha1.New, baseKey)
mac.Write([]byte("checksum"))
checksumKey := mac.Sum(nil)
mac.Reset()
mac.Write([]byte("encryption"))
encryptionKey := func() []byte { sum := mac.Sum(nil); return sum[:16] }()
mac = hmac.New(sha1.New, checksumKey)
mac.Write(encrypted)
if !bytes.Equal(mac.Sum(nil), checksum) {
z.log.Warnf("zeroconf received request with bad checksum")
writer.WriteHeader(http.StatusBadRequest)
return nil
}
bc, err := aes.NewCipher(encryptionKey)
if err != nil {
return fmt.Errorf("failed initializing aes cihper: %w", err)
}
decrypted := make([]byte, len(encrypted))
cipher.NewCTR(bc, iv).XORKeyStream(decrypted, encrypted)
z.userLock.Lock()
// check if we are authenticating the same user that is holding the session
if z.currentUser == username || z.authenticatingUser == username {
z.userLock.Unlock()
writer.WriteHeader(http.StatusOK)
return json.NewEncoder(writer).Encode(AddUserResponse{
Status: 101,
StatusString: "OK",
SpotifyError: 0,
})
}
if z.authenticatingUser != "" {
z.userLock.Unlock()
z.log.Debug("zeroconf is authenticating another user")
writer.WriteHeader(http.StatusForbidden)
return nil
}
z.authenticatingUser = username
z.userLock.Unlock()
// dispatch user request and wait response
resChan := make(chan bool)
z.reqsChan <- NewUserRequest{
Username: username,
AuthBlob: decrypted,
DeviceName: deviceName,
result: resChan,
}
// wait for auth result
res := <-resChan
z.userLock.Lock()
if !res {
z.authenticatingUser = ""
z.userLock.Unlock()
z.log.WithField("username", librespot.ObfuscateUsername(username)).
Infof("refused zeroconf from %s", deviceName)
writer.WriteHeader(http.StatusForbidden)
return nil
}
// update user holding the session
z.authenticatingUser = ""
z.currentUser = username
z.userLock.Unlock()
z.log.WithField("username", librespot.ObfuscateUsername(username)).
Infof("accepted zeroconf from %s", deviceName)
writer.WriteHeader(http.StatusOK)
return json.NewEncoder(writer).Encode(AddUserResponse{
Status: 101,
StatusString: "OK",
SpotifyError: 0,
})
}
type HandleNewRequestFunc func(req NewUserRequest) bool
func (z *Zeroconf) Serve(handler HandleNewRequestFunc) error {
defer z.discovery.Shutdown()
mux := http.NewServeMux()
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
if err := request.ParseForm(); err != nil {
z.log.WithError(err).Warn("failed handling invalid request form")
writer.WriteHeader(http.StatusBadRequest)
return
}
writer.Header().Set("Content-Type", "application/json")
action := request.Form.Get("action")
switch action {
case "getInfo":
if err := z.handleGetInfo(writer, request); err != nil {
z.log.WithError(err).Warn("failed handling zeroconf get info request")
writer.WriteHeader(http.StatusInternalServerError)
}
case "addUser":
if err := z.handleAddUser(writer, request); err != nil {
z.log.WithError(err).Warn("failed handling zeroconf add user request")
writer.WriteHeader(http.StatusInternalServerError)
}
default:
z.log.Warnf("unknown zeroconf action: %s", action)
writer.WriteHeader(http.StatusBadRequest)
}
})
serveErr := make(chan error, 1)
go func() { serveErr <- http.Serve(z.listener, mux) }()
for {
select {
case err := <-serveErr:
return err
case req := <-z.reqsChan:
req.result <- handler(req)
}
}
}