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