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
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set et sw=2 ts=2: */
/***************************************************************************
* muniad.cc
*
* Thu Feb 16 15:03:28 CET 2012
* Copyright 2012 Bent Bisballe Nyeng
* deva@aasimon.org
****************************************************************************/
/*
* This file is part of Munia.
*
* Munia 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 2 of the License, or
* (at your option) any later version.
*
* Munia 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 Munia; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <sys/time.h>
#include <list>
#include <libwebsockets.h>
#include "http.h"
#include "task.h"
#define LWS_NO_FORK
static int close_testing;
/*
* this is just an example of parsing handshake headers, you don't need this
* in your code unless you will filter allowing connections by the header
* content
*/
static void dump_handshake_info(struct lws_tokens *lwst)
{
int n;
static const char *token_names[WSI_TOKEN_COUNT] = {
/*[WSI_TOKEN_GET_URI] =*/ "GET URI",
/*[WSI_TOKEN_HOST] =*/ "Host",
/*[WSI_TOKEN_CONNECTION] =*/ "Connection",
/*[WSI_TOKEN_KEY1] =*/ "key 1",
/*[WSI_TOKEN_KEY2] =*/ "key 2",
/*[WSI_TOKEN_PROTOCOL] =*/ "Protocol",
/*[WSI_TOKEN_UPGRADE] =*/ "Upgrade",
/*[WSI_TOKEN_ORIGIN] =*/ "Origin",
/*[WSI_TOKEN_DRAFT] =*/ "Draft",
/*[WSI_TOKEN_CHALLENGE] =*/ "Challenge",
/* new for 04 */
/*[WSI_TOKEN_KEY] =*/ "Key",
/*[WSI_TOKEN_VERSION] =*/ "Version",
/*[WSI_TOKEN_SWORIGIN] =*/ "Sworigin",
/* new for 05 */
/*[WSI_TOKEN_EXTENSIONS] =*/ "Extensions",
/* client receives these */
/*[WSI_TOKEN_ACCEPT] =*/ "Accept",
/*[WSI_TOKEN_NONCE] =*/ "Nonce",
/*[WSI_TOKEN_HTTP] =*/ "Http",
/*[WSI_TOKEN_MUXURL] =*/ "MuxURL",
};
for (n = 0; n < WSI_TOKEN_COUNT; n++) {
if (lwst[n].token == NULL || lwst[n].token_len == 0) continue;
fprintf(stderr, " %s = ", token_names[n]);
if(fwrite(lwst[n].token, 1, lwst[n].token_len, stderr)) {}
fprintf(stderr, "\n");
}
}
/* lws-mirror_protocol */
#define MAX_MESSAGE_QUEUE 1024
struct per_session_data__lws_mirror {
struct libwebsocket *wsi;
int ringbuffer_tail;
};
struct a_message {
void *payload;
size_t len;
};
typedef std::list<struct libwebsocket*> ClientList;
static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
static int ringbuffer_head;
static ClientList clientlist;
static int id_count = 0;
static int callback_lws_mirror(struct libwebsocket_context * context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
int n;
struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
printf("Current number of clients: %d\n", clientlist.size());
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
{
fprintf(stderr, "callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n");
pss->ringbuffer_tail = ringbuffer_head;
pss->wsi = wsi;
clientlist.push_back(wsi);
// send all current tasks
char buf[32];
std::string init_str;
TaskList::iterator it;
for(it = tasklist.begin(); it != tasklist.end(); it++) {
struct task t = *it;
sprintf(buf, "add %d %s %s %d %d;",
t.id, t.title.c_str(), t.desc.c_str(), t.x, t.y);
init_str.append(buf);
}
libwebsocket_write(wsi, (unsigned char*) init_str.data(), init_str.length(), LWS_WRITE_TEXT);
}
break;
case LWS_CALLBACK_CLOSED:
{
printf("Closing connection\n");
clientlist.remove(wsi);
}
case LWS_CALLBACK_SERVER_WRITEABLE:
{
printf("LWS_CALLBACK_SERVER_WRITEABLE\n");
if(close_testing) break;
if(pss->ringbuffer_tail != ringbuffer_head) {
n = libwebsocket_write(wsi, (unsigned char *)
ringbuffer[pss->ringbuffer_tail].payload +
LWS_SEND_BUFFER_PRE_PADDING,
ringbuffer[pss->ringbuffer_tail].len,
LWS_WRITE_TEXT);
if(n < 0) {
fprintf(stderr, "ERROR writing to socket");
exit(1);
}
if(pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1)) pss->ringbuffer_tail = 0;
else pss->ringbuffer_tail++;
if(((ringbuffer_head - pss->ringbuffer_tail) % MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
libwebsocket_rx_flow_control(wsi, 1);
libwebsocket_callback_on_writable(context, wsi);
}
}
break;
case LWS_CALLBACK_BROADCAST:
printf("LWS_CALLBACK_BROADCAST\n");
n = libwebsocket_write(wsi, (unsigned char*)in, len, LWS_WRITE_TEXT);
if (n < 0) fprintf(stderr, "mirror write failed\n");
break;
case LWS_CALLBACK_RECEIVE:
{
printf("LWS_CALLBACK_RECEIVE\n");
printf("%s\n", (char*)in);
std::string data;
data.append((char*)in, len);
struct a_message &msg = ringbuffer[ringbuffer_head];
if(msg.payload) {
free(msg.payload);
msg.payload = NULL;
}
char* buf = (char*) malloc(1024);
int buf_len = 0;
std::string cmd = data.substr(0, data.find(' '));
printf("Cmd: %s\n", cmd.c_str());
if(cmd == "add") {
printf("Handling add cmd:\n");
int offset = cmd.length() + 1;
std::string title = data.substr(offset, data.find(' ', offset) - offset);
offset += title.length() + 1;
std::string desc = data.substr(offset, data.find(' ', offset) - offset);
offset += desc.length() + 1;
std::string x_str = data.substr(offset, data.find(' ', offset) - offset);
int x = atoi(x_str.c_str());
offset += x_str.length() + 1;
std::string y_str = data.substr(offset, data.find(' ', offset) - offset);
int y = atoi(y_str.c_str());
struct task t;
t.x = x;
t.y = y;
t.title = title;
t.desc = desc;
t.id = id_count; id_count++;
tasklist.push_back(t);
buf_len = sprintf(buf, "add %d %s %s %d %d;",
t.id, t.title.c_str(), t.desc.c_str(),
t.x, t.y);
printf("Adding task: %s\n", buf);
} else if(cmd == "del") {
printf("Delete\n");
int offset = cmd.length() + 1;
std::string id_str = data.substr(offset, data.find(' ', offset) - offset);
int id = atoi(id_str.c_str());
printf("Deleting task with id %d\n", id);
bool id_found = false;
TaskList::iterator it;
for(it = tasklist.begin(); it != tasklist.end(); it++) {
struct task t = *it;
if(t.id == id) {
id_found = true;
tasklist.erase(it);
break;
}
}
if(!id_found) {
printf("\t!!!Could not locate task with id %d\n", id);
}
buf_len = sprintf(buf, "del %d;", id);
printf("Deleting task: %s\n", buf);
} else if(cmd == "move") {
printf("Move\n");
int offset = cmd.length() + 1;
std::string s_id = data.substr(offset, data.find(' ', offset) - offset);
int id = atoi(s_id.c_str());
offset += s_id.length() + 1;
std::string x_str = data.substr(offset, data.find(' ', offset) - offset);
int x = atoi(x_str.c_str());
offset += x_str.length() + 1;
std::string y_str = data.substr(offset, data.find(' ', offset) - offset);
int y = atoi(y_str.c_str());
printf("Moving task with id %d to (%d,%d)\n", id, x, y);
bool id_found = false;
TaskList::iterator it;
for(it = tasklist.begin(); it != tasklist.end(); it++) {
struct task t = *it;
if(t.id == id) {
id_found = true;
t.x = x;
t.y = y;
break;
}
}
if(!id_found) {
printf("\t!!!Could not locate task with id %d\n", id);
}
buf_len = sprintf(buf, "move %d %d %d;", id, x / 300 * 300, y);
printf("Moving task: %s\n", buf);
} else if(cmd == "update") {
printf("Update\n");
} else if(cmd == "d") {
memcpy(buf, in, len);
buf_len = len;
}
else { // unknown command
printf("Unknown command :(\n");
break;
}
// msg.payload = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING);
// msg.len = len;
// memcpy((char *)msg.payload + LWS_SEND_BUFFER_PRE_PADDING, in, len);
// if(ringbuffer_head == (MAX_MESSAGE_QUEUE - 1)) ringbuffer_head = 0;
// else ringbuffer_head++;
msg.payload = malloc(LWS_SEND_BUFFER_PRE_PADDING + buf_len
+ LWS_SEND_BUFFER_POST_PADDING);
msg.len = buf_len;
memcpy((char *)msg.payload + LWS_SEND_BUFFER_PRE_PADDING,
buf, buf_len);
if(ringbuffer_head == (MAX_MESSAGE_QUEUE - 1)) ringbuffer_head = 0;
else ringbuffer_head++;
if(((ringbuffer_head - pss->ringbuffer_tail) % MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
libwebsocket_rx_flow_control(wsi, 0);
libwebsocket_callback_on_writable_all_protocol(libwebsockets_get_protocol(wsi));
}
break;
/*
* this just demonstrates how to use the protocol filter. If you won't
* study and reject connections based on header content, you don't need
* to handle this callback
*/
case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
printf("LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION\n");
dump_handshake_info((struct lws_tokens *)(long)user);
/* you could return non-zero here and kill the connection */
break;
default:
break;
}
return 0;
}
/* list of supported protocols and callbacks */
static struct libwebsocket_protocols protocols[] = {
/* first protocol must always be HTTP handler */
{
"http-only", /* name */
callback_http, /* callback */
0 /* per_session_data_size */
},
{
"lws-mirror-protocol",
callback_lws_mirror,
sizeof(struct per_session_data__lws_mirror)
},
{
NULL, NULL, 0 /* End of list */
}
};
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "port", required_argument, NULL, 'p' },
{ "ssl", no_argument, NULL, 's' },
{ "killmask", no_argument, NULL, 'k' },
{ "interface", required_argument, NULL, 'i' },
{ "closetest", no_argument, NULL, 'c' },
{ NULL, 0, 0, 0 }
};
int main(int argc, char **argv)
{
int n = 0;
const char *cert_path =
LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
const char *key_path =
LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
LWS_SEND_BUFFER_POST_PADDING];
int port = 7681;
int use_ssl = 0;
struct libwebsocket_context *context;
int opts = 0;
char interface_name[128] = "";
const char * interface = NULL;
#ifdef LWS_NO_FORK
// unsigned int oldus = 0;
#endif
fprintf(stderr, "libwebsockets test server\n"
"(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
"licensed under LGPL2.1\n");
while (n >= 0) {
n = getopt_long(argc, argv, "ci:khsp:", options, NULL);
if (n < 0)
continue;
switch (n) {
case 's':
use_ssl = 1;
break;
case 'k':
opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
break;
case 'p':
port = atoi(optarg);
break;
case 'i':
strncpy(interface_name, optarg, sizeof interface_name);
interface_name[(sizeof interface_name) - 1] = '\0';
interface = interface_name;
break;
case 'c':
close_testing = 1;
fprintf(stderr, " Close testing mode -- closes on "
"client after 50 dumb increments"
"and suppresses lws_mirror spam\n");
break;
case 'h':
fprintf(stderr, "Usage: test-server "
"[--port=<p>] [--ssl]\n");
exit(1);
}
}
if (!use_ssl)
cert_path = key_path = NULL;
context = libwebsocket_create_context(port, interface, protocols,
libwebsocket_internal_extensions,
cert_path, key_path, -1, -1, opts);
if (context == NULL) {
fprintf(stderr, "libwebsocket init failed\n");
return -1;
}
buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
#ifdef LWS_NO_FORK
/*
* This example shows how to work with no forked service loop
*/
fprintf(stderr, " Using no-fork service loop\n");
while (1) {
/*
* This example server does not fork or create a thread for
* websocket service, it all runs in this single loop. So,
* we have to give the websockets an opportunity to service
* "manually".
*
* If no socket is needing service, the call below returns
* immediately and quickly.
*/
libwebsocket_service(context, 50);
}
#else
/*
* This example shows how to work with the forked websocket service loop
*/
fprintf(stderr, " Using forked service loop\n");
/*
* This forks the websocket service action into a subprocess so we
* don't have to take care about it.
*/
n = libwebsockets_fork_service_loop(context);
if (n < 0) {
fprintf(stderr, "Unable to fork service loop %d\n", n);
return 1;
}
while (1) {
usleep(50000);
/*
* This broadcasts to all dumb-increment-protocol connections
* at 20Hz.
*
* We're just sending a character 'x', in these examples the
* callbacks send their own per-connection content.
*
* You have to send something with nonzero length to get the
* callback actions delivered.
*
* We take care of pre-and-post padding allocation.
*/
libwebsockets_broadcast(&protocols[PROTOCOL_DUMB_INCREMENT],
&buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
}
#endif
libwebsocket_context_destroy(context);
return 0;
}
#ifdef TEST_MUNIAD
//Additional dependency files
//deps:
//Required cflags (autoconf vars may be used)
//cflags:
//Required link options (autoconf vars may be used)
//libs:
#include "test.h"
TEST_BEGIN;
// TODO: Put some testcode here (see test.h for usable macros).
TEST_TRUE(false, "No tests yet!");
TEST_END;
#endif/*TEST_MUNIAD*/
|