Fix displayed idle and online time, add CHANGES files, and some code clean up
[umurmur.git] / shm_utils / umurmurd-websocket / src / uMurmurd_Websocket.c
1 /*
2  * uMurmurd Websocket - HTTP/JSON server example
3  *
4  * Copyright (C) 2014 Michael P. Pounders <>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21 #ifdef CMAKE_BUILD
22 #include "lws_config.h"
23 #endif
24
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <getopt.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <syslog.h>
33 #include <signal.h>
34 #include <sys/time.h>
35 #include <sys/stat.h>
36
37 #include <jansson.h>
38 #include <libwebsockets.h>
39 #include "../../../src/sharedmemory.h"
40
41 struct pollfd *pollfds;
42 char *resource_path = "../web";
43 int max_poll_elements, *fd_lookup, count_pollfds, force_exit = 0, autoupdate = 0;
44
45 enum demo_protocols {
46         /* always first */
47         PROTOCOL_HTTP = 0,
48         PROTOCOL_JSON_UMURMURD,
49         /* always last */
50         DEMO_PROTOCOL_COUNT
51 };
52
53 /*
54  * We take a strict whitelist approach to stop ../ attacks
55  */
56
57 struct serveable {
58         const char *urlpath;
59         const char *mimetype;
60 }; 
61
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" },
69   
70         /* last one is the default served if no match */
71         { "/mon_umurmurd.html", "text/html" },
72 };
73
74 struct per_session_data__http {
75         int fd;
76 };
77
78 /* this protocol server (always the first one) just knows how to do HTTP */
79
80 static int callback_http( struct libwebsocket_context *context,
81                                       struct libwebsocket *wsi,
82                                       enum libwebsocket_callback_reasons reason, void *user,
83                                                                     void *in, size_t len)
84 {
85 #if 0
86         char client_name[128];
87         char client_ip[128];
88 #endif
89         char buf[256];
90         char leaf_path[1024];
91         int n, m;
92         unsigned char *p;
93         static unsigned char buffer[4096];
94         struct stat stat_buf;
95         struct per_session_data__http *pss =
96                         (struct per_session_data__http *)user;
97
98         switch (reason) {
99         case LWS_CALLBACK_HTTP:
100
101                 /* check for the "send a big file by hand" example case */
102
103                 if (!strcmp((const char *)in, "/leaf.jpg")) {
104                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
105                                 return -1;
106                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
107
108                         /* well, let's demonstrate how to send the hard way */
109
110                         p = buffer;
111
112                         pss->fd = open(leaf_path, O_RDONLY);
113
114                         if (pss->fd < 0)
115                                 return -1;
116
117                         fstat(pss->fd, &stat_buf);
118
119                         /*
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.
123                          */
124
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);
131
132                         /*
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)
137                          */
138
139                         n = libwebsocket_write(wsi, buffer,
140                                    p - buffer, LWS_WRITE_HTTP);
141
142                         if (n < 0) {
143                                 close(pss->fd);
144                                 return -1;
145                         }
146                         /*
147                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
148                          */
149                         libwebsocket_callback_on_writable(context, wsi);
150                         break;
151                 }
152
153                 /* if not, send a file the easy way */
154
155                 for (n = 0; n < (sizeof(whitelist) / sizeof(whitelist[0]) - 1); n++)
156                         if (in && strcmp((const char *)in, whitelist[n].urlpath) == 0)
157                                 break;
158
159                 sprintf(buf, "%s%s", resource_path, whitelist[n].urlpath);
160
161                 if (libwebsockets_serve_http_file(context, wsi, buf, whitelist[n].mimetype))
162                         return -1; /* through completion or error, close the socket */
163
164                 /*
165                  * notice that the sending of the file completes asynchronously,
166                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
167                  * it's done
168                  */
169
170                 break;
171
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 */
175                 return -1;
176
177         case LWS_CALLBACK_HTTP_WRITEABLE:
178                 /*
179                  * we can send more of whatever it is we were sending
180                  */
181
182                 do {
183                         n = read(pss->fd, buffer, sizeof buffer);
184                         /* problem reading, close conn */
185                         if (n < 0)
186                                 goto bail;
187                         /* sent it all, close conn */
188                         if (n == 0)
189                                 goto bail;
190                         /*
191                          * because it's HTTP and not websocket, don't need to take
192                          * care about pre and postamble
193                          */
194                         m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP);
195                         if (m < 0)
196                                 /* write failed, close conn */
197                                 goto bail;
198                         if (m != n)
199                                 /* partial write, adjust */
200                                 lseek(pss->fd, m - n, SEEK_CUR);
201
202                 } while (!lws_send_pipe_choked(wsi));
203                 libwebsocket_callback_on_writable(context, wsi);
204                 break;
205
206 bail:
207                 close(pss->fd);
208                 return -1;
209
210         /*
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.
216          */
217
218         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
219 #if 0
220                 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
221                              sizeof(client_name), client_ip, sizeof(client_ip));
222
223                 fprintf(stderr, "Received network connect from %s (%s)\n",
224                                                         client_name, client_ip);
225 #endif
226                 /* if we returned non-zero from here, we kill the connection */
227                 break;
228
229         default:
230                 break;
231         }
232
233         return 0;
234 }
235
236 /*
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
239  * content
240  */
241
242 static void
243 dump_handshake_info(struct libwebsocket *wsi)
244 {
245         int n;
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",
257
258                 /* new for 04 */
259                 /*[WSI_TOKEN_KEY]                       =*/ "Key",
260                 /*[WSI_TOKEN_VERSION]               =*/ "Version",
261                 /*[WSI_TOKEN_SWORIGIN]            =*/ "Sworigin",
262
263                 /* new for 05 */
264                 /*[WSI_TOKEN_EXTENSIONS]          =*/ "Extensions",
265
266                 /* client receives these */
267                 /*[WSI_TOKEN_ACCEPT]                =*/ "Accept",
268                 /*[WSI_TOKEN_NONCE]                   =*/ "Nonce",
269                 /*[WSI_TOKEN_HTTP]                    =*/ "Http",
270                 /*[WSI_TOKEN_MUXURL]          =*/ "MuxURL",
271         };
272         char buf[256];
273
274         for (n = 0; n < WSI_TOKEN_COUNT; n++) {
275                 if (!lws_hdr_total_length(wsi, n))
276                         continue;
277
278                 lws_hdr_copy(wsi, buf, sizeof buf, n);
279
280                 fprintf(stderr, "    %s = %s\n", token_names[n], buf);
281         }
282 }
283
284 void *getJsonData( unsigned char * buf, int *n )
285 {
286
287 int cc;
288 json_t *jarr1;
289 char *result = NULL;
290
291 json_t *root = NULL, *server = NULL, *client, *clients;
292
293     root = json_object();
294     clients = json_object();
295
296           
297           server = json_pack( "{s:{:s:i,s:i}}", 
298                               "server", 
299                               "clients_max", shmptr->server_max_clients, 
300                               "clients_connected", shmptr->clientcount );
301     
302         json_object_update( root, server );
303           
304         if( shmptr->clientcount )
305         {  
306           jarr1 = json_array();
307               
308           for( cc = 0 ; cc < shmptr->server_max_clients ; cc++ )
309           {
310           
311           if( !shmptr->client[cc].authenticated )
312             continue;
313                                                                                
314           client = json_pack( "{:s:s,s:s,s:i,s:s,s:i,s:i}", 
315                                             "username", 
316                                             shmptr->client[cc].username, 
317                                             "ipaddress", 
318                                             shmptr->client[cc].ipaddress,
319                                             "udp_port",
320                                             shmptr->client[cc].udp_port,
321                                             "channel",
322                                             shmptr->client[cc].channel,
323                                             "online_secs",
324                                             shmptr->client[cc].online_secs,
325                                             "idle_secs",
326                                             shmptr->client[cc].idle_secs                                                                                        
327                                             );                                                                                                                                                   
328           json_array_append_new( jarr1, client );
329                      
330           } 
331  json_object_set_new( clients, "clients", jarr1 );         
332  json_object_update( root, clients );
333  
334 }
335   //json_dump_file(root, "json.txt", JSON_PRESERVE_ORDER | JSON_INDENT(4) );        
336   result = json_dumps(root, JSON_PRESERVE_ORDER | JSON_COMPACT );
337
338   *n = sprintf( (char *)&buf[LWS_SEND_BUFFER_PRE_PADDING], "%s", result  );
339      
340
341   if( result )
342     free( result );
343         
344   
345
346   json_decref(root);
347   return 0;         
348 }
349
350 struct per_session_data__umurmurd_json {
351         int test;
352 };
353
354 static int
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)
359 {
360         int m, n;
361
362         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 +
363                                                         LWS_SEND_BUFFER_POST_PADDING];
364         
365         //struct per_session_data__umurmurd_json *pss = (struct per_session_data__umurmurd_json *)user;
366
367         switch (reason) {
368
369         case LWS_CALLBACK_ESTABLISHED:
370                 lwsl_info("callback_umurmurd_json: LWS_CALLBACK_ESTABLISHED\n");            
371                 break;
372
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 );
376
377     if( m == n )
378         return 1;
379                 break;
380
381         case LWS_CALLBACK_RECEIVE:
382         //fprintf(stderr, "rx %d\n", (int)len);
383 //              if (len < 6)
384 //                      break;
385                 if( strcmp((const char *)in, "update\n") == 0 )
386     {
387                         libwebsocket_callback_on_writable_all_protocol(libwebsockets_get_protocol( wsi ));
388       break;
389     }
390     else if( strcmp((const char *)in, "autoupdate\n") == 0 )
391     {
392       autoupdate = !autoupdate;  //toggle
393       break;
394     }
395       
396         /*
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
400          */
401
402         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
403                 dump_handshake_info(wsi);
404                 /* you could return non-zero here and kill the connection */
405                 break;
406
407         default:
408                 break;
409         }
410
411         return 0;
412 }
413
414
415
416 /* list of supported protocols and callbacks */
417
418 static struct libwebsocket_protocols protocols[] = {
419         /* first protocol must always be HTTP handler */
420
421         {
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 */
426         },
427         {
428                 "umurmurd-json-protocol",
429                 callback_umurmurd_json,
430                 sizeof(struct per_session_data__umurmurd_json),
431                 128,
432         },
433         { NULL, NULL, 0, 0 } /* terminator */
434 };
435
436 void sighandler(int sig)
437 {
438         force_exit = 1;
439 }
440
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' },
449         { NULL, 0, 0, 0 }
450 };
451
452 int main(int argc, char **argv)
453 {
454         char cert_path[1024];
455         char key_path[1024];
456         int n = 0;
457         int use_ssl = 0;
458         struct libwebsocket_context *context;
459         int opts = 0;
460         char interface_name[128] = "";
461         const char *iface = NULL;
462         uint64_t oldus = 0;
463         struct lws_context_creation_info info;
464
465   int syslog_options = LOG_PID | LOG_PERROR; 
466
467         int debug_level = 7;
468
469         int daemonize = 0;
470
471
472         memset(&info, 0, sizeof info);
473         info.port = 7681;
474
475         while (n >= 0) {
476                 n = getopt_long(argc, argv, "i:hsp:d:Dr:", options, NULL);
477                 if (n < 0)
478                         continue;
479                 switch (n) {
480                 case 'D':
481                         daemonize = 1;
482                         syslog_options &= ~LOG_PERROR;
483                         break;
484
485                 case 'd':
486                         debug_level = atoi(optarg);
487                         break;
488                 case 's':
489                         use_ssl = 1;
490                         break;
491                 case 'p':
492                         info.port = atoi(optarg);
493                         break;
494                 case 'i':
495                         strncpy(interface_name, optarg, sizeof interface_name);
496                         interface_name[(sizeof interface_name) - 1] = '\0';
497                         iface = interface_name;
498                         break;
499                 case 'r':
500                         resource_path = optarg;
501                         printf("Setting resource path to \"%s\"\n", resource_path);
502                         break;
503                 case 'h':
504                         fprintf(stderr, "Usage: test-server "
505                                         "[--port=<p>] [--ssl] "
506                                         "[-d <log bitfield>] "
507                                         "[--resource_path <path>]\n");
508                         exit(1);
509                 }
510         }
511
512 key_t key = 0x53021d79;
513
514                     if( ( shmid = shmget( key, 0, 0) ) == -1 )
515                     {
516                         perror("shmget");
517                         printf( "umurmurd doesn't seem to be running\n\r" );                        
518                         exit(EXIT_FAILURE);
519                     }
520
521                     
522                     if( ( shmptr = shmat( shmid,0, 0 ) ) == (void *) -1 )   
523                     {
524                         perror("shmat");
525                         exit(EXIT_FAILURE);
526                     }
527
528
529         /* 
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
533          */
534         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
535                 fprintf(stderr, "Failed to daemonize\n");
536                 return 1;
537         }
538
539
540         signal(SIGINT, sighandler);
541
542
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);
546
547
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);
550
551         lwsl_notice("uMurmurd Websocket server - "
552                         "(C) Copyright 2014 Michael J. Pounders <> - "
553                                                     "licensed under LGPL2.1\n");
554
555         info.iface = iface;
556         info.protocols = protocols;
557
558         info.extensions = libwebsocket_get_internal_extensions();
559
560         if (!use_ssl) {
561                 info.ssl_cert_filepath = NULL;
562                 info.ssl_private_key_filepath = NULL;
563         } else {
564                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
565                         lwsl_err("resource path too long\n");
566                         return -1;
567                 }
568                 sprintf(cert_path, "%s/ssl/umurmurd_websocket.pem",
569                                                                 resource_path);
570                 if (strlen(resource_path) > sizeof(key_path) - 32) {
571                         lwsl_err("resource path too long\n");
572                         return -1;
573                 }
574                 sprintf(key_path, "%s/ssl/umurmurd_websocket.key.pem",
575                                                                 resource_path);
576
577                 info.ssl_cert_filepath = cert_path;
578                 info.ssl_private_key_filepath = key_path;
579         }
580         info.gid = -1;
581         info.uid = -1;
582         info.options = opts;
583
584         context = libwebsocket_create_context(&info);
585         if (context == NULL) {
586                 lwsl_err("libwebsocket init failed\n");
587                 return -1;
588         }
589
590         n = 0;
591         while (n >= 0 && !force_exit) {
592                 struct timeval tv;
593
594                 gettimeofday(&tv, NULL);
595
596                 /*
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)
600                  */
601     if( autoupdate )
602     {
603                   if(((unsigned int)tv.tv_sec - oldus) > 1 )
604       {
605                          libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_JSON_UMURMURD]);
606         oldus = tv.tv_sec;
607                   }
608     }
609
610                 /*
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.
614                  *
615                  * If no socket needs service, it'll return anyway after
616                  * the number of ms in the second argument.
617                  */
618
619                 n = libwebsocket_service(context, 50);
620
621         }
622
623
624         libwebsocket_context_destroy(context);
625
626         lwsl_notice("uMurmurd Websocket server exited cleanly\n");
627
628   shmdt( shmptr );
629         closelog();
630
631         return 0;
632 }