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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
local xxtea = require("./xxtea")
local text_protocols = require("./text")
local cfg = UI.Schema({
bind_ip = UI.Text("", {
label = "This computer's address",
placeholder = "blank = automatic",
tooltip = "The network address your program sends to. Blank listens on every network this computer is on. Restart after changing.",
}),
port = UI.Slider(0, {
label = "Port",
min = 0,
max = 65535,
step = 1,
tooltip = "The port your program sends to. 0 picks a random port on the next start. Restart after changing.",
}),
device_code = UI.Text("00000000", {
label = "Device code",
placeholder = "8 hex digits, e.g. AF425414",
tooltip = "The code your program is configured with. Restart after changing.",
}),
controller_ip = UI.Text("", {
label = "Controlling computer's address",
placeholder = "blank = private network addresses",
tooltip = "Only these addresses are answered. Separate several with commas. Blank answers this computer and private network addresses. Restart after changing.",
}),
})
local CMD_MOUSE_MOVE = 0xAEDE7345
local CMD_MOUSE_LEFT = 0x9823AE8D
local CMD_MOUSE_MIDDLE = 0x97A3AE8D
local CMD_MOUSE_RIGHT = 0x238D8212
local CMD_MOUSE_WHEEL = 0xFFEEAD38
local CMD_AUTOMOVE = 0xAEDE7346
local CMD_BEZIER = 0xA238455A
local CMD_KEYBOARD = 0x123C2C2F
local CMD_MONITOR = 0x27388020
local MOUSE = {
[CMD_MOUSE_MOVE] = "move",
[CMD_MOUSE_LEFT] = "buttons",
[CMD_MOUSE_MIDDLE] = "buttons",
[CMD_MOUSE_RIGHT] = "buttons",
[CMD_MOUSE_WHEEL] = "buttons",
[CMD_AUTOMOVE] = "timed",
[CMD_BEZIER] = "timed",
}
local HEADER_BYTES = 16
local MOUSE_BYTES = 72
local KEYBOARD_BYTES = 28
local ENCRYPTED_BYTES = 128
local MONITOR_ON = 0xAA55
local MAX_MOVE_MS = 10000
local RANDOM_PORTS = { 10001, 49151 }
local socket = nil
local code = 0
local key = nil
local allowed = nil
local held_buttons = {}
local held_keys = {}
local skipped = {}
local repress = {}
local monitor = nil
local motion_x, motion_y, motion_wheel = 0, 0, 0
local last_report = nil
local function set_button(n, down)
if down ~= (held_buttons[n] == true) then
if down then
HID.Down(`Mouse{n}`)
else
HID.Up(`Mouse{n}`)
end
held_buttons[n] = down or nil
end
end
local function set_buttons(mask)
for n = 1, 5 do
set_button(n, bit32.btest(mask, bit32.lshift(1, n - 1)))
end
end
local function press_usage(usage, down)
local ok, err = pcall(down and HID.Down or HID.Up, `usage:{usage}`)
if not ok then
if not skipped[usage] then
skipped[usage] = true
Log.Warn(`KMBox Net: skipped key usage {usage}: {err}`)
end
return
end
held_keys[usage] = down or nil
end
local function set_keys(data)
local want = {}
local ctrl = string.byte(data, HEADER_BYTES + 1)
for bit = 0, 7 do
if bit32.btest(ctrl, bit32.lshift(1, bit)) then
want[0xE0 + bit] = true
end
end
for i = HEADER_BYTES + 3, KEYBOARD_BYTES do
local usage = string.byte(data, i)
if usage ~= 0 then
want[usage] = true
end
end
for usage in pairs(held_keys) do
if not want[usage] then
press_usage(usage, false)
end
end
for usage in pairs(want) do
if not held_keys[usage] then
press_usage(usage, true)
end
end
end
local function timed_move(dx, dy, ms, done)
Run(function()
local start = os.clock()
local sent_x, sent_y = 0, 0
local t = 0
while t < 1 do
Sleep(1)
t = if ms > 0 then math.min(1, (os.clock() - start) * 1000 / ms) else 1
local x, y = math.round(dx * t), math.round(dy * t)
if x ~= sent_x or y ~= sent_y then
HID.Move(x - sent_x, y - sent_y)
sent_x, sent_y = x, y
end
end
done()
end)
end
local text = text_protocols.new({
button = set_button,
key = press_usage,
send = function(ip, port, bytes)
socket:SendTo(ip, port, bytes)
end,
})
local function handle(data, ip, port)
if data:match("^[%g%s]+$") and data:find("(", 1, true) then
local reply = text.handle(data, ip)
if reply then
socket:SendTo(ip, port, reply)
end
return
end
local plain = #data >= HEADER_BYTES and string.unpack("<I4", data) == code
if not plain and #data >= ENCRYPTED_BYTES then
data = xxtea.decrypt(string.sub(data, 1, ENCRYPTED_BYTES), key)
end
if #data < HEADER_BYTES then
return
end
local device, rand, _, cmd = string.unpack("<I4I4I4I4", data)
if device ~= code then
return
end
local head = string.sub(data, 1, HEADER_BYTES)
local function reply()
socket:SendTo(ip, port, head)
end
local kind = MOUSE[cmd]
if kind then
if #data < MOUSE_BYTES then
return
end
local button, x, y, wheel =
string.unpack("<i4i4i4i4", data, HEADER_BYTES + 1)
if kind == "timed" then
timed_move(x, y, math.min(rand, MAX_MOVE_MS), reply)
return
end
if kind == "buttons" then
set_buttons(button)
end
if x ~= 0 or y ~= 0 then
HID.Move(x, y)
end
if wheel ~= 0 then
HID.Scroll(-wheel)
end
elseif cmd == CMD_KEYBOARD then
if #data < KEYBOARD_BYTES then
return
end
set_keys(data)
elseif cmd == CMD_MONITOR then
local high = bit32.rshift(rand, 16)
if rand ~= 0 and (high == MONITOR_ON or high == 0xFFFF) then
monitor = { ip = ip, port = bit32.band(rand, 0xFFFF) }
last_report = nil
else
monitor = nil
end
end
reply()
end
local function parse_config()
local ip = cfg.bind_ip:match("^%s*(.-)%s*$")
if ip == "" then
ip = "0.0.0.0"
elseif ip:find(":") then
error("KMBox Net: This computer's address must be an IPv4 address")
end
local device = cfg.device_code:match("^%s*(.-)%s*$")
if device == "" then
device = "00000000"
end
local hex = device:match("^%x%x%x%x%x%x%x%x$")
if not hex then
error("KMBox Net: set Device code to the 8 hex digits your program uses")
end
local controllers = {}
for addr in cfg.controller_ip:gmatch("[^,%s]+") do
controllers[addr] = true
end
return ip, tonumber(hex, 16), if next(controllers) then controllers else nil
end
local function is_local(ip)
local a, b = ip:match("^(%d+)%.(%d+)%.%d+%.%d+$")
a, b = tonumber(a), tonumber(b)
return a == 127
or a == 10
or (a == 172 and b ~= nil and b >= 16 and b <= 31)
or (a == 192 and b == 168)
or (a == 169 and b == 254)
end
local function on_datagram(data, from, port)
if allowed then
if not allowed[from] then
return
end
elseif not is_local(from) then
return
end
local ok, err = pcall(handle, data, from, port)
if not ok then
Log.Warn(`KMBox Net: {err}`)
end
end
local function listen(ip)
if cfg.port ~= 0 then
local ok, result = pcall(Net.UDPListen, ip, cfg.port, on_datagram)
if not ok then
error(
`KMBox Net: port {cfg.port} is unavailable; choose another or set 0 for a random one ({result})`
)
end
return result
end
for _ = 1, 5 do
local ok, result = pcall(
Net.UDPListen,
ip,
math.floor(Math.Random(RANDOM_PORTS[1], RANDOM_PORTS[2])),
on_datagram
)
if ok then
cfg.port = result.port
return result
end
end
error("KMBox Net: no free random port found; set Port to a free port")
end
function OnStart()
local ip, device, controllers = parse_config()
code, key, allowed = device, xxtea.key_for(device), controllers
socket = listen(ip)
local shown = ip
if ip == "0.0.0.0" then
local likely = Net.LocalIP and Net.LocalIP()
shown = if likely then `{likely} (likely)` else "all addresses"
end
Log.Info(
`KMBox Net listening on {ip}:{socket.port}, code {string.format(
"%08X",
device
)}`
)
UI.Notify(`KMBox Net: {shown}, port {socket.port}`, "success")
end
function OnStop()
if socket then
socket:Stop()
socket = nil
end
held_buttons, held_keys, skipped, repress = {}, {}, {}, {}
monitor, last_report = nil, nil
text.reset()
end
function OnInputUp(name)
repress[name] = true
end
local function restore_held()
for name in pairs(repress) do
local button = tonumber(name:match("^Mouse(%d)$"))
local usage = HID.Usage(name)
if button and held_buttons[button] then
HID.Down(name)
elseif usage and held_keys[usage] then
HID.Down(`usage:{usage}`)
end
end
table.clear(repress)
end
function OnInputMove(dx, dy)
motion_x += dx
motion_y += dy
end
function OnInputScroll(delta)
motion_wheel += delta
end
local function clamp16(n)
return math.clamp(n, -32768, 32767)
end
function OnTick()
restore_held()
text.tick()
if not monitor then
motion_x, motion_y, motion_wheel = 0, 0, 0
return
end
local buttons = 0
for n = 1, 5 do
if Input.IsDown(`Mouse{n}`) then
buttons = bit32.bor(buttons, bit32.lshift(1, n - 1))
end
end
local mods, keys = 0, {}
for _, name in Input.GetActiveKeys() do
local usage = HID.Usage(name)
if usage and usage >= 0xE0 then
mods = bit32.bor(mods, bit32.lshift(1, usage - 0xE0))
elseif usage and #keys < 10 then
table.insert(keys, usage)
end
end
table.sort(keys)
for i = #keys + 1, 10 do
keys[i] = 0
end
local report = string.pack(
"<BBhhhBB" .. string.rep("B", 10),
1,
buttons,
clamp16(motion_x),
clamp16(motion_y),
clamp16(motion_wheel),
1,
mods,
table.unpack(keys)
)
local moved = motion_x ~= 0 or motion_y ~= 0 or motion_wheel ~= 0
motion_x, motion_y, motion_wheel = 0, 0, 0
if moved or report ~= last_report then
last_report = report
socket:SendTo(monitor.ip, monitor.port, report)
end
end