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