absorb README.rst into main README and code
[profile/ivi/libwebsockets.git] / test-server / test-server-extpoll.c
1 /*
2  * libwebsockets-test-server-extpoll - libwebsockets external poll loop sample
3  *
4  * This acts the same as libwebsockets-test-server but works with the poll
5  * loop taken out of libwebsockets and into this app.  It's an example of how
6  * you can integrate libwebsockets polling into an app that already has its
7  * own poll loop.
8  *
9  * Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
10  *
11  *  This library is free software; you can redistribute it and/or
12  *  modify it under the terms of the GNU Lesser General Public
13  *  License as published by the Free Software Foundation:
14  *  version 2.1 of the License.
15  *
16  *  This library is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  *  Lesser General Public License for more details.
20  *
21  *  You should have received a copy of the GNU Lesser General Public
22  *  License along with this library; if not, write to the Free Software
23  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
24  *  MA  02110-1301  USA
25  */
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <getopt.h>
31 #include <string.h>
32 #include <sys/time.h>
33 #ifdef __MINGW32__
34 #include "../win32port/win32helpers/websock-w32.h"
35 #else
36 #ifdef __MINGW64__
37 #include "../win32port/win32helpers/websock-w32.h"
38 #else
39 #include <poll.h>
40 #endif
41 #endif
42
43 #include "../lib/libwebsockets.h"
44
45
46 /*
47  * This demo server shows how to use libwebsockets for one or more
48  * websocket protocols in the same server
49  *
50  * It defines the following websocket protocols:
51  *
52  *  dumb-increment-protocol:  once the socket is opened, an incrementing
53  *                              ascii string is sent down it every 50ms.
54  *                              If you send "reset\n" on the websocket, then
55  *                              the incrementing number is reset to 0.
56  *
57  *  lws-mirror-protocol: copies any received packet to every connection also
58  *                              using this protocol, including the sender
59  */
60
61 #define MAX_POLL_ELEMENTS 100
62 struct pollfd pollfds[100];
63 int count_pollfds = 0;
64
65  
66
67 enum demo_protocols {
68         /* always first */
69         PROTOCOL_HTTP = 0,
70
71         PROTOCOL_DUMB_INCREMENT,
72         PROTOCOL_LWS_MIRROR,
73
74         /* always last */
75         DEMO_PROTOCOL_COUNT
76 };
77
78
79 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
80
81 /* this protocol server (always the first one) just knows how to do HTTP */
82
83 static int callback_http(struct libwebsocket_context * this,
84                 struct libwebsocket *wsi,
85                 enum libwebsocket_callback_reasons reason, void *user,
86                                                            void *in, size_t len)
87 {
88         int n;
89         char client_name[128];
90         char client_ip[128];
91
92         switch (reason) {
93         case LWS_CALLBACK_HTTP:
94                 fprintf(stderr, "serving HTTP URI %s\n", (char *)in);
95
96                 if (in && strcmp(in, "/favicon.ico") == 0) {
97                         if (libwebsockets_serve_http_file(wsi,
98                              LOCAL_RESOURCE_PATH"/favicon.ico", "image/x-icon"))
99                                 fprintf(stderr, "Failed to send favicon\n");
100                         break;
101                 }
102
103                 /* send the script... when it runs it'll start websockets */
104
105                 if (libwebsockets_serve_http_file(wsi,
106                                   LOCAL_RESOURCE_PATH"/test.html", "text/html"))
107                         fprintf(stderr, "Failed to send HTTP file\n");
108                 /* we are done with this connnection */
109                 return 1;
110
111         /*
112          * callback for confirming to continue with client IP appear in
113          * protocol 0 callback since no websocket protocol has been agreed
114          * yet.  You can just ignore this if you won't filter on client IP
115          * since the default uhandled callback return is 0 meaning let the
116          * connection continue.
117          */
118
119         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
120
121                 libwebsockets_get_peer_addresses((int)(long)user, client_name,
122                              sizeof(client_name), client_ip, sizeof(client_ip));
123
124                 fprintf(stderr, "Received network connect from %s (%s)\n",
125                                                         client_name, client_ip);
126
127                 /* if we returned non-zero from here, we kill the connection */
128                 break;
129
130         /*
131          * callbacks for managing the external poll() array appear in
132          * protocol 0 callback
133          */
134
135         case LWS_CALLBACK_ADD_POLL_FD:
136                 pollfds[count_pollfds].fd = (int)(long)user;
137                 pollfds[count_pollfds].events = (int)len;
138                 pollfds[count_pollfds++].revents = 0;
139                 break;
140
141         case LWS_CALLBACK_DEL_POLL_FD:
142                 for (n = 0; n < count_pollfds; n++)
143                         if (pollfds[n].fd == (int)(long)user)
144                                 while (n < count_pollfds) {
145                                         pollfds[n] = pollfds[n + 1];
146                                         n++;
147                                 }
148                 count_pollfds--;
149                 break;
150
151         case LWS_CALLBACK_SET_MODE_POLL_FD:
152                 for (n = 0; n < count_pollfds; n++)
153                         if (pollfds[n].fd == (int)(long)user)
154                                 pollfds[n].events |= (int)(long)len;
155                 break;
156
157         case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
158                 for (n = 0; n < count_pollfds; n++)
159                         if (pollfds[n].fd == (int)(long)user)
160                                 pollfds[n].events &= ~(int)(long)len;
161                 break;
162
163         default:
164                 break;
165         }
166
167         return 0;
168 }
169
170 /*
171  * this is just an example of parsing handshake headers, you don't need this
172  * in your code unless you will filter allowing connections by the header
173  * content
174  */
175
176 static void
177 dump_handshake_info(struct lws_tokens *lwst)
178 {
179         int n;
180         static const char *token_names[] = {
181                 [WSI_TOKEN_GET_URI] = "GET URI",
182                 [WSI_TOKEN_HOST] = "Host",
183                 [WSI_TOKEN_CONNECTION] = "Connection",
184                 [WSI_TOKEN_KEY1] = "key 1",
185                 [WSI_TOKEN_KEY2] = "key 2",
186                 [WSI_TOKEN_PROTOCOL] = "Protocol",
187                 [WSI_TOKEN_UPGRADE] = "Upgrade",
188                 [WSI_TOKEN_ORIGIN] = "Origin",
189                 [WSI_TOKEN_DRAFT] = "Draft",
190                 [WSI_TOKEN_CHALLENGE] = "Challenge",
191
192                 /* new for 04 */
193                 [WSI_TOKEN_KEY] = "Key",
194                 [WSI_TOKEN_VERSION] = "Version",
195                 [WSI_TOKEN_SWORIGIN] = "Sworigin",
196
197                 /* new for 05 */
198                 [WSI_TOKEN_EXTENSIONS] = "Extensions",
199
200                 /* client receives these */
201                 [WSI_TOKEN_ACCEPT] = "Accept",
202                 [WSI_TOKEN_NONCE] = "Nonce",
203                 [WSI_TOKEN_HTTP] = "Http",
204                 [WSI_TOKEN_MUXURL]      = "MuxURL",
205         };
206         
207         for (n = 0; n < WSI_TOKEN_COUNT; n++) {
208                 if (lwst[n].token == NULL)
209                         continue;
210
211                 fprintf(stderr, "    %s = %s\n", token_names[n], lwst[n].token);
212         }
213 }
214
215 /* dumb_increment protocol */
216
217 /*
218  * one of these is auto-created for each connection and a pointer to the
219  * appropriate instance is passed to the callback in the user parameter
220  *
221  * for this example protocol we use it to individualize the count for each
222  * connection.
223  */
224
225 struct per_session_data__dumb_increment {
226         int number;
227 };
228
229 static int
230 callback_dumb_increment(struct libwebsocket_context * this,
231                         struct libwebsocket *wsi,
232                         enum libwebsocket_callback_reasons reason,
233                                                void *user, void *in, size_t len)
234 {
235         int n;
236         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
237                                                   LWS_SEND_BUFFER_POST_PADDING];
238         unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
239         struct per_session_data__dumb_increment *pss = user;
240
241         switch (reason) {
242
243         case LWS_CALLBACK_ESTABLISHED:
244                 pss->number = 0;
245                 break;
246
247         /*
248          * in this protocol, we just use the broadcast action as the chance to
249          * send our own connection-specific data and ignore the broadcast info
250          * that is available in the 'in' parameter
251          */
252
253         case LWS_CALLBACK_BROADCAST:
254                 n = sprintf((char *)p, "%d", pss->number++);
255                 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
256                 if (n < 0) {
257                         fprintf(stderr, "ERROR writing to socket");
258                         return 1;
259                 }
260                 break;
261
262         case LWS_CALLBACK_RECEIVE:
263                 fprintf(stderr, "rx %d\n", (int)len);
264                 if (len < 6)
265                         break;
266                 if (strcmp(in, "reset\n") == 0)
267                         pss->number = 0;
268                 break;
269
270         /*
271          * this just demonstrates how to use the protocol filter. If you won't
272          * study and reject connections based on header content, you don't need
273          * to handle this callback
274          */
275
276         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
277                 dump_handshake_info((struct lws_tokens *)(long)user);
278                 /* you could return non-zero here and kill the connection */
279                 break;
280
281         default:
282                 break;
283         }
284
285         return 0;
286 }
287
288
289 /* lws-mirror_protocol */
290
291 #define MAX_MESSAGE_QUEUE 64
292
293 struct per_session_data__lws_mirror {
294         struct libwebsocket *wsi;
295         int ringbuffer_tail;
296 };
297
298 struct a_message {
299         void *payload;
300         size_t len;
301 };
302
303 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
304 static int ringbuffer_head;
305
306
307 static int
308 callback_lws_mirror(struct libwebsocket_context * this,
309                         struct libwebsocket *wsi,
310                         enum libwebsocket_callback_reasons reason,
311                                                void *user, void *in, size_t len)
312 {
313         int n;
314         struct per_session_data__lws_mirror *pss = user;
315
316         switch (reason) {
317
318         case LWS_CALLBACK_ESTABLISHED:
319                 pss->ringbuffer_tail = ringbuffer_head;
320                 pss->wsi = wsi;
321                 libwebsocket_callback_on_writable(this, wsi);
322                 break;
323
324         case LWS_CALLBACK_SERVER_WRITEABLE:
325
326                 if (pss->ringbuffer_tail != ringbuffer_head) {
327
328                         n = libwebsocket_write(wsi, (unsigned char *)
329                                    ringbuffer[pss->ringbuffer_tail].payload +
330                                    LWS_SEND_BUFFER_PRE_PADDING,
331                                    ringbuffer[pss->ringbuffer_tail].len,
332                                                                 LWS_WRITE_TEXT);
333
334                         if (n < 0) {
335                                 fprintf(stderr, "ERROR writing to socket");
336                                 exit(1);
337                         }
338
339                         if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
340                                 pss->ringbuffer_tail = 0;
341                         else
342                                 pss->ringbuffer_tail++;
343
344                         if (((ringbuffer_head - pss->ringbuffer_tail) %
345                                   MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
346                                 libwebsocket_rx_flow_control(wsi, 1);
347
348                         libwebsocket_callback_on_writable(this, wsi);
349
350                 }
351                 break;
352
353         case LWS_CALLBACK_BROADCAST:
354                 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
355                 if (n < 0)
356                         fprintf(stderr, "mirror write failed\n");
357                 break;
358
359         case LWS_CALLBACK_RECEIVE:
360
361                 if (ringbuffer[ringbuffer_head].payload)
362                         free(ringbuffer[ringbuffer_head].payload);
363
364                 ringbuffer[ringbuffer_head].payload =
365                                 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
366                                                   LWS_SEND_BUFFER_POST_PADDING);
367                 ringbuffer[ringbuffer_head].len = len;
368                 memcpy((char *)ringbuffer[ringbuffer_head].payload +
369                                           LWS_SEND_BUFFER_PRE_PADDING, in, len);
370                 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
371                         ringbuffer_head = 0;
372                 else
373                         ringbuffer_head++;
374
375                 if (((ringbuffer_head - pss->ringbuffer_tail) %
376                                   MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
377                         libwebsocket_rx_flow_control(wsi, 0);
378
379                 libwebsocket_callback_on_writable_all_protocol(
380                                                libwebsockets_get_protocol(wsi));
381                 break;
382
383         /*
384          * this just demonstrates how to use the protocol filter. If you won't
385          * study and reject connections based on header content, you don't need
386          * to handle this callback
387          */
388
389         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
390                 dump_handshake_info((struct lws_tokens *)(long)user);
391                 /* you could return non-zero here and kill the connection */
392                 break;
393
394         default:
395                 break;
396         }
397
398         return 0;
399 }
400
401
402 /* list of supported protocols and callbacks */
403
404 static struct libwebsocket_protocols protocols[] = {
405         /* first protocol must always be HTTP handler */
406
407         {
408                 "http-only",            /* name */
409                 callback_http,          /* callback */
410                 0                       /* per_session_data_size */
411         },
412         {
413                 "dumb-increment-protocol",
414                 callback_dumb_increment,
415                 sizeof(struct per_session_data__dumb_increment),
416         },
417         {
418                 "lws-mirror-protocol",
419                 callback_lws_mirror,
420                 sizeof(struct per_session_data__lws_mirror)
421         },
422         {
423                 NULL, NULL, 0           /* End of list */
424         }
425 };
426
427 static struct option options[] = {
428         { "help",       no_argument,            NULL, 'h' },
429         { "debug",      required_argument,      NULL, 'd' },
430         { "port",       required_argument,      NULL, 'p' },
431         { "ssl",        no_argument,            NULL, 's' },
432         { "killmask",   no_argument,            NULL, 'k' },
433         { "interface",  required_argument,      NULL, 'i' },
434         { NULL, 0, 0, 0 }
435 };
436
437 int main(int argc, char **argv)
438 {
439         int n = 0;
440         const char *cert_path =
441                            LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
442         const char *key_path =
443                        LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
444         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
445                                                   LWS_SEND_BUFFER_POST_PADDING];
446         int port = 7681;
447         int use_ssl = 0;
448         struct libwebsocket_context *context;
449         int opts = 0;
450         unsigned int oldus = 0;
451         char interface_name[128] = "";
452         const char *interface_ptr = NULL;
453
454         fprintf(stderr, "libwebsockets test server with external poll()\n"
455                         "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
456                                                     "licensed under LGPL2.1\n");
457
458         while (n >= 0) {
459                 n = getopt_long(argc, argv, "i:khsp:d:", options, NULL);
460                 if (n < 0)
461                         continue;
462                 switch (n) {
463                 case 'd':
464                         lws_set_log_level(atoi(optarg), NULL);
465                         break;
466                 case 's':
467                         use_ssl = 1;
468                         break;
469                 case 'k':
470                         opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
471                         break;
472                 case 'p':
473                         port = atoi(optarg);
474                         break;
475                 case 'i':
476                         strncpy(interface_name, optarg, sizeof interface_name);
477                         interface_name[(sizeof interface_name) - 1] = '\0';
478                         interface_ptr = interface_name;
479                         break;
480                 case 'h':
481                         fprintf(stderr, "Usage: test-server "
482                                         "[--port=<p>] [--ssl] "
483                                         "[-d <log bitfield>]\n");
484                         exit(1);
485                 }
486         }
487
488         if (!use_ssl)
489                 cert_path = key_path = NULL;
490
491         context = libwebsocket_create_context(port, interface_ptr, protocols,
492                                         libwebsocket_internal_extensions,
493                                         cert_path, key_path, NULL, -1, -1,
494                                         opts, NULL);
495         if (context == NULL) {
496                 fprintf(stderr, "libwebsocket init failed\n");
497                 return -1;
498         }
499
500         buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
501
502         /*
503          * This is an example of an existing application's explicit poll()
504          * loop that libwebsockets can integrate with.
505          */
506
507         while (1) {
508                 struct timeval tv;
509
510                 /*
511                  * this represents an existing server's single poll action
512                  * which also includes libwebsocket sockets
513                  */
514
515                 n = poll(pollfds, count_pollfds, 25);
516                 if (n < 0)
517                         goto done;
518
519                 if (n)
520                         for (n = 0; n < count_pollfds; n++)
521                                 if (pollfds[n].revents)
522                                         /*
523                                         * returns immediately if the fd does not
524                                         * match anything under libwebsockets
525                                         * control
526                                         */
527                                         if (libwebsocket_service_fd(context,
528                                                                   &pollfds[n]))
529                                                 goto done;
530
531                 /* do our broadcast periodically */
532
533                 gettimeofday(&tv, NULL);
534
535                 /*
536                  * This broadcasts to all dumb-increment-protocol connections
537                  * at 20Hz.
538                  *
539                  * We're just sending a character 'x', in these examples the
540                  * callbacks send their own per-connection content.
541                  *
542                  * You have to send something with nonzero length to get the
543                  * callback actions delivered.
544                  *
545                  * We take care of pre-and-post padding allocation.
546                  */
547
548                 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
549                         libwebsockets_broadcast(
550                                         &protocols[PROTOCOL_DUMB_INCREMENT],
551                                         &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
552                         oldus = tv.tv_usec;
553                 }
554         }
555
556 done:
557         libwebsocket_context_destroy(context);
558
559         return 0;
560 }