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