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