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