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