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_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
38 /* location of the certificate revocation list */
39 extern char crl_path[1024];
42 extern int debug_level;
48 PROTOCOL_DUMB_INCREMENT,
56 * We take a strict whitelist approach to stop ../ attacks
64 * this is just an example of parsing handshake headers, you don't need this
65 * in your code unless you will filter allowing connections by the header
69 dump_handshake_info(struct lws *wsi)
73 const unsigned char *c;
76 c = lws_token_to_string(n);
82 len = lws_hdr_total_length(wsi, n);
83 if (!len || len > sizeof(buf) - 1) {
88 lws_hdr_copy(wsi, buf, sizeof buf, n);
89 buf[sizeof(buf) - 1] = '\0';
91 fprintf(stderr, " %s = %s\n", (char *)c, buf);
96 const char * get_mimetype(const char *file)
103 if (!strcmp(&file[n - 4], ".ico"))
104 return "image/x-icon";
106 if (!strcmp(&file[n - 4], ".png"))
109 if (!strcmp(&file[n - 5], ".html"))
112 if (!strcmp(&file[n - 4], ".css"))
115 if (!strcmp(&file[n - 3], ".js"))
116 return "text/javascript";
122 static const char * const param_names[] = {
129 enum enum_param_names {
137 file_upload_cb(void *data, const char *name, const char *filename,
138 char *buf, int len, enum lws_spa_fileupload_states state)
140 struct per_session_data__http *pss =
141 (struct per_session_data__http *)data;
146 strncpy(pss->filename, filename, sizeof(pss->filename) - 1);
147 /* we get the original filename in @filename arg, but for
148 * simple demo use a fixed name so we don't have to deal with
150 pss->post_fd = (lws_filefd_type)open("/tmp/post-file",
151 O_CREAT | O_TRUNC | O_RDWR, 0600);
153 case LWS_UFS_FINAL_CONTENT:
154 case LWS_UFS_CONTENT:
156 pss->file_length += len;
158 /* if the file length is too big, drop it */
159 if (pss->file_length > 100000)
162 n = write((int)pss->post_fd, buf, len);
163 lwsl_notice("%s: write %d says %d\n", __func__, len, n);
165 if (state == LWS_UFS_CONTENT)
167 close((int)pss->post_fd);
168 pss->post_fd = LWS_INVALID_FILE;
175 /* this protocol server (always the first one) handles HTTP,
177 * Some misc callbacks that aren't associated with a protocol also turn up only
178 * here on the first protocol server.
181 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
182 void *in, size_t len)
184 struct per_session_data__http *pss =
185 (struct per_session_data__http *)user;
186 unsigned char buffer[4096 + LWS_PRE];
187 lws_filepos_t amount, file_len, sent;
188 char leaf_path[1024];
189 const char *mimetype;
191 unsigned char *end, *start;
194 #ifndef LWS_NO_CLIENT
195 struct per_session_data__http *pss1;
202 struct lws_pollargs *pa = (struct lws_pollargs *)in;
207 case LWS_CALLBACK_HTTP:
209 lwsl_info("lws_http_serve: %s\n", (const char *)in);
211 if (debug_level & LLL_INFO) {
212 dump_handshake_info(wsi);
214 /* dump the individual URI Arg parameters */
216 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
217 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
218 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
223 lws_get_peer_simple(wsi, buf, sizeof(buf));
224 lwsl_info("HTTP connect from %s\n", buf);
228 lws_return_http_status(wsi,
229 HTTP_STATUS_BAD_REQUEST, NULL);
233 #if !defined(LWS_NO_CLIENT) && defined(LWS_OPENSSL_SUPPORT)
234 if (!strncmp(in, "/proxytest", 10)) {
235 struct lws_client_connect_info i;
236 char *rootpath = "/git/";
237 const char *p = (const char *)in;
239 if (lws_get_child(wsi))
242 pss->client_finished = 0;
243 memset(&i, 0, sizeof(i));
244 i.context = lws_get_context(wsi);
245 i.address = "libwebsockets.org";
247 i.ssl_connection = 1;
249 i.path = (char *)in + 10;
256 i.uri_replace_from = "libwebsockets.org/git/";
257 i.uri_replace_to = "/proxytest/";
259 if (!lws_client_connect_via_info(&i)) {
260 lwsl_err("proxy connect fail\n");
269 /* this example server has no concept of directories */
270 if (strchr((const char *)in + 1, '/')) {
271 lws_return_http_status(wsi, HTTP_STATUS_NOT_ACCEPTABLE, NULL);
276 /* if a legal POST URL, let it continue and accept data */
277 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
280 /* check for the "send a big file by hand" example case */
282 if (!strcmp((const char *)in, "/leaf.jpg")) {
283 lws_fop_flags_t flags = LWS_O_RDONLY;
285 if (strlen(resource_path) > sizeof(leaf_path) - 10)
287 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
289 /* well, let's demonstrate how to send the hard way */
291 p = buffer + LWS_PRE;
292 end = p + sizeof(buffer) - LWS_PRE;
294 pss->fop_fd = lws_vfs_file_open(
295 lws_get_fops(lws_get_context(wsi)),
298 lwsl_err("failed to open file %s\n", leaf_path);
301 file_len = lws_vfs_get_length(pss->fop_fd);
304 * we will send a big jpeg file, but it could be
305 * anything. Set the Content-Type: appropriately
306 * so the browser knows what to do with it.
308 * Notice we use the APIs to build the header, which
309 * will do the right thing for HTTP 1/1.1 and HTTP2
310 * depending on what connection it happens to be working
313 if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &p, end))
315 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
316 (unsigned char *)"libwebsockets",
319 if (lws_add_http_header_by_token(wsi,
320 WSI_TOKEN_HTTP_CONTENT_TYPE,
321 (unsigned char *)"image/jpeg",
324 if (lws_add_http_header_content_length(wsi,
328 if (lws_finalize_http_header(wsi, &p, end))
332 * send the http headers...
333 * this won't block since it's the first payload sent
334 * on the connection since it was established
335 * (too small for partial)
337 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
338 * which also means you can't send body too in one step,
339 * this is mandated by changes in HTTP2
343 lwsl_info("%s\n", buffer + LWS_PRE);
345 n = lws_write(wsi, buffer + LWS_PRE,
346 p - (buffer + LWS_PRE),
347 LWS_WRITE_HTTP_HEADERS);
349 lws_vfs_file_close(&pss->fop_fd);
353 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
355 lws_callback_on_writable(wsi);
359 /* if not, send a file the easy way */
360 if (!strncmp(in, "/cgit-data/", 11)) {
361 in = (char *)in + 11;
362 strcpy(buf, "/usr/share/cgit");
364 strcpy(buf, resource_path);
366 if (strcmp(in, "/")) {
367 if (*((const char *)in) != '/')
369 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
370 } else /* default file to serve */
371 strcat(buf, "/test.html");
372 buf[sizeof(buf) - 1] = '\0';
374 /* refuse to serve files we don't understand */
375 mimetype = get_mimetype(buf);
377 lwsl_err("Unknown mimetype for %s\n", buf);
378 lws_return_http_status(wsi,
379 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
383 /* demonstrates how to set a cookie on / */
385 other_headers = leaf_path;
386 p = (unsigned char *)leaf_path;
387 if (!strcmp((const char *)in, "/") &&
388 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
389 /* this isn't very unguessable but it'll do for us */
390 gettimeofday(&tv, NULL);
391 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
392 (unsigned int)tv.tv_sec,
393 (unsigned int)tv.tv_usec);
395 if (lws_add_http_header_by_name(wsi,
396 (unsigned char *)"set-cookie:",
397 (unsigned char *)b64, n, &p,
398 (unsigned char *)leaf_path + sizeof(leaf_path)))
401 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
403 "Strict-Transport-Security:",
405 "max-age=15768000 ; "
406 "includeSubDomains", 36, &p,
407 (unsigned char *)leaf_path +
410 n = (char *)p - leaf_path;
412 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
413 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
414 return -1; /* error or can't reuse connection: close the socket */
417 * notice that the sending of the file completes asynchronously,
418 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
423 case LWS_CALLBACK_CLIENT_RECEIVE:
424 ((char *)in)[len] = '\0';
425 lwsl_info("rx %d '%s'\n", (int)len, (char *)in);
428 case LWS_CALLBACK_HTTP_BODY:
429 /* create the POST argument parser if not already existing */
431 pss->spa = lws_spa_create(wsi, param_names,
432 ARRAY_SIZE(param_names), 1024,
433 file_upload_cb, pss);
437 pss->filename[0] = '\0';
438 pss->file_length = 0;
441 /* let it parse the POST data */
442 if (lws_spa_process(pss->spa, in, len))
446 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
447 lwsl_debug("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
449 * the whole of the sent body arrived,
450 * respond to the client with a redirect to show the
454 /* call to inform no more payload data coming */
455 lws_spa_finalize(pss->spa);
457 p = (unsigned char *)pss->result + LWS_PRE;
458 end = p + sizeof(pss->result) - LWS_PRE - 1;
459 p += sprintf((char *)p,
460 "<html><body><h1>Form results (after urldecoding)</h1>"
461 "<table><tr><td>Name</td><td>Length</td><td>Value</td></tr>");
463 for (n = 0; n < ARRAY_SIZE(param_names); n++)
464 p += lws_snprintf((char *)p, end - p,
465 "<tr><td><b>%s</b></td><td>%d</td><td>%s</td></tr>",
467 lws_spa_get_length(pss->spa, n),
468 lws_spa_get_string(pss->spa, n));
470 p += lws_snprintf((char *)p, end - p, "</table><br><b>filename:</b> %s, <b>length</b> %ld",
471 pss->filename, pss->file_length);
473 p += lws_snprintf((char *)p, end - p, "</body></html>");
474 pss->result_len = p - (unsigned char *)(pss->result + LWS_PRE);
476 p = buffer + LWS_PRE;
478 end = p + sizeof(buffer) - LWS_PRE;
480 if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &p, end))
483 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
484 (unsigned char *)"text/html", 9, &p, end))
486 if (lws_add_http_header_content_length(wsi, pss->result_len, &p, end))
488 if (lws_finalize_http_header(wsi, &p, end))
491 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
495 n = lws_write(wsi, (unsigned char *)pss->result + LWS_PRE,
496 pss->result_len, LWS_WRITE_HTTP);
500 case LWS_CALLBACK_HTTP_DROP_PROTOCOL:
501 lwsl_debug("LWS_CALLBACK_HTTP_DROP_PROTOCOL\n");
503 /* called when our wsi user_space is going to be destroyed */
505 lws_spa_destroy(pss->spa);
509 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
512 case LWS_CALLBACK_HTTP_WRITEABLE:
513 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
515 if (pss->client_finished)
518 if (!lws_get_child(wsi) && !pss->fop_fd) {
519 lwsl_notice("fop_fd NULL\n");
523 #ifndef LWS_NO_CLIENT
524 if (pss->reason_bf & 2) {
525 char *px = buf + LWS_PRE;
526 int lenx = sizeof(buf) - LWS_PRE;
528 * our sink is writeable and our source has something
529 * to read. So read a lump of source material of
530 * suitable size to send or what's available, whichever
535 pss->reason_bf &= ~2;
536 wsi1 = lws_get_child(wsi);
539 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
542 if (pss->client_finished)
548 if (lws_get_child(wsi))
553 * we can send more of whatever it is we were sending
557 /* we'd like the send this much */
558 n = sizeof(buffer) - LWS_PRE;
560 /* but if the peer told us he wants less, we can adapt */
561 m = lws_get_peer_write_allowance(wsi);
563 /* -1 means not using a protocol that has this info */
565 /* right now, peer can't handle anything */
568 if (m != -1 && m < n)
569 /* he couldn't handle that much */
572 n = lws_vfs_file_read(pss->fop_fd,
573 &amount, buffer + LWS_PRE, n);
574 /* problem reading, close conn */
576 lwsl_err("problem reading file\n");
580 /* sent it all, close conn */
584 * To support HTTP2, must take care about preamble space
586 * identification of when we send the last payload frame
587 * is handled by the library itself if you sent a
588 * content-length header
590 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
592 lwsl_err("write failed\n");
593 /* write failed, close conn */
596 if (m) /* while still active, extend timeout */
597 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
600 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
602 lws_callback_on_writable(wsi);
605 lws_vfs_file_close(&pss->fop_fd);
610 lws_vfs_file_close(&pss->fop_fd);
615 * callback for confirming to continue with client IP appear in
616 * protocol 0 callback since no websocket protocol has been agreed
617 * yet. You can just ignore this if you won't filter on client IP
618 * since the default unhandled callback return is 0 meaning let the
619 * connection continue.
621 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
622 /* if we returned non-zero from here, we kill the connection */
625 #ifndef LWS_NO_CLIENT
626 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
627 char ctype[64], ctlen = 0;
628 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
629 p = buffer + LWS_PRE;
630 end = p + sizeof(buffer) - LWS_PRE;
631 if (lws_add_http_header_status(lws_get_parent(wsi), HTTP_STATUS_OK, &p, end))
633 if (lws_add_http_header_by_token(lws_get_parent(wsi),
634 WSI_TOKEN_HTTP_SERVER,
635 (unsigned char *)"libwebsockets",
639 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
641 if (lws_add_http_header_by_token(lws_get_parent(wsi),
642 WSI_TOKEN_HTTP_CONTENT_TYPE,
643 (unsigned char *)ctype, ctlen, &p, end))
647 if (lws_add_http_header_content_length(lws_get_parent(wsi),
651 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
655 lwsl_info("%s\n", buffer + LWS_PRE);
657 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
658 p - (buffer + LWS_PRE),
659 LWS_WRITE_HTTP_HEADERS);
664 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
665 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
668 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
669 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
670 assert(lws_get_parent(wsi));
671 if (!lws_get_parent(wsi))
673 pss1 = lws_wsi_user(lws_get_parent(wsi));
674 pss1->reason_bf |= 2;
675 lws_callback_on_writable(lws_get_parent(wsi));
677 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
678 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", (int)len);
679 assert(lws_get_parent(wsi));
680 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
681 len, LWS_WRITE_HTTP);
685 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
686 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
687 assert(lws_get_parent(wsi));
688 if (!lws_get_parent(wsi))
690 pss1 = lws_wsi_user(lws_get_parent(wsi));
691 pss1->client_finished = 1;
696 * callbacks for managing the external poll() array appear in
697 * protocol 0 callback
700 case LWS_CALLBACK_LOCK_POLL:
702 * lock mutex to protect pollfd state
703 * called before any other POLL related callback
704 * if protecting wsi lifecycle change, len == 1
706 test_server_lock(len);
709 case LWS_CALLBACK_UNLOCK_POLL:
711 * unlock mutex to protect pollfd state when
712 * called after any other POLL related callback
713 * if protecting wsi lifecycle change, len == 1
715 test_server_unlock(len);
719 case LWS_CALLBACK_ADD_POLL_FD:
721 if (count_pollfds >= max_poll_elements) {
722 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
726 fd_lookup[pa->fd] = count_pollfds;
727 pollfds[count_pollfds].fd = pa->fd;
728 pollfds[count_pollfds].events = pa->events;
729 pollfds[count_pollfds++].revents = 0;
732 case LWS_CALLBACK_DEL_POLL_FD:
733 if (!--count_pollfds)
735 m = fd_lookup[pa->fd];
736 /* have the last guy take up the vacant slot */
737 pollfds[m] = pollfds[count_pollfds];
738 fd_lookup[pollfds[count_pollfds].fd] = m;
741 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
742 pollfds[fd_lookup[pa->fd]].events = pa->events;
746 case LWS_CALLBACK_GET_THREAD_ID:
748 * if you will call "lws_callback_on_writable"
749 * from a different thread, return the caller thread ID
750 * here so lws can use this information to work out if it
751 * should signal the poll() loop to exit and restart early
754 /* return pthread_getthreadid_np(); */
758 #if defined(LWS_OPENSSL_SUPPORT)
759 case LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION:
760 /* Verify the client certificate */
761 if (!len || (SSL_get_verify_result((SSL*)in) != X509_V_OK)) {
762 int err = X509_STORE_CTX_get_error((X509_STORE_CTX*)user);
763 int depth = X509_STORE_CTX_get_error_depth((X509_STORE_CTX*)user);
764 const char* msg = X509_verify_cert_error_string(err);
765 lwsl_err("LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: SSL error: %s (%d), depth: %d\n", msg, err, depth);
769 #if defined(LWS_HAVE_SSL_CTX_set1_param)
770 case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS:
772 /* Enable CRL checking */
773 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
774 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
775 SSL_CTX_set1_param((SSL_CTX*)user, param);
776 X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX*)user);
777 X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
778 n = X509_load_cert_crl_file(lookup, crl_path, X509_FILETYPE_PEM);
779 X509_VERIFY_PARAM_free(param);
783 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))