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"))
121 if (!strcmp(&file[n - 3], ".js"))
122 return "text/javascript";
128 static const char * const param_names[] = {
135 enum enum_param_names {
143 file_upload_cb(void *data, const char *name, const char *filename,
144 char *buf, int len, enum lws_spa_fileupload_states state)
146 struct per_session_data__http *pss =
147 (struct per_session_data__http *)data;
152 strncpy(pss->filename, filename, sizeof(pss->filename) - 1);
153 /* we get the original filename in @filename arg, but for
154 * simple demo use a fixed name so we don't have to deal with
156 pss->post_fd = open("/tmp/post-file",
157 O_CREAT | O_TRUNC | O_RDWR, 0600);
159 case LWS_UFS_FINAL_CONTENT:
160 case LWS_UFS_CONTENT:
162 pss->file_length += len;
164 /* if the file length is too big, drop it */
165 if (pss->file_length > 100000)
168 n = write(pss->post_fd, buf, len);
169 lwsl_notice("%s: write %d says %d\n", __func__, len, n);
171 if (state == LWS_UFS_CONTENT)
174 pss->post_fd = LWS_INVALID_FILE;
181 /* this protocol server (always the first one) handles HTTP,
183 * Some misc callbacks that aren't associated with a protocol also turn up only
184 * here on the first protocol server.
187 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
188 void *in, size_t len)
190 struct per_session_data__http *pss =
191 (struct per_session_data__http *)user;
192 unsigned char buffer[4096 + LWS_PRE];
193 unsigned long amount, file_len, sent;
194 char leaf_path[1024];
195 const char *mimetype;
197 unsigned char *end, *start;
200 #ifndef LWS_NO_CLIENT
201 struct per_session_data__http *pss1;
208 struct lws_pollargs *pa = (struct lws_pollargs *)in;
213 case LWS_CALLBACK_HTTP:
215 lwsl_info("lws_http_serve: %s\n",in);
217 if (debug_level & LLL_INFO) {
218 dump_handshake_info(wsi);
220 /* dump the individual URI Arg parameters */
222 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
223 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
224 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
229 lws_get_peer_simple(wsi, buf, sizeof(buf));
230 lwsl_info("HTTP connect from %s\n", buf);
234 lws_return_http_status(wsi,
235 HTTP_STATUS_BAD_REQUEST, NULL);
239 #ifndef LWS_NO_CLIENT
240 if (!strncmp(in, "/proxytest", 10)) {
241 struct lws_client_connect_info i;
242 char *rootpath = "/";
243 const char *p = (const char *)in;
245 if (lws_get_child(wsi))
248 pss->client_finished = 0;
249 memset(&i,0, sizeof(i));
250 i.context = lws_get_context(wsi);
251 i.address = "git.libwebsockets.org";
253 i.ssl_connection = 0;
255 i.path = (char *)in + 10;
258 i.host = "git.libwebsockets.org";
262 i.uri_replace_from = "git.libwebsockets.org/";
263 i.uri_replace_to = "/proxytest/";
264 if (!lws_client_connect_via_info(&i)) {
265 lwsl_err("proxy connect fail\n");
276 /* this example server has no concept of directories */
277 if (strchr((const char *)in + 1, '/')) {
278 lws_return_http_status(wsi, HTTP_STATUS_NOT_ACCEPTABLE, NULL);
283 /* if a legal POST URL, let it continue and accept data */
284 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
287 /* check for the "send a big file by hand" example case */
289 if (!strcmp((const char *)in, "/leaf.jpg")) {
290 if (strlen(resource_path) > sizeof(leaf_path) - 10)
292 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
294 /* well, let's demonstrate how to send the hard way */
296 p = buffer + LWS_PRE;
297 end = p + sizeof(buffer) - LWS_PRE;
299 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
302 if (pss->fd == LWS_INVALID_FILE) {
303 lwsl_err("failed to open file %s\n", leaf_path);
308 * we will send a big jpeg file, but it could be
309 * anything. Set the Content-Type: appropriately
310 * so the browser knows what to do with it.
312 * Notice we use the APIs to build the header, which
313 * will do the right thing for HTTP 1/1.1 and HTTP2
314 * depending on what connection it happens to be working
317 if (lws_add_http_header_status(wsi, 200, &p, end))
319 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
320 (unsigned char *)"libwebsockets",
323 if (lws_add_http_header_by_token(wsi,
324 WSI_TOKEN_HTTP_CONTENT_TYPE,
325 (unsigned char *)"image/jpeg",
328 if (lws_add_http_header_content_length(wsi,
332 if (lws_finalize_http_header(wsi, &p, end))
336 * send the http headers...
337 * this won't block since it's the first payload sent
338 * on the connection since it was established
339 * (too small for partial)
341 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
342 * which also means you can't send body too in one step,
343 * this is mandated by changes in HTTP2
347 lwsl_info("%s\n", buffer + LWS_PRE);
349 n = lws_write(wsi, buffer + LWS_PRE,
350 p - (buffer + LWS_PRE),
351 LWS_WRITE_HTTP_HEADERS);
353 lws_plat_file_close(wsi, pss->fd);
357 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
359 lws_callback_on_writable(wsi);
363 /* if not, send a file the easy way */
364 if (!strncmp(in, "/cgit-data/", 11)) {
365 in = (char *)in + 11;
366 strcpy(buf, "/usr/share/cgit");
368 strcpy(buf, resource_path);
370 if (strcmp(in, "/")) {
371 if (*((const char *)in) != '/')
373 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
374 } else /* default file to serve */
375 strcat(buf, "/test.html");
376 buf[sizeof(buf) - 1] = '\0';
378 /* refuse to serve files we don't understand */
379 mimetype = get_mimetype(buf);
381 lwsl_err("Unknown mimetype for %s\n", buf);
382 lws_return_http_status(wsi,
383 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
387 /* demonstrates how to set a cookie on / */
389 other_headers = leaf_path;
390 p = (unsigned char *)leaf_path;
391 if (!strcmp((const char *)in, "/") &&
392 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
393 /* this isn't very unguessable but it'll do for us */
394 gettimeofday(&tv, NULL);
395 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
396 (unsigned int)tv.tv_sec,
397 (unsigned int)tv.tv_usec);
399 if (lws_add_http_header_by_name(wsi,
400 (unsigned char *)"set-cookie:",
401 (unsigned char *)b64, n, &p,
402 (unsigned char *)leaf_path + sizeof(leaf_path)))
405 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
407 "Strict-Transport-Security:",
409 "max-age=15768000 ; "
410 "includeSubDomains", 36, &p,
411 (unsigned char *)leaf_path +
414 n = (char *)p - leaf_path;
416 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
417 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
418 return -1; /* error or can't reuse connection: close the socket */
421 * notice that the sending of the file completes asynchronously,
422 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
427 case LWS_CALLBACK_HTTP_BODY:
428 /* create the POST argument parser if not already existing */
430 pss->spa = lws_spa_create(wsi, param_names,
431 ARRAY_SIZE(param_names), 1024,
432 file_upload_cb, pss);
436 pss->filename[0] = '\0';
437 pss->file_length = 0;
440 /* let it parse the POST data */
441 if (lws_spa_process(pss->spa, in, len))
445 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
446 lwsl_debug("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
448 * the whole of the sent body arrived,
449 * respond to the client with a redirect to show the
453 /* call to inform no more payload data coming */
454 lws_spa_finalize(pss->spa);
456 p = (unsigned char *)pss->result + LWS_PRE;
457 end = p + sizeof(pss->result) - LWS_PRE - 1;
458 p += sprintf((char *)p,
459 "<html><body><h1>Form results (after urldecoding)</h1>"
460 "<table><tr><td>Name</td><td>Length</td><td>Value</td></tr>");
462 for (n = 0; n < ARRAY_SIZE(param_names); n++)
463 p += lws_snprintf((char *)p, end - p,
464 "<tr><td><b>%s</b></td><td>%d</td><td>%s</td></tr>",
466 lws_spa_get_length(pss->spa, n),
467 lws_spa_get_string(pss->spa, n));
469 p += lws_snprintf((char *)p, end - p, "</table><br><b>filename:</b> %s, <b>length</b> %ld",
470 pss->filename, pss->file_length);
472 p += lws_snprintf((char *)p, end - p, "</body></html>");
473 pss->result_len = p - (unsigned char *)(pss->result + LWS_PRE);
475 p = buffer + LWS_PRE;
477 end = p + sizeof(buffer) - LWS_PRE;
479 if (lws_add_http_header_status(wsi, 200, &p, end))
482 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
483 (unsigned char *)"text/html", 9, &p, end))
485 if (lws_add_http_header_content_length(wsi, pss->result_len, &p, end))
487 if (lws_finalize_http_header(wsi, &p, end))
490 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
494 n = lws_write(wsi, (unsigned char *)pss->result + LWS_PRE,
495 pss->result_len, LWS_WRITE_HTTP);
499 case LWS_CALLBACK_HTTP_DROP_PROTOCOL:
500 lwsl_debug("LWS_CALLBACK_HTTP_DROP_PROTOCOL\n");
502 /* called when our wsi user_space is going to be destroyed */
504 lws_spa_destroy(pss->spa);
508 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
511 case LWS_CALLBACK_HTTP_WRITEABLE:
512 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
514 if (pss->client_finished)
517 if (pss->fd == LWS_INVALID_FILE)
520 #ifndef LWS_NO_CLIENT
521 if (pss->reason_bf & 2) {
522 char *px = buf + LWS_PRE;
523 int lenx = sizeof(buf) - LWS_PRE;
525 * our sink is writeable and our source has something
526 * to read. So read a lump of source material of
527 * suitable size to send or what's available, whichever
530 pss->reason_bf &= ~2;
531 wsi1 = lws_get_child(wsi);
534 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
537 if (pss->client_finished)
543 * we can send more of whatever it is we were sending
547 /* we'd like the send this much */
548 n = sizeof(buffer) - LWS_PRE;
550 /* but if the peer told us he wants less, we can adapt */
551 m = lws_get_peer_write_allowance(wsi);
553 /* -1 means not using a protocol that has this info */
555 /* right now, peer can't handle anything */
558 if (m != -1 && m < n)
559 /* he couldn't handle that much */
562 n = lws_plat_file_read(wsi, pss->fd,
563 &amount, buffer + LWS_PRE, n);
564 /* problem reading, close conn */
566 lwsl_err("problem reading file\n");
570 /* sent it all, close conn */
574 * To support HTTP2, must take care about preamble space
576 * identification of when we send the last payload frame
577 * is handled by the library itself if you sent a
578 * content-length header
580 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
582 lwsl_err("write failed\n");
583 /* write failed, close conn */
586 if (m) /* while still active, extend timeout */
587 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
590 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
592 lws_callback_on_writable(wsi);
595 lws_plat_file_close(wsi, pss->fd);
596 pss->fd = LWS_INVALID_FILE;
600 lws_plat_file_close(wsi, pss->fd);
605 * callback for confirming to continue with client IP appear in
606 * protocol 0 callback since no websocket protocol has been agreed
607 * yet. You can just ignore this if you won't filter on client IP
608 * since the default unhandled callback return is 0 meaning let the
609 * connection continue.
611 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
612 /* if we returned non-zero from here, we kill the connection */
615 #ifndef LWS_NO_CLIENT
616 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
617 char ctype[64], ctlen = 0;
618 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
619 p = buffer + LWS_PRE;
620 end = p + sizeof(buffer) - LWS_PRE;
621 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
623 if (lws_add_http_header_by_token(lws_get_parent(wsi),
624 WSI_TOKEN_HTTP_SERVER,
625 (unsigned char *)"libwebsockets",
629 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
631 if (lws_add_http_header_by_token(lws_get_parent(wsi),
632 WSI_TOKEN_HTTP_CONTENT_TYPE,
633 (unsigned char *)ctype, ctlen, &p, end))
637 if (lws_add_http_header_content_length(lws_get_parent(wsi),
641 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
645 lwsl_info("%s\n", buffer + LWS_PRE);
647 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
648 p - (buffer + LWS_PRE),
649 LWS_WRITE_HTTP_HEADERS);
654 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
655 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
658 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
659 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
660 assert(lws_get_parent(wsi));
661 if (!lws_get_parent(wsi))
663 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
664 // wsi, lws_get_socket_fd(wsi),
665 // lws_get_parent(wsi),
666 // lws_get_socket_fd(lws_get_parent(wsi)), len);
667 pss1 = lws_wsi_user(lws_get_parent(wsi));
668 pss1->reason_bf |= 2;
669 lws_callback_on_writable(lws_get_parent(wsi));
671 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
672 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
673 assert(lws_get_parent(wsi));
674 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
675 len, LWS_WRITE_HTTP);
679 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
680 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
681 assert(lws_get_parent(wsi));
682 if (!lws_get_parent(wsi))
684 pss1 = lws_wsi_user(lws_get_parent(wsi));
685 pss1->client_finished = 1;
690 * callbacks for managing the external poll() array appear in
691 * protocol 0 callback
694 case LWS_CALLBACK_LOCK_POLL:
696 * lock mutex to protect pollfd state
697 * called before any other POLL related callback
698 * if protecting wsi lifecycle change, len == 1
700 test_server_lock(len);
703 case LWS_CALLBACK_UNLOCK_POLL:
705 * unlock mutex to protect pollfd state when
706 * called after any other POLL related callback
707 * if protecting wsi lifecycle change, len == 1
709 test_server_unlock(len);
713 case LWS_CALLBACK_ADD_POLL_FD:
715 if (count_pollfds >= max_poll_elements) {
716 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
720 fd_lookup[pa->fd] = count_pollfds;
721 pollfds[count_pollfds].fd = pa->fd;
722 pollfds[count_pollfds].events = pa->events;
723 pollfds[count_pollfds++].revents = 0;
726 case LWS_CALLBACK_DEL_POLL_FD:
727 if (!--count_pollfds)
729 m = fd_lookup[pa->fd];
730 /* have the last guy take up the vacant slot */
731 pollfds[m] = pollfds[count_pollfds];
732 fd_lookup[pollfds[count_pollfds].fd] = m;
735 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
736 pollfds[fd_lookup[pa->fd]].events = pa->events;
740 case LWS_CALLBACK_GET_THREAD_ID:
742 * if you will call "lws_callback_on_writable"
743 * from a different thread, return the caller thread ID
744 * here so lws can use this information to work out if it
745 * should signal the poll() loop to exit and restart early
748 /* return pthread_getthreadid_np(); */
752 #if defined(LWS_USE_POLARSSL)
754 #if defined(LWS_USE_MBEDTLS)
756 #if defined(LWS_OPENSSL_SUPPORT)
757 case LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION:
758 /* Verify the client certificate */
759 if (!len || (SSL_get_verify_result((SSL*)in) != X509_V_OK)) {
760 int err = X509_STORE_CTX_get_error((X509_STORE_CTX*)user);
761 int depth = X509_STORE_CTX_get_error_depth((X509_STORE_CTX*)user);
762 const char* msg = X509_verify_cert_error_string(err);
763 lwsl_err("LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: SSL error: %s (%d), depth: %d\n", msg, err, depth);
767 #if defined(LWS_HAVE_SSL_CTX_set1_param)
768 case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS:
770 /* Enable CRL checking */
771 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
772 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
773 SSL_CTX_set1_param((SSL_CTX*)user, param);
774 X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX*)user);
775 X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
776 n = X509_load_cert_crl_file(lookup, crl_path, X509_FILETYPE_PEM);
777 X509_VERIFY_PARAM_free(param);
781 lwsl_err("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: SSL error: %s (%d)\n", ERR_error_string(n, errbuf), n);
797 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
799 if (lws_http_transaction_completed(wsi))