2 * libwebsockets-test-server - libwebsockets test implementation
4 * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
6 * This file is made available under the Creative Commons CC0 1.0
7 * Universal Public Domain Dedication.
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.
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
20 #include "test-server.h"
23 * This demo server shows how to use libwebsockets for one or more
24 * websocket protocols in the same server
26 * It defines the following websocket protocols:
28 * dumb-increment-protocol: once the socket is opened, an incrementing
29 * ascii string is sent down it every 50ms.
30 * If you send "reset\n" on the websocket, then
31 * the incrementing number is reset to 0.
33 * lws-mirror-protocol: copies any received packet to every connection also
34 * using this protocol, including the sender
37 #ifdef LWS_OPENSSL_SUPPORT
38 #include <openssl/err.h>
41 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
42 /* location of the certificate revocation list */
43 char crl_path[1024] = "";
46 extern int debug_level;
52 PROTOCOL_DUMB_INCREMENT,
60 * We take a strict whitelist approach to stop ../ attacks
68 * this is just an example of parsing handshake headers, you don't need this
69 * in your code unless you will filter allowing connections by the header
73 dump_handshake_info(struct lws *wsi)
77 const unsigned char *c;
80 c = lws_token_to_string(n);
86 len = lws_hdr_total_length(wsi, n);
87 if (!len || len > sizeof(buf) - 1) {
92 lws_hdr_copy(wsi, buf, sizeof buf, n);
93 buf[sizeof(buf) - 1] = '\0';
95 fprintf(stderr, " %s = %s\n", (char *)c, buf);
100 const char * get_mimetype(const char *file)
102 int n = strlen(file);
107 if (!strcmp(&file[n - 4], ".ico"))
108 return "image/x-icon";
110 if (!strcmp(&file[n - 4], ".png"))
113 if (!strcmp(&file[n - 5], ".html"))
116 if (!strcmp(&file[n - 4], ".css"))
122 /* this protocol server (always the first one) handles HTTP,
124 * Some misc callbacks that aren't associated with a protocol also turn up only
125 * here on the first protocol server.
128 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
129 void *in, size_t len)
131 struct per_session_data__http *pss =
132 (struct per_session_data__http *)user;
133 unsigned char buffer[4096 + LWS_PRE];
134 unsigned long amount, file_len, sent;
135 char leaf_path[1024];
136 const char *mimetype;
141 #ifndef LWS_NO_CLIENT
142 struct per_session_data__http *pss1;
149 struct lws_pollargs *pa = (struct lws_pollargs *)in;
154 case LWS_CALLBACK_HTTP:
156 lwsl_notice("lws_http_serve: %s\n",in);
158 if (debug_level & LLL_INFO) {
159 dump_handshake_info(wsi);
161 /* dump the individual URI Arg parameters */
163 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
164 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
165 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
170 char name[100], rip[50];
171 lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
172 sizeof(name), rip, sizeof(rip));
173 sprintf(buf, "%s (%s)", name, rip);
174 lwsl_notice("HTTP connect from %s\n", buf);
178 lws_return_http_status(wsi,
179 HTTP_STATUS_BAD_REQUEST, NULL);
183 #ifndef LWS_NO_CLIENT
184 if (!strncmp(in, "/proxytest", 10)) {
185 struct lws_client_connect_info i;
186 char *rootpath = "/";
187 const char *p = (const char *)in;
189 if (lws_get_child(wsi))
192 pss->client_finished = 0;
193 memset(&i,0, sizeof(i));
194 i.context = lws_get_context(wsi);
195 i.address = "git.libwebsockets.org";
197 i.ssl_connection = 0;
199 i.path = (char *)in + 10;
202 i.host = "git.libwebsockets.org";
206 i.uri_replace_from = "git.libwebsockets.org/";
207 i.uri_replace_to = "/proxytest/";
208 if (!lws_client_connect_via_info(&i)) {
209 lwsl_err("proxy connect fail\n");
220 /* this example server has no concept of directories */
221 if (strchr((const char *)in + 1, '/')) {
222 lws_return_http_status(wsi, HTTP_STATUS_NOT_ACCEPTABLE, NULL);
227 /* if a legal POST URL, let it continue and accept data */
228 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
231 /* check for the "send a big file by hand" example case */
233 if (!strcmp((const char *)in, "/leaf.jpg")) {
234 if (strlen(resource_path) > sizeof(leaf_path) - 10)
236 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
238 /* well, let's demonstrate how to send the hard way */
240 p = buffer + LWS_PRE;
241 end = p + sizeof(buffer) - LWS_PRE;
243 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
246 if (pss->fd == LWS_INVALID_FILE) {
247 lwsl_err("faild to open file %s\n", leaf_path);
252 * we will send a big jpeg file, but it could be
253 * anything. Set the Content-Type: appropriately
254 * so the browser knows what to do with it.
256 * Notice we use the APIs to build the header, which
257 * will do the right thing for HTTP 1/1.1 and HTTP2
258 * depending on what connection it happens to be working
261 if (lws_add_http_header_status(wsi, 200, &p, end))
263 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
264 (unsigned char *)"libwebsockets",
267 if (lws_add_http_header_by_token(wsi,
268 WSI_TOKEN_HTTP_CONTENT_TYPE,
269 (unsigned char *)"image/jpeg",
272 if (lws_add_http_header_content_length(wsi,
276 if (lws_finalize_http_header(wsi, &p, end))
280 * send the http headers...
281 * this won't block since it's the first payload sent
282 * on the connection since it was established
283 * (too small for partial)
285 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
286 * which also means you can't send body too in one step,
287 * this is mandated by changes in HTTP2
291 lwsl_info("%s\n", buffer + LWS_PRE);
293 n = lws_write(wsi, buffer + LWS_PRE,
294 p - (buffer + LWS_PRE),
295 LWS_WRITE_HTTP_HEADERS);
297 lws_plat_file_close(wsi, pss->fd);
301 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
303 lws_callback_on_writable(wsi);
307 /* if not, send a file the easy way */
308 if (!strncmp(in, "/cgit-data/", 11)) {
309 in = (char *)in + 11;
310 strcpy(buf, "/usr/share/cgit");
312 strcpy(buf, resource_path);
314 if (strcmp(in, "/")) {
315 if (*((const char *)in) != '/')
317 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
318 } else /* default file to serve */
319 strcat(buf, "/test.html");
320 buf[sizeof(buf) - 1] = '\0';
322 /* refuse to serve files we don't understand */
323 mimetype = get_mimetype(buf);
325 lwsl_err("Unknown mimetype for %s\n", buf);
326 lws_return_http_status(wsi,
327 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
331 /* demonstrates how to set a cookie on / */
333 other_headers = leaf_path;
334 p = (unsigned char *)leaf_path;
335 if (!strcmp((const char *)in, "/") &&
336 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
337 /* this isn't very unguessable but it'll do for us */
338 gettimeofday(&tv, NULL);
339 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
340 (unsigned int)tv.tv_sec,
341 (unsigned int)tv.tv_usec);
343 if (lws_add_http_header_by_name(wsi,
344 (unsigned char *)"set-cookie:",
345 (unsigned char *)b64, n, &p,
346 (unsigned char *)leaf_path + sizeof(leaf_path)))
349 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
351 "Strict-Transport-Security:",
353 "max-age=15768000 ; "
354 "includeSubDomains", 36, &p,
355 (unsigned char *)leaf_path +
358 n = (char *)p - leaf_path;
360 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
361 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
362 return -1; /* error or can't reuse connection: close the socket */
365 * notice that the sending of the file completes asynchronously,
366 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
371 case LWS_CALLBACK_HTTP_BODY:
372 strncpy(buf, in, 20);
377 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
378 (const char *)buf, (int)len);
382 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
383 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
384 /* the whole of the sent body arrived, close or reuse the connection */
385 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
388 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
391 case LWS_CALLBACK_HTTP_WRITEABLE:
392 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
394 if (pss->client_finished)
397 if (pss->fd == LWS_INVALID_FILE)
400 #ifndef LWS_NO_CLIENT
401 if (pss->reason_bf & 2) {
402 char *px = buf + LWS_PRE;
403 int lenx = sizeof(buf) - LWS_PRE;
405 * our sink is writeable and our source has something
406 * to read. So read a lump of source material of
407 * suitable size to send or what's available, whichever
410 pss->reason_bf &= ~2;
411 wsi1 = lws_get_child(wsi);
414 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
417 if (pss->client_finished)
423 * we can send more of whatever it is we were sending
427 /* we'd like the send this much */
428 n = sizeof(buffer) - LWS_PRE;
430 /* but if the peer told us he wants less, we can adapt */
431 m = lws_get_peer_write_allowance(wsi);
433 /* -1 means not using a protocol that has this info */
435 /* right now, peer can't handle anything */
438 if (m != -1 && m < n)
439 /* he couldn't handle that much */
442 n = lws_plat_file_read(wsi, pss->fd,
443 &amount, buffer + LWS_PRE, n);
444 /* problem reading, close conn */
446 lwsl_err("problem reading file\n");
450 /* sent it all, close conn */
454 * To support HTTP2, must take care about preamble space
456 * identification of when we send the last payload frame
457 * is handled by the library itself if you sent a
458 * content-length header
460 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
462 lwsl_err("write failed\n");
463 /* write failed, close conn */
466 if (m) /* while still active, extend timeout */
467 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
470 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
472 lws_callback_on_writable(wsi);
475 lws_plat_file_close(wsi, pss->fd);
476 pss->fd = LWS_INVALID_FILE;
480 lws_plat_file_close(wsi, pss->fd);
485 * callback for confirming to continue with client IP appear in
486 * protocol 0 callback since no websocket protocol has been agreed
487 * yet. You can just ignore this if you won't filter on client IP
488 * since the default unhandled callback return is 0 meaning let the
489 * connection continue.
491 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
492 /* if we returned non-zero from here, we kill the connection */
495 #ifndef LWS_NO_CLIENT
496 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
497 char ctype[64], ctlen = 0;
498 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
499 p = buffer + LWS_PRE;
500 end = p + sizeof(buffer) - LWS_PRE;
501 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
503 if (lws_add_http_header_by_token(lws_get_parent(wsi),
504 WSI_TOKEN_HTTP_SERVER,
505 (unsigned char *)"libwebsockets",
509 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
511 if (lws_add_http_header_by_token(lws_get_parent(wsi),
512 WSI_TOKEN_HTTP_CONTENT_TYPE,
513 (unsigned char *)ctype, ctlen, &p, end))
517 if (lws_add_http_header_content_length(lws_get_parent(wsi),
521 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
525 lwsl_info("%s\n", buffer + LWS_PRE);
527 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
528 p - (buffer + LWS_PRE),
529 LWS_WRITE_HTTP_HEADERS);
534 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
535 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
538 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
539 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
540 assert(lws_get_parent(wsi));
541 if (!lws_get_parent(wsi))
543 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
544 // wsi, lws_get_socket_fd(wsi),
545 // lws_get_parent(wsi),
546 // lws_get_socket_fd(lws_get_parent(wsi)), len);
547 pss1 = lws_wsi_user(lws_get_parent(wsi));
548 pss1->reason_bf |= 2;
549 lws_callback_on_writable(lws_get_parent(wsi));
551 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
552 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
553 assert(lws_get_parent(wsi));
554 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
555 len, LWS_WRITE_HTTP);
559 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
560 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
561 assert(lws_get_parent(wsi));
562 if (!lws_get_parent(wsi))
564 pss1 = lws_wsi_user(lws_get_parent(wsi));
565 pss1->client_finished = 1;
570 * callbacks for managing the external poll() array appear in
571 * protocol 0 callback
574 case LWS_CALLBACK_LOCK_POLL:
576 * lock mutex to protect pollfd state
577 * called before any other POLL related callback
578 * if protecting wsi lifecycle change, len == 1
580 test_server_lock(len);
583 case LWS_CALLBACK_UNLOCK_POLL:
585 * unlock mutex to protect pollfd state when
586 * called after any other POLL related callback
587 * if protecting wsi lifecycle change, len == 1
589 test_server_unlock(len);
593 case LWS_CALLBACK_ADD_POLL_FD:
595 if (count_pollfds >= max_poll_elements) {
596 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
600 fd_lookup[pa->fd] = count_pollfds;
601 pollfds[count_pollfds].fd = pa->fd;
602 pollfds[count_pollfds].events = pa->events;
603 pollfds[count_pollfds++].revents = 0;
606 case LWS_CALLBACK_DEL_POLL_FD:
607 if (!--count_pollfds)
609 m = fd_lookup[pa->fd];
610 /* have the last guy take up the vacant slot */
611 pollfds[m] = pollfds[count_pollfds];
612 fd_lookup[pollfds[count_pollfds].fd] = m;
615 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
616 pollfds[fd_lookup[pa->fd]].events = pa->events;
620 case LWS_CALLBACK_GET_THREAD_ID:
622 * if you will call "lws_callback_on_writable"
623 * from a different thread, return the caller thread ID
624 * here so lws can use this information to work out if it
625 * should signal the poll() loop to exit and restart early
628 /* return pthread_getthreadid_np(); */
632 #if defined(LWS_OPENSSL_SUPPORT)
633 case LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION:
634 /* Verify the client certificate */
635 if (!len || (SSL_get_verify_result((SSL*)in) != X509_V_OK)) {
636 int err = X509_STORE_CTX_get_error((X509_STORE_CTX*)user);
637 int depth = X509_STORE_CTX_get_error_depth((X509_STORE_CTX*)user);
638 const char* msg = X509_verify_cert_error_string(err);
639 lwsl_err("LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: SSL error: %s (%d), depth: %d\n", msg, err, depth);
643 #if defined(LWS_HAVE_SSL_CTX_set1_param)
644 case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS:
646 /* Enable CRL checking */
647 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
648 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
649 SSL_CTX_set1_param((SSL_CTX*)user, param);
650 X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX*)user);
651 X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
652 n = X509_load_cert_crl_file(lookup, crl_path, X509_FILETYPE_PEM);
653 X509_VERIFY_PARAM_free(param);
657 lwsl_err("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: SSL error: %s (%d)\n", ERR_error_string(n, errbuf), n);
671 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
673 if (lws_http_transaction_completed(wsi))