-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.c
575 lines (481 loc) · 16.5 KB
/
websocket.c
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/* Copyright (c) Mon Jan 23 10:52:34 PST 2023 The chromeOSLinux Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* WebSocket server that provides an interface to an extension running in
* Chromium OS, used for clipboard synchronization and URL handling.
*
*/
#include "websocket.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <netinet/tcp.h>
/* WebSocket constants */
#define VERSION "V2"
#define PORT 30001
/* Pipe constants */
const char* PIPE_DIR = "/tmp/chromeOSLinux-ext";
const char* PIPEIN_FILENAME = "/tmp/chromeOSLinux-ext/in";
const char* PIPEOUT_FILENAME = "/tmp/chromeOSLinux-ext/out";
const char* PIPE_VERSION_FILE = "/tmp/chromeOSLinux-ext/version";
const int PIPEOUT_WRITE_TIMEOUT = 3000;
/* File descriptors */
static int pipein_fd = -1;
static int pipeout_fd = -1;
static void pipeout_close();
static int socket_client_handle_unrequested(const char* buffer,
const int length);
/* Open a pipe in non-blocking mode, then set it back to blocking mode. */
/* Returns fd on success, -1 if the pipe cannot be open, -2 if the O_NONBLOCK
* flag cannot be cleared. */
static int pipe_open_block(const char* path, int oflag) {
int fd;
log(3, "%s", path);
fd = open(path, oflag | O_NONBLOCK);
if (fd < 0)
return -1;
/* Remove non-blocking flag */
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0 || fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) < 0) {
syserror("error in fnctl GETFL/SETFL.");
close(fd);
return -2;
}
return fd;
}
/**/
/* Pipe out functions */
/**/
/* Open the pipe out. Returns 0 on success, -1 on error. */
static int pipeout_open() {
int i;
log(2, "Opening pipe out...");
/* Unfortunately, in the case where no reader is available (yet), opening
* pipes for writing behaves as follows: In blocking mode, "open" blocks.
* In non-blocking mode, it fails (returns -1). This means that we cannot
* open the pipe, then use functions like poll/select to detect when a
* reader becomes available. Waiting forever is also not an option: we do
* want to block this server if a client "forgets" to read the answer back.
* Therefore, we are forced to poll manually.
* Using usleep is simpler, and probably better than measuring time elapsed:
* If the system hangs for a while (like during large I/O writes), this will
* still wait around PIPEOUT_WRITE_TIMEOUT ms of actual user time, instead
* of clock time. */
for (i = 0; i < PIPEOUT_WRITE_TIMEOUT/10; i++) {
pipeout_fd = pipe_open_block(PIPEOUT_FILENAME, O_WRONLY);
if (pipeout_fd >= 0)
break;
if (pipeout_fd == -2) /* fnctl error: this is fatal. */
exit(1);
usleep(10000);
}
if (pipeout_fd < 0) {
error("Timeout while opening.");
return -1;
}
return 0;
}
static void pipeout_close() {
log(2, "Closing...");
if (pipeout_fd < 0)
return;
close(pipeout_fd);
pipeout_fd = -1;
}
static int pipeout_write(char* buffer, int len) {
int n;
log(3, "(fd=%d, len=%d)", pipeout_fd, len);
if (pipeout_fd < 0)
return -1;
n = block_write(pipeout_fd, buffer, len);
if (n != len) {
error("Error writing to pipe.");
pipeout_close();
}
return n;
}
/* Open pipe out, write a string, then close the pipe. */
static void pipeout_error(char* str) {
pipeout_open();
pipeout_write(str, strlen(str));
pipeout_close();
}
/**/
/* Pipe in functions */
/**/
/* Flush the pipe (in case of error), close it, then reopen it. Reopening is
* necessary to prevent poll from getting continuous POLLHUP when the process
* that writes into the pipe terminates (chromeOSLinuxurlhandler for example).
* This MUST be called before anything is written to pipeout to avoid race
* condition, where we would flush out legitimate data from a second process */
static void pipein_reopen() {
if (pipein_fd >= 0) {
char buffer[BUFFERSIZE];
while (read(pipein_fd, buffer, BUFFERSIZE) > 0);
close(pipein_fd);
}
pipein_fd = pipe_open_block(PIPEIN_FILENAME, O_RDONLY);
if (pipein_fd < 0) {
syserror("Cannot open pipe in.");
exit(1);
}
}
/* Read data from the pipe, and forward it to the socket client. */
static void pipein_read() {
int n;
char buffer[FRAMEMAXHEADERSIZE+BUFFERSIZE];
int first = 1;
char firstchar = '\0';
if (client_fd < 0) {
log(1, "No client FD.");
pipein_reopen();
pipeout_error("EError: not connected.");
return;
}
while (1) {
n = read(pipein_fd, buffer+FRAMEMAXHEADERSIZE, BUFFERSIZE);
log(3, "n=%d", n);
if (n < 0) {
/* This is very unlikely, and fatal. */
syserror("Error reading from pipe.");
exit(1);
} else if (n == 0) {
break;
}
if (first)
firstchar = buffer[FRAMEMAXHEADERSIZE];
/* Write a text frame for the first packet, then cont frames. */
n = socket_client_write_frame(buffer, n,
first ? WS_OPCODE_TEXT : WS_OPCODE_CONT, 0);
if (n < 0) {
error("Error writing frame.");
pipein_reopen();
pipeout_error("EError: socket write error.");
return;
}
first = 0;
}
log(3, "EOF");
pipein_reopen();
/* Empty FIN frame to finish the message. */
n = socket_client_write_frame(buffer, 0,
first ? WS_OPCODE_TEXT : WS_OPCODE_CONT, 1);
if (n < 0) {
error("Error writing frame.");
pipeout_error("EError: socket write error");
return;
}
log(2, "Reading answer from client...");
int fin = 0;
uint32_t maskkey;
int retry = 0;
first = 1;
/* Ignore return value, so we still read the frame even if pipeout
* cannot be open. */
pipeout_open();
/* Read possibly fragmented message from WebSocket. */
while (fin != 1) {
int len = socket_client_read_frame_header(&fin, &maskkey, &retry);
log(3, "len=%d fin=%d retry=%d...", len, fin, retry);
if (retry)
continue;
if (len < 0)
goto exit;
/* Read the whole frame, and write it to pipeout */
while (len > 0) {
int rlen = (len > BUFFERSIZE) ? BUFFERSIZE: len;
if (socket_client_read_frame_data(buffer, rlen, maskkey) < 0)
goto exit;
/* Check first byte */
if (first && buffer[0] != firstchar && buffer[0] != 'E') {
/* This is not a response: unrequested packet */
if (!fin && len < BUFFERSIZE) {
/* !fin, and buffer not full, finish reading... */
rlen = socket_client_read_frame(buffer+len,
sizeof(buffer)-len);
if (rlen < 0)
goto exit;
len += rlen;
}
if (len >= BUFFERSIZE) {
error("Unrequested command too long: (>%d bytes).", len);
socket_client_close(1);
goto exit;
}
if (socket_client_handle_unrequested(buffer, len) < 0)
goto exit;
/* Command was handled, try reading the answer again. */
fin = 0;
break;
}
/* Ignore return value as well */
pipeout_write(buffer, rlen);
len -= rlen;
first = 0;
}
}
exit:
pipeout_close();
}
/* Check if filename is a valid FIFO pipe. If not create it.
* Returns 0 on success, -1 on error. */
int checkfifo(const char* filename) {
struct stat fstat;
/* Check if file exists: if not, create the FIFO. */
if (access(filename, F_OK) < 0) {
if (mkfifo(filename,
S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) < 0) {
syserror("Cannot create FIFO pipe.");
return -1;
}
return 0;
}
/* We must be able to read and write the file. (only one direction is
* necessary in chromeOSLinuxwebsocket, but chromeOSLinuxclip needs the other direction)
*/
if (access(filename, R_OK|W_OK) < 0) {
error("%s exists, but not readable and writable.",
filename);
return -1;
}
if (stat(filename, &fstat) < 0) {
syserror("Cannot stat FIFO pipe.");
return -1;
}
if (!S_ISFIFO(fstat.st_mode)) {
error("%s exists, but is not a FIFO pipe.", filename);
return -1;
}
return 0;
}
/* Initialise FIFO pipes. */
void pipe_init() {
struct stat fstat;
/* Check if directory exists: if not, create it. */
if (access(PIPE_DIR, F_OK) < 0) {
if (mkdir(PIPE_DIR, S_IRWXU|S_IRWXG|S_IRWXO) < 0) {
syserror("Cannot create FIFO pipe directory.");
exit(1);
}
} else {
if (stat(PIPE_DIR, &fstat) < 0) {
syserror("Cannot stat FIFO pipe directory.");
exit(1);
}
if (!S_ISDIR(fstat.st_mode)) {
error("%s exists, but is not a directory.", PIPE_DIR);
exit(1);
}
}
if (checkfifo(PIPEIN_FILENAME) < 0 ||
checkfifo(PIPEOUT_FILENAME) < 0) {
/* checkfifo prints an error already. */
exit(1);
}
/* Create a file with the version number of the protocol */
FILE *vers = fopen(PIPE_VERSION_FILE, "w");
if (!vers
|| fputs(VERSION "\n", vers) == EOF
|| fclose(vers) == EOF) {
error("Unable to write to %s.", PIPE_VERSION_FILE);
exit(1);
}
pipein_reopen();
}
/* Handle unrequested packet from extension.
* Returns 0 on success. On error, returns -1 and closes websocket connection.
*/
static int socket_client_handle_unrequested(const char* buffer,
const int length) {
/* Process the client request. */
switch (buffer[0]) {
case 'C': { /* Send a command to chromeOSLinuxcycle */
char reply[BUFFERSIZE];
int replylength = 1;
reply[FRAMEMAXHEADERSIZE] = 'C';
char* cmd = "chromeOSLinuxcycle";
char param[length];
memcpy(param, buffer+1, length-1);
param[length-1] = '\0';
char* args[] = { cmd, param, NULL };
log(2, "Received chromeOSLinuxcycle command (%s)", param);
/* We are only interested in the output for list commands */
if (param[0] == 'l') {
int n = popen2(cmd, args, NULL, 0,
&reply[FRAMEMAXHEADERSIZE+1],
BUFFERSIZE-FRAMEMAXHEADERSIZE-1);
if (n < 0) {
error("Call to chromeOSLinuxcycle failed.");
socket_client_close(0);
return -1;
}
replylength += n;
} else if (param[0] == 'O') {
/* Extra OK response from a C back-and-forth. Disregard. */
break;
} else {
/* Launch command in background (this is necessary as
chromeOSLinuxcycle may send a websocket command, leaving us
deadlocked...) */
pid_t pid = fork();
if (pid < 0) {
syserror("Fork error.");
exit(1);
} else if (pid == 0) {
/* Double-fork to avoid zombies */
pid_t pid2 = fork();
if (pid2 < 0) {
syserror("Fork error.");
exit(1);
} else if (pid2 == 0) {
execvp(cmd, args);
error("Error running '%s'.", cmd);
exit(127);
}
exit(0);
}
/* Wait for first fork to complete. */
waitpid(pid, NULL, 0);
}
if (socket_client_write_frame(reply, replylength,
WS_OPCODE_TEXT, 1) < 0) {
error("Write error.");
socket_client_close(0);
return -1;
}
break;
}
default: {
int len = length > 64 ? 64 : length;
char dump[len+1];
memcpy(dump, buffer, len);
dump[len] = '\0';
error("Received an unexpected packet from client (%s).", dump);
socket_client_close(0);
return -1;
}
}
return 0;
}
/* Unrequested data came in from WebSocket client. */
static void socket_client_read() {
char buffer[BUFFERSIZE];
int length;
length = socket_client_read_frame(buffer, sizeof(buffer));
if (length < 0) {
socket_client_close(1);
return;
}
if (length >= BUFFERSIZE) {
error("Unrequested command too long: (>%d bytes).", length);
socket_client_close(1);
return;
}
/* Ignore return value (connection gets closed on error) */
socket_client_handle_unrequested(buffer, length);
}
static int terminate = 0;
static void signal_handler(int sig) {
terminate = 1;
}
int main(int argc, char **argv) {
int n;
/* Poll array:
* 0 - server_fd
* 1 - pipein_fd
* 2 - client_fd (if any)
*/
struct pollfd fds[3];
int nfds = 3;
sigset_t sigmask;
sigset_t sigmask_orig;
struct sigaction act;
int c;
while ((c = getopt(argc, argv, "v:")) != -1) {
switch (c) {
case 'v':
verbose = atoi(optarg);
break;
default:
fprintf(stderr, "%s [-v 0-3]\n", argv[0]);
return 1;
}
}
/* Termination signal handler. */
memset(&act, 0, sizeof(act));
act.sa_handler = signal_handler;
if (sigaction(SIGHUP, &act, 0) < 0 ||
sigaction(SIGINT, &act, 0) < 0 ||
sigaction(SIGTERM, &act, 0) < 0) {
syserror("sigaction error.");
return 2;
}
/* Ignore SIGPIPE in all cases: it may happen, since we write to pipes, but
* it is not fatal. */
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGPIPE);
if (sigprocmask(SIG_BLOCK, &sigmask, NULL) < 0) {
syserror("sigprocmask error.");
return 2;
}
/* Ignore terminating signals, except when ppoll is running. Save current
* mask in sigmask_orig. */
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGHUP);
sigaddset(&sigmask, SIGINT);
sigaddset(&sigmask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &sigmask, &sigmask_orig) < 0) {
syserror("sigprocmask error.");
return 2;
}
/* Prepare pollfd structure. */
memset(fds, 0, sizeof(fds));
fds[0].events = POLLIN;
fds[1].events = POLLIN;
fds[2].events = POLLIN;
/* Initialise pipe and WebSocket server */
socket_server_init(PORT);
pipe_init();
while (!terminate) {
/* Make sure fds is up to date. */
fds[0].fd = server_fd;
fds[1].fd = pipein_fd;
fds[2].fd = client_fd;
/* Only handle signals in ppoll: this makes sure we complete processing
* the current request before bailing out. */
n = ppoll(fds, nfds, NULL, &sigmask_orig);
log(3, "poll ret=%d (%d, %d, %d)\n", n,
fds[0].revents, fds[1].revents, fds[2].revents);
if (n < 0) {
/* Do not print error when ppoll is interupted by a signal. */
if (errno != EINTR || verbose >= 1)
syserror("ppoll error.");
break;
}
if (fds[0].revents & POLLIN) {
log(1, "WebSocket accept.");
socket_server_accept(VERSION);
n--;
}
if (fds[1].revents & POLLIN) {
log(2, "Pipe fd ready.");
pipein_read();
n--;
}
if (fds[2].revents & POLLIN) {
log(2, "Client fd ready.");
socket_client_read();
n--;
}
if (n > 0) { /* Some events were not handled, this is a problem */
error("Some poll events could not be handled: "
"ret=%d (%d, %d, %d).",
n, fds[0].revents, fds[1].revents, fds[2].revents);
break;
}
}
log(1, "Terminating...");
if (client_fd)
socket_client_close(1);
return 0;
}