Support for HTTP POST.
[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 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
397 bail:
398                 close(pss->fd);
399                 return -1;
400
401         /*
402          * callback for confirming to continue with client IP appear in
403          * protocol 0 callback since no websocket protocol has been agreed
404          * yet.  You can just ignore this if you won't filter on client IP
405          * since the default uhandled callback return is 0 meaning let the
406          * connection continue.
407          */
408
409         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
410 #if 0
411                 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
412                              sizeof(client_name), client_ip, sizeof(client_ip));
413
414                 fprintf(stderr, "Received network connect from %s (%s)\n",
415                                                         client_name, client_ip);
416 #endif
417                 /* if we returned non-zero from here, we kill the connection */
418                 break;
419
420 #ifdef EXTERNAL_POLL
421         /*
422          * callbacks for managing the external poll() array appear in
423          * protocol 0 callback
424          */
425
426         case LWS_CALLBACK_ADD_POLL_FD:
427
428                 if (count_pollfds >= max_poll_elements) {
429                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
430                         return 1;
431                 }
432
433                 fd_lookup[fd] = count_pollfds;
434                 pollfds[count_pollfds].fd = fd;
435                 pollfds[count_pollfds].events = (int)(long)len;
436                 pollfds[count_pollfds++].revents = 0;
437                 break;
438
439         case LWS_CALLBACK_DEL_POLL_FD:
440                 if (!--count_pollfds)
441                         break;
442                 m = fd_lookup[fd];
443                 /* have the last guy take up the vacant slot */
444                 pollfds[m] = pollfds[count_pollfds];
445                 fd_lookup[pollfds[count_pollfds].fd] = m;
446                 break;
447
448         case LWS_CALLBACK_SET_MODE_POLL_FD:
449                 pollfds[fd_lookup[fd]].events |= (int)(long)len;
450                 break;
451
452         case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
453                 pollfds[fd_lookup[fd]].events &= ~(int)(long)len;
454                 break;
455 #endif
456
457         default:
458                 break;
459         }
460
461         return 0;
462 }
463
464
465 /* dumb_increment protocol */
466
467 /*
468  * one of these is auto-created for each connection and a pointer to the
469  * appropriate instance is passed to the callback in the user parameter
470  *
471  * for this example protocol we use it to individualize the count for each
472  * connection.
473  */
474
475 struct per_session_data__dumb_increment {
476         int number;
477 };
478
479 static int
480 callback_dumb_increment(struct libwebsocket_context *context,
481                         struct libwebsocket *wsi,
482                         enum libwebsocket_callback_reasons reason,
483                                                void *user, void *in, size_t len)
484 {
485         int n, m;
486         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
487                                                   LWS_SEND_BUFFER_POST_PADDING];
488         unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
489         struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user;
490
491         switch (reason) {
492
493         case LWS_CALLBACK_ESTABLISHED:
494                 lwsl_info("callback_dumb_increment: "
495                                                  "LWS_CALLBACK_ESTABLISHED\n");
496                 pss->number = 0;
497                 break;
498
499         case LWS_CALLBACK_SERVER_WRITEABLE:
500                 n = sprintf((char *)p, "%d", pss->number++);
501                 m = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
502                 if (m < n) {
503                         lwsl_err("ERROR %d writing to di socket\n", n);
504                         return -1;
505                 }
506                 if (close_testing && pss->number == 50) {
507                         lwsl_info("close tesing limit, closing\n");
508                         return -1;
509                 }
510                 break;
511
512         case LWS_CALLBACK_RECEIVE:
513 //              fprintf(stderr, "rx %d\n", (int)len);
514                 if (len < 6)
515                         break;
516                 if (strcmp((const char *)in, "reset\n") == 0)
517                         pss->number = 0;
518                 break;
519         /*
520          * this just demonstrates how to use the protocol filter. If you won't
521          * study and reject connections based on header content, you don't need
522          * to handle this callback
523          */
524
525         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
526                 dump_handshake_info(wsi);
527                 /* you could return non-zero here and kill the connection */
528                 break;
529
530         default:
531                 break;
532         }
533
534         return 0;
535 }
536
537
538 /* lws-mirror_protocol */
539
540 #define MAX_MESSAGE_QUEUE 32
541
542 struct per_session_data__lws_mirror {
543         struct libwebsocket *wsi;
544         int ringbuffer_tail;
545 };
546
547 struct a_message {
548         void *payload;
549         size_t len;
550 };
551
552 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
553 static int ringbuffer_head;
554
555 static int
556 callback_lws_mirror(struct libwebsocket_context *context,
557                         struct libwebsocket *wsi,
558                         enum libwebsocket_callback_reasons reason,
559                                                void *user, void *in, size_t len)
560 {
561         int n;
562         struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
563
564         switch (reason) {
565
566         case LWS_CALLBACK_ESTABLISHED:
567                 lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n");
568                 pss->ringbuffer_tail = ringbuffer_head;
569                 pss->wsi = wsi;
570                 break;
571
572         case LWS_CALLBACK_PROTOCOL_DESTROY:
573                 lwsl_notice("mirror protocol cleaning up\n");
574                 for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)
575                         if (ringbuffer[n].payload)
576                                 free(ringbuffer[n].payload);
577                 break;
578
579         case LWS_CALLBACK_SERVER_WRITEABLE:
580                 if (close_testing)
581                         break;
582                 while (pss->ringbuffer_tail != ringbuffer_head) {
583
584                         n = libwebsocket_write(wsi, (unsigned char *)
585                                    ringbuffer[pss->ringbuffer_tail].payload +
586                                    LWS_SEND_BUFFER_PRE_PADDING,
587                                    ringbuffer[pss->ringbuffer_tail].len,
588                                                                 LWS_WRITE_TEXT);
589                         if (n < ringbuffer[pss->ringbuffer_tail].len) {
590                                 lwsl_err("ERROR %d writing to mirror socket\n", n);
591                                 return -1;
592                         }
593                         if (n < ringbuffer[pss->ringbuffer_tail].len)
594                                 lwsl_err("mirror partial write %d vs %d\n",
595                                        n, ringbuffer[pss->ringbuffer_tail].len);
596
597                         if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
598                                 pss->ringbuffer_tail = 0;
599                         else
600                                 pss->ringbuffer_tail++;
601
602                         if (((ringbuffer_head - pss->ringbuffer_tail) &
603                                   (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15))
604                                 libwebsocket_rx_flow_allow_all_protocol(
605                                                libwebsockets_get_protocol(wsi));
606
607                         // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
608
609                         if (lws_send_pipe_choked(wsi)) {
610                                 libwebsocket_callback_on_writable(context, wsi);
611                                 break;
612                         }
613                         /*
614                          * for tests with chrome on same machine as client and
615                          * server, this is needed to stop chrome choking
616                          */
617                         usleep(1);
618                 }
619                 break;
620
621         case LWS_CALLBACK_RECEIVE:
622
623                 if (((ringbuffer_head - pss->ringbuffer_tail) &
624                                   (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {
625                         lwsl_err("dropping!\n");
626                         goto choke;
627                 }
628
629                 if (ringbuffer[ringbuffer_head].payload)
630                         free(ringbuffer[ringbuffer_head].payload);
631
632                 ringbuffer[ringbuffer_head].payload =
633                                 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
634                                                   LWS_SEND_BUFFER_POST_PADDING);
635                 ringbuffer[ringbuffer_head].len = len;
636                 memcpy((char *)ringbuffer[ringbuffer_head].payload +
637                                           LWS_SEND_BUFFER_PRE_PADDING, in, len);
638                 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
639                         ringbuffer_head = 0;
640                 else
641                         ringbuffer_head++;
642
643                 if (((ringbuffer_head - pss->ringbuffer_tail) &
644                                   (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))
645                         goto done;
646
647 choke:
648                 lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi);
649                 libwebsocket_rx_flow_control(wsi, 0);
650
651 //              lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
652 done:
653                 libwebsocket_callback_on_writable_all_protocol(
654                                                libwebsockets_get_protocol(wsi));
655                 break;
656
657         /*
658          * this just demonstrates how to use the protocol filter. If you won't
659          * study and reject connections based on header content, you don't need
660          * to handle this callback
661          */
662
663         case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
664                 dump_handshake_info(wsi);
665                 /* you could return non-zero here and kill the connection */
666                 break;
667
668         default:
669                 break;
670         }
671
672         return 0;
673 }
674
675
676 /* list of supported protocols and callbacks */
677
678 static struct libwebsocket_protocols protocols[] = {
679         /* first protocol must always be HTTP handler */
680
681         {
682                 "http-only",            /* name */
683                 callback_http,          /* callback */
684                 sizeof (struct per_session_data__http), /* per_session_data_size */
685                 0,                      /* max frame size / rx buffer */
686         },
687         {
688                 "dumb-increment-protocol",
689                 callback_dumb_increment,
690                 sizeof(struct per_session_data__dumb_increment),
691                 10,
692         },
693         {
694                 "lws-mirror-protocol",
695                 callback_lws_mirror,
696                 sizeof(struct per_session_data__lws_mirror),
697                 128,
698         },
699         { NULL, NULL, 0, 0 } /* terminator */
700 };
701
702 void sighandler(int sig)
703 {
704         force_exit = 1;
705 }
706
707 static struct option options[] = {
708         { "help",       no_argument,            NULL, 'h' },
709         { "debug",      required_argument,      NULL, 'd' },
710         { "port",       required_argument,      NULL, 'p' },
711         { "ssl",        no_argument,            NULL, 's' },
712         { "interface",  required_argument,      NULL, 'i' },
713         { "closetest",  no_argument,            NULL, 'c' },
714 #ifndef LWS_NO_DAEMONIZE
715         { "daemonize",  no_argument,            NULL, 'D' },
716 #endif
717         { "resource_path", required_argument,           NULL, 'r' },
718         { NULL, 0, 0, 0 }
719 };
720
721 int main(int argc, char **argv)
722 {
723         char cert_path[1024];
724         char key_path[1024];
725         int n = 0;
726         int use_ssl = 0;
727         struct libwebsocket_context *context;
728         int opts = 0;
729         char interface_name[128] = "";
730         const char *iface = NULL;
731 #ifndef WIN32
732         int syslog_options = LOG_PID | LOG_PERROR;
733 #endif
734         unsigned int oldus = 0;
735         struct lws_context_creation_info info;
736
737         int debug_level = 7;
738 #ifndef LWS_NO_DAEMONIZE
739         int daemonize = 0;
740 #endif
741
742         memset(&info, 0, sizeof info);
743         info.port = 7681;
744
745         while (n >= 0) {
746                 n = getopt_long(argc, argv, "ci:hsp:d:Dr:", options, NULL);
747                 if (n < 0)
748                         continue;
749                 switch (n) {
750 #ifndef LWS_NO_DAEMONIZE
751                 case 'D':
752                         daemonize = 1;
753                         #ifndef WIN32
754                         syslog_options &= ~LOG_PERROR;
755                         #endif
756                         break;
757 #endif
758                 case 'd':
759                         debug_level = atoi(optarg);
760                         break;
761                 case 's':
762                         use_ssl = 1;
763                         break;
764                 case 'p':
765                         info.port = atoi(optarg);
766                         break;
767                 case 'i':
768                         strncpy(interface_name, optarg, sizeof interface_name);
769                         interface_name[(sizeof interface_name) - 1] = '\0';
770                         iface = interface_name;
771                         break;
772                 case 'c':
773                         close_testing = 1;
774                         fprintf(stderr, " Close testing mode -- closes on "
775                                            "client after 50 dumb increments"
776                                            "and suppresses lws_mirror spam\n");
777                         break;
778                 case 'r':
779                         resource_path = optarg;
780                         printf("Setting resource path to \"%s\"\n", resource_path);
781                         break;
782                 case 'h':
783                         fprintf(stderr, "Usage: test-server "
784                                         "[--port=<p>] [--ssl] "
785                                         "[-d <log bitfield>] "
786                                         "[--resource_path <path>]\n");
787                         exit(1);
788                 }
789         }
790
791 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
792         /* 
793          * normally lock path would be /var/lock/lwsts or similar, to
794          * simplify getting started without having to take care about
795          * permissions or running as root, set to /tmp/.lwsts-lock
796          */
797         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
798                 fprintf(stderr, "Failed to daemonize\n");
799                 return 1;
800         }
801 #endif
802
803         signal(SIGINT, sighandler);
804
805 #ifndef WIN32
806         /* we will only try to log things according to our debug_level */
807         setlogmask(LOG_UPTO (LOG_DEBUG));
808         openlog("lwsts", syslog_options, LOG_DAEMON);
809 #endif
810
811         /* tell the library what debug level to emit and to send it to syslog */
812         lws_set_log_level(debug_level, lwsl_emit_syslog);
813
814         lwsl_notice("libwebsockets test server - "
815                         "(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
816                                                     "licensed under LGPL2.1\n");
817 #ifdef EXTERNAL_POLL
818         max_poll_elements = getdtablesize();
819         pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
820         fd_lookup = malloc(max_poll_elements * sizeof (int));
821         if (pollfds == NULL || fd_lookup == NULL) {
822                 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
823                 return -1;
824         }
825 #endif
826
827         info.iface = iface;
828         info.protocols = protocols;
829 #ifndef LWS_NO_EXTENSIONS
830         info.extensions = libwebsocket_get_internal_extensions();
831 #endif
832         if (!use_ssl) {
833                 info.ssl_cert_filepath = NULL;
834                 info.ssl_private_key_filepath = NULL;
835         } else {
836                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
837                         lwsl_err("resource path too long\n");
838                         return -1;
839                 }
840                 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
841                                                                 resource_path);
842                 if (strlen(resource_path) > sizeof(key_path) - 32) {
843                         lwsl_err("resource path too long\n");
844                         return -1;
845                 }
846                 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
847                                                                 resource_path);
848
849                 info.ssl_cert_filepath = cert_path;
850                 info.ssl_private_key_filepath = key_path;
851         }
852         info.gid = -1;
853         info.uid = -1;
854         info.options = opts;
855
856         context = libwebsocket_create_context(&info);
857         if (context == NULL) {
858                 lwsl_err("libwebsocket init failed\n");
859                 return -1;
860         }
861
862         n = 0;
863         while (n >= 0 && !force_exit) {
864                 struct timeval tv;
865
866                 gettimeofday(&tv, NULL);
867
868                 /*
869                  * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
870                  * live websocket connection using the DUMB_INCREMENT protocol,
871                  * as soon as it can take more packets (usually immediately)
872                  */
873
874                 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
875                         libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]);
876                         oldus = tv.tv_usec;
877                 }
878
879 #ifdef EXTERNAL_POLL
880
881                 /*
882                  * this represents an existing server's single poll action
883                  * which also includes libwebsocket sockets
884                  */
885
886                 n = poll(pollfds, count_pollfds, 50);
887                 if (n < 0)
888                         continue;
889
890
891                 if (n)
892                         for (n = 0; n < count_pollfds; n++)
893                                 if (pollfds[n].revents)
894                                         /*
895                                         * returns immediately if the fd does not
896                                         * match anything under libwebsockets
897                                         * control
898                                         */
899                                         if (libwebsocket_service_fd(context,
900                                                                   &pollfds[n]) < 0)
901                                                 goto done;
902 #else
903                 /*
904                  * If libwebsockets sockets are all we care about,
905                  * you can use this api which takes care of the poll()
906                  * and looping through finding who needed service.
907                  *
908                  * If no socket needs service, it'll return anyway after
909                  * the number of ms in the second argument.
910                  */
911
912                 n = libwebsocket_service(context, 50);
913 #endif
914         }
915
916 #ifdef EXTERNAL_POLL
917 done:
918 #endif
919
920         libwebsocket_context_destroy(context);
921
922         lwsl_notice("libwebsockets-test-server exited cleanly\n");
923
924 #ifndef WIN32
925         closelog();
926 #endif
927
928         return 0;
929 }