/
scan.go
329 lines (282 loc) · 7.83 KB
/
scan.go
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Copyright (C) 2021 Toitware ApS. All rights reserved.
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file.
package commands
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"sort"
"strings"
"time"
"github.com/libp2p/go-reuseport"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"github.com/toitlang/jaguar/cmd/jag/directory"
"github.com/toitware/ubjson"
"gopkg.in/yaml.v2"
)
const (
scanTimeout = 600 * time.Millisecond
scanPort = 1990
scanHttpPort = 9000
)
func ScanCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "scan [device-name-or-IP]",
Short: "Scan for Jaguar devices",
Long: "Scan for Jaguar devices.\n" +
"Unless 'device' is an address, listen for UDP packets broadcasted by the devices.\n" +
"In that case you need to be on the same network as the device.\n" +
"If a device selection is given, automatically select that device.\n" +
"If the device selection is an address, connect to it using TCP.",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
cfg, err := directory.GetDeviceConfig()
if err != nil {
return err
}
var autoSelect deviceSelect = nil
if len(args) == 1 {
autoSelect = parseDeviceSelection(args[0])
}
port, err := cmd.Flags().GetUint("port")
if err != nil {
return err
}
timeout, err := cmd.Flags().GetDuration("timeout")
if err != nil {
return err
}
outputter, err := parseOutputFlag(cmd)
if err != nil {
return err
}
if outputter != nil && autoSelect != nil {
return fmt.Errorf("listing and device-selection are exclusive")
}
cmd.SilenceUsage = true
if outputter != nil {
scanCtx, cancel := context.WithTimeout(ctx, scanTimeout)
var devices []Device
var err error
devices, err = scan(scanCtx, autoSelect, port)
cancel()
if err != nil {
return err
}
return outputter.Encode(Devices{devices})
}
device, _, err := scanAndPickDevice(ctx, timeout, port, autoSelect, false)
if err != nil {
return err
}
if autoSelect != nil {
outputter = yaml.NewEncoder(os.Stdout)
err = outputter.Encode(device)
if err != nil {
return err
}
}
cfg.Set("device", device)
return cfg.WriteConfig()
},
}
cmd.Flags().BoolP("list", "l", false, "if set, list the devices")
cmd.Flags().StringP("output", "o", "short", "set output format to json, yaml or short (works only with '--list')")
cmd.Flags().UintP("port", "p", scanPort, "UDP port to scan for devices on (ignored when an address is given)")
cmd.Flags().DurationP("timeout", "t", scanTimeout, "how long to scan")
return cmd
}
type deviceSelect interface {
Match(d Device) bool
Address() string
}
type deviceIDSelect string
func (s deviceIDSelect) Match(d Device) bool {
return string(s) == d.ID
}
func (s deviceIDSelect) Address() string {
return ""
}
func (s deviceIDSelect) String() string {
return fmt.Sprintf("device with ID: '%s'", string(s))
}
type deviceNameSelect string
func (s deviceNameSelect) Match(d Device) bool {
return string(s) == d.Name
}
func (s deviceNameSelect) Address() string {
return ""
}
func (s deviceNameSelect) String() string {
return fmt.Sprintf("device with name: '%s'", string(s))
}
type deviceAddressSelect string
func (s deviceAddressSelect) Match(d Device) bool {
// The device address contains the 'http://' prefix and a port number.
m := string(s)
if !strings.HasPrefix(m, "http://") {
m = "http://" + m
}
if !strings.Contains(m, ":") {
m += ":"
}
return strings.HasPrefix(d.Address, m)
}
func (s deviceAddressSelect) Address() string {
if strings.HasPrefix(string(s), "http://") {
// Trim the 'http://' prefix.
return string(s[7:])
}
return string(s)
}
func (s deviceAddressSelect) String() string {
return fmt.Sprintf("device with address: '%s'", string(s))
}
func scanAndPickDevice(ctx context.Context, scanTimeout time.Duration, port uint, autoSelect deviceSelect, manualPick bool) (*Device, bool, error) {
if autoSelect == nil {
fmt.Println("Scanning ...")
} else {
fmt.Println("Scanning for ", autoSelect)
}
scanCtx, cancel := context.WithTimeout(ctx, scanTimeout)
devices, err := scan(scanCtx, autoSelect, port)
cancel()
if err != nil {
return nil, false, err
}
if len(devices) == 0 {
return nil, false, fmt.Errorf("didn't find any Jaguar devices.\nPerhaps you need to be on the same wifi as the device.\nYou can also specify the IP address of the device")
}
if autoSelect != nil {
for _, d := range devices {
if autoSelect.Match(d) {
return &d, true, nil
}
}
if manualPick {
return nil, false, fmt.Errorf("couldn't find %s", autoSelect)
}
}
prompt := promptui.Select{
Label: "Choose what Jaguar device you want to use",
Items: devices,
Templates: &promptui.SelectTemplates{},
}
i, _, err := prompt.Run()
if err != nil {
return nil, false, fmt.Errorf("you didn't select anything")
}
res := devices[i]
return &res, false, nil
}
func scan(ctx context.Context, ds deviceSelect, port uint) ([]Device, error) {
if ds != nil && ds.Address() != "" {
addr := ds.Address()
if !strings.Contains(addr, ":") {
addr = addr + ":" + fmt.Sprint(scanHttpPort)
}
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+addr+"/identify", nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
buf, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("got non-OK from device: %s", res.Status)
}
dev, err := parseDevice(buf)
if err != nil {
return nil, fmt.Errorf("failed to parse identify. reason %w", err)
} else if dev == nil {
return nil, fmt.Errorf("invalid identify response")
}
return []Device{*dev}, nil
}
pc, err := reuseport.ListenPacket("udp4", fmt.Sprintf(":%d", port))
if err != nil {
return nil, err
}
defer pc.Close()
if deadline, ok := ctx.Deadline(); ok {
if err := pc.SetDeadline(deadline); err != nil {
return nil, err
}
}
devices := map[string]Device{}
looping:
for {
select {
case <-ctx.Done():
err := ctx.Err()
if err == context.DeadlineExceeded {
break looping
}
return nil, err
default:
}
buf := make([]byte, 1024)
n, _, err := pc.ReadFrom(buf)
if err != nil {
if isTimeoutError(err) {
break looping
}
return nil, err
}
dev, err := parseDevice(buf[:n])
if err != nil {
fmt.Println("Failed to parse identify", err)
} else if dev != nil {
devices[dev.Address] = *dev
}
}
var res []Device
for _, d := range devices {
res = append(res, d)
}
sort.Slice(res, func(i, j int) bool { return res[i].Name < res[j].Name })
return res, nil
}
type udpMessage struct {
Method string `json:"method"`
Payload map[string]interface{} `json:"payload"`
}
func parseDevice(bytes []byte) (*Device, error) {
var device Device
var msg udpMessage
if err := ubjson.Unmarshal(bytes, &msg); err != nil {
if err := json.Unmarshal(bytes, &msg); err != nil {
return nil, fmt.Errorf("could not parse message: %s. Reason: %w", string(bytes), err)
}
}
if msg.Method != "jaguar.identify" {
return nil, nil
}
// We marshal the payload into JSON again, so we can use the reflection
// based support in encoding/json to fill in the fields in the device
// struct before returning it.
payload, err := json.Marshal(msg.Payload)
if err != nil {
return nil, fmt.Errorf("failed to re-marshal jaguar.identify: %s. reason: %w", string(bytes), err)
}
if err := json.Unmarshal(payload, &device); err != nil {
return nil, fmt.Errorf("failed to parse payload of jaguar.identify: %s. reason: %w", string(bytes), err)
}
return &device, nil
}
func isTimeoutError(err error) bool {
e, ok := err.(net.Error)
return ok && e.Timeout()
}