-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclipboard-server
executable file
·417 lines (383 loc) · 11.6 KB
/
clipboard-server
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
#!/usr/bin/env node
/**
* title : clipboard-server
* description : Forward clipboard access over a http socket
* author : Wei Kin Huang
* date : 2022-05-28
* version : 1.0.0
* requires : node pbcopy pbpaste quick-toast
* =============================================================================
* Usage: clipboard-server COMMAND [OPTION]...
* Forward clipboard access over a http socket.
* Example: clipboard-server start --enable-paste
*
* Commands:
* start Run the server in the background
* stop Stop the server if it is running
* restart Restart the server
* server Start the server in the foreground
*
* Options:
* -e, --enable-paste Disable local clipboard access, only alloys the remote
* server to send contents to local clipboard.
* default: false
* -n, --notify Show a notification when the clipboard is accessed
* default: false
* -p, --pidfile FILE Path to the pid file for the server.
* default: ~/.config/clipboard-server/clipboard-server.pid
* -s, --socket FILE|PORT A port number or path to the socket file location
* default: ~/.config/clipboard-server/clipboard-server.sock
*
* Using over SSH
*
* Via binding a socket on the remote host
* ssh -o StreamLocalBindMask=0177 -R /tmp/clipboard-server.sock:$HOME/.config/clipboard-server/clipboard-server.sock user@HOST
* If the remote host doesn't have StreamLocalBindUnlink=yes in sshd_config, it will not clean up the socket file, in
* this case use a port instead
*
* Via binding a port on the remote host
* ssh -R 127.0.0.1:29009:$HOME/.config/clipboard-server/clipboard-server.sock user@HOST
*
* This server is integrated with the dotfiles provided pbcopy/pbpaste commands when used over ssh, additionally a env
* var must be exported on the remote host to make use of this server:
*
* export CLIPBOARD_SERVER_PORT=29009 # the remote bound port
* or if using a socket (the default is /tmp/clipboard-server.sock if not set)
* export CLIPBOARD_SERVER_SOCK=/tmp/clipboard-server.sock
*
* Testing
*
* To read from the clipboard
* curl -sSLi --unix-socket ~/.config/clipboard-server/clipboard-server.sock -X GET http://localhost/clipboard
*
* To write to the clipboard
* date | curl -i -sSL --unix-socket ~/.config/clipboard-server/clipboard-server.sock http://localhost/clipboard --data-binary @-
*/
const http = require("http");
const childProcess = require("child_process");
// const fs = require("fs/promises");
const os = require("os");
const path = require("path");
const legacyFs = require("fs");
const { promisify } = require("util");
// proxy for fs/promises until node 18 is standard
const fs = {
stat: promisify(legacyFs.stat),
mkdir: promisify(legacyFs.mkdir),
readFile: promisify(legacyFs.readFile),
unlink: promisify(legacyFs.unlink),
writeFile: promisify(legacyFs.writeFile),
}
// set umask for files to be 0600
process.umask(0o0177);
async function setClipboard(req, res) {
return await new Promise((resolve, reject) => {
const subprocess = childProcess.spawn("pbcopy", {
stdio: ["pipe", "pipe", process.stderr],
});
subprocess.on("exit", resolve);
subprocess.on("error", reject);
req.on("error", reject);
req.on("end", resolve);
// echo 123 | curl -i 127.0.0.1:9999/clipboard --data-binary @-
req.pipe(subprocess.stdin);
subprocess.stdout.pipe(res);
});
}
async function getClipboard(res) {
return await new Promise((resolve, reject) => {
const subprocess = childProcess.spawn("pbpaste", {
stdio: ["pipe", "pipe", process.stderr],
});
subprocess.on("exit", resolve);
subprocess.on("error", reject);
res.on("error", reject);
res.on("end", resolve);
// curl -i 127.0.0.1:9999/clipboard
subprocess.stdout.pipe(res);
});
}
async function showNotification(message) {
return await new Promise((resolve, reject) => {
const subprocess = childProcess.spawn("quick-toast", ["Clipboard Server", message], {
stdio: "ignore",
});
subprocess.on("exit", resolve);
subprocess.on("error", reject);
});
}
async function createBaseDir(filepath) {
const dirname = path.dirname(filepath);
try {
await fs.stat(dirname);
return;
} catch {}
const mask = process.umask(0o0077);
await fs.mkdir(dirname, { recursive: true, mode: 0o700 });
process.umask(mask);
}
async function getPidFromPidFile(pidFile) {
try {
const pid = parseInt(await (await fs.readFile(pidFile, "utf8")).trim(), 10);
if (isNaN(pid) || pid < 1) {
return -1;
}
return pid;
} catch {
// pidfile doesn't exist
return -1;
}
}
function isRunning(pid) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function socketIsFile(socket) {
return /^\/.+\.sock/.test(socket);
}
function isValidSocket(socket) {
return socketIsFile(socket) || /^\d+$/.test(socket);
}
async function isListening(socket) {
return await new Promise((resolve, reject) => {
const options = {
path: "/ping",
};
if (socketIsFile(socket)) {
options.socketPath = socket;
} else {
options.host = "localhost";
options.port = parseInt(socket, 10);
}
const req = http.get(options, (res) => {
if (res.statusCode === 200) {
resolve();
} else {
reject(res);
}
});
req.on("error", reject);
req.end();
});
}
async function start({ pidFile, socket, enablePaste, notify }) {
// check if pid file exists
const existingPid = await getPidFromPidFile(pidFile);
// check if already running
if (existingPid > 0 && isRunning(existingPid)) {
// process already running
return;
}
// clean up previous socket file
if (socketIsFile(socket)) {
try {
await fs.unlink(socket);
} catch {}
}
const args = ["--pidfile", pidFile, "--socket", socket];
if (enablePaste) {
args.push("--enable-paste");
}
if (notify) {
args.push("--notify");
}
// spawn detached process
const subprocess = childProcess.spawn(
process.argv[0],
[process.argv[1], "server", ...args],
{
detached: true,
stdio: "ignore",
}
);
// detach process fully
subprocess.unref();
// wait for socket ready
let ready = false;
for (let i = 0; i < 30; i++) {
try {
await isListening(socket);
ready = true;
break;
} catch {}
await new Promise((r) => setTimeout(r, 20));
}
if (!ready) {
// kill process and exit
try {
subprocess.kill();
} catch {}
throw new Error("Unable to start server");
}
// write child pid to file
// console.log(subprocess.pid);
await createBaseDir(pidFile);
await fs.writeFile(pidFile, String(subprocess.pid), "utf8");
}
async function stop({ pidFile }) {
// check if pid file exists
const existingPid = await getPidFromPidFile(pidFile);
// check if already running
if (existingPid <= 0 || !isRunning(existingPid)) {
// process not running, clean up
try {
await fs.unlink(pidFile);
} catch {}
return;
}
// kill child process
process.kill(existingPid, "SIGHUP");
// clean up pid file
try {
await fs.unlink(pidFile);
} catch {}
}
async function server({ socket, enablePaste, notify }) {
if (socketIsFile(socket)) {
await createBaseDir(socket);
// cleanup
process.on("SIGHUP", () => {
try {
legacyFs.unlinkSync(socket);
} catch {}
process.exit();
});
}
const server = http.createServer({});
server.on("error", (err) => console.error(err));
server.on("request", async (req, res) => {
try {
switch (req.url) {
case "/clipboard":
if (req.method === "GET") {
if (notify) {
showNotification("Clipboard read").catch(() => {});
}
res.setHeader("content-type", "application/octet-stream");
if (enablePaste) {
await getClipboard(res);
} else {
res.statusMessage = "Forbidden";
res.statusCode = 403;
res.end();
}
} else if (req.method === "POST") {
if (notify) {
showNotification("Clipboard written").catch(() => {});
}
res.setHeader("content-type", "text/plain");
res.statusCode = 200;
await setClipboard(req, res);
res.end();
} else {
throw new Error("Unknown request method");
}
break;
case "/ping":
res.setHeader("content-type", "text/plain");
res.statusCode = 200;
res.end("ok\n");
break;
default:
res.statusMessage = "Not Found";
res.statusCode = 404;
res.end();
break;
}
} catch (e) {
res.statusMessage = "Forbidden";
res.statusCode = 500;
res.end();
}
});
server.listen(socket, () => console.log("ready"));
}
function help() {
return `
Usage: clipboard-server COMMAND [OPTION]...
Forward clipboard access over a http socket.
Example: clipboard-server start --enable-paste
Commands:
start Run the server in the background
stop Stop the server if it is running
restart Restart the server
server Start the server in the foreground
Options:
-e, --enable-paste Disable local clipboard access, only alloys the remote
server to send contents to local clipboard.
default: false
-n, --notify Show a notification when the clipboard is accessed
default: false
-p, --pidfile FILE Path to the pid file for the server.
default: ~/.config/clipboard-server/clipboard-server.pid
-s, --socket FILE|PORT A port number or path to the socket file location
default: ~/.config/clipboard-server/clipboard-server.sock
--help Show this message
`.trim();
}
async function main([_1, _2, subcommand, ...args]) {
const userInfo = os.userInfo();
let showHelp = subcommand == "--help";
const opts = {
pidFile: `${userInfo.homedir}/.config/clipboard-server/clipboard-server.pid`,
socket: `${userInfo.homedir}/.config/clipboard-server/clipboard-server.sock`,
enablePaste: false,
};
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case "-e":
case "--enable-paste":
opts.enablePaste = true;
break;
case "-n":
case "--notify":
opts.notify = true;
break;
case "-p":
case "--pidfile":
opts.pidFile = args[++i];
break;
case "--socket":
case "-s":
opts.socket = args[++i];
if (!isValidSocket(opts.socket)) {
throw new Error("socket must be a file or a port.");
}
break;
case "--help":
showHelp = true;
break;
}
}
if (showHelp) {
console.log(help());
return;
}
switch (subcommand) {
case "start":
await start(opts);
break;
case "stop":
await stop(opts);
break;
case "restart":
try {
await stop(opts);
} catch {}
await start(opts);
break;
case "server":
await server(opts);
break;
default:
throw new Error("Unknown command");
}
}
main(process.argv).catch((err) => {
console.error(err);
process.exit(1);
});