forked from quackduck/uniclip
-
Notifications
You must be signed in to change notification settings - Fork 2
/
uniclip.go
431 lines (403 loc) · 11.3 KB
/
uniclip.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
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
421
422
423
424
425
426
427
428
429
430
431
package main
import (
"bufio"
"bytes"
"compress/flate"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/gob"
"errors"
"fmt"
"golang.org/x/crypto/ssh/terminal"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"golang.org/x/crypto/scrypt"
)
var (
secondsBetweenChecksForClipChange = 1
helpMsg = `Uniclip - Universal Clipboard
With Uniclip, you can copy from one device and paste on another.
Usage: uniclip [--secure/-s] [--debug/-d] [ <address> | --help/-h ]
Examples:
uniclip # start a new clipboard
uniclip 192.168.86.24:53701 # join the clipboard at 192.168.86.24:53701
uniclip -d # start a new clipboard with debug output
uniclip -d --secure 192.168.86.24:53701 # join the clipboard with debug output and enable encryption
Running just ` + "`uniclip`" + ` will start a new clipboard.
It will also provide an address with which you can connect to the same clipboard with another device.
Refer to https://github.com/meliksah/uniclip for more information`
listOfClients = make([]*bufio.Writer, 0)
localClipboard string
printDebugInfo = false
version = "dev"
cryptoStrength = 16384
secure = false
password []byte
)
// TODO: Add a way to reconnect (if computer goes to sleep)
func main() {
if len(os.Args) > 4 {
handleError(errors.New("too many arguments"))
fmt.Println(helpMsg)
return
}
if hasOption, _ := argsHaveOption("help", "h"); hasOption {
fmt.Println(helpMsg)
return
}
if hasOption, i := argsHaveOption("debug", "d"); hasOption {
printDebugInfo = true
os.Args = removeElemFromSlice(os.Args, i) // delete the debug option and run again
main()
return
}
// --secure encrypts your data
if hasOption, i := argsHaveOption("secure", "s"); hasOption {
secure = true
os.Args = removeElemFromSlice(os.Args, i) // delete the secure option and run again
fmt.Print("Password for --secure: ")
password, _ = terminal.ReadPassword(int(syscall.Stdin))
fmt.Println()
main()
return
}
if hasOption, _ := argsHaveOption("version", "v"); hasOption {
fmt.Println(version)
return
}
if len(os.Args) == 2 { // has exactly one argument
ConnectToServer(os.Args[1])
return
}
makeServer()
}
func makeServer() {
fmt.Println("Starting a new clipboard")
l, err := net.Listen("tcp4", ":") //nolint // complains about binding to all interfaces
if err != nil {
handleError(err)
return
}
defer l.Close()
port := strconv.Itoa(l.Addr().(*net.TCPAddr).Port)
fmt.Println("Run", "`uniclip", getOutboundIP().String()+":"+port+"`", "to join this clipboard")
fmt.Println()
for {
c, err := l.Accept()
if err != nil {
handleError(err)
return
}
fmt.Println("Connected to device at " + c.RemoteAddr().String())
go HandleClient(c)
}
}
// Handle a client as a server
func HandleClient(c net.Conn) {
w := bufio.NewWriter(c)
listOfClients = append(listOfClients, w)
defer c.Close()
go MonitorSentClips(bufio.NewReader(c))
MonitorLocalClip(w)
}
// Connect to the server (which starts a new clipboard)
func ConnectToServer(address string) {
c, err := net.Dial("tcp4", address)
if c == nil {
handleError(err)
fmt.Println("Could not connect to", address)
return
}
if err != nil {
handleError(err)
return
}
defer func() { _ = c.Close() }()
fmt.Println("Connected to the clipboard")
go MonitorSentClips(bufio.NewReader(c))
MonitorLocalClip(bufio.NewWriter(c))
}
// monitors for changes to the local clipboard and writes them to w
func MonitorLocalClip(w *bufio.Writer) {
for {
localClipboard = getLocalClip()
//debug("clipboard changed so sending it. localClipboard =", localClipboard)
err := sendClipboard(w, localClipboard)
if err != nil {
handleError(err)
return
}
for localClipboard == getLocalClip() {
time.Sleep(time.Second * time.Duration(secondsBetweenChecksForClipChange))
}
}
}
// monitors for clipboards sent through r
func MonitorSentClips(r *bufio.Reader) {
var foreignClipboard string
var foreignClipboardBytes []byte
for {
err := gob.NewDecoder(r).Decode(&foreignClipboardBytes)
if err != nil {
if err == io.EOF {
return // no need to monitor: disconnected
}
handleError(err)
continue // continue getting next message
}
// decrypt if needed
if secure {
foreignClipboardBytes, err = decrypt(password, foreignClipboardBytes)
if err != nil {
handleError(err)
continue
}
} else {
foreignClipboardBytes = []byte(foreignClipboard)
}
foreignClipboard = string(foreignClipboardBytes)
// hacky way to prevent empty clipboard TODO: find out why empty cb happens
if foreignClipboard == "" {
continue
}
//foreignClipboard = decompress(foreignClipboardBytes)
setLocalClip(foreignClipboard)
localClipboard = foreignClipboard
debug("rcvd:", foreignClipboard)
for i := range listOfClients {
if listOfClients[i] != nil {
err = sendClipboard(listOfClients[i], foreignClipboard)
if err != nil {
listOfClients[i] = nil
fmt.Println("Error when trying to send the clipboard to a device. Will not contact that device again.")
}
}
}
}
}
// sendClipboard compresses and then if secure is enabled, encrypts data
func sendClipboard(w *bufio.Writer, clipboard string) error {
var clipboardBytes []byte
var err error
clipboardBytes = []byte(clipboard)
//clipboardBytes = compress(clipboard)
//fmt.Printf("cmpr: %x\ndcmp: %x\nstr: %s\n\ncmpr better by %d\n", clipboardBytes, []byte(clipboard), clipboard, len(clipboardBytes)-len(clipboard))
if secure {
clipboardBytes, err = encrypt(password, clipboardBytes)
if err != nil {
return err
}
} else {
clipboardBytes = []byte(clipboard)
}
err = gob.NewEncoder(w).Encode(clipboardBytes)
if err != nil {
return err
}
debug("sent:", clipboard)
//if secure {
// debug("--secure is enabled, so actually sent as:", hex.EncodeToString(clipboardBytes))
//}
return w.Flush()
}
// Thanks to https://bruinsslot.jp/post/golang-crypto/ for crypto logic
func encrypt(key, data []byte) ([]byte, error) {
key, salt, err := deriveKey(key, nil)
if err != nil {
return nil, err
}
blockCipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(blockCipher)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
ciphertext = append(ciphertext, salt...)
return ciphertext, nil
}
func decrypt(key, data []byte) ([]byte, error) {
salt, data := data[len(data)-32:], data[:len(data)-32]
key, _, err := deriveKey(key, salt)
if err != nil {
return nil, err
}
blockCipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(blockCipher)
if err != nil {
return nil, err
}
nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func deriveKey(password, salt []byte) ([]byte, []byte, error) {
if salt == nil {
salt = make([]byte, 32)
if _, err := rand.Read(salt); err != nil {
return nil, nil, err
}
}
key, err := scrypt.Key(password, salt, cryptoStrength, 8, 1, 32)
if err != nil {
return nil, nil, err
}
return key, salt, nil
}
func compress(str string) []byte {
var buf bytes.Buffer
zw, _ := flate.NewWriter(&buf, -1)
_, _ = zw.Write([]byte(str))
_ = zw.Close()
return buf.Bytes()
}
func decompress(b []byte) string {
var buf bytes.Buffer
_, _ = buf.Write(b)
zr := flate.NewReader(&buf)
decompressed, err := ioutil.ReadAll(zr)
if err != nil {
handleError(err)
return "Issues while decompressing clipboard"
}
_ = zr.Close()
return string(decompressed)
}
func runGetClipCommand() string {
var out []byte
var err error
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("pbpaste")
case "windows": //nolint // complains about literal string "windows" being used multiple times
cmd = exec.Command("powershell.exe", "-command", "Get-Clipboard")
default:
if _, err = exec.LookPath("xclip"); err == nil {
cmd = exec.Command("xclip", "-out", "-selection", "clipboard")
} else if _, err = exec.LookPath("xsel"); err == nil {
cmd = exec.Command("xsel", "--output", "--clipboard")
} else if _, err = exec.LookPath("wl-paste"); err == nil {
cmd = exec.Command("wl-paste", "--no-newline")
} else if _, err = exec.LookPath("termux-clipboard-get"); err == nil {
cmd = exec.Command("termux-clipboard-get")
} else {
handleError(errors.New("sorry, uniclip won't work if you don't have xsel, xclip, wayland or Termux installed :(\nyou can create an issue at https://github.com/meliksah/uniclip/issues"))
os.Exit(2)
}
}
if out, err = cmd.Output(); err != nil {
handleError(err)
return "An error occurred wile getting the local clipboard"
}
if runtime.GOOS == "windows" {
return strings.TrimSuffix(string(out), "\r\n") // powershell's get-clipboard adds a windows newline to the end for some reason
}
return string(out)
}
func getLocalClip() string {
str := runGetClipCommand()
//for ; str == ""; str = runGetClipCommand() { // wait until it's not empty
// time.Sleep(time.Millisecond * 100)
//}
return str
}
func setLocalClip(s string) {
var copyCmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
copyCmd = exec.Command("pbcopy")
case "windows":
copyCmd = exec.Command("clip")
default:
if _, err := exec.LookPath("xclip"); err == nil {
copyCmd = exec.Command("xclip", "-in", "-selection", "clipboard")
} else if _, err = exec.LookPath("xsel"); err == nil {
copyCmd = exec.Command("xsel", "--input", "--clipboard")
} else if _, err = exec.LookPath("wl-copy"); err == nil {
copyCmd = exec.Command("wl-copy")
} else if _, err = exec.LookPath("termux-clipboard-set"); err == nil {
copyCmd = exec.Command("termux-clipboard-set")
} else {
handleError(errors.New("sorry, uniclip won't work if you don't have xsel, xclip, wayland or Termux:API installed :(\nyou can create an issue at https://github.com/meliksah/uniclip/issues"))
os.Exit(2)
}
}
in, err := copyCmd.StdinPipe()
if err != nil {
handleError(err)
return
}
if err = copyCmd.Start(); err != nil {
handleError(err)
return
}
if _, err = in.Write([]byte(s)); err != nil {
handleError(err)
return
}
if err = in.Close(); err != nil {
handleError(err)
return
}
if err = copyCmd.Wait(); err != nil {
handleError(err)
return
}
}
func getOutboundIP() net.IP {
// https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go/37382208#37382208
conn, err := net.Dial("udp", "8.8.8.8:80") // address can be anything. Doesn't even have to exist
if err != nil {
handleError(err)
return nil
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
func handleError(err error) {
if err == io.EOF {
fmt.Println("Disconnected")
} else {
fmt.Fprintln(os.Stderr, "error: ["+err.Error()+"]")
}
}
func debug(a ...interface{}) {
if printDebugInfo {
fmt.Println("verbose:", a)
}
}
func argsHaveOption(long string, short string) (hasOption bool, foundAt int) {
for i, arg := range os.Args {
if arg == "--"+long || arg == "-"+short {
return true, i
}
}
return false, 0
}
// keep order
func removeElemFromSlice(slice []string, i int) []string {
return append(slice[:i], slice[i+1:]...)
}