Optionally allow non-SSL connections on same port as SSL
[platform/upstream/libwebsockets.git] / test-server / test-server.c
1 /*
2  * libwebsockets-test-server - libwebsockets test implementation
3  *
4  * Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21 #ifdef CMAKE_BUILD
22 #include "lws_config.h"
23 #endif
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <getopt.h>
29 #include <string.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <assert.h>
34 #ifdef WIN32
35
36 #ifdef EXTERNAL_POLL
37         #ifndef WIN32_LEAN_AND_MEAN
38         #define WIN32_LEAN_AND_MEAN
39         #endif
40         #include <winsock2.h>
41         #include <ws2tcpip.h>
42         #include <stddef.h>
43
44         #include "websock-w32.h"
45 #endif
46
47 #else // NOT WIN32
48 #include <syslog.h>
49 #endif
50
51 #include <signal.h>
52
53 #include "../lib/libwebsockets.h"
54
55 static int close_testing;
56 int max_poll_elements;
57
58 struct pollfd *pollfds;
59 int *fd_lookup;
60 int count_pollfds;
61 int force_exit = 0;
62
63 /*
64  * This demo server shows how to use libwebsockets for one or more
65  * websocket protocols in the same server
66  *
67  * It defines the following websocket protocols:
68  *
69  *  dumb-increment-protocol:  once the socket is opened, an incrementing
70  *                              ascii string is sent down it every 50ms.
71  *                              If you send "reset\n" on the websocket, then
72  *                              the incrementing number is reset to 0.
73  *
74  *  lws-mirror-protocol: copies any received packet to every connection also
75  *                              using this protocol, including the sender
76  */
77
78 enum demo_protocols {
79         /* always first */
80         PROTOCOL_HTTP = 0,
81
82         PROTOCOL_DUMB_INCREMENT,
83         PROTOCOL_LWS_MIRROR,
84
85         /* always last */
86         DEMO_PROTOCOL_COUNT
87 };
88
89
90 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
91 char *resource_path = LOCAL_RESOURCE_PATH;
92
93 /*
94  * We take a strict whitelist approach to stop ../ attacks
95  */
96
97 struct serveable {
98         const char *urlpath;
99         const char *mimetype;
100 }; 
101
102 struct per_session_data__http {
103         int fd;
104 };
105
106 /*
107  * this is just an example of parsing handshake headers, you don't need this
108  * in your code unless you will filter allowing connections by the header
109  * content
110  */
111
112 static void
113 dump_handshake_info(struct libwebsocket *wsi)
114 {
115         int n;
116         static const char *token_names[] = {
117                 /*[WSI_TOKEN_GET_URI]           =*/ "GET URI",
118                 /*[WSI_TOKEN_POST_URI]          =*/ "POST URI",
119                 /*[WSI_TOKEN_HOST]              =*/ "Host",
120                 /*[WSI_TOKEN_CONNECTION]        =*/ "Connection",
121                 /*[WSI_TOKEN_KEY1]              =*/ "key 1",
122                 /*[WSI_TOKEN_KEY2]              =*/ "key 2",
123                 /*[WSI_TOKEN_PROTOCOL]          =*/ "Protocol",
124                 /*[WSI_TOKEN_UPGRADE]           =*/ "Upgrade",
125                 /*[WSI_TOKEN_ORIGIN]            =*/ "Origin",
126                 /*[WSI_TOKEN_DRAFT]             =*/ "Draft",
127                 /*[WSI_TOKEN_CHALLENGE]         =*/ "Challenge",
128
129                 /* new for 04 */
130                 /*[WSI_TOKEN_KEY]               =*/ "Key",
131                 /*[WSI_TOKEN_VERSION]           =*/ "Version",
132                 /*[WSI_TOKEN_SWORIGIN]          =*/ "Sworigin",
133
134                 /* new for 05 */
135                 /*[WSI_TOKEN_EXTENSIONS]        =*/ "Extensions",
136
137                 /* client receives these */
138                 /*[WSI_TOKEN_ACCEPT]            =*/ "Accept",
139                 /*[WSI_TOKEN_NONCE]             =*/ "Nonce",
140                 /*[WSI_TOKEN_HTTP]              =*/ "Http",
141
142                 "Accept:",
143                 "If-Modified-Since:",
144                 "Accept-Encoding:",
145                 "Accept-Language:",
146                 "Pragma:",
147                 "Cache-Control:",
148                 "Authorization:",
149                 "Cookie:",
150                 "Content-Length:",
151                 "Content-Type:",
152                 "Date:",
153                 "Range:",
154                 "Referer:",
155                 "Uri-Args:",
156
157                 /*[WSI_TOKEN_MUXURL]    =*/ "MuxURL",
158         };
159         char buf[256];
160
161         for (n = 0; n < sizeof(token_names) / sizeof(token_names[0]); n++) {
162                 if (!lws_hdr_total_length(wsi, n))
163                         continue;
164
165                 lws_hdr_copy(wsi, buf, sizeof buf, n);
166
167                 fprintf(stderr, "    %s = %s\n", token_names[n], buf);
168         }
169 }
170
171 const char * get_mimetype(const char *file)
172 {
173         int n = strlen(file);
174
175         if (n < 5)
176                 return NULL;
177
178         if (!strcmp(&file[n - 4], ".ico"))
179                 return "image/x-icon";
180
181         if (!strcmp(&file[n - 4], ".png"))
182                 return "image/png";
183
184         if (!strcmp(&file[n - 5], ".html"))
185                 return "text/html";
186
187         return NULL;
188 }
189
190 /* this protocol server (always the first one) just knows how to do HTTP */
191
192 static int callback_http(struct libwebsocket_context *context,
193                 struct libwebsocket *wsi,
194                 enum libwebsocket_callback_reasons reason, void *user,
195                                                            void *in, size_t len)
196 {
197 #if 0
198         char client_name[128];
199         char client_ip[128];
200 #endif
201         char buf[256];
202         char leaf_path[1024];
203         char b64[64];
204         struct timeval tv;
205         int n, m;
206         unsigned char *p;
207         char *other_headers;
208         static unsigned char buffer[4096];
209         struct stat stat_buf;
210         struct per_session_data__http *pss =
211                         (struct per_session_data__http *)user;
212         const char *mimetype;
213 #ifdef EXTERNAL_POLL
214         int fd = (int)(long)in;
215 #endif
216
217         switch (reason) {
218         case LWS_CALLBACK_HTTP:
219
220                 dump_handshake_info(wsi);
221
222                 if (len < 1) {
223                         libwebsockets_return_http_status(context, wsi,
224                                                 HTTP_STATUS_BAD_REQUEST, NULL);
225                         return -1;
226                 }
227
228                 /* this server has no concept of directories */
229                 if (strchr((const char *)in + 1, '/')) {
230                         libwebsockets_return_http_status(context, wsi,
231                                                 HTTP_STATUS_FORBIDDEN, NULL);
232                         return -1;
233                 }
234
235                 /* if a legal POST URL, let it continue and accept data */
236                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
237                         return 0;
238
239                 /* check for the "send a big file by hand" example case */
240
241                 if (!strcmp((const char *)in, "/leaf.jpg")) {
242                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
243                                 return -1;
244                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
245
246                         /* well, let's demonstrate how to send the hard way */
247
248                         p = buffer;
249
250 #ifdef WIN32
251                         pss->fd = open(leaf_path, O_RDONLY | _O_BINARY);
252 #else
253                         pss->fd = open(leaf_path, O_RDONLY);
254 #endif
255
256                         if (pss->fd < 0)
257                                 return -1;
258
259                         fstat(pss->fd, &stat_buf);
260
261                         /*
262                          * we will send a big jpeg file, but it could be
263                          * anything.  Set the Content-Type: appropriately
264                          * so the browser knows what to do with it.
265                          */
266
267                         p += sprintf((char *)p,
268                                 "HTTP/1.0 200 OK\x0d\x0a"
269                                 "Server: libwebsockets\x0d\x0a"
270                                 "Content-Type: image/jpeg\x0d\x0a"
271                                         "Content-Length: %u\x0d\x0a\x0d\x0a",
272                                         (unsigned int)stat_buf.st_size);
273
274                         /*
275                          * send the http headers...
276                          * this won't block since it's the first payload sent
277                          * on the connection since it was established
278                          * (too small for partial)
279                          */
280
281                         n = libwebsocket_write(wsi, buffer,
282                                    p - buffer, LWS_WRITE_HTTP);
283
284                         if (n < 0) {
285                                 close(pss->fd);
286                                 return -1;
287                         }
288                         /*
289                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
290                          */
291                         libwebsocket_callback_on_writable(context, wsi);
292                         break;
293                 }
294
295                 /* if not, send a file the easy way */
296                 strcpy(buf, resource_path);
297                 if (strcmp(in, "/")) {
298                         if (*((const char *)in) != '/')
299                                 strcat(buf, "/");
300                         strncat(buf, in, sizeof(buf) - strlen(resource_path));
301                 } else /* default file to serve */
302                         strcat(buf, "/test.html");
303                 buf[sizeof(buf) - 1] = '\0';
304
305                 /* refuse to serve files we don't understand */
306                 mimetype = get_mimetype(buf);
307                 if (!mimetype) {
308                         lwsl_err("Unknown mimetype for %s\n", buf);
309                         libwebsockets_return_http_status(context, wsi,
310                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
311                         return -1;
312                 }
313
314                 /* demostrates how to set a cookie on / */
315
316                 other_headers = NULL;
317                 if (!strcmp((const char *)in, "/") &&
318                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
319                         /* this isn't very unguessable but it'll do for us */
320                         gettimeofday(&tv, NULL);
321                         sprintf(b64, "LWS_%u_%u_COOKIE",
322                                 (unsigned int)tv.tv_sec,
323                                 (unsigned int)tv.tv_usec);
324
325                         sprintf(leaf_path,
326                                 "Set-Cookie: test=LWS_%u_%u_COOKIE;Max-Age=360000\x0d\x0a",
327                             (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);
328                         other_headers = leaf_path;
329                         lwsl_err(other_headers);
330                 }
331
332                 if (libwebsockets_serve_http_file(context, wsi, buf,
333                                                 mimetype, other_headers))
334                         return -1; /* through completion or error, close the socket */
335
336                 /*
337                  * notice that the sending of the file completes asynchronously,
338                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
339                  * it's done
340                  */
341
342                 break;
343
344         case LWS_CALLBACK_HTTP_BODY:
345                 strncpy(buf, in, 20);
346                 buf[20] = '\0';
347                 if (len < 20)
348                         buf[len] = '\0';
349
350                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
351                                 (const char *)buf, (int)len);
352
353                 break;
354
355         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
356                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
357                 /* the whole of the sent body arried, close the connection */
358                 libwebsockets_return_http_status(context, wsi,
359                                                 HTTP_STATUS_OK, NULL);
360
361                 return -1;
362
363         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
364 //              lwsl_info("LWS_CALLBACK_HTTP_FILE_COMPLETION seen\n");
365                 /* kill the connection after we sent one file */
366                 return -1;
367
368         case LWS_CALLBACK_HTTP_WRITEABLE:
369                 /*
370                  * we can send more of whatever it is we were sending
371                  */
372
373                 do {
374                         n = read(pss->fd, buffer, sizeof buffer);
375                         /* problem reading, close conn */
376                         if (n < 0)
377                                 goto bail;
378                         /* sent it all, close conn */
379                         if (n == 0)
380                                 goto flush_bail;
381                         /*
382                          * because it's HTTP and not websocket, don't need to take
383                          * care about pre and postamble
384                          */
385                         m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP);
386                         if (m < 0)
387                                 /* write failed, close conn */
388                                 goto bail;
389                         if (m != n)
390                                 /* partial write, adjust */
391                                 lseek(pss->fd, m - n, SEEK_CUR);
392
393                 } while (!lws_send_pipe_choked(wsi));
394                 libwebsocket_callback_on_writable(context, wsi);
395                 break;
396 flush_bail:
397                 /* true if still partial pending */
398                 if (lws_send_pipe_choked(wsi)) {
399                         libwebsocket_callback_on_writable(context, wsi);
400                         break;
401                 }
402
403 bail:
404                 close(pss->fd);
405                 return -1;
406
407         /*
408          * callback for confirming to continue with client IP appear in
409          * protocol 0 callback since no websocket protocol has been agreed
410          * yet.  You can just ignore this if you won't filter on client IP
411          * since the default uhandled callback return is 0 meaning let the
412          * connection continue.
413          */
414
415         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
416 #if 0
417                 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
418                              sizeof(client_name), client_ip, sizeof(client_ip));
419
420                 fprintf(stderr, "Received network connect from %s (%s)\n",
421                                                         client_name, client_ip);
422 #endif
423                 /* if we returned non-zero from here, we kill the connection */
424                 break;
425
426 #ifdef EXTERNAL_POLL
427         /*
428          * callbacks for managing the external poll() array appear in
429          * protocol 0 callback
430          */
431
432         case LWS_CALLBACK_ADD_POLL_FD:
433
434                 if (count_pollfds >= max_poll_elements) {
435                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
436                         return 1;
437                 }
438
439                 fd_lookup[fd] = count_pollfds;
440                 pollfds[count_pollfds].fd = fd;
441                 pollfds[count_pollfds].events = (int)(long)len;
442                 pollfds[count_pollfds++].revents = 0;
443                 break;
444
445         case LWS_CALLBACK_DEL_POLL_FD:
446                 if (!--count_pollfds)
447                         break;
448                 m = fd_lookup[fd];
449                 /* have the last guy take up the vacant slot */
450                 pollfds[m] = pollfds[count_pollfds];
451                 fd_lookup[pollfds[count_pollfds].fd] = m;
452                 break;
453
454         case LWS_CALLBACK_SET_MODE_POLL_FD:
455                 pollfds[fd_lookup[fd]].events |= (int)(long)len;
456                 break;
457
458         case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
459                 pollfds[fd_lookup[fd]].events &= ~(int)(long)len;
460                 break;
461 #endif
462
463         default:
464                 break;
465         }
466
467         return 0;
468 }
469
470
471 /* dumb_increment protocol */
472
473 /*
474  * one of these is auto-created for each connection and a pointer to the
475  * appropriate instance is passed to the callback in the user parameter
476  *
477  * for this example protocol we use it to individualize the count for each
478  * connection.
479  */
480
481 struct per_session_data__dumb_increment {
482         int number;
483 };
484
485 static int
486 callback_dumb_increment(struct libwebsocket_context *context,
487                         struct libwebsocket *wsi,
488                         enum libwebsocket_callback_reasons reason,
489                                                void *user, void *in, size_t len)
490 {
491         int n, m;
492         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
493                                                   LWS_SEND_BUFFER_POST_PADDING];
494         unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
495         struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user;
496
497         switch (reason) {
498
499         case LWS_CALLBACK_ESTABLISHED:
500                 lwsl_info("callback_dumb_increment: "
501                                                  "LWS_CALLBACK_ESTABLISHED\n");
502                 pss->number = 0;
503                 break;
504
505         case LWS_CALLBACK_SERVER_WRITEABLE:
506                 n = sprintf((char *)p, "%d", pss->number++);
507                 m = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
508                 if (m < n) {
509                         lwsl_err("ERROR %d writing to di socket\n", n);
510                         return -1;
511                 }
512                 if (close_testing && pss->number == 50) {
513                         lwsl_info("close tesing limit, closing\n");
514                         return -1;
515                 }
516                 break;
517
518         case LWS_CALLBACK_RECEIVE:
519 //              fprintf(stderr, "rx %d\n", (int)len);
520                 if (len < 6)
521                         break;
522                 if (strcmp((const char *)in, "reset\n") == 0)
523                         pss->number = 0;
524                 break;
525         /*
526          * this just demonstrates how to use the protocol filter. If you won't
527          * study and reject connections based on header content, you don't need
528          * to handle this callback
529          */
530
531         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
532                 dump_handshake_info(wsi);
533                 /* you could return non-zero here and kill the connection */
534                 break;
535
536         default:
537                 break;
538         }
539
540         return 0;
541 }
542
543
544 /* lws-mirror_protocol */
545
546 #define MAX_MESSAGE_QUEUE 32
547
548 struct per_session_data__lws_mirror {
549         struct libwebsocket *wsi;
550         int ringbuffer_tail;
551 };
552
553 struct a_message {
554         void *payload;
555         size_t len;
556 };
557
558 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
559 static int ringbuffer_head;
560
561 static int
562 callback_lws_mirror(struct libwebsocket_context *context,
563                         struct libwebsocket *wsi,
564                         enum libwebsocket_callback_reasons reason,
565                                                void *user, void *in, size_t len)
566 {
567         int n;
568         struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
569
570         switch (reason) {
571
572         case LWS_CALLBACK_ESTABLISHED:
573                 lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n");
574                 pss->ringbuffer_tail = ringbuffer_head;
575                 pss->wsi = wsi;
576                 break;
577
578         case LWS_CALLBACK_PROTOCOL_DESTROY:
579                 lwsl_notice("mirror protocol cleaning up\n");
580                 for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)
581                         if (ringbuffer[n].payload)
582                                 free(ringbuffer[n].payload);
583                 break;
584
585         case LWS_CALLBACK_SERVER_WRITEABLE:
586                 if (close_testing)
587                         break;
588                 while (pss->ringbuffer_tail != ringbuffer_head) {
589
590                         n = libwebsocket_write(wsi, (unsigned char *)
591                                    ringbuffer[pss->ringbuffer_tail].payload +
592                                    LWS_SEND_BUFFER_PRE_PADDING,
593                                    ringbuffer[pss->ringbuffer_tail].len,
594                                                                 LWS_WRITE_TEXT);
595                         if (n < 0) {
596                                 lwsl_err("ERROR %d writing to mirror socket\n", n);
597                                 return -1;
598                         }
599                         if (n < ringbuffer[pss->ringbuffer_tail].len)
600                                 lwsl_err("mirror partial write %d vs %d\n",
601                                        n, ringbuffer[pss->ringbuffer_tail].len);
602
603                         if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
604                                 pss->ringbuffer_tail = 0;
605                         else
606                                 pss->ringbuffer_tail++;
607
608                         if (((ringbuffer_head - pss->ringbuffer_tail) &
609                                   (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15))
610                                 libwebsocket_rx_flow_allow_all_protocol(
611                                                libwebsockets_get_protocol(wsi));
612
613                         // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
614
615                         if (lws_send_pipe_choked(wsi)) {
616                                 libwebsocket_callback_on_writable(context, wsi);
617                                 break;
618                         }
619                         /*
620                          * for tests with chrome on same machine as client and
621                          * server, this is needed to stop chrome choking
622                          */
623                         usleep(1);
624                 }
625                 break;
626
627         case LWS_CALLBACK_RECEIVE:
628
629                 if (((ringbuffer_head - pss->ringbuffer_tail) &
630                                   (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {
631                         lwsl_err("dropping!\n");
632                         goto choke;
633                 }
634
635                 if (ringbuffer[ringbuffer_head].payload)
636                         free(ringbuffer[ringbuffer_head].payload);
637
638                 ringbuffer[ringbuffer_head].payload =
639                                 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
640                                                   LWS_SEND_BUFFER_POST_PADDING);
641                 ringbuffer[ringbuffer_head].len = len;
642                 memcpy((char *)ringbuffer[ringbuffer_head].payload +
643                                           LWS_SEND_BUFFER_PRE_PADDING, in, len);
644                 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
645                         ringbuffer_head = 0;
646                 else
647                         ringbuffer_head++;
648
649                 if (((ringbuffer_head - pss->ringbuffer_tail) &
650                                   (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))
651                         goto done;
652
653 choke:
654                 lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi);
655                 libwebsocket_rx_flow_control(wsi, 0);
656
657 //              lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
658 done:
659                 libwebsocket_callback_on_writable_all_protocol(
660                                                libwebsockets_get_protocol(wsi));
661                 break;
662
663         /*
664          * this just demonstrates how to use the protocol filter. If you won't
665          * study and reject connections based on header content, you don't need
666          * to handle this callback
667          */
668
669         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
670                 dump_handshake_info(wsi);
671                 /* you could return non-zero here and kill the connection */
672                 break;
673
674         default:
675                 break;
676         }
677
678         return 0;
679 }
680
681
682 /* list of supported protocols and callbacks */
683
684 static struct libwebsocket_protocols protocols[] = {
685         /* first protocol must always be HTTP handler */
686
687         {
688                 "http-only",            /* name */
689                 callback_http,          /* callback */
690                 sizeof (struct per_session_data__http), /* per_session_data_size */
691                 0,                      /* max frame size / rx buffer */
692         },
693         {
694                 "dumb-increment-protocol",
695                 callback_dumb_increment,
696                 sizeof(struct per_session_data__dumb_increment),
697                 10,
698         },
699         {
700                 "lws-mirror-protocol",
701                 callback_lws_mirror,
702                 sizeof(struct per_session_data__lws_mirror),
703                 128,
704         },
705         { NULL, NULL, 0, 0 } /* terminator */
706 };
707
708 void sighandler(int sig)
709 {
710         force_exit = 1;
711 }
712
713 static struct option options[] = {
714         { "help",       no_argument,            NULL, 'h' },
715         { "debug",      required_argument,      NULL, 'd' },
716         { "port",       required_argument,      NULL, 'p' },
717         { "ssl",        no_argument,            NULL, 's' },
718         { "allow-non-ssl",      no_argument,            NULL, 'a' },
719         { "interface",  required_argument,      NULL, 'i' },
720         { "closetest",  no_argument,            NULL, 'c' },
721 #ifndef LWS_NO_DAEMONIZE
722         { "daemonize",  no_argument,            NULL, 'D' },
723 #endif
724         { "resource_path", required_argument,           NULL, 'r' },
725         { NULL, 0, 0, 0 }
726 };
727
728 int main(int argc, char **argv)
729 {
730         char cert_path[1024];
731         char key_path[1024];
732         int n = 0;
733         int use_ssl = 0;
734         struct libwebsocket_context *context;
735         int opts = 0;
736         char interface_name[128] = "";
737         const char *iface = NULL;
738 #ifndef WIN32
739         int syslog_options = LOG_PID | LOG_PERROR;
740 #endif
741         unsigned int oldus = 0;
742         struct lws_context_creation_info info;
743
744         int debug_level = 7;
745 #ifndef LWS_NO_DAEMONIZE
746         int daemonize = 0;
747 #endif
748
749         memset(&info, 0, sizeof info);
750         info.port = 7681;
751
752         while (n >= 0) {
753                 n = getopt_long(argc, argv, "ci:hsap:d:Dr:", options, NULL);
754                 if (n < 0)
755                         continue;
756                 switch (n) {
757 #ifndef LWS_NO_DAEMONIZE
758                 case 'D':
759                         daemonize = 1;
760                         #ifndef WIN32
761                         syslog_options &= ~LOG_PERROR;
762                         #endif
763                         break;
764 #endif
765                 case 'd':
766                         debug_level = atoi(optarg);
767                         break;
768                 case 's':
769                         use_ssl = 1;
770                         break;
771                 case 'a':
772                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
773                         break;
774                 case 'p':
775                         info.port = atoi(optarg);
776                         break;
777                 case 'i':
778                         strncpy(interface_name, optarg, sizeof interface_name);
779                         interface_name[(sizeof interface_name) - 1] = '\0';
780                         iface = interface_name;
781                         break;
782                 case 'c':
783                         close_testing = 1;
784                         fprintf(stderr, " Close testing mode -- closes on "
785                                            "client after 50 dumb increments"
786                                            "and suppresses lws_mirror spam\n");
787                         break;
788                 case 'r':
789                         resource_path = optarg;
790                         printf("Setting resource path to \"%s\"\n", resource_path);
791                         break;
792                 case 'h':
793                         fprintf(stderr, "Usage: test-server "
794                                         "[--port=<p>] [--ssl] "
795                                         "[-d <log bitfield>] "
796                                         "[--resource_path <path>]\n");
797                         exit(1);
798                 }
799         }
800
801 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
802         /* 
803          * normally lock path would be /var/lock/lwsts or similar, to
804          * simplify getting started without having to take care about
805          * permissions or running as root, set to /tmp/.lwsts-lock
806          */
807         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
808                 fprintf(stderr, "Failed to daemonize\n");
809                 return 1;
810         }
811 #endif
812
813         signal(SIGINT, sighandler);
814
815 #ifndef WIN32
816         /* we will only try to log things according to our debug_level */
817         setlogmask(LOG_UPTO (LOG_DEBUG));
818         openlog("lwsts", syslog_options, LOG_DAEMON);
819 #endif
820
821         /* tell the library what debug level to emit and to send it to syslog */
822         lws_set_log_level(debug_level, lwsl_emit_syslog);
823
824         lwsl_notice("libwebsockets test server - "
825                         "(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
826                                                     "licensed under LGPL2.1\n");
827 #ifdef EXTERNAL_POLL
828         max_poll_elements = getdtablesize();
829         pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
830         fd_lookup = malloc(max_poll_elements * sizeof (int));
831         if (pollfds == NULL || fd_lookup == NULL) {
832                 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
833                 return -1;
834         }
835 #endif
836
837         info.iface = iface;
838         info.protocols = protocols;
839 #ifndef LWS_NO_EXTENSIONS
840         info.extensions = libwebsocket_get_internal_extensions();
841 #endif
842         if (!use_ssl) {
843                 info.ssl_cert_filepath = NULL;
844                 info.ssl_private_key_filepath = NULL;
845         } else {
846                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
847                         lwsl_err("resource path too long\n");
848                         return -1;
849                 }
850                 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
851                                                                 resource_path);
852                 if (strlen(resource_path) > sizeof(key_path) - 32) {
853                         lwsl_err("resource path too long\n");
854                         return -1;
855                 }
856                 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
857                                                                 resource_path);
858
859                 info.ssl_cert_filepath = cert_path;
860                 info.ssl_private_key_filepath = key_path;
861         }
862         info.gid = -1;
863         info.uid = -1;
864         info.options = opts;
865
866         context = libwebsocket_create_context(&info);
867         if (context == NULL) {
868                 lwsl_err("libwebsocket init failed\n");
869                 return -1;
870         }
871
872         n = 0;
873         while (n >= 0 && !force_exit) {
874                 struct timeval tv;
875
876                 gettimeofday(&tv, NULL);
877
878                 /*
879                  * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
880                  * live websocket connection using the DUMB_INCREMENT protocol,
881                  * as soon as it can take more packets (usually immediately)
882                  */
883
884                 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
885                         libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]);
886                         oldus = tv.tv_usec;
887                 }
888
889 #ifdef EXTERNAL_POLL
890
891                 /*
892                  * this represents an existing server's single poll action
893                  * which also includes libwebsocket sockets
894                  */
895
896                 n = poll(pollfds, count_pollfds, 50);
897                 if (n < 0)
898                         continue;
899
900
901                 if (n)
902                         for (n = 0; n < count_pollfds; n++)
903                                 if (pollfds[n].revents)
904                                         /*
905                                         * returns immediately if the fd does not
906                                         * match anything under libwebsockets
907                                         * control
908                                         */
909                                         if (libwebsocket_service_fd(context,
910                                                                   &pollfds[n]) < 0)
911                                                 goto done;
912 #else
913                 /*
914                  * If libwebsockets sockets are all we care about,
915                  * you can use this api which takes care of the poll()
916                  * and looping through finding who needed service.
917                  *
918                  * If no socket needs service, it'll return anyway after
919                  * the number of ms in the second argument.
920                  */
921
922                 n = libwebsocket_service(context, 50);
923 #endif
924         }
925
926 #ifdef EXTERNAL_POLL
927 done:
928 #endif
929
930         libwebsocket_context_destroy(context);
931
932         lwsl_notice("libwebsockets-test-server exited cleanly\n");
933
934 #ifndef WIN32
935         closelog();
936 #endif
937
938         return 0;
939 }