Repository navigation
Expand file tree
/
Copy pathwol.go
More file actions
211 lines (195 loc) · 5.32 KB
/
Copy pathwol.go
File metadata and controls
211 lines (195 loc) · 5.32 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
package main
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net"
"net/netip"
"os"
"path/filepath"
"strings"
"time"
"github.com/zakijss/minideck/atomicfile"
)
var errMAC = message("A MAC address is six pairs of hex digits, like 3C:7C:3F:12:AB:9E.")
// ParseMAC reads a MAC address written with colons, dashes, dots or
// nothing between the digits.
func ParseMAC(s string) (net.HardwareAddr, error) {
var digits []byte
for _, c := range strings.TrimSpace(s) {
switch {
case c == ':' || c == '-' || c == '.' || c == ' ':
case c >= '0' && c <= '9', c >= 'a' && c <= 'f', c >= 'A' && c <= 'F':
digits = append(digits, byte(c))
default:
return nil, errMAC
}
}
if len(digits) != 12 {
return nil, errMAC
}
mac := make(net.HardwareAddr, 6)
if _, err := hex.Decode(mac, digits); err != nil {
return nil, errMAC
}
return mac, nil
}
// FormatMAC writes a MAC as AA:BB:CC:DD:EE:FF.
func FormatMAC(m net.HardwareAddr) string { return strings.ToUpper(m.String()) }
// MagicPacket is the Wake-on-LAN frame for mac: six 0xFF bytes, then the
// MAC sixteen times.
func MagicPacket(mac net.HardwareAddr) []byte {
p := make([]byte, 0, 102)
for i := 0; i < 6; i++ {
p = append(p, 0xff)
}
for i := 0; i < 16; i++ {
p = append(p, mac[:6]...)
}
return p
}
// wakePorts are where magic packets go: 9 (discard) is the usual one, 7
// (echo) the older one some network cards listen on.
var wakePorts = []int{9, 7}
// Wake sends the magic packet for mac to the network's broadcast address.
// Wi-Fi sends broadcasts once, unacknowledged, so it goes three times: the
// first synchronously (to report errors), the others in the background.
func Wake(sub Subnet, mac net.HardwareAddr) error {
if len(mac) != 6 {
return errMAC
}
c, err := net.ListenUDP("udp4", &net.UDPAddr{IP: sub.Self.AsSlice()})
if err != nil {
return err
}
pkt := MagicPacket(mac)
send := func() error {
var first error
for _, port := range wakePorts {
if _, err := c.WriteToUDP(pkt, &net.UDPAddr{IP: sub.Broadcast.AsSlice(), Port: port}); err != nil && first == nil {
first = err
}
}
return first
}
if err := send(); err != nil {
c.Close()
return err
}
go func() {
defer c.Close()
for i := 0; i < 2; i++ {
time.Sleep(150 * time.Millisecond)
send()
}
}()
return nil
}
// Device is a saved Wake-on-LAN target.
type Device struct {
Name string `json:"name"`
MAC string `json:"mac"`
IP string `json:"ip,omitempty"` // where a scan last saw it (for reference)
// Seen is when a scan last found it.
Seen time.Time `json:"seen,omitzero"`
}
// loadDevices reads devices.json; a missing file is an empty list.
func loadDevices(dir string) ([]Device, error) {
b, err := os.ReadFile(filepath.Join(dir, "devices.json"))
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, err
}
var f struct {
Devices []Device `json:"devices"`
}
if err := json.Unmarshal(b, &f); err != nil {
return nil, fmt.Errorf("devices.json: %w", err)
}
return f.Devices, nil
}
// saveDevices writes devices.json.
func saveDevices(dir string, ds []Device) error {
if ds == nil {
ds = []Device{}
}
b, err := json.MarshalIndent(struct {
Devices []Device `json:"devices"`
}{ds}, "", " ")
if err != nil {
return err
}
return atomicfile.Write(filepath.Join(dir, "devices.json"), append(b, '\n'), 0o644)
}
// After a wake-up, the device is watched at the address a scan last saw it
// at: one connection to each of awakePorts every wakeEvery, for at most
// wakeWait. Accepted or refused, any answer means it is up. Only one
// address on the Miyoo's own network is ever probed.
var (
awakePorts = []int{22, 80, 445, 3389, 5900}
wakeEvery = 3 * time.Second
wakeWait = 3 * time.Minute
)
// What the Wake tab says about the device last woken.
const (
wakeWaiting = "Waking…"
wakeAwake = "Awake"
wakeNoAnswer = "No answer"
)
// wakeCheck probes addr until it answers (true) or ctx ends (false).
func wakeCheck(ctx context.Context, addr netip.Addr, ports []int, every time.Duration) bool {
t := time.NewTicker(every)
defer t.Stop()
for {
for _, p := range ports {
if up, _ := probe(ctx, addr, p, portTimeout); up {
return true
}
}
select {
case <-ctx.Done():
return false
case <-t.C:
}
}
}
// watchWake starts watching d after a wake-up sent on sub, if its last
// address is known and on that network. Waking another device stops the
// previous watch.
func (a *app) watchWake(sub Subnet, d Device) {
if a.wakeCancel != nil {
a.wakeCancel()
}
a.wakeMAC, a.wakeState, a.wakeRes, a.wakeCancel = d.MAC, "", nil, nil
ip, err := netip.ParseAddr(d.IP)
if err != nil || !sub.Net.Contains(ip) || ip == sub.Self {
return
}
ctx, cancel := context.WithTimeout(context.Background(), wakeWait)
res := make(chan bool, 1)
a.wakeState, a.wakeRes, a.wakeCancel = wakeWaiting, res, cancel
go func() { res <- wakeCheck(ctx, ip, awakePorts, wakeEvery) }()
}
// woke records the watch's answer; a device that came up is saved as seen.
func (a *app) woke(awake bool) {
a.wakeCancel()
a.wakeRes, a.wakeCancel = nil, nil
if !awake {
a.wakeState = wakeNoAnswer
return
}
a.wakeState = wakeAwake
for i, d := range a.devices {
if strings.EqualFold(d.MAC, a.wakeMAC) {
a.devices[i].Seen = time.Now()
if err := saveDevices(a.dir, a.devices); err != nil {
log.Printf("devices: %v", err)
}
return
}
}
}