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 #if defined(LWS_USE_POLARSSL)
39 #if defined(LWS_USE_MBEDTLS)
41 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
42 /* location of the certificate revocation list */
43 extern char crl_path[1024];
48 extern int debug_level;
54 PROTOCOL_DUMB_INCREMENT,
62 * We take a strict whitelist approach to stop ../ attacks
70 * this is just an example of parsing handshake headers, you don't need this
71 * in your code unless you will filter allowing connections by the header
75 dump_handshake_info(struct lws *wsi)
79 const unsigned char *c;
82 c = lws_token_to_string(n);
88 len = lws_hdr_total_length(wsi, n);
89 if (!len || len > sizeof(buf) - 1) {
94 lws_hdr_copy(wsi, buf, sizeof buf, n);
95 buf[sizeof(buf) - 1] = '\0';
97 fprintf(stderr, " %s = %s\n", (char *)c, buf);
102 const char * get_mimetype(const char *file)
104 int n = strlen(file);
109 if (!strcmp(&file[n - 4], ".ico"))
110 return "image/x-icon";
112 if (!strcmp(&file[n - 4], ".png"))
115 if (!strcmp(&file[n - 5], ".html"))
118 if (!strcmp(&file[n - 4], ".css"))
124 /* this protocol server (always the first one) handles HTTP,
126 * Some misc callbacks that aren't associated with a protocol also turn up only
127 * here on the first protocol server.
130 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
131 void *in, size_t len)
133 struct per_session_data__http *pss =
134 (struct per_session_data__http *)user;
135 unsigned char buffer[4096 + LWS_PRE];
136 unsigned long amount, file_len, sent;
137 char leaf_path[1024];
138 const char *mimetype;
140 unsigned char *end, *start;
143 #ifndef LWS_NO_CLIENT
144 struct per_session_data__http *pss1;
151 struct lws_pollargs *pa = (struct lws_pollargs *)in;
156 case LWS_CALLBACK_HTTP:
158 lwsl_notice("lws_http_serve: %s\n",in);
160 if (debug_level & LLL_INFO) {
161 dump_handshake_info(wsi);
163 /* dump the individual URI Arg parameters */
165 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
166 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
167 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
172 char name[100], rip[50];
173 lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
174 sizeof(name), rip, sizeof(rip));
175 sprintf(buf, "%s (%s)", name, rip);
176 lwsl_notice("HTTP connect from %s\n", buf);
180 lws_return_http_status(wsi,
181 HTTP_STATUS_BAD_REQUEST, NULL);
185 #ifndef LWS_NO_CLIENT
186 if (!strncmp(in, "/proxytest", 10)) {
187 struct lws_client_connect_info i;
188 char *rootpath = "/";
189 const char *p = (const char *)in;
191 if (lws_get_child(wsi))
194 pss->client_finished = 0;
195 memset(&i,0, sizeof(i));
196 i.context = lws_get_context(wsi);
197 i.address = "git.libwebsockets.org";
199 i.ssl_connection = 0;
201 i.path = (char *)in + 10;
204 i.host = "git.libwebsockets.org";
208 i.uri_replace_from = "git.libwebsockets.org/";
209 i.uri_replace_to = "/proxytest/";
210 if (!lws_client_connect_via_info(&i)) {
211 lwsl_err("proxy connect fail\n");
222 /* this example server has no concept of directories */
223 if (strchr((const char *)in + 1, '/')) {
224 lws_return_http_status(wsi, HTTP_STATUS_NOT_ACCEPTABLE, NULL);
229 if (!strncmp(in, "/postresults", 12)) {
230 m = sprintf(buf, "<html><body>Form results: '%s'<br>"
231 "</body></html>", pss->post_string);
233 p = buffer + LWS_PRE;
235 end = p + sizeof(buffer) - LWS_PRE;
237 if (lws_add_http_header_status(wsi, 200, &p, end))
239 if (lws_add_http_header_by_token(wsi,
240 WSI_TOKEN_HTTP_CONTENT_TYPE,
241 (unsigned char *)"text/html",
244 if (lws_add_http_header_content_length(wsi, m, &p,
247 if (lws_finalize_http_header(wsi, &p, end))
250 n = lws_write(wsi, start, p - start,
251 LWS_WRITE_HTTP_HEADERS);
255 n = lws_write(wsi, (unsigned char *)buf, m, LWS_WRITE_HTTP);
262 /* if a legal POST URL, let it continue and accept data */
263 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
266 /* check for the "send a big file by hand" example case */
268 if (!strcmp((const char *)in, "/leaf.jpg")) {
269 if (strlen(resource_path) > sizeof(leaf_path) - 10)
271 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
273 /* well, let's demonstrate how to send the hard way */
275 p = buffer + LWS_PRE;
276 end = p + sizeof(buffer) - LWS_PRE;
278 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
281 if (pss->fd == LWS_INVALID_FILE) {
282 lwsl_err("faild to open file %s\n", leaf_path);
287 * we will send a big jpeg file, but it could be
288 * anything. Set the Content-Type: appropriately
289 * so the browser knows what to do with it.
291 * Notice we use the APIs to build the header, which
292 * will do the right thing for HTTP 1/1.1 and HTTP2
293 * depending on what connection it happens to be working
296 if (lws_add_http_header_status(wsi, 200, &p, end))
298 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
299 (unsigned char *)"libwebsockets",
302 if (lws_add_http_header_by_token(wsi,
303 WSI_TOKEN_HTTP_CONTENT_TYPE,
304 (unsigned char *)"image/jpeg",
307 if (lws_add_http_header_content_length(wsi,
311 if (lws_finalize_http_header(wsi, &p, end))
315 * send the http headers...
316 * this won't block since it's the first payload sent
317 * on the connection since it was established
318 * (too small for partial)
320 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
321 * which also means you can't send body too in one step,
322 * this is mandated by changes in HTTP2
326 lwsl_info("%s\n", buffer + LWS_PRE);
328 n = lws_write(wsi, buffer + LWS_PRE,
329 p - (buffer + LWS_PRE),
330 LWS_WRITE_HTTP_HEADERS);
332 lws_plat_file_close(wsi, pss->fd);
336 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
338 lws_callback_on_writable(wsi);
342 /* if not, send a file the easy way */
343 if (!strncmp(in, "/cgit-data/", 11)) {
344 in = (char *)in + 11;
345 strcpy(buf, "/usr/share/cgit");
347 strcpy(buf, resource_path);
349 if (strcmp(in, "/")) {
350 if (*((const char *)in) != '/')
352 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
353 } else /* default file to serve */
354 strcat(buf, "/test.html");
355 buf[sizeof(buf) - 1] = '\0';
357 /* refuse to serve files we don't understand */
358 mimetype = get_mimetype(buf);
360 lwsl_err("Unknown mimetype for %s\n", buf);
361 lws_return_http_status(wsi,
362 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
366 /* demonstrates how to set a cookie on / */
368 other_headers = leaf_path;
369 p = (unsigned char *)leaf_path;
370 if (!strcmp((const char *)in, "/") &&
371 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
372 /* this isn't very unguessable but it'll do for us */
373 gettimeofday(&tv, NULL);
374 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
375 (unsigned int)tv.tv_sec,
376 (unsigned int)tv.tv_usec);
378 if (lws_add_http_header_by_name(wsi,
379 (unsigned char *)"set-cookie:",
380 (unsigned char *)b64, n, &p,
381 (unsigned char *)leaf_path + sizeof(leaf_path)))
384 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
386 "Strict-Transport-Security:",
388 "max-age=15768000 ; "
389 "includeSubDomains", 36, &p,
390 (unsigned char *)leaf_path +
393 n = (char *)p - leaf_path;
395 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
396 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
397 return -1; /* error or can't reuse connection: close the socket */
400 * notice that the sending of the file completes asynchronously,
401 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
406 case LWS_CALLBACK_HTTP_BODY:
407 lwsl_notice("LWS_CALLBACK_HTTP_BODY: len %d\n", (int)len);
408 strncpy(pss->post_string, in, sizeof (pss->post_string) -1);
409 pss->post_string[sizeof(pss->post_string) - 1] = '\0';
410 if (len < sizeof(pss->post_string) - 1)
411 pss->post_string[len] = '\0';
414 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
415 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
417 * the whole of the sent body arrived,
418 * respond to the client with a redirect to show the
421 p = (unsigned char *)buf + LWS_PRE;
422 n = lws_http_redirect(wsi,
423 HTTP_STATUS_SEE_OTHER, /* 303 */
424 (unsigned char *)"/postresults", 12, /* location + len */
425 &p, /* temp buffer to use */
426 p + sizeof(buf) - 1 - LWS_PRE /* buffer len */
430 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
433 case LWS_CALLBACK_HTTP_WRITEABLE:
434 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
436 if (pss->client_finished)
439 if (pss->fd == LWS_INVALID_FILE)
442 #ifndef LWS_NO_CLIENT
443 if (pss->reason_bf & 2) {
444 char *px = buf + LWS_PRE;
445 int lenx = sizeof(buf) - LWS_PRE;
447 * our sink is writeable and our source has something
448 * to read. So read a lump of source material of
449 * suitable size to send or what's available, whichever
452 pss->reason_bf &= ~2;
453 wsi1 = lws_get_child(wsi);
456 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
459 if (pss->client_finished)
465 * we can send more of whatever it is we were sending
469 /* we'd like the send this much */
470 n = sizeof(buffer) - LWS_PRE;
472 /* but if the peer told us he wants less, we can adapt */
473 m = lws_get_peer_write_allowance(wsi);
475 /* -1 means not using a protocol that has this info */
477 /* right now, peer can't handle anything */
480 if (m != -1 && m < n)
481 /* he couldn't handle that much */
484 n = lws_plat_file_read(wsi, pss->fd,
485 &amount, buffer + LWS_PRE, n);
486 /* problem reading, close conn */
488 lwsl_err("problem reading file\n");
492 /* sent it all, close conn */
496 * To support HTTP2, must take care about preamble space
498 * identification of when we send the last payload frame
499 * is handled by the library itself if you sent a
500 * content-length header
502 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
504 lwsl_err("write failed\n");
505 /* write failed, close conn */
508 if (m) /* while still active, extend timeout */
509 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
512 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
514 lws_callback_on_writable(wsi);
517 lws_plat_file_close(wsi, pss->fd);
518 pss->fd = LWS_INVALID_FILE;
522 lws_plat_file_close(wsi, pss->fd);
527 * callback for confirming to continue with client IP appear in
528 * protocol 0 callback since no websocket protocol has been agreed
529 * yet. You can just ignore this if you won't filter on client IP
530 * since the default unhandled callback return is 0 meaning let the
531 * connection continue.
533 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
534 /* if we returned non-zero from here, we kill the connection */
537 #ifndef LWS_NO_CLIENT
538 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
539 char ctype[64], ctlen = 0;
540 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
541 p = buffer + LWS_PRE;
542 end = p + sizeof(buffer) - LWS_PRE;
543 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
545 if (lws_add_http_header_by_token(lws_get_parent(wsi),
546 WSI_TOKEN_HTTP_SERVER,
547 (unsigned char *)"libwebsockets",
551 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
553 if (lws_add_http_header_by_token(lws_get_parent(wsi),
554 WSI_TOKEN_HTTP_CONTENT_TYPE,
555 (unsigned char *)ctype, ctlen, &p, end))
559 if (lws_add_http_header_content_length(lws_get_parent(wsi),
563 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
567 lwsl_info("%s\n", buffer + LWS_PRE);
569 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
570 p - (buffer + LWS_PRE),
571 LWS_WRITE_HTTP_HEADERS);
576 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
577 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
580 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
581 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
582 assert(lws_get_parent(wsi));
583 if (!lws_get_parent(wsi))
585 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
586 // wsi, lws_get_socket_fd(wsi),
587 // lws_get_parent(wsi),
588 // lws_get_socket_fd(lws_get_parent(wsi)), len);
589 pss1 = lws_wsi_user(lws_get_parent(wsi));
590 pss1->reason_bf |= 2;
591 lws_callback_on_writable(lws_get_parent(wsi));
593 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
594 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
595 assert(lws_get_parent(wsi));
596 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
597 len, LWS_WRITE_HTTP);
601 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
602 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
603 assert(lws_get_parent(wsi));
604 if (!lws_get_parent(wsi))
606 pss1 = lws_wsi_user(lws_get_parent(wsi));
607 pss1->client_finished = 1;
612 * callbacks for managing the external poll() array appear in
613 * protocol 0 callback
616 case LWS_CALLBACK_LOCK_POLL:
618 * lock mutex to protect pollfd state
619 * called before any other POLL related callback
620 * if protecting wsi lifecycle change, len == 1
622 test_server_lock(len);
625 case LWS_CALLBACK_UNLOCK_POLL:
627 * unlock mutex to protect pollfd state when
628 * called after any other POLL related callback
629 * if protecting wsi lifecycle change, len == 1
631 test_server_unlock(len);
635 case LWS_CALLBACK_ADD_POLL_FD:
637 if (count_pollfds >= max_poll_elements) {
638 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
642 fd_lookup[pa->fd] = count_pollfds;
643 pollfds[count_pollfds].fd = pa->fd;
644 pollfds[count_pollfds].events = pa->events;
645 pollfds[count_pollfds++].revents = 0;
648 case LWS_CALLBACK_DEL_POLL_FD:
649 if (!--count_pollfds)
651 m = fd_lookup[pa->fd];
652 /* have the last guy take up the vacant slot */
653 pollfds[m] = pollfds[count_pollfds];
654 fd_lookup[pollfds[count_pollfds].fd] = m;
657 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
658 pollfds[fd_lookup[pa->fd]].events = pa->events;
662 case LWS_CALLBACK_GET_THREAD_ID:
664 * if you will call "lws_callback_on_writable"
665 * from a different thread, return the caller thread ID
666 * here so lws can use this information to work out if it
667 * should signal the poll() loop to exit and restart early
670 /* return pthread_getthreadid_np(); */
674 #if defined(LWS_USE_POLARSSL)
676 #if defined(LWS_USE_MBEDTLS)
678 #if defined(LWS_OPENSSL_SUPPORT)
679 case LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION:
680 /* Verify the client certificate */
681 if (!len || (SSL_get_verify_result((SSL*)in) != X509_V_OK)) {
682 int err = X509_STORE_CTX_get_error((X509_STORE_CTX*)user);
683 int depth = X509_STORE_CTX_get_error_depth((X509_STORE_CTX*)user);
684 const char* msg = X509_verify_cert_error_string(err);
685 lwsl_err("LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: SSL error: %s (%d), depth: %d\n", msg, err, depth);
689 #if defined(LWS_HAVE_SSL_CTX_set1_param)
690 case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS:
692 /* Enable CRL checking */
693 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
694 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
695 SSL_CTX_set1_param((SSL_CTX*)user, param);
696 X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX*)user);
697 X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
698 n = X509_load_cert_crl_file(lookup, crl_path, X509_FILETYPE_PEM);
699 X509_VERIFY_PARAM_free(param);
703 lwsl_err("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: SSL error: %s (%d)\n", ERR_error_string(n, errbuf), n);
719 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
721 if (lws_http_transaction_completed(wsi))