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 extern int debug_level;
43 PROTOCOL_DUMB_INCREMENT,
51 * We take a strict whitelist approach to stop ../ attacks
59 * this is just an example of parsing handshake headers, you don't need this
60 * in your code unless you will filter allowing connections by the header
64 dump_handshake_info(struct lws *wsi)
68 const unsigned char *c;
71 c = lws_token_to_string(n);
77 len = lws_hdr_total_length(wsi, n);
78 if (!len || len > sizeof(buf) - 1) {
83 lws_hdr_copy(wsi, buf, sizeof buf, n);
84 buf[sizeof(buf) - 1] = '\0';
86 fprintf(stderr, " %s = %s\n", (char *)c, buf);
91 const char * get_mimetype(const char *file)
98 if (!strcmp(&file[n - 4], ".ico"))
99 return "image/x-icon";
101 if (!strcmp(&file[n - 4], ".png"))
104 if (!strcmp(&file[n - 5], ".html"))
107 if (!strcmp(&file[n - 4], ".css"))
113 /* this protocol server (always the first one) handles HTTP,
115 * Some misc callbacks that aren't associated with a protocol also turn up only
116 * here on the first protocol server.
119 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
120 void *in, size_t len)
122 struct per_session_data__http *pss =
123 (struct per_session_data__http *)user;
124 unsigned char buffer[4096 + LWS_PRE];
125 unsigned long amount, file_len, sent;
126 char leaf_path[1024];
127 const char *mimetype;
132 #ifndef LWS_NO_CLIENT
133 struct per_session_data__http *pss1;
140 struct lws_pollargs *pa = (struct lws_pollargs *)in;
145 case LWS_CALLBACK_HTTP:
147 lwsl_notice("lws_http_serve: %s\n",in);
149 if (debug_level & LLL_INFO) {
150 dump_handshake_info(wsi);
152 /* dump the individual URI Arg parameters */
154 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
155 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
156 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
161 char name[100], rip[50];
162 lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
163 sizeof(name), rip, sizeof(rip));
164 sprintf(buf, "%s (%s)", name, rip);
165 lwsl_notice("HTTP connect from %s\n", buf);
169 lws_return_http_status(wsi,
170 HTTP_STATUS_BAD_REQUEST, NULL);
174 #ifndef LWS_NO_CLIENT
175 if (!strncmp(in, "/proxytest", 10)) {
176 struct lws_client_connect_info i;
177 char *rootpath = "/";
178 const char *p = (const char *)in;
180 if (lws_get_child(wsi))
183 pss->client_finished = 0;
184 memset(&i,0, sizeof(i));
185 i.context = lws_get_context(wsi);
186 i.address = "git.libwebsockets.org";
188 i.ssl_connection = 0;
190 i.path = (char *)in + 10;
193 i.host = "git.libwebsockets.org";
197 i.uri_replace_from = "git.libwebsockets.org/";
198 i.uri_replace_to = "/proxytest/";
199 if (!lws_client_connect_via_info(&i)) {
200 lwsl_err("proxy connect fail\n");
211 /* this example server has no concept of directories */
212 if (strchr((const char *)in + 1, '/')) {
213 lws_return_http_status(wsi, HTTP_STATUS_NOT_ACCEPTABLE, NULL);
219 if (!strncmp(in, "/cgitest", 8)) {
220 static char *cmd[] = {
223 INSTALL_DATADIR"/libwebsockets-test-server/lws-cgi-test.sh",
224 // "/var/www/cgi-bin/cgit",
228 lwsl_notice("%s: cgitest\n", __func__);
229 n = lws_cgi(wsi, cmd, 8, 5);
231 lwsl_err("%s: cgi failed\n");
234 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, WSI_TOKEN_CONNECTION,
240 (unsigned char *)"close", 5, &p, end))
242 n = lws_write(wsi, buffer + LWS_PRE,
243 p - (buffer + LWS_PRE),
244 LWS_WRITE_HTTP_HEADERS);
246 /* the cgi starts by outputting headers, we can't
247 * finalize the headers until we see the end of that
254 /* if a legal POST URL, let it continue and accept data */
255 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
258 /* check for the "send a big file by hand" example case */
260 if (!strcmp((const char *)in, "/leaf.jpg")) {
261 if (strlen(resource_path) > sizeof(leaf_path) - 10)
263 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
265 /* well, let's demonstrate how to send the hard way */
267 p = buffer + LWS_PRE;
268 end = p + sizeof(buffer) - LWS_PRE;
270 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
273 if (pss->fd == LWS_INVALID_FILE) {
274 lwsl_err("faild to open file %s\n", leaf_path);
279 * we will send a big jpeg file, but it could be
280 * anything. Set the Content-Type: appropriately
281 * so the browser knows what to do with it.
283 * Notice we use the APIs to build the header, which
284 * will do the right thing for HTTP 1/1.1 and HTTP2
285 * depending on what connection it happens to be working
288 if (lws_add_http_header_status(wsi, 200, &p, end))
290 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
291 (unsigned char *)"libwebsockets",
294 if (lws_add_http_header_by_token(wsi,
295 WSI_TOKEN_HTTP_CONTENT_TYPE,
296 (unsigned char *)"image/jpeg",
299 if (lws_add_http_header_content_length(wsi,
303 if (lws_finalize_http_header(wsi, &p, end))
307 * send the http headers...
308 * this won't block since it's the first payload sent
309 * on the connection since it was established
310 * (too small for partial)
312 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
313 * which also means you can't send body too in one step,
314 * this is mandated by changes in HTTP2
318 lwsl_info("%s\n", buffer + LWS_PRE);
320 n = lws_write(wsi, buffer + LWS_PRE,
321 p - (buffer + LWS_PRE),
322 LWS_WRITE_HTTP_HEADERS);
324 lws_plat_file_close(wsi, pss->fd);
328 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
330 lws_callback_on_writable(wsi);
334 /* if not, send a file the easy way */
335 if (!strncmp(in, "/cgit-data/", 11)) {
336 in = (char *)in + 11;
337 strcpy(buf, "/usr/share/cgit");
339 strcpy(buf, resource_path);
341 if (strcmp(in, "/")) {
342 if (*((const char *)in) != '/')
344 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
345 } else /* default file to serve */
346 strcat(buf, "/test.html");
347 buf[sizeof(buf) - 1] = '\0';
349 /* refuse to serve files we don't understand */
350 mimetype = get_mimetype(buf);
352 lwsl_err("Unknown mimetype for %s\n", buf);
353 lws_return_http_status(wsi,
354 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
358 /* demonstrates how to set a cookie on / */
360 other_headers = leaf_path;
361 p = (unsigned char *)leaf_path;
362 if (!strcmp((const char *)in, "/") &&
363 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
364 /* this isn't very unguessable but it'll do for us */
365 gettimeofday(&tv, NULL);
366 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
367 (unsigned int)tv.tv_sec,
368 (unsigned int)tv.tv_usec);
370 if (lws_add_http_header_by_name(wsi,
371 (unsigned char *)"set-cookie:",
372 (unsigned char *)b64, n, &p,
373 (unsigned char *)leaf_path + sizeof(leaf_path)))
376 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
378 "Strict-Transport-Security:",
380 "max-age=15768000 ; "
381 "includeSubDomains", 36, &p,
382 (unsigned char *)leaf_path +
385 n = (char *)p - leaf_path;
387 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
388 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
389 return -1; /* error or can't reuse connection: close the socket */
392 * notice that the sending of the file completes asynchronously,
393 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
398 case LWS_CALLBACK_HTTP_BODY:
399 strncpy(buf, in, 20);
404 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
405 (const char *)buf, (int)len);
409 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
410 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
411 /* the whole of the sent body arrived, close or reuse the connection */
412 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
415 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
418 case LWS_CALLBACK_HTTP_WRITEABLE:
419 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
421 if (pss->client_finished)
424 if (pss->fd == LWS_INVALID_FILE)
427 if (pss->reason_bf & 1) {
428 if (lws_cgi_write_split_stdout_headers(wsi) < 0)
431 pss->reason_bf &= ~1;
435 #ifndef LWS_NO_CLIENT
436 if (pss->reason_bf & 2) {
437 char *px = buf + LWS_PRE;
438 int lenx = sizeof(buf) - LWS_PRE;
440 * our sink is writeable and our source has something
441 * to read. So read a lump of source material of
442 * suitable size to send or what's available, whichever
445 pss->reason_bf &= ~2;
446 wsi1 = lws_get_child(wsi);
449 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
452 if (pss->client_finished)
458 * we can send more of whatever it is we were sending
462 /* we'd like the send this much */
463 n = sizeof(buffer) - LWS_PRE;
465 /* but if the peer told us he wants less, we can adapt */
466 m = lws_get_peer_write_allowance(wsi);
468 /* -1 means not using a protocol that has this info */
470 /* right now, peer can't handle anything */
473 if (m != -1 && m < n)
474 /* he couldn't handle that much */
477 n = lws_plat_file_read(wsi, pss->fd,
478 &amount, buffer + LWS_PRE, n);
479 /* problem reading, close conn */
481 lwsl_err("problem reading file\n");
485 /* sent it all, close conn */
489 * To support HTTP2, must take care about preamble space
491 * identification of when we send the last payload frame
492 * is handled by the library itself if you sent a
493 * content-length header
495 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
497 lwsl_err("write failed\n");
498 /* write failed, close conn */
501 if (m) /* while still active, extend timeout */
502 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
505 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
507 lws_callback_on_writable(wsi);
510 lws_plat_file_close(wsi, pss->fd);
511 pss->fd = LWS_INVALID_FILE;
515 lws_plat_file_close(wsi, pss->fd);
520 * callback for confirming to continue with client IP appear in
521 * protocol 0 callback since no websocket protocol has been agreed
522 * yet. You can just ignore this if you won't filter on client IP
523 * since the default unhandled callback return is 0 meaning let the
524 * connection continue.
526 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
527 /* if we returned non-zero from here, we kill the connection */
530 #ifndef LWS_NO_CLIENT
531 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
532 char ctype[64], ctlen = 0;
533 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
534 p = buffer + LWS_PRE;
535 end = p + sizeof(buffer) - LWS_PRE;
536 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
538 if (lws_add_http_header_by_token(lws_get_parent(wsi),
539 WSI_TOKEN_HTTP_SERVER,
540 (unsigned char *)"libwebsockets",
544 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
546 if (lws_add_http_header_by_token(lws_get_parent(wsi),
547 WSI_TOKEN_HTTP_CONTENT_TYPE,
548 (unsigned char *)ctype, ctlen, &p, end))
552 if (lws_add_http_header_content_length(lws_get_parent(wsi),
556 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
560 lwsl_info("%s\n", buffer + LWS_PRE);
562 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
563 p - (buffer + LWS_PRE),
564 LWS_WRITE_HTTP_HEADERS);
569 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
570 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
573 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
574 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
575 assert(lws_get_parent(wsi));
576 if (!lws_get_parent(wsi))
578 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
579 // wsi, lws_get_socket_fd(wsi),
580 // lws_get_parent(wsi),
581 // lws_get_socket_fd(lws_get_parent(wsi)), len);
582 pss1 = lws_wsi_user(lws_get_parent(wsi));
583 pss1->reason_bf |= 2;
584 lws_callback_on_writable(lws_get_parent(wsi));
586 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
587 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
588 assert(lws_get_parent(wsi));
589 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
590 len, LWS_WRITE_HTTP);
594 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
595 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
596 assert(lws_get_parent(wsi));
597 if (!lws_get_parent(wsi))
599 pss1 = lws_wsi_user(lws_get_parent(wsi));
600 pss1->client_finished = 1;
605 /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
607 * - POST data goes on subprocess stdin
608 * - subprocess stdout goes on http via writeable callback
609 * - subprocess stderr goes to the logs
611 case LWS_CALLBACK_CGI:
612 pss->args = *((struct lws_cgi_args *)in);
613 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
614 switch (pss->args.ch) { /* which of stdin/out/err ? */
616 /* TBD stdin rx flow control */
620 /* when writing to MASTER would not block */
621 lws_callback_on_writable(wsi);
624 n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
626 //lwsl_notice("stderr reads %d\n", n);
628 if (buf[n - 1] != '\n')
631 lwsl_notice("CGI-stderr: %s\n", buf);
637 case LWS_CALLBACK_CGI_TERMINATED:
638 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
639 /* because we sent on openended http, close the connection */
642 case LWS_CALLBACK_CGI_STDIN_DATA: /* POST body for stdin */
643 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
644 pss->args = *((struct lws_cgi_args *)in);
645 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
646 pss->args.data, pss->args.len);
647 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
648 if (n < pss->args.len)
649 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
655 * callbacks for managing the external poll() array appear in
656 * protocol 0 callback
659 case LWS_CALLBACK_LOCK_POLL:
661 * lock mutex to protect pollfd state
662 * called before any other POLL related callback
663 * if protecting wsi lifecycle change, len == 1
665 test_server_lock(len);
668 case LWS_CALLBACK_UNLOCK_POLL:
670 * unlock mutex to protect pollfd state when
671 * called after any other POLL related callback
672 * if protecting wsi lifecycle change, len == 1
674 test_server_unlock(len);
678 case LWS_CALLBACK_ADD_POLL_FD:
680 if (count_pollfds >= max_poll_elements) {
681 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
685 fd_lookup[pa->fd] = count_pollfds;
686 pollfds[count_pollfds].fd = pa->fd;
687 pollfds[count_pollfds].events = pa->events;
688 pollfds[count_pollfds++].revents = 0;
691 case LWS_CALLBACK_DEL_POLL_FD:
692 if (!--count_pollfds)
694 m = fd_lookup[pa->fd];
695 /* have the last guy take up the vacant slot */
696 pollfds[m] = pollfds[count_pollfds];
697 fd_lookup[pollfds[count_pollfds].fd] = m;
700 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
701 pollfds[fd_lookup[pa->fd]].events = pa->events;
705 case LWS_CALLBACK_GET_THREAD_ID:
707 * if you will call "lws_callback_on_writable"
708 * from a different thread, return the caller thread ID
709 * here so lws can use this information to work out if it
710 * should signal the poll() loop to exit and restart early
713 /* return pthread_getthreadid_np(); */
723 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
725 if (lws_http_transaction_completed(wsi))