-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.go
278 lines (268 loc) · 7.91 KB
/
main.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
/*
* Copyright (c) 2018-2019 Unrud <[email protected]>
*
* This file is part of Remote-Touchpad.
*
* Remote-Touchpad is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Remote-Touchpad is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Remote-Touchpad. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"flag"
"fmt"
"github.com/unrud/remote-touchpad/inputcontrol"
"github.com/unrud/remote-touchpad/terminal"
"golang.org/x/net/websocket"
"log"
mathrand "math/rand"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const (
defaultSecretLength int = 8
authenticationRateLimit time.Duration = time.Second / 10
authenticationRateBurst int = 10
challengeLength int = 8
defaultBind string = ":0"
version string = "1.4.8"
prettyAppName string = "Remote Touchpad"
)
type config struct {
UpdateRate uint `json:"updateRate"`
ScrollSpeed float64 `json:"scrollSpeed"`
MoveSpeed float64 `json:"moveSpeed"`
MouseScrollSpeed float64 `json:"mouseScrollSpeed"`
MouseMoveSpeed float64 `json:"mouseMoveSpeed"`
}
func processCommand(controller inputcontrol.Controller, command string) error {
if len(command) == 0 {
return errors.New("empty command")
}
if command == "S" {
return controller.PointerScroll(0, 0, true)
}
if command[0] == 't' {
text := command[1:]
if !utf8.ValidString(text) {
return errors.New("invalid utf-8")
}
return controller.KeyboardText(text)
}
arguments := strings.Split(command[1:], ";")
if command[0] == 'k' && len(arguments) != 1 ||
command[0] != 'k' && len(arguments) != 2 {
return errors.New("wrong number of arguments")
}
x, err := strconv.ParseInt(arguments[0], 10, 32)
if err != nil {
return err
}
if command[0] == 'k' {
if x < 0 || x >= int64(inputcontrol.KeyLimit) {
return errors.New("unsupported key")
}
return controller.KeyboardKey(inputcontrol.Key(x))
}
y, err := strconv.ParseInt(arguments[1], 10, 32)
if err != nil {
return err
}
if command[0] == 'm' {
return controller.PointerMove(int(x), int(y))
}
if command[0] == 's' {
return controller.PointerScroll(int(x), int(y), false)
}
if command[0] == 'S' {
return controller.PointerScroll(int(x), int(y), true)
}
if command[0] == 'b' {
if x < 0 || x >= int64(inputcontrol.PointerButtonLimit) {
return errors.New("unsupported pointer button")
}
b := true
if y == 0 {
b = false
}
return controller.PointerButton(inputcontrol.PointerButton(x), b)
}
return errors.New("unsupported command")
}
type challenge struct {
message, expectedResponse string
}
func (c challenge) verify(response string) bool {
return c.expectedResponse == response
}
func authenticationChallengeGenerator(secret string, challenges chan<- challenge) {
unsecureSource := mathrand.NewSource(time.Now().UnixNano())
unsecureRand := mathrand.New(unsecureSource)
b := make([]byte, challengeLength)
for {
if _, err := unsecureRand.Read(b[:]); err != nil {
log.Fatal(err)
}
message := base64.StdEncoding.EncodeToString(b[:])
mac := hmac.New(sha256.New, []byte(message))
mac.Write([]byte(secret))
challenges <- challenge{
message: message,
expectedResponse: base64.StdEncoding.EncodeToString(mac.Sum(nil)),
}
time.Sleep(authenticationRateLimit)
}
}
func secureRandBase64(length int) string {
b := make([]byte, length)
if _, err := rand.Read(b[:]); err != nil {
log.Fatal(err)
}
return base64.StdEncoding.EncodeToString(b[:])
}
func main() {
terminal.SetTitle(prettyAppName)
var bind, certFile, keyFile, secret string
var showVersion bool
var config config
flag.BoolVar(&showVersion, "version", false, "show program's version number and exit")
flag.StringVar(&bind, "bind", defaultBind, "bind server to [HOSTNAME]:PORT")
flag.StringVar(&secret, "secret", "", "shared secret for client authentication")
flag.StringVar(&certFile, "cert", "", "file containing TLS certificate")
flag.StringVar(&keyFile, "key", "", "file containing TLS private key")
flag.UintVar(&config.UpdateRate, "update-rate", 30, "number of updates per second")
flag.Float64Var(&config.MoveSpeed, "move-speed", 1, "move speed multiplier")
flag.Float64Var(&config.ScrollSpeed, "scroll-speed", 1, "scroll speed multiplier")
flag.Float64Var(&config.MouseMoveSpeed, "mouse-move-speed", 1, "mouse move speed multiplier")
flag.Float64Var(&config.MouseScrollSpeed, "mouse-scroll-speed", 1, "mouse scroll speed multiplier")
flag.Parse()
if showVersion {
fmt.Println(version)
return
}
if certFile != "" && keyFile == "" {
log.Fatal("TLS private key file missing")
}
if certFile == "" && keyFile != "" {
log.Fatal("TLS certificate file missing")
}
tls := certFile != "" && keyFile != ""
if secret == "" {
secret = secureRandBase64(defaultSecretLength)
}
if len(inputcontrol.Controllers) == 0 {
log.Fatal("compiled without controller")
}
var controller inputcontrol.Controller
var controllerName string
var platformErrs []error
for _, controllerInfo := range inputcontrol.Controllers {
controllerName = controllerInfo.Name
var err error
controller, err = controllerInfo.Init()
if err == nil {
break
} else {
var unsupportedErr *inputcontrol.UnsupportedPlatformError
wrappedErr := fmt.Errorf("%v controller: %w", controllerName, err)
if errors.As(err, &unsupportedErr) {
platformErrs = append(platformErrs, wrappedErr)
} else {
log.Fatal(wrappedErr)
}
}
}
if controller == nil {
log.Fatal(fmt.Errorf("unsupported platform:\n%w", errors.Join(platformErrs...)))
}
defer controller.Close()
authenticationChallenges := make(chan challenge, authenticationRateBurst)
go authenticationChallengeGenerator(secret, authenticationChallenges)
listener, err := net.Listen("tcp", bind)
if err != nil {
log.Fatal(err)
}
addr := listener.Addr().(*net.TCPAddr)
host := ""
bindHost, _, err := net.SplitHostPort(bind)
if err != nil {
log.Fatal(err)
}
for _, b := range addr.IP {
if b != 0 {
host = bindHost
break
}
}
if host == "" {
host = findDefaultHost()
}
port := addr.Port
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webdataFS)))
mux.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) {
var message string
challenge := <-authenticationChallenges
websocket.Message.Send(ws, challenge.message)
if err := websocket.Message.Receive(ws, &message); err != nil {
return
}
if !challenge.verify(message) {
return
}
websocket.JSON.Send(ws, config)
for {
if err := websocket.Message.Receive(ws, &message); err != nil {
return
}
if err := processCommand(controller, message); err != nil {
log.Print(fmt.Errorf("%s controller: %w", controllerName, err))
return
}
}
}))
domain := host
if port != 80 && !tls || port != 443 && tls {
domain = net.JoinHostPort(host, strconv.Itoa(port))
}
scheme := "http"
if tls {
scheme = "https"
}
url := fmt.Sprintf("%s://%s/#%s", scheme, domain, secret)
fmt.Println(url)
if qrCode, err := terminal.GenerateQRCode(url, terminal.SupportsColor(os.Stdout.Fd())); err == nil {
fmt.Print(qrCode)
} else {
log.Printf("QR code error: %v", err)
}
if !tls {
fmt.Println("▌ WARNING: TLS is not enabled ▐")
fmt.Println("▌Don't use in an untrusted network!▐")
}
if tls {
err = http.ServeTLS(listener, mux, certFile, keyFile)
} else {
err = http.Serve(listener, mux)
}
log.Fatal(err)
}