test-server-pthreads.c 9.8 KB

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