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