console_httpd.c 20.3 KB
Newer Older
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
/*
	Copyright Jeroen Vreeken (jeroen@vreeken.net), 2014

	This program 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.

	This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
#include <errno.h>
#include <time.h>
#include <magic.h>
#include <libwebsockets.h>
#include <sys/ioctl.h>
Jeroen Vreeken's avatar
Jeroen Vreeken committed
28
#include <sys/types.h>
Jeroen Vreeken's avatar
Jeroen Vreeken committed
29
#include <sys/stat.h>
Jeroen Vreeken's avatar
Jeroen Vreeken committed
30
#include <dirent.h>
Jeroen Vreeken's avatar
Jeroen Vreeken committed
31
32
33
34
35
36
37
38
39

#include <dt_port_numbers.h>
#include <utils/tcp_connect.h>
#include <utils/dt_host.h>
#include <trace/trace.h>
#include <command/command.h>

magic_t magic;

Jeroen Vreeken's avatar
Jeroen Vreeken committed
40
41
42
43
44
45
46
47
48
struct writebuf {
	char *data;
	char *msg;
	size_t msg_len;
	
	struct writebuf *next;
};

struct ws_client {
49
	struct lws *wsi;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
	
	struct writebuf *writeq;
	
	struct ws_client *next;
};

struct writebuf *writebuf_alloc(size_t msglen)
{
	struct writebuf *wb;
	
	wb = malloc(sizeof(struct writebuf));
	if (!wb)
		return NULL;
	
	wb->data = malloc(msglen +
	    LWS_SEND_BUFFER_PRE_PADDING +
	    LWS_SEND_BUFFER_POST_PADDING);

	wb->msg = wb->data + LWS_SEND_BUFFER_PRE_PADDING;

	return wb;
}

void writebuf_free(struct writebuf *wb)
{
	free(wb->data);
	free(wb);
}

void writebuf_add(struct ws_client *client, struct writebuf *wb)
{
	struct writebuf **entry;
	
	for (entry = &client->writeq; *entry; entry = &(*entry)->next);
	
	*entry = wb;
	wb->next = NULL;
}

struct writebuf *writebuf_next(struct ws_client *client)
{
	struct writebuf *wb;
	
	if (!client->writeq)
		return NULL;
	
	wb = client->writeq;
	client->writeq = wb->next;
	
	return wb;
}

struct ws_client *ws_client_list = NULL;

104
struct ws_client *ws_client_add(struct lws *wsi)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
{
	struct ws_client *client;
	
	client = calloc(sizeof(struct ws_client), 1);
	if (!client)
		return NULL;
	
	client->wsi = wsi;
	
	client->next = ws_client_list;
	ws_client_list = client;
	
	return client;
}

void ws_client_remove(struct ws_client *client)
{
	struct ws_client **entry;
	
	for (entry = &ws_client_list; *entry; entry = &(*entry)->next) {
		if (*entry == client) {
			struct writebuf *wb;
			while ((wb = writebuf_next(client))) {
				writebuf_free(wb);
			}
			
			*entry = (*entry)->next;
			free(client);
			return;
		}
	}
}

138
struct ws_client *ws_client_get_by_wsi(struct lws *wsi)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
{
	struct ws_client *entry;
	
	for (entry = ws_client_list; entry; entry = entry->next)
		if (entry->wsi == wsi)
			return entry;
	
	printf("wsi %p not found\n", wsi);
	return NULL;
}

void ws_client_flush(struct ws_client *client)
{
	while (client->writeq) {
		struct writebuf *wb;
		
		if (lws_send_pipe_choked(client->wsi))
			break;
		
		wb = writebuf_next(client);

160
		lws_write(client->wsi, (unsigned char *)wb->msg, wb->msg_len, LWS_WRITE_TEXT);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
161
162
163
164
165
		
		writebuf_free(wb);
	}
	
	if (client->writeq) {
166
		lws_callback_on_writable(client->wsi);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
167
168
169
	}
}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
170
#define MAX_POLL_ELEMENTS 1024
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
struct pollfd pollfds[MAX_POLL_ELEMENTS];
int count_pollfds = 0;

static int poll_add(int fd, short events)
{
	if (count_pollfds >= MAX_POLL_ELEMENTS)
		return -1;

	pollfds[count_pollfds].fd = fd;
	pollfds[count_pollfds].events = events;
	pollfds[count_pollfds].revents = 0;
	count_pollfds++;
	
	return 0;
}

static void poll_remove(int fd)
{
	int n;
	
	for (n = 0; n < count_pollfds; n++)
		if (pollfds[n].fd == fd) {
			while (n < count_pollfds) {
				pollfds[n] = pollfds[n + 1];
				n++;
			}
			count_pollfds--;
		}
}

static void poll_set(int fd, short events)
{
	int n;
	
	for (n = 0; n < count_pollfds; n++)
		if (pollfds[n].fd == fd)
			pollfds[n].events = events;

}

#define LINEBUF_SIZE 8192
struct status {
	char *ident;
214
	struct lws *wsi;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
	int fd;
	char *host;
	int port;
	
	unsigned char linebuf[LINEBUF_SIZE];
	int pos;
	
	char pre[LWS_SEND_BUFFER_PRE_PADDING];
	char msg[LINEBUF_SIZE * 2];
	char post[LWS_SEND_BUFFER_POST_PADDING];
	
	struct status *next;
};

struct status *status_list;

231
static void start_status(struct lws *wsi, char *ident)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
{
	struct status *status = calloc(sizeof(struct status), 1);
	char *host;
	int port = -1;
	int fd = -1;

	printf("new status\n");
	
	if (!status)
		return;
	
	host = dt_host_console();
	
	if (!strcmp(ident, "sat"))
		port = CONSOLE_SAT_STAT_PORT;
	else if (!strcmp(ident, "sun"))
		port = CONSOLE_SUN_STAT_PORT;
	else if (!strcmp(ident, "moon"))
		port = CONSOLE_MOON_STAT_PORT;
	else if (!strcmp(ident, "auth"))
		port = CONSOLE_STATUS_PORT;
	else if (!strcmp(ident, "j2000"))
		port = CONSOLE_J2000_POS_PORT;
	else if (!strcmp(ident, "log"))
		port = CONSOLE_LOG_PORT;
	else if (!strcmp(ident, "weather"))
		port = CONSOLE_WEATHER_PORT;
	else if (!strcmp(ident, "dt_model"))
		port = CONSOLE_DT_MODEL_STAT_PORT;
	
	fd = tcp_connect(host, port);
	if (fd >= 0)
		poll_add(fd, POLLIN | POLLERR);
	
	status->wsi = wsi;
	status->ident = ident;
	status->fd = fd;
	status->port = port;
	status->host = host;
	
	status->next = status_list;
	status_list = status;
}

static int status_handle(struct status *status)
{
	int r;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
279
	char *linebuf = (char *)status->linebuf;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
280
281
282
283
284
285
286
287
288
289
	int pos = status->pos;
	int fd = status->fd;
	char *ident = status->ident;
	
	r = read(fd, linebuf + pos, LINEBUF_SIZE - 1 - pos);
	if (r > 0) {
		int i;
		
		for (i = 0; i <r; i++) {
			if (linebuf[pos + i] == '\n') {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
290
291
292
293
294
				struct ws_client *ws_client;
				struct writebuf *wb;
				
				ws_client = ws_client_get_by_wsi(status->wsi);
				wb = writebuf_alloc(strlen(ident)+strlen(linebuf)+100);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
295
296
				
				linebuf[pos + i] = 0;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
297
				wb->msg_len = sprintf(wb->msg,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
298
299
				    "status %s %s\n",
				    ident, linebuf);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
300
301
302
				writebuf_add(ws_client, wb);
				ws_client_flush(ws_client);

Jeroen Vreeken's avatar
Jeroen Vreeken committed
303
304
305
306
307
308
309
310
311
				if (r - i - 1 > 0)
					memmove(
					    linebuf, 
					    linebuf + pos + i + 1, 
					    r - i - 1);
				pos -= pos + i +1;
			}
		}
		pos += r;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
312
	} else if (r == 0 || errno != EAGAIN) {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
313
314
		close(fd);
		poll_remove(fd);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
315
		fd = -1;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
316
317
318
319
320
321
322
323
324
325
326
	}
	status->pos = pos;
	status->fd = fd;

	return 0;
}

static int status_reconnect(struct status *status)
{
	int fd;
	
327
	printf("reconnect: %s\n", status->ident);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
328
329
330
331
332
333
334
335
336
337
338
	fd = tcp_connect(status->host, status->port);
	if (fd >= 0) {
		poll_add(fd, POLLIN | POLLERR);
		status->pos = 0;
	}
	
	status->fd = fd;
	
	return 0;
}

339
static int status_remove(struct lws *wsi)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
{
	struct status **status;
	struct status **next;
	
	for (status = &status_list; *status; status = next)
	{
		if ((*status)->wsi == wsi) {
			struct status *tmp = *status;
			
			close(tmp->fd);
			poll_remove(tmp->fd);
			free(tmp->ident);
			next = status;
			*next = (*next)->next;
			free(tmp);
		} else {
			next = &(*status)->next;
		}
	}
	return 0;
}


Jeroen Vreeken's avatar
Jeroen Vreeken committed
363
#define MAX_TRACE_ELEMENTS 1024
Jeroen Vreeken's avatar
Jeroen Vreeken committed
364
365
366
struct trace *traces[MAX_TRACE_ELEMENTS];
int count_traces = 0;

367
static int trace_remove(struct lws *wsi)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
{
	int n;
	for (n = 0; n < count_traces; n++) {
		if (traces[n]->private == wsi) {
			int fd = trace_fd_get(traces[n]);

			if (fd >= 0) {
				poll_remove(fd);
			}
			trace_free(traces[n]);
			memmove(traces + n, traces + n + 1, sizeof(struct trace *) * (count_traces - n - 1));
			n--;
			count_traces--;
		}
	}
	return 0;
}

386
static void handler_trace_value(struct trace *trace, int channel,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
387
388
    struct trace_value *value)
{
389
	struct lws *wsi;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
390
391
	struct ws_client *ws_client;
	struct writebuf *wb;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
392
393
	
	wsi = trace->private;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
394
395
	ws_client = ws_client_get_by_wsi(wsi);
	wb = writebuf_alloc(strlen(trace->name) + 100);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
396
397
398

	switch (trace->type) {
		case TRACE_VALUE_TYPE_FLOAT:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
399
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %e\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
400
401
402
403
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.f);
			break;
		case TRACE_VALUE_TYPE_BOOL:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
404
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
405
406
407
408
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.b);
			break;
		case TRACE_VALUE_TYPE_UINT8:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
409
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %u\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
410
411
412
413
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.u8);
			break;
		case TRACE_VALUE_TYPE_UINT16:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
414
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %u\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
415
416
417
418
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.u16);
			break;
		case TRACE_VALUE_TYPE_UINT32:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
419
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %u\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
420
421
422
423
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.u32);
			break;
		case TRACE_VALUE_TYPE_SINT8:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
424
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
425
426
427
428
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.s8);
			break;
		case TRACE_VALUE_TYPE_SINT16:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
429
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
430
431
432
433
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.s16);
			break;
		case TRACE_VALUE_TYPE_SINT32:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
434
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
435
436
437
438
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.s32);
			break;
	}
Jeroen Vreeken's avatar
Jeroen Vreeken committed
439
440
	writebuf_add(ws_client, wb);
	ws_client_flush(ws_client);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
441
442
}

443
static void start_trace(struct lws *wsi, int freq, char *variable)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
444
445
446
447
448
{
	struct trace *trace;
	struct timespec t_int;
	enum trace_interval_type type;
	int fd;
449
450
	char *host;
	int port;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
451

Jeroen Vreeken's avatar
Jeroen Vreeken committed
452
453
	if (count_traces + 1 >= MAX_TRACE_ELEMENTS)
		return;
454
455
456
457
458
459
460
461
462
	
	if (dt_host_trace_proxy()) {
		host = dt_host_console();
		port = CONSOLE_TRACE_PORT;
	} else {
		host = dt_host_controller();
		port = CTRL_TRACE_PORT;
	}
	trace = trace_open(host, port);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
463
464
465
	if (!trace)
		return;
	
466
	trace_name_set(trace, 0, variable);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
467
468
469
470
471
472
473
474
475
	free(variable);
	
	trace_autorecover(trace, true);
	
	trace->private = wsi;
	
	if (freq) {
		uint64_t nsec;
		
476
		nsec = 1000000000ull / freq;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
477
478
		
		type = TRACE_INTERVAL_TYPE_INTERVAL;
479
480
		t_int.tv_sec = nsec / 1000000000ull;
		t_int.tv_nsec = nsec - (uint64_t)t_int.tv_sec * 1000000000ull;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
		t_int.tv_sec = 0;
		t_int.tv_nsec = 500000000;
		
	} else {
		type = TRACE_INTERVAL_TYPE_CHANGED;
		t_int.tv_sec = 0;
		t_int.tv_nsec = 0;
	}
	
	trace_interval_set(trace, &t_int, type);

	trace->handler_value = handler_trace_value;
	fd = trace_fd_get(trace);
	
	poll_add(fd, POLLIN | POLLERR);
	
	traces[count_traces] = trace;
	count_traces++;
}


static void do_command(char *ident, char *command)
{
	char *host;
	int port = -1;
	int fd;
	
	host = dt_host_console();
	
	if (!strcmp(ident, "sat"))
		port = CONSOLE_SAT_CMD_PORT;
	else if (!strcmp(ident, "sun"))
		port = CONSOLE_SUN_CMD_PORT;
	else if (!strcmp(ident, "moon"))
		port = CONSOLE_MOON_CMD_PORT;
	else if (!strcmp(ident, "auth"))
		port = CONSOLE_ACTIVE_PORT;
	else if (!strcmp(ident, "j2000"))
		port = CONSOLE_J2000_CMD_PORT;
	else if (!strcmp(ident, "offset"))
		port = CONSOLE_OFFSET_PORT;
	else if (!strcmp(ident, "azel"))
		port = CONSOLE_AZEL_PORT;
	else if (!strcmp(ident, "manual"))
		port = CONSOLE_MANUAL_CMD_PORT;
	else if (!strcmp(ident, "dt_model"))
		port = CONSOLE_DT_MODEL_CMD_PORT;

	fd = tcp_connect(host, port);
	
	if (fd >= 0) {
		ioctl(fd, FIONBIO, &(int){ 0 });
		
		write(fd, command, strlen(command));

		write(fd,"\n", 1);
		fsync(fd);
		tcp_flushwrite(fd);

		close(fd);
	}
}

struct command **commands = NULL;
int nr_commands = 0;


static struct command *get_command( 
    char *name, char *id, enum command_value_type vtype)
{
	struct command *command = NULL;
	int i;
553
554
	char *host;
	int port;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
555
	
556
557
558
559
560
561
562
563
	if (dt_host_trace_proxy()) {
		host = dt_host_console();
		port = CONSOLE_COMMAND_PORT;
	} else {
		host = dt_host_controller();
		port = CTRL_COMMAND_PORT;
	}
		
Jeroen Vreeken's avatar
Jeroen Vreeken committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
	for (i = 0; i < nr_commands; i++) {
		if (!strcmp(commands[i]->name, name)) {
			command = commands[i];
			break;
		}
	}
	
	if (!command) {
		struct command **cl;
		cl = realloc(commands, 
		    sizeof(struct command *) * (nr_commands + 1));
		if (!cl)
			goto err;
		commands = cl;
		
579
		command = command_open_simple(host, port,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
580
581
582
583
584
585
586
587
588
589
590
591
592
593
		    name, "override", vtype);
		if (!command)
			goto err;
		
		cl[nr_commands] = command;
		nr_commands++;
	}

err:
	return command;
}

#define READ_SIZE 4096

594
int exec_cgi(struct lws *wsi, char *requested_uri, char *resource_path)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
{
	FILE *fpipe;
	unsigned char *outdata = NULL;
	size_t pos = 0, r;
	char *wd = get_current_dir_name();
	
	chdir(dt_host_htdocs_path());
	
	fpipe = popen(resource_path, "r");
	if (!fpipe) {
		free(wd);
		return -1;
	}
	
	do {
		outdata = realloc(outdata, pos + READ_SIZE);
		r = fread(outdata + pos, 1, READ_SIZE, fpipe);
		if (r > 0) {
			pos += r;
		}
	} while (r > 0);
	
	if (!lws_send_pipe_choked(wsi))
618
		lws_write(wsi, outdata, pos, LWS_WRITE_HTTP);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
619
620
621
622
623
624
625
626
	
	pclose(fpipe);
	free(outdata);
	free(wd);
	
	return -1;
}

627
int list_dir(struct lws *wsi, char *requested_uri, char *resource_path)
Jeroen Vreeken's avatar
Jeroen Vreeken committed
628
629
630
{
	unsigned char *outdata = malloc(1000);
	size_t pos = 0;
631
632
	struct dirent **namelist;
	int n, i;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
633
	unsigned char *h = outdata;
634
	char *server = "console_httpd lws";
Jeroen Vreeken's avatar
Jeroen Vreeken committed
635
636
	char *type = "text/html";
	
637
	if (lws_add_http_header_status(wsi, 200, &h, outdata + 1000))
Jeroen Vreeken's avatar
Jeroen Vreeken committed
638
		return 1;
639
	if (lws_add_http_header_by_token(wsi,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
640
641
642
	    WSI_TOKEN_HTTP_SERVER,
	    (unsigned char *)server, strlen(server), &h, outdata + 1000))
		return 1;
643
	if (lws_add_http_header_by_token(wsi,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
644
645
646
	    WSI_TOKEN_HTTP_CONTENT_TYPE,
	    (unsigned char *)type, strlen(type), &h, outdata + 1000))
		return 1;
647
	if (lws_finalize_http_header(wsi, &h, outdata + 1000))
Jeroen Vreeken's avatar
Jeroen Vreeken committed
648
649
650
		return 1;
	pos += h - outdata;

651
	lws_write(wsi, outdata, pos, LWS_WRITE_HTTP_HEADERS);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
652
653
654
655
	free(outdata);
	outdata = NULL;
	pos = 0;

656
657
	n = scandir(resource_path, &namelist, NULL, alphasort);
	for (i = 0; i < n; i++) {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
658
		errno = 0;
659
660
661
662

		if (namelist[i]->d_type != DT_REG) {
			printf("%s is not a regular file\n", namelist[i]->d_name);
			continue;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
663
		}
664
665
666
667
668
669
670
671
672
				
		char *line;
		asprintf(&line, "<a href='%s'>%s</a><br>\n", 
		    namelist[i]->d_name, namelist[i]->d_name);
		
		outdata = realloc(outdata, pos + strlen(line) + 1);
		strcpy((char*)outdata + pos, line);
		pos += strlen(line);
		free(line);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
673
	}
674
675
	if (n >= 0)
		free(namelist);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
676
677
	
	if (!lws_send_pipe_choked(wsi))
678
		lws_write(wsi, outdata, pos, LWS_WRITE_HTTP);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
679
680
681
682
683
684
	
	free(outdata);
	
	return -1;
}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
685
686


687
688
static int callback_http(struct lws *wsi,
                         enum lws_callback_reasons reason, void *user,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
689
690
691
692
693
694
695
                         void *in, size_t len)
{
	int r = 0;
	
	switch (reason) {
		case LWS_CALLBACK_RECEIVE: {
			char *rcv = in;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
696
			struct ws_client *ws_client;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
697
698
			printf("lws receive: %s\n", rcv);
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
699
700
			ws_client = ws_client_get_by_wsi(wsi);
			if (!ws_client) {
701
				ws_client = ws_client_add(wsi);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
702
703
			}
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
704
705
706
			if (!strncmp(rcv, "status ", 7)) {
				char *ident;
				
707
				sscanf(rcv, "%*s %ms", &ident);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
708
709
710
711
712
				start_status(wsi, ident);
			} else if (!strncmp(rcv, "trace ", 6)) {
				int freq;
				char *variable;
				
713
				sscanf(rcv, "%*s %d %ms", &freq, &variable);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
714
715
716
717
718
				start_trace(wsi, freq, variable);
			} else if (!strncmp(rcv, "command ", 8)) {
				char *ident;
				char *command;
				
719
				sscanf(rcv, "%*s %ms", &ident);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
720
721
722
723
724
725
726
727
728
729
730
				command = rcv + 8 + strlen(ident) + 1;
				do_command(ident, command);
				
				free(ident);
			} else if (!strncmp(rcv, "controller_command ", 19)) {
				char *name;
				char *type;
				struct command_entry entry;
				struct command *command;
				enum command_value_type vtype;
		
731
				sscanf(rcv, "%*s %ms %ms", &name, &type);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
732
733
734
735
736
737
738
739
				if (!strcmp(type, "bool")) {
					int v;
					sscanf(rcv, "%*s %*s %*s %d", &v);
			
					entry.value.b = v;
					entry.type = COMMAND_PTYPE_SETPOINT;
					vtype = COMMAND_VALUE_TYPE_BOOL;
				}
740
741
742
743
744
745
746
747
748
749
750
				if (!strcmp(type, "uint32")) {
					unsigned v;
					sscanf(rcv, "%*s %*s %*s %d", &v);
			
					entry.value.u32 = v;
					entry.type = COMMAND_PTYPE_SETPOINT;
					vtype = COMMAND_VALUE_TYPE_UINT32;
				}
				if (!strcmp(type, "float")) {
					float v;
					char *vstr;
751
					sscanf(rcv, "%*s %*s %*s %ms", &vstr);
752
753
754
755
756
757
758
759
760
761
762
763
764
					if (!strcmp(vstr, "TRACK")) {
						entry.value.f = 0.0;
						entry.type = COMMAND_PTYPE_SETPOINT_TRACK;
						vtype = COMMAND_VALUE_TYPE_FLOAT;
					} else {
						sscanf(rcv, "%*s %*s %*s %f", &v);
			
						entry.value.f = v;
						entry.type = COMMAND_PTYPE_SETPOINT;
						vtype = COMMAND_VALUE_TYPE_FLOAT;
					}
					free(vstr);
				}
Jeroen Vreeken's avatar
Jeroen Vreeken committed
765
766
767
768
769
770
771
772
773
774
775
776
777
778
				free(type);
		
				command = get_command(name, "override", vtype);
				if (command) {
					command_send(command, &entry);
				}
				free(name);
			}
			
			break;
		}
		case LWS_CALLBACK_CLOSED:
			status_remove(wsi);
			trace_remove(wsi);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
779
780
			ws_client_remove(ws_client_get_by_wsi(wsi));
			printf("Close connection %p\n", wsi);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
			break;

		case LWS_CALLBACK_HTTP: {
			char *requested_uri = (char *) in;
			int i;
			printf("requested URI: %s ", requested_uri);
           
	   		for (i = 0; strlen(in) > 4 && i < strlen(in) - 3; i++) {
				/* Don't go outside the htdocs dir */
				if (!strncmp(in + i, "/../", 4))
					break;
			}
	   
			if (strcmp(requested_uri, "/") == 0) {
				requested_uri = "/index.html";
			}
Jeroen Vreeken's avatar
Jeroen Vreeken committed
797
798
799
800
801
802
803
			char *cwd;
			if (strncmp(requested_uri, "/traces", 7) == 0) {
				cwd = dt_host_traces_path();
				requested_uri += 7;
			} else {
				cwd = dt_host_htdocs_path();
			}
Jeroen Vreeken's avatar
Jeroen Vreeken committed
804
			char *resource_path;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
805
806
			struct stat statbuf;
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
807
808
809
810
			resource_path = malloc(strlen(cwd) + strlen(requested_uri) + 1);
                   
			sprintf(resource_path, "%s%s", cwd, requested_uri);
			printf("resource path: %s\n", resource_path);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
811
			stat(resource_path, &statbuf);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
812
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
813
			if (S_ISDIR(statbuf.st_mode)) {
814
				r = list_dir(wsi, requested_uri, resource_path);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
815
			} else if (!strcmp(
Jeroen Vreeken's avatar
Jeroen Vreeken committed
816
817
818
819
			    resource_path + strlen(resource_path) - strlen(".cgi"),
			    ".cgi")) {
				r = exec_cgi(wsi, requested_uri, resource_path);
			} else {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
820
821
822
823
824
825
826
827
				const char *mime;
				
				if (!strcmp(
				    resource_path + strlen(resource_path) - strlen(".js"),
				    ".js"))
					mime = "application/javascript";
				else
					mime = magic_file(magic, resource_path);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
828

Jeroen Vreeken's avatar
Jeroen Vreeken committed
829
830
831
				if (!mime)
					mime = "application/octet-stream";

832
				r = lws_serve_http_file(wsi, 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
833
834
835
836
837
838
839
840
				    resource_path, mime, NULL, 0);
                   	}
			
			free(resource_path);
			break;
		}

		case LWS_CALLBACK_ADD_POLL_FD: {
841
			struct lws_pollargs *args = in;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
842
843
844
845
846
	
			poll_add(args->fd, args->events);
			break;
		}
		case LWS_CALLBACK_DEL_POLL_FD: {
847
			struct lws_pollargs *args = in;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
848
849
850
851
852
		
			poll_remove(args->fd);
			break;
		}
		case LWS_CALLBACK_CHANGE_MODE_POLL_FD: {
853
			struct lws_pollargs *args = in;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
854
855
856
857
858
		
			poll_set(args->fd, args->events);
			break;
		}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
859
860
861
862
863
864
865
866
867
868
		case LWS_CALLBACK_SERVER_WRITEABLE: {
			struct ws_client *ws_client;
			
			ws_client = ws_client_get_by_wsi(wsi);
			if (ws_client) {
				ws_client_flush(ws_client);
			}
			break;
		}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
869
870
871
872
873
874
875
876
877
	        default:
//			if (reason != 30)
//				printf("unhandled callback (%d)\n", reason);
			break;
	}

	return r;
}

878
static struct lws_protocols protocols[] = {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
    // first protocol must always be HTTP handler
    {
        "http-only",        // name
        callback_http,      // callback
        0                   // per_session_data_size
    },
    {
        NULL, NULL, 0       // end of list
    }
};

int main(void) {
	magic = magic_open(MAGIC_MIME_TYPE);
	if (magic_load(magic, NULL))
		printf("magic_load failed\n");

895
	struct lws_context *context;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
896
897
898
899
900
901
902
903
	struct lws_context_creation_info creation_info = {
		.port = dt_host_htdocs_port(),
		.iface = NULL,
		.protocols = protocols,
		.gid = -1,
		.uid = -1,
	};
    
904
	context = lws_create_context(&creation_info);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
    
	if (context == NULL) {
		fprintf(stderr, "libwebsocket init failed\n");
		return -1;
	}
    
	printf("starting server...\n");
    
	time_t prev = time(NULL);
	
	while (1) {
		int n;
		struct status *status;
		time_t now;
		
Jeroen Vreeken's avatar
Jeroen Vreeken committed
920
		n = poll(pollfds, count_pollfds, 1000);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
		if (n < 0)
			break;

		for (n = 0; n < count_pollfds; n++)
			if (pollfds[n].revents) {
				struct status *status;
				int i;
				
				for (i = 0; i < count_traces; i++) {
					struct trace *trace = traces[i];
					int fd = trace_fd_get(trace);
					
					if (fd == pollfds[n].fd) {
						trace_handle(trace, NULL);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
935
						if (trace_fd_get(trace) != fd) {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
936
937
938
939
940
941
942
943
944
945
946
							poll_remove(fd);
						}
						break;
					}
				}
				for (status = status_list; status; status = status->next) {
					if (status->fd == pollfds[n].fd) {
						status_handle(status);
						break;
					}
				}
947
				lws_service_fd(context, &pollfds[n]);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
			}
		
		now = time(NULL);
		if (prev == now)
			continue;
		prev = now;
		for (status = status_list; status; status = status->next) {
			if (status->fd < 0)
				status_reconnect(status);
				
		}
		for (n = 0; n < count_traces; n++) {
			int fd = trace_fd_get(traces[n]);
			if (fd < 0) {
				if (trace_check(traces[n])) {
					fd = trace_fd_get(traces[n]);
					poll_add(fd, POLLIN | POLLERR);
				}
			}
		}
	}
    
970
	lws_context_destroy(context);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
971
972
973
974
	magic_close(magic);
    
	return 0;
}