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