console_httpd.c 20.8 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
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
struct writebuf {
	char *data;
	char *msg;
	size_t msg_len;
	
	struct writebuf *next;
};

struct ws_client {
	struct libwebsocket_context *context;
	struct libwebsocket *wsi;
	
	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;

struct ws_client *ws_client_add(struct libwebsocket_context *context, struct libwebsocket *wsi)
{
	struct ws_client *client;
	
	client = calloc(sizeof(struct ws_client), 1);
	if (!client)
		return NULL;
	
	client->context = context;
	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;
		}
	}
}

struct ws_client *ws_client_get_by_wsi(struct libwebsocket *wsi)
{
	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);

		libwebsocket_write(client->wsi, (unsigned char *)wb->msg, wb->msg_len, LWS_WRITE_TEXT);
		
		writebuf_free(wb);
	}
	
	if (client->writeq) {
		libwebsocket_callback_on_writable(client->context, client->wsi);
	}
}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
172
#define MAX_POLL_ELEMENTS 1024
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
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;
	struct libwebsocket *wsi;
	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;

static void start_status(struct libwebsocket *wsi, char *ident)
{
	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
281
	char *linebuf = (char *)status->linebuf;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
282
283
284
285
286
287
288
289
290
291
	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
292
293
294
295
296
				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
297
298
				
				linebuf[pos + i] = 0;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
299
				wb->msg_len = sprintf(wb->msg,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
300
301
				    "status %s %s\n",
				    ident, linebuf);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
302
303
304
				writebuf_add(ws_client, wb);
				ws_client_flush(ws_client);

Jeroen Vreeken's avatar
Jeroen Vreeken committed
305
306
307
308
309
310
311
312
313
				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
314
	} else if (r == 0 || errno != EAGAIN) {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
315
316
		close(fd);
		poll_remove(fd);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
317
		fd = -1;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
318
319
320
321
322
323
324
325
326
327
328
	}
	status->pos = pos;
	status->fd = fd;

	return 0;
}

static int status_reconnect(struct status *status)
{
	int fd;
	
329
	printf("reconnect: %s\n", status->ident);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
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
	fd = tcp_connect(status->host, status->port);
	if (fd >= 0) {
		poll_add(fd, POLLIN | POLLERR);
		status->pos = 0;
	}
	
	status->fd = fd;
	
	return 0;
}

static int status_remove(struct libwebsocket *wsi)
{
	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
365
#define MAX_TRACE_ELEMENTS 1024
Jeroen Vreeken's avatar
Jeroen Vreeken committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
struct trace *traces[MAX_TRACE_ELEMENTS];
int count_traces = 0;

static int trace_remove(struct libwebsocket *wsi)
{
	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;
}

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

	switch (trace->type) {
		case TRACE_VALUE_TYPE_FLOAT:
Jeroen Vreeken's avatar
Jeroen Vreeken committed
401
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %e\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
402
403
404
405
			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
406
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
407
408
409
410
			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
411
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %u\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
412
413
414
415
			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
416
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %u\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
417
418
419
420
			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
421
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %u\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
422
423
424
425
			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
426
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
427
428
429
430
			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
431
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
432
433
434
435
			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
436
			wb->msg_len = sprintf(wb->msg, "trace %s %ld.%09ld %d\n", 
Jeroen Vreeken's avatar
Jeroen Vreeken committed
437
438
439
440
			trace->name,
			value->t.tv_sec, value->t.tv_nsec, value->value.s32);
			break;
	}
Jeroen Vreeken's avatar
Jeroen Vreeken committed
441
442
	writebuf_add(ws_client, wb);
	ws_client_flush(ws_client);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
443
444
445
446
447
448
449
450
}

static void start_trace(struct libwebsocket *wsi, int freq, char *variable)
{
	struct trace *trace;
	struct timespec t_int;
	enum trace_interval_type type;
	int fd;
451
452
	char *host;
	int port;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
453

Jeroen Vreeken's avatar
Jeroen Vreeken committed
454
455
	if (count_traces + 1 >= MAX_TRACE_ELEMENTS)
		return;
456
457
458
459
460
461
462
463
464
	
	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
465
466
467
	if (!trace)
		return;
	
468
	trace_name_set(trace, 0, variable);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
469
470
471
472
473
474
475
476
477
	free(variable);
	
	trace_autorecover(trace, true);
	
	trace->private = wsi;
	
	if (freq) {
		uint64_t nsec;
		
478
		nsec = 1000000000ull / freq;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
479
480
		
		type = TRACE_INTERVAL_TYPE_INTERVAL;
481
482
		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
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
		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;
555
556
	char *host;
	int port;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
557
	
558
559
560
561
562
563
564
565
	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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
	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;
		
581
		command = command_open_simple(host, port,
Jeroen Vreeken's avatar
Jeroen Vreeken committed
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
		    name, "override", vtype);
		if (!command)
			goto err;
		
		cl[nr_commands] = command;
		nr_commands++;
	}

err:
	return command;
}

#define READ_SIZE 4096

int exec_cgi(struct libwebsocket *wsi, char *requested_uri, char *resource_path)
{
	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))
		libwebsocket_write(wsi, outdata, pos, LWS_WRITE_HTTP);
	
	pclose(fpipe);
	free(outdata);
	free(wd);
	
	return -1;
}

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

	libwebsocket_write(wsi, outdata, pos, LWS_WRITE_HTTP_HEADERS);
	free(outdata);
	outdata = NULL;
	pos = 0;

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

		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
665
		}
666
667
668
669
670
671
672
673
674
				
		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
675
	}
676
677
	if (n >= 0)
		free(namelist);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
678
679
680
681
682
683
684
685
686
	
	if (!lws_send_pipe_choked(wsi))
		libwebsocket_write(wsi, outdata, pos, LWS_WRITE_HTTP);
	
	free(outdata);
	
	return -1;
}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
687
688
689
690
691
692
693
694
695
696
697
698


static int callback_http(struct libwebsocket_context *context,
                         struct libwebsocket *wsi,
                         enum libwebsocket_callback_reasons reason, void *user,
                         void *in, size_t len)
{
	int r = 0;
	
	switch (reason) {
		case LWS_CALLBACK_RECEIVE: {
			char *rcv = in;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
699
			struct ws_client *ws_client;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
700
701
			printf("lws receive: %s\n", rcv);
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
702
703
704
705
706
			ws_client = ws_client_get_by_wsi(wsi);
			if (!ws_client) {
				ws_client = ws_client_add(context, wsi);
			}
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
			if (!strncmp(rcv, "status ", 7)) {
				char *ident;
				
				sscanf(rcv, "%*s %as", &ident);
				start_status(wsi, ident);
			} else if (!strncmp(rcv, "trace ", 6)) {
				int freq;
				char *variable;
				
				sscanf(rcv, "%*s %d %as", &freq, &variable);
				start_trace(wsi, freq, variable);
			} else if (!strncmp(rcv, "command ", 8)) {
				char *ident;
				char *command;
				
				sscanf(rcv, "%*s %as", &ident);
				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;
		
				sscanf(rcv, "%*s %as %as", &name, &type);
				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;
				}
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
				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;
					sscanf(rcv, "%*s %*s %*s %as", &vstr);
					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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
				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
782
783
			ws_client_remove(ws_client_get_by_wsi(wsi));
			printf("Close connection %p\n", wsi);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
			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
800
801
802
803
804
805
806
			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
807
			char *resource_path;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
808
809
			struct stat statbuf;
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
810
811
812
813
			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
814
			stat(resource_path, &statbuf);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
815
			
Jeroen Vreeken's avatar
Jeroen Vreeken committed
816
			if (S_ISDIR(statbuf.st_mode)) {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
817
818
				r = list_dir(context, wsi, requested_uri, resource_path);
			} else if (!strcmp(
Jeroen Vreeken's avatar
Jeroen Vreeken committed
819
820
821
822
			    resource_path + strlen(resource_path) - strlen(".cgi"),
			    ".cgi")) {
				r = exec_cgi(wsi, requested_uri, resource_path);
			} else {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
823
824
825
826
827
828
829
830
				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
831

Jeroen Vreeken's avatar
Jeroen Vreeken committed
832
833
834
				if (!mime)
					mime = "application/octet-stream";

Jeroen Vreeken's avatar
Jeroen Vreeken committed
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
				r = libwebsockets_serve_http_file(context, wsi, 
				    resource_path, mime, NULL, 0);
                   	}
			
			free(resource_path);
			break;
		}

		case LWS_CALLBACK_ADD_POLL_FD: {
			struct libwebsocket_pollargs *args = in;
	
			poll_add(args->fd, args->events);
			break;
		}
		case LWS_CALLBACK_DEL_POLL_FD: {
			struct libwebsocket_pollargs *args = in;
		
			poll_remove(args->fd);
			break;
		}
		case LWS_CALLBACK_CHANGE_MODE_POLL_FD: {
			struct libwebsocket_pollargs *args = in;
		
			poll_set(args->fd, args->events);
			break;
		}

Jeroen Vreeken's avatar
Jeroen Vreeken committed
862
863
864
865
866
867
868
869
870
871
		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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
	        default:
//			if (reason != 30)
//				printf("unhandled callback (%d)\n", reason);
			break;
	}

	return r;
}

static struct libwebsocket_protocols protocols[] = {
    // 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");

	struct libwebsocket_context *context;
	struct lws_context_creation_info creation_info = {
		.port = dt_host_htdocs_port(),
		.iface = NULL,
		.protocols = protocols,
		.gid = -1,
		.uid = -1,
	};
    
	context = libwebsocket_create_context(&creation_info);
    
	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
923
		n = poll(pollfds, count_pollfds, 1000);
Jeroen Vreeken's avatar
Jeroen Vreeken committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
		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
938
						if (trace_fd_get(trace) != fd) {
Jeroen Vreeken's avatar
Jeroen Vreeken committed
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
							poll_remove(fd);
						}
						break;
					}
				}
				for (status = status_list; status; status = status->next) {
					if (status->fd == pollfds[n].fd) {
						status_handle(status);
						break;
					}
				}
				libwebsocket_service_fd(context, &pollfds[n]);
			}
		
		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);
				}
			}
		}
	}
    
	libwebsocket_context_destroy(context);
	magic_close(magic);
    
	return 0;
}