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