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
|
#include <errno.h>
#include <json.h>
#include <libwebsockets.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include "server.h"
#include "terminal.h"
#include "utils.h"
// initial message list
static char initial_cmds[] = {SET_WINDOW_TITLE, SET_PREFERENCES};
static int send_initial_message(struct lws *wsi, int index) {
unsigned char message[LWS_PRE + 1 + 4096];
unsigned char *p = &message[LWS_PRE];
char buffer[128];
int n = 0;
char cmd = initial_cmds[index];
switch (cmd) {
case SET_WINDOW_TITLE:
gethostname(buffer, sizeof(buffer) - 1);
n = sprintf((char *)p, "%c%s (%s)", cmd, server->command, buffer);
break;
case SET_PREFERENCES:
n = sprintf((char *)p, "%c%s", cmd, server->prefs_json);
break;
default:
break;
}
return lws_write(wsi, p, (size_t)n, LWS_WRITE_BINARY);
}
static bool parse_window_size(struct pss_tty *pss, int *cols, int *rows) {
char json[pss->len];
strncpy(json, pss->buffer + 1, pss->len - 1);
json[pss->len - 1] = '\0';
json_object *obj = json_tokener_parse(json);
struct json_object *o = NULL;
if (!json_object_object_get_ex(obj, "columns", &o)) {
lwsl_err("columns field not exists, json: %s\n", json);
return false;
}
*cols = json_object_get_int(o);
if (!json_object_object_get_ex(obj, "rows", &o)) {
lwsl_err("rows field not exists, json: %s\n", json);
return false;
}
*rows = json_object_get_int(o);
json_object_put(obj);
return true;
}
static bool check_host_origin(struct lws *wsi) {
int origin_length = lws_hdr_total_length(wsi, WSI_TOKEN_ORIGIN);
char buf[origin_length + 1];
memset(buf, 0, sizeof(buf));
int len = lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_ORIGIN);
if (len <= 0) {
return false;
}
const char *prot, *address, *path;
int port;
if (lws_parse_uri(buf, &prot, &address, &port, &path)) return false;
if (port == 80 || port == 443) {
sprintf(buf, "%s", address);
} else {
sprintf(buf, "%s:%d", address, port);
}
int host_length = lws_hdr_total_length(wsi, WSI_TOKEN_HOST);
if (host_length != strlen(buf)) return false;
char host_buf[host_length + 1];
memset(host_buf, 0, sizeof(host_buf));
len = lws_hdr_copy(wsi, host_buf, sizeof(host_buf), WSI_TOKEN_HOST);
return len > 0 && strcasecmp(buf, host_buf) == 0;
}
static void close_cb(uv_handle_t *handle) {
struct pty_proc *proc = container_of((uv_pipe_t *)handle, struct pty_proc, pipe);
free(proc);
}
static void pty_proc_free(struct pty_proc *proc) {
uv_read_stop((uv_stream_t *)&proc->pipe);
close(proc->pty);
if (proc->pty_buffer != NULL) {
free(proc->pty_buffer);
proc->pty_buffer = NULL;
}
for (int i = 0; i < proc->argc; i++) {
free(proc->args[i]);
}
uv_close((uv_handle_t *)&proc->pipe, close_cb);
}
static void alloc_cb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = xmalloc(suggested_size);
buf->len = suggested_size;
}
static void read_cb(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) {
struct pss_tty *pss = (struct pss_tty *)stream->data;
struct pty_proc *proc = pss->proc;
proc->pty_len = nread;
uv_read_stop(stream);
if (nread == UV_ENOBUFS || nread == 0) return;
if (nread > 0) {
proc->pty_buffer = xmalloc(LWS_PRE + 1 + (size_t)nread);
memcpy(proc->pty_buffer + LWS_PRE + 1, buf->base, (size_t)nread);
} else {
proc->pty_buffer = NULL;
if (nread != UV_EOF) {
proc->err_count++;
lwsl_err("read_cb: %s (%s)\n", uv_err_name(nread), uv_strerror(nread));
}
}
free(buf->base);
lws_callback_on_writable(pss->wsi);
}
static void child_cb(uv_signal_t *handle, int signum) {
pid_t pid;
int stat;
struct pty_proc *proc;
LIST_HEAD(proc, pty_proc) *procs = handle->data;
LIST_FOREACH(proc, procs, entry) {
do
pid = waitpid(proc->pid, &stat, WNOHANG);
while (pid == -1 && errno == EINTR);
if (pid <= 0) continue;
if (WIFEXITED(stat)) {
proc->status = WEXITSTATUS(stat);
lwsl_notice("process exited with code %d, pid: %d\n", proc->status, proc->pid);
} else if (WIFSIGNALED(stat)) {
int sig = WTERMSIG(stat);
char sig_name[20];
proc->status = 128 + sig;
get_sig_name(sig, sig_name, sizeof(sig_name));
lwsl_notice("process killed with signal %d (%s), pid: %d\n", sig, sig_name, proc->pid);
}
LIST_REMOVE(proc, entry);
if (proc->state == STATE_KILL) {
pty_proc_free(proc);
} else {
proc->state = STATE_EXIT;
}
}
}
static int spawn_process(struct pss_tty *pss) {
struct pty_proc *proc = pss->proc;
// append url args to arguments
char *argv[server->argc + proc->argc + 1];
int i, n = 0;
for (i = 0; i < server->argc; i++) {
argv[n++] = server->argv[i];
}
for (i = 0; i < proc->argc; i++) {
argv[n++] = proc->args[i];
}
argv[n] = NULL;
uv_signal_start(&server->watcher, child_cb, SIGCHLD);
// ensure the lws socket fd close-on-exec
fd_set_cloexec(lws_get_socket_fd(pss->wsi));
// create process with pseudo-tty
proc->pid = pty_fork(&proc->pty, argv[0], argv, server->terminal_type);
if (proc->pid < 0) {
lwsl_err("pty_fork: %d (%s)\n", errno, strerror(errno));
return 1;
}
lwsl_notice("started process, pid: %d\n", proc->pid);
proc->pipe.data = pss;
uv_pipe_open(&proc->pipe, proc->pty);
lws_callback_on_writable(pss->wsi);
return 0;
}
static void kill_process(struct pty_proc *proc) {
if (proc->pid <= 0) return;
pid_t pid = proc->pid;
int sig = server->sig_code;
char *sig_name = server->sig_name;
lwsl_notice("killing process %d with signal: %d (%s)\n", pid, sig, sig_name);
int pgid = getpgid(pid);
if (uv_kill(pgid > 0 ? -pgid : pid, sig) != 0) {
lwsl_err("kill: %d, errno: %d (%s)\n", pid, errno, strerror(errno));
}
}
static void write_cb(uv_write_t *req, int status) {
if (status != 0) lwsl_warn("uv_write callback returned status: %d\n", status);
free(req->data);
free(req);
}
int callback_tty(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in,
size_t len) {
struct pss_tty *pss = (struct pss_tty *)user;
struct pty_proc *proc;
char buf[256];
size_t n = 0;
switch (reason) {
case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
if (server->once && server->client_count > 0) {
lwsl_warn("refuse to serve WS client due to the --once option.\n");
return 1;
}
if (server->max_clients > 0 && server->client_count == server->max_clients) {
lwsl_warn("refuse to serve WS client due to the --max-clients option.\n");
return 1;
}
n = lws_hdr_copy(wsi, pss->path, sizeof(pss->path), WSI_TOKEN_GET_URI);
#if defined(LWS_ROLE_H2)
if (n <= 0) n = lws_hdr_copy(wsi, pss->path, sizeof(pss->path), WSI_TOKEN_HTTP_COLON_PATH);
#endif
if (strncmp(pss->path, endpoints.ws, n) != 0) {
lwsl_warn("refuse to serve WS client for illegal ws path: %s\n", buf);
return 1;
}
if (server->check_origin && !check_host_origin(wsi)) {
lwsl_warn(
"refuse to serve WS client from different origin due to the "
"--check-origin option.\n");
return 1;
}
break;
case LWS_CALLBACK_ESTABLISHED:
pss->initialized = false;
pss->initial_cmd_index = 0;
pss->authenticated = false;
pss->wsi = wsi;
pss->buffer = NULL;
pss->proc = proc = xmalloc(sizeof(struct pty_proc));
memset(proc, 0, sizeof(struct pty_proc));
proc->status = -1;
proc->state = STATE_INIT;
uv_pipe_init(server->loop, &proc->pipe, 0);
if (server->url_arg) {
while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_URI_ARGS, n++) > 0) {
if (strncmp(buf, "arg=", 4) == 0) {
proc->args = xrealloc(proc->args, (proc->argc + 1) * sizeof(char *));
proc->args[proc->argc] = strdup(&buf[4]);
proc->argc++;
}
}
}
LIST_INSERT_HEAD(&server->procs, proc, entry);
server->client_count++;
#if LWS_LIBRARY_VERSION_NUMBER >= 2004000
lws_get_peer_simple(lws_get_network_wsi(wsi), pss->address, sizeof(pss->address));
#else
char name[100];
lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name, sizeof(name), pss->address,
sizeof(pss->address));
#endif
lwsl_notice("WS %s - %s, clients: %d\n", pss->path, pss->address, server->client_count);
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
proc = pss->proc;
if (!pss->initialized) {
if (pss->initial_cmd_index == sizeof(initial_cmds)) {
pss->initialized = true;
uv_read_start((uv_stream_t *)&proc->pipe, alloc_cb, read_cb);
break;
}
if (send_initial_message(wsi, pss->initial_cmd_index) < 0) {
lwsl_err("failed to send initial message, index: %d\n", pss->initial_cmd_index);
lws_close_reason(wsi, LWS_CLOSE_STATUS_UNEXPECTED_CONDITION, NULL, 0);
return -1;
}
pss->initial_cmd_index++;
lws_callback_on_writable(wsi);
break;
}
// read error or client exited, close connection
if (proc->status == 0 || proc->pty_len == UV_EOF) {
lws_close_reason(wsi, LWS_CLOSE_STATUS_NORMAL, NULL, 0);
return 1;
} else if (proc->status > 0 || (proc->pty_len < 0 && proc->err_count == MAX_READ_RETRY)) {
lws_close_reason(wsi, LWS_CLOSE_STATUS_UNEXPECTED_CONDITION, NULL, 0);
return -1;
}
if (proc->pty_buffer != NULL && proc->pty_len > 0) {
proc->pty_buffer[LWS_PRE] = OUTPUT;
n = (size_t)(proc->pty_len + 1);
if (lws_write(wsi, (unsigned char *)proc->pty_buffer + LWS_PRE, n, LWS_WRITE_BINARY) < n) {
lwsl_err("write OUTPUT to WS\n");
}
free(proc->pty_buffer);
proc->pty_buffer = NULL;
}
uv_read_start((uv_stream_t *)&proc->pipe, alloc_cb, read_cb);
break;
case LWS_CALLBACK_RECEIVE:
if (pss->buffer == NULL) {
pss->buffer = xmalloc(len);
pss->len = len;
memcpy(pss->buffer, in, len);
} else {
pss->buffer = xrealloc(pss->buffer, pss->len + len);
memcpy(pss->buffer + pss->len, in, len);
pss->len += len;
}
const char command = pss->buffer[0];
// check auth
if (server->credential != NULL && !pss->authenticated && command != JSON_DATA) {
lwsl_warn("WS client not authenticated\n");
return 1;
}
// check if there are more fragmented messages
if (lws_remaining_packet_payload(wsi) > 0 || !lws_is_final_fragment(wsi)) {
return 0;
}
proc = pss->proc;
switch (command) {
case INPUT:
if (proc->pty == 0) break;
if (server->readonly) break;
char *data = xmalloc(pss->len - 1);
memcpy(data, pss->buffer + 1, pss->len - 1);
uv_buf_t b = {data, pss->len - 1};
uv_write_t *req = xmalloc(sizeof(uv_write_t));
req->data = data;
int err = uv_write(req, (uv_stream_t *)&proc->pipe, &b, 1, write_cb);
if (err) {
lwsl_err("uv_write: %s (%s)\n", uv_err_name(err), uv_strerror(err));
return -1;
}
break;
case RESIZE_TERMINAL: {
int cols, rows;
if (parse_window_size(pss, &cols, &rows)) {
if (pty_resize(proc->pty, cols, rows) < 0) {
lwsl_err("pty_resize: %d (%s)\n", errno, strerror(errno));
}
}
} break;
case PAUSE:
if (proc->state == STATE_INIT) {
uv_read_stop((uv_stream_t *)&proc->pipe);
proc->state = STATE_PAUSE;
}
break;
case RESUME:
if (proc->state == STATE_PAUSE) {
uv_read_start((uv_stream_t *)&proc->pipe, alloc_cb, read_cb);
proc->state = STATE_INIT;
}
break;
case JSON_DATA:
if (proc->pid > 0) break;
if (server->credential != NULL) {
json_object *obj = json_tokener_parse(pss->buffer);
struct json_object *o = NULL;
if (json_object_object_get_ex(obj, "AuthToken", &o)) {
const char *token = json_object_get_string(o);
if (token != NULL && !strcmp(token, server->credential))
pss->authenticated = true;
else
lwsl_warn("WS authentication failed with token: %s\n", token);
}
if (!pss->authenticated) {
lws_close_reason(wsi, LWS_CLOSE_STATUS_POLICY_VIOLATION, NULL, 0);
return -1;
}
}
if (spawn_process(pss) != 0) return 1;
break;
default:
lwsl_warn("ignored unknown message type: %c\n", command);
break;
}
if (pss->buffer != NULL) {
free(pss->buffer);
pss->buffer = NULL;
}
break;
case LWS_CALLBACK_CLOSED:
if (pss->wsi == NULL) break;
server->client_count--;
lwsl_notice("WS closed from %s, clients: %d\n", pss->address, server->client_count);
if (pss->buffer != NULL) {
free(pss->buffer);
}
proc = pss->proc;
if (proc->state == STATE_EXIT) {
pty_proc_free(proc);
} else {
proc->state = STATE_KILL;
uv_read_stop((uv_stream_t *)&proc->pipe);
kill_process(proc);
}
if (server->once && server->client_count == 0) {
lwsl_notice("exiting due to the --once option.\n");
force_exit = true;
lws_cancel_service(context);
exit(0);
}
break;
default:
break;
}
return 0;
}
|