test-server-v2.0: disable setting default protocol
[platform/upstream/libwebsockets.git] / test-server / test-server-pthreads.c
1 /*
2  * libwebsockets-test-server - libwebsockets test implementation
3  *
4  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
5  *
6  * This file is made available under the Creative Commons CC0 1.0
7  * Universal Public Domain Dedication.
8  *
9  * The person who associated a work with this deed has dedicated
10  * the work to the public domain by waiving all of his or her rights
11  * to the work worldwide under copyright law, including all related
12  * and neighboring rights, to the extent allowed by law. You can copy,
13  * modify, distribute and perform the work, even for commercial purposes,
14  * all without asking permission.
15  *
16  * The test apps are intended to be adapted for use in your code, which
17  * may be proprietary.  So unlike the library itself, they are licensed
18  * Public Domain.
19  */
20
21 #include "test-server.h"
22 #include <pthread.h>
23
24 int close_testing;
25 int max_poll_elements;
26 int debug_level = 7;
27
28 #ifdef EXTERNAL_POLL
29 struct lws_pollfd *pollfds;
30 int *fd_lookup;
31 int count_pollfds;
32 #endif
33 volatile int force_exit = 0;
34 struct lws_context *context;
35
36 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
37 char crl_path[1024] = "";
38 #endif
39
40 /*
41  * This mutex lock protects code that changes or relies on wsi list outside of
42  * the service thread.  The service thread will acquire it when changing the
43  * wsi list and other threads should acquire it while dereferencing wsis or
44  * calling apis like lws_callback_on_writable_all_protocol() which
45  * use the wsi list and wsis from a different thread context.
46  */
47 pthread_mutex_t lock_established_conns;
48
49 /* http server gets files from this path */
50 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
51 char *resource_path = LOCAL_RESOURCE_PATH;
52
53 /*
54  * multithreaded version - protect wsi lifecycle changes in the library
55  * these are called from protocol 0 callbacks
56  */
57
58 void test_server_lock(int care)
59 {
60         if (care)
61                 pthread_mutex_lock(&lock_established_conns);
62 }
63 void test_server_unlock(int care)
64 {
65         if (care)
66                 pthread_mutex_unlock(&lock_established_conns);
67 }
68
69 /*
70  * This demo server shows how to use libwebsockets for one or more
71  * websocket protocols in the same server
72  *
73  * It defines the following websocket protocols:
74  *
75  *  dumb-increment-protocol:  once the socket is opened, an incrementing
76  *                              ascii string is sent down it every 50ms.
77  *                              If you send "reset\n" on the websocket, then
78  *                              the incrementing number is reset to 0.
79  *
80  *  lws-mirror-protocol: copies any received packet to every connection also
81  *                              using this protocol, including the sender
82  */
83
84 enum demo_protocols {
85         /* always first */
86         PROTOCOL_HTTP = 0,
87
88         PROTOCOL_DUMB_INCREMENT,
89         PROTOCOL_LWS_MIRROR,
90
91         /* always last */
92         DEMO_PROTOCOL_COUNT
93 };
94
95 /* list of supported protocols and callbacks */
96
97 static struct lws_protocols protocols[] = {
98         /* first protocol must always be HTTP handler */
99
100         {
101                 "http-only",            /* name */
102                 callback_http,          /* callback */
103                 sizeof (struct per_session_data__http), /* per_session_data_size */
104                 0,                      /* max frame size / rx buffer */
105         },
106         {
107                 "dumb-increment-protocol",
108                 callback_dumb_increment,
109                 sizeof(struct per_session_data__dumb_increment),
110                 10,
111         },
112         {
113                 "lws-mirror-protocol",
114                 callback_lws_mirror,
115                 sizeof(struct per_session_data__lws_mirror),
116                 128,
117         },
118         { NULL, NULL, 0, 0 } /* terminator */
119 };
120
121 void *thread_dumb_increment(void *threadid)
122 {
123         while (!force_exit) {
124                 /*
125                  * this lock means wsi in the active list cannot
126                  * disappear underneath us, because the code to add and remove
127                  * them is protected by the same lock
128                  */
129                 pthread_mutex_lock(&lock_established_conns);
130                 lws_callback_on_writable_all_protocol(context,
131                                 &protocols[PROTOCOL_DUMB_INCREMENT]);
132                 pthread_mutex_unlock(&lock_established_conns);
133                 usleep(100000);
134         }
135
136         pthread_exit(NULL);
137 }
138
139 void *thread_service(void *threadid)
140 {
141         while (lws_service_tsi(context, 50, (int)(long)threadid) >= 0 && !force_exit)
142                 ;
143
144         pthread_exit(NULL);
145 }
146
147 void sighandler(int sig)
148 {
149         force_exit = 1;
150         lws_cancel_service(context);
151 }
152
153 static const struct lws_extension exts[] = {
154         {
155                 "permessage-deflate",
156                 lws_extension_callback_pm_deflate,
157                 "permessage-deflate; client_no_context_takeover; client_max_window_bits"
158         },
159         {
160                 "deflate-frame",
161                 lws_extension_callback_pm_deflate,
162                 "deflate_frame"
163         },
164         { NULL, NULL, NULL /* terminator */ }
165 };
166
167 static struct option options[] = {
168         { "help",       no_argument,            NULL, 'h' },
169         { "debug",      required_argument,      NULL, 'd' },
170         { "port",       required_argument,      NULL, 'p' },
171         { "ssl",        no_argument,            NULL, 's' },
172         { "allow-non-ssl",      no_argument,    NULL, 'a' },
173         { "interface",  required_argument,      NULL, 'i' },
174         { "closetest",  no_argument,            NULL, 'c' },
175         { "libev",  no_argument,                NULL, 'e' },
176         { "threads",  required_argument,        NULL, 'j' },
177 #ifndef LWS_NO_DAEMONIZE
178         { "daemonize",  no_argument,            NULL, 'D' },
179 #endif
180         { "resource_path", required_argument,   NULL, 'r' },
181         { NULL, 0, 0, 0 }
182 };
183
184 int main(int argc, char **argv)
185 {
186         struct lws_context_creation_info info;
187         char interface_name[128] = "";
188         const char *iface = NULL;
189         pthread_t pthread_dumb, pthread_service[32];
190         char cert_path[1024];
191         char key_path[1024];
192         int threads = 1;
193         int use_ssl = 0;
194         void *retval;
195         int opts = 0;
196         int n = 0;
197 #ifndef _WIN32
198 /* LOG_PERROR is not POSIX standard, and may not be portable */
199 #ifdef __sun
200         int syslog_options = LOG_PID;
201 #else
202         int syslog_options = LOG_PID | LOG_PERROR;
203 #endif
204 #endif
205 #ifndef LWS_NO_DAEMONIZE
206         int daemonize = 0;
207 #endif
208
209         /*
210          * take care to zero down the info struct, he contains random garbaage
211          * from the stack otherwise
212          */
213         memset(&info, 0, sizeof info);
214         info.port = 7681;
215
216         pthread_mutex_init(&lock_established_conns, NULL);
217
218         while (n >= 0) {
219                 n = getopt_long(argc, argv, "eci:hsap:d:Dr:j:", options, NULL);
220                 if (n < 0)
221                         continue;
222                 switch (n) {
223                 case 'j':
224                         threads = atoi(optarg);
225                         if (threads > ARRAY_SIZE(pthread_service)) {
226                                 lwsl_err("Max threads %lu\n",
227                                          (unsigned long)ARRAY_SIZE(pthread_service));
228                                 return 1;
229                         }
230                         break;
231                 case 'e':
232                         opts |= LWS_SERVER_OPTION_LIBEV;
233                         break;
234 #ifndef LWS_NO_DAEMONIZE
235                 case 'D':
236                         daemonize = 1;
237                         #if !defined(_WIN32) && !defined(__sun)
238                         syslog_options &= ~LOG_PERROR;
239                         #endif
240                         break;
241 #endif
242                 case 'd':
243                         debug_level = atoi(optarg);
244                         break;
245                 case 's':
246                         use_ssl = 1;
247                         break;
248                 case 'a':
249                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
250                         break;
251                 case 'p':
252                         info.port = atoi(optarg);
253                         break;
254                 case 'i':
255                         strncpy(interface_name, optarg, sizeof interface_name);
256                         interface_name[(sizeof interface_name) - 1] = '\0';
257                         iface = interface_name;
258                         break;
259                 case 'c':
260                         close_testing = 1;
261                         fprintf(stderr, " Close testing mode -- closes on "
262                                            "client after 50 dumb increments"
263                                            "and suppresses lws_mirror spam\n");
264                         break;
265                 case 'r':
266                         resource_path = optarg;
267                         printf("Setting resource path to \"%s\"\n", resource_path);
268                         break;
269                 case 'h':
270                         fprintf(stderr, "Usage: test-server "
271                                         "[--port=<p>] [--ssl] "
272                                         "[-d <log bitfield>] "
273                                         "[--resource_path <path>]\n");
274                         exit(1);
275                 }
276         }
277
278 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
279         /*
280          * normally lock path would be /var/lock/lwsts or similar, to
281          * simplify getting started without having to take care about
282          * permissions or running as root, set to /tmp/.lwsts-lock
283          */
284         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
285                 fprintf(stderr, "Failed to daemonize\n");
286                 return 1;
287         }
288 #endif
289
290         signal(SIGINT, sighandler);
291
292 #ifndef _WIN32
293         /* we will only try to log things according to our debug_level */
294         setlogmask(LOG_UPTO (LOG_DEBUG));
295         openlog("lwsts", syslog_options, LOG_DAEMON);
296 #endif
297
298         /* tell the library what debug level to emit and to send it to syslog */
299         lws_set_log_level(debug_level, lwsl_emit_syslog);
300         lwsl_notice("libwebsockets test server pthreads - license LGPL2.1+SLE\n");
301         lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
302
303         printf("Using resource path \"%s\"\n", resource_path);
304 #ifdef EXTERNAL_POLL
305         max_poll_elements = getdtablesize();
306         pollfds = malloc(max_poll_elements * sizeof (struct lws_pollfd));
307         fd_lookup = malloc(max_poll_elements * sizeof (int));
308         if (pollfds == NULL || fd_lookup == NULL) {
309                 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
310                 return -1;
311         }
312 #endif
313
314         info.iface = iface;
315         info.protocols = protocols;
316         info.extensions = exts;
317
318         info.ssl_cert_filepath = NULL;
319         info.ssl_private_key_filepath = NULL;
320
321         if (use_ssl) {
322                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
323                         lwsl_err("resource path too long\n");
324                         return -1;
325                 }
326                 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
327                         resource_path);
328                 if (strlen(resource_path) > sizeof(key_path) - 32) {
329                         lwsl_err("resource path too long\n");
330                         return -1;
331                 }
332                 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
333                         resource_path);
334
335                 info.ssl_cert_filepath = cert_path;
336                 info.ssl_private_key_filepath = key_path;
337         }
338         info.gid = -1;
339         info.uid = -1;
340         info.options = opts;
341         info.count_threads = threads;
342         info.extensions = exts;
343         info.max_http_header_pool = 4;
344
345         context = lws_create_context(&info);
346         if (context == NULL) {
347                 lwsl_err("libwebsocket init failed\n");
348                 return -1;
349         }
350
351         /* start the dumb increment thread */
352
353         n = pthread_create(&pthread_dumb, NULL, thread_dumb_increment, 0);
354         if (n) {
355                 lwsl_err("Unable to create dumb thread\n");
356                 goto done;
357         }
358
359         /*
360          * notice the actual number of threads may be capped by the library,
361          * so use lws_get_count_threads() to get the actual amount of threads
362          * initialized.
363          */
364
365         for (n = 0; n < lws_get_count_threads(context); n++)
366                 if (pthread_create(&pthread_service[n], NULL, thread_service,
367                                    (void *)(long)n))
368                         lwsl_err("Failed to start service thread\n");
369
370         /* wait for all the service threads to exit */
371
372         while ((--n) >= 0)
373                 pthread_join(pthread_service[n], &retval);
374
375         /* wait for pthread_dumb to exit */
376         pthread_join(pthread_dumb, &retval);
377
378 done:
379         lws_context_destroy(context);
380         pthread_mutex_destroy(&lock_established_conns);
381
382         lwsl_notice("libwebsockets-test-server exited cleanly\n");
383
384 #ifndef _WIN32
385         closelog();
386 #endif
387
388         return 0;
389 }