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