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