2 * uMurmurd Websocket - HTTP/JSON server example
4 * Copyright (C) 2014 Michael P. Pounders <>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "lws_config.h"
38 #include <libwebsockets.h>
39 #include "../../../src/sharedmemory.h"
41 struct pollfd *pollfds;
42 char *resource_path = "../web";
43 int max_poll_elements, *fd_lookup, count_pollfds, force_exit = 0, autoupdate = 0;
48 PROTOCOL_JSON_UMURMURD,
54 * We take a strict whitelist approach to stop ../ attacks
62 static const struct serveable whitelist[] = {
63 { "/favicon.ico", "image/x-icon" },
64 { "/css/mon_umurmurd.css", "text/css" },
65 { "/css/json.human.css", "text/css" },
66 { "/js/crel.js", "text/javascript" },
67 { "/js/json.human.js", "text/javascript" },
68 { "/js/jquery.min.js", "text/javascript" },
70 /* last one is the default served if no match */
71 { "/mon_umurmurd.html", "text/html" },
74 struct per_session_data__http {
78 /* this protocol server (always the first one) just knows how to do HTTP */
80 static int callback_http( struct libwebsocket_context *context,
81 struct libwebsocket *wsi,
82 enum libwebsocket_callback_reasons reason, void *user,
86 char client_name[128];
93 static unsigned char buffer[4096];
95 struct per_session_data__http *pss =
96 (struct per_session_data__http *)user;
99 case LWS_CALLBACK_HTTP:
101 /* check for the "send a big file by hand" example case */
103 if (!strcmp((const char *)in, "/leaf.jpg")) {
104 if (strlen(resource_path) > sizeof(leaf_path) - 10)
106 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
108 /* well, let's demonstrate how to send the hard way */
112 pss->fd = open(leaf_path, O_RDONLY);
117 fstat(pss->fd, &stat_buf);
120 * we will send a big jpeg file, but it could be
121 * anything. Set the Content-Type: appropriately
122 * so the browser knows what to do with it.
125 p += sprintf((char *)p,
126 "HTTP/1.0 200 OK\x0d\x0a"
127 "Server: libwebsockets\x0d\x0a"
128 "Content-Type: image/jpeg\x0d\x0a"
129 "Content-Length: %u\x0d\x0a\x0d\x0a",
130 (unsigned int)stat_buf.st_size);
133 * send the http headers...
134 * this won't block since it's the first payload sent
135 * on the connection since it was established
136 * (too small for partial)
139 n = libwebsocket_write(wsi, buffer,
140 p - buffer, LWS_WRITE_HTTP);
147 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
149 libwebsocket_callback_on_writable(context, wsi);
153 /* if not, send a file the easy way */
155 for (n = 0; n < (sizeof(whitelist) / sizeof(whitelist[0]) - 1); n++)
156 if (in && strcmp((const char *)in, whitelist[n].urlpath) == 0)
159 sprintf(buf, "%s%s", resource_path, whitelist[n].urlpath);
161 if (libwebsockets_serve_http_file(context, wsi, buf, whitelist[n].mimetype))
162 return -1; /* through completion or error, close the socket */
165 * notice that the sending of the file completes asynchronously,
166 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
172 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
173 // lwsl_info("LWS_CALLBACK_HTTP_FILE_COMPLETION seen\n");
174 /* kill the connection after we sent one file */
177 case LWS_CALLBACK_HTTP_WRITEABLE:
179 * we can send more of whatever it is we were sending
183 n = read(pss->fd, buffer, sizeof buffer);
184 /* problem reading, close conn */
187 /* sent it all, close conn */
191 * because it's HTTP and not websocket, don't need to take
192 * care about pre and postamble
194 m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP);
196 /* write failed, close conn */
199 /* partial write, adjust */
200 lseek(pss->fd, m - n, SEEK_CUR);
202 } while (!lws_send_pipe_choked(wsi));
203 libwebsocket_callback_on_writable(context, wsi);
211 * callback for confirming to continue with client IP appear in
212 * protocol 0 callback since no websocket protocol has been agreed
213 * yet. You can just ignore this if you won't filter on client IP
214 * since the default uhandled callback return is 0 meaning let the
215 * connection continue.
218 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
220 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
221 sizeof(client_name), client_ip, sizeof(client_ip));
223 fprintf(stderr, "Received network connect from %s (%s)\n",
224 client_name, client_ip);
226 /* if we returned non-zero from here, we kill the connection */
237 * this is just an example of parsing handshake headers, you don't need this
238 * in your code unless you will filter allowing connections by the header
243 dump_handshake_info(struct libwebsocket *wsi)
246 static const char *token_names[WSI_TOKEN_COUNT] = {
247 /*[WSI_TOKEN_GET_URI] =*/ "GET URI",
248 /*[WSI_TOKEN_HOST] =*/ "Host",
249 /*[WSI_TOKEN_CONNECTION] =*/ "Connection",
250 /*[WSI_TOKEN_KEY1] =*/ "key 1",
251 /*[WSI_TOKEN_KEY2] =*/ "key 2",
252 /*[WSI_TOKEN_PROTOCOL] =*/ "Protocol",
253 /*[WSI_TOKEN_UPGRADE] =*/ "Upgrade",
254 /*[WSI_TOKEN_ORIGIN] =*/ "Origin",
255 /*[WSI_TOKEN_DRAFT] =*/ "Draft",
256 /*[WSI_TOKEN_CHALLENGE] =*/ "Challenge",
259 /*[WSI_TOKEN_KEY] =*/ "Key",
260 /*[WSI_TOKEN_VERSION] =*/ "Version",
261 /*[WSI_TOKEN_SWORIGIN] =*/ "Sworigin",
264 /*[WSI_TOKEN_EXTENSIONS] =*/ "Extensions",
266 /* client receives these */
267 /*[WSI_TOKEN_ACCEPT] =*/ "Accept",
268 /*[WSI_TOKEN_NONCE] =*/ "Nonce",
269 /*[WSI_TOKEN_HTTP] =*/ "Http",
270 /*[WSI_TOKEN_MUXURL] =*/ "MuxURL",
274 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
275 if (!lws_hdr_total_length(wsi, n))
278 lws_hdr_copy(wsi, buf, sizeof buf, n);
280 fprintf(stderr, " %s = %s\n", token_names[n], buf);
284 void *getJsonData( unsigned char * buf, int *n )
291 json_t *root = NULL, *server = NULL, *client, *clients;
293 root = json_object();
294 clients = json_object();
297 server = json_pack( "{s:{:s:i,s:i}}",
299 "clients_max", shmptr->server_max_clients,
300 "clients_connected", shmptr->clientcount );
302 json_object_update( root, server );
304 if( shmptr->clientcount )
306 jarr1 = json_array();
308 for( cc = 0 ; cc < shmptr->server_max_clients ; cc++ )
311 if( !shmptr->client[cc].authenticated )
314 client = json_pack( "{:s:s,s:s,s:i,s:s,s:i,s:i}",
316 shmptr->client[cc].username,
318 shmptr->client[cc].ipaddress,
320 shmptr->client[cc].udp_port,
322 shmptr->client[cc].channel,
324 shmptr->client[cc].online_secs,
326 shmptr->client[cc].idle_secs
328 json_array_append_new( jarr1, client );
331 json_object_set_new( clients, "clients", jarr1 );
332 json_object_update( root, clients );
335 //json_dump_file(root, "json.txt", JSON_PRESERVE_ORDER | JSON_INDENT(4) );
336 result = json_dumps(root, JSON_PRESERVE_ORDER | JSON_COMPACT );
338 *n = sprintf( (char *)&buf[LWS_SEND_BUFFER_PRE_PADDING], "%s", result );
350 struct per_session_data__umurmurd_json {
355 callback_umurmurd_json( struct libwebsocket_context *context,
356 struct libwebsocket *wsi,
357 enum libwebsocket_callback_reasons reason,
358 void *user, void *in, size_t len)
362 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 +
363 LWS_SEND_BUFFER_POST_PADDING];
365 //struct per_session_data__umurmurd_json *pss = (struct per_session_data__umurmurd_json *)user;
369 case LWS_CALLBACK_ESTABLISHED:
370 lwsl_info("callback_umurmurd_json: LWS_CALLBACK_ESTABLISHED\n");
373 case LWS_CALLBACK_SERVER_WRITEABLE:
374 getJsonData( buf, &n );
375 m = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], n, LWS_WRITE_TEXT); //printf("N: %d M: %d\n", n, m );
381 case LWS_CALLBACK_RECEIVE:
382 //fprintf(stderr, "rx %d\n", (int)len);
385 if( strcmp((const char *)in, "update\n") == 0 )
387 libwebsocket_callback_on_writable_all_protocol(libwebsockets_get_protocol( wsi ));
390 else if( strcmp((const char *)in, "autoupdate\n") == 0 )
392 autoupdate = !autoupdate; //toggle
397 * this just demonstrates how to use the protocol filter. If you won't
398 * study and reject connections based on header content, you don't need
399 * to handle this callback
402 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
403 dump_handshake_info(wsi);
404 /* you could return non-zero here and kill the connection */
416 /* list of supported protocols and callbacks */
418 static struct libwebsocket_protocols protocols[] = {
419 /* first protocol must always be HTTP handler */
422 "http-only", /* name */
423 callback_http, /* callback */
424 sizeof (struct per_session_data__http), /* per_session_data_size */
425 0, /* max frame size / rx buffer */
428 "umurmurd-json-protocol",
429 callback_umurmurd_json,
430 sizeof(struct per_session_data__umurmurd_json),
433 { NULL, NULL, 0, 0 } /* terminator */
436 void sighandler(int sig)
441 static struct option options[] = {
442 { "help", no_argument, NULL, 'h' },
443 { "debug", required_argument, NULL, 'd' },
444 { "port", required_argument, NULL, 'p' },
445 { "ssl", no_argument, NULL, 's' },
446 { "interface", required_argument, NULL, 'i' },
447 { "daemonize", no_argument, NULL, 'D' },
448 { "resource_path", required_argument, NULL, 'r' },
452 int main(int argc, char **argv)
454 char cert_path[1024];
458 struct libwebsocket_context *context;
460 char interface_name[128] = "";
461 const char *iface = NULL;
463 struct lws_context_creation_info info;
465 int syslog_options = LOG_PID | LOG_PERROR;
472 memset(&info, 0, sizeof info);
476 n = getopt_long(argc, argv, "i:hsp:d:Dr:", options, NULL);
482 syslog_options &= ~LOG_PERROR;
486 debug_level = atoi(optarg);
492 info.port = atoi(optarg);
495 strncpy(interface_name, optarg, sizeof interface_name);
496 interface_name[(sizeof interface_name) - 1] = '\0';
497 iface = interface_name;
500 resource_path = optarg;
501 printf("Setting resource path to \"%s\"\n", resource_path);
504 fprintf(stderr, "Usage: test-server "
505 "[--port=<p>] [--ssl] "
506 "[-d <log bitfield>] "
507 "[--resource_path <path>]\n");
512 key_t key = 0x53021d79;
514 if( ( shmid = shmget( key, 0, 0) ) == -1 )
517 printf( "umurmurd doesn't seem to be running\n\r" );
522 if( ( shmptr = shmat( shmid,0, 0 ) ) == (void *) -1 )
530 * normally lock path would be /var/lock/lwsts or similar, to
531 * simplify getting started without having to take care about
532 * permissions or running as root, set to /tmp/.lwsts-lock
534 if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
535 fprintf(stderr, "Failed to daemonize\n");
540 signal(SIGINT, sighandler);
543 /* we will only try to log things according to our debug_level */
544 setlogmask(LOG_UPTO (LOG_DEBUG));
545 openlog("lwsts", syslog_options, LOG_DAEMON);
548 /* tell the library what debug level to emit and to send it to syslog */
549 lws_set_log_level(debug_level, lwsl_emit_syslog);
551 lwsl_notice("uMurmurd Websocket server - "
552 "(C) Copyright 2014 Michael J. Pounders <> - "
553 "licensed under LGPL2.1\n");
556 info.protocols = protocols;
558 info.extensions = libwebsocket_get_internal_extensions();
561 info.ssl_cert_filepath = NULL;
562 info.ssl_private_key_filepath = NULL;
564 if (strlen(resource_path) > sizeof(cert_path) - 32) {
565 lwsl_err("resource path too long\n");
568 sprintf(cert_path, "%s/ssl/umurmurd_websocket.pem",
570 if (strlen(resource_path) > sizeof(key_path) - 32) {
571 lwsl_err("resource path too long\n");
574 sprintf(key_path, "%s/ssl/umurmurd_websocket.key.pem",
577 info.ssl_cert_filepath = cert_path;
578 info.ssl_private_key_filepath = key_path;
584 context = libwebsocket_create_context(&info);
585 if (context == NULL) {
586 lwsl_err("libwebsocket init failed\n");
591 while (n >= 0 && !force_exit) {
594 gettimeofday(&tv, NULL);
597 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
598 * live websocket connection using the DUMB_INCREMENT protocol,
599 * as soon as it can take more packets (usually immediately)
603 if(((unsigned int)tv.tv_sec - oldus) > 1 )
605 libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_JSON_UMURMURD]);
611 * If libwebsockets sockets are all we care about,
612 * you can use this api which takes care of the poll()
613 * and looping through finding who needed service.
615 * If no socket needs service, it'll return anyway after
616 * the number of ms in the second argument.
619 n = libwebsocket_service(context, 50);
624 libwebsocket_context_destroy(context);
626 lwsl_notice("uMurmurd Websocket server exited cleanly\n");