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;
144 case LWS_CALLBACK_HTTP:
146 if (debug_level & LLL_INFO) {
147 dump_handshake_info(wsi);
149 /* dump the individual URI Arg parameters */
151 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
152 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
153 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
158 char name[100], rip[50];
159 lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
160 sizeof(name), rip, sizeof(rip));
161 sprintf(buf, "%s (%s)", name, rip);
162 lwsl_notice("HTTP connect from %s\n", buf);
166 lws_return_http_status(wsi,
167 HTTP_STATUS_BAD_REQUEST, NULL);
171 #ifndef LWS_NO_CLIENT
172 if (!strncmp(in, "/proxytest", 10)) {
173 struct lws_client_connect_info i;
174 char *rootpath = "/";
175 const char *p = (const char *)in;
177 if (lws_get_child(wsi))
180 pss->client_finished = 0;
181 memset(&i,0, sizeof(i));
182 i.context = lws_get_context(wsi);
183 i.address = "git.libwebsockets.org";
185 i.ssl_connection = 0;
187 i.path = (char *)in + 10;
190 i.host = "git.libwebsockets.org";
194 i.uri_replace_from = "git.libwebsockets.org/";
195 i.uri_replace_to = "/proxytest/";
196 if (!lws_client_connect_via_info(&i)) {
197 lwsl_err("proxy connect fail\n");
208 /* this example server has no concept of directories */
209 if (strchr((const char *)in + 1, '/')) {
210 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
216 if (!strncmp(in, "/cgitest", 8)) {
217 static char *cmd[] = {
220 INSTALL_DATADIR"/libwebsockets-test-server/lws-cgi-test.sh",
221 // "/var/www/cgi-bin/cgit",
225 lwsl_notice("%s: cgitest\n", __func__);
226 n = lws_cgi(wsi, cmd, 8, 5);
228 lwsl_err("%s: cgi failed\n");
231 p = buffer + LWS_PRE;
232 end = p + sizeof(buffer) - LWS_PRE;
234 if (lws_add_http_header_status(wsi, 200, &p, end))
236 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
237 (unsigned char *)"close", 5, &p, end))
239 n = lws_write(wsi, buffer + LWS_PRE,
240 p - (buffer + LWS_PRE),
241 LWS_WRITE_HTTP_HEADERS);
243 /* the cgi starts by outputting headers, we can't
244 * finalize the headers until we see the end of that
251 /* if a legal POST URL, let it continue and accept data */
252 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
255 /* check for the "send a big file by hand" example case */
257 if (!strcmp((const char *)in, "/leaf.jpg")) {
258 if (strlen(resource_path) > sizeof(leaf_path) - 10)
260 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
262 /* well, let's demonstrate how to send the hard way */
264 p = buffer + LWS_PRE;
265 end = p + sizeof(buffer) - LWS_PRE;
267 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
270 if (pss->fd == LWS_INVALID_FILE) {
271 lwsl_err("faild to open file %s\n", leaf_path);
276 * we will send a big jpeg file, but it could be
277 * anything. Set the Content-Type: appropriately
278 * so the browser knows what to do with it.
280 * Notice we use the APIs to build the header, which
281 * will do the right thing for HTTP 1/1.1 and HTTP2
282 * depending on what connection it happens to be working
285 if (lws_add_http_header_status(wsi, 200, &p, end))
287 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
288 (unsigned char *)"libwebsockets",
291 if (lws_add_http_header_by_token(wsi,
292 WSI_TOKEN_HTTP_CONTENT_TYPE,
293 (unsigned char *)"image/jpeg",
296 if (lws_add_http_header_content_length(wsi,
300 if (lws_finalize_http_header(wsi, &p, end))
304 * send the http headers...
305 * this won't block since it's the first payload sent
306 * on the connection since it was established
307 * (too small for partial)
309 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
310 * which also means you can't send body too in one step,
311 * this is mandated by changes in HTTP2
315 lwsl_info("%s\n", buffer + LWS_PRE);
317 n = lws_write(wsi, buffer + LWS_PRE,
318 p - (buffer + LWS_PRE),
319 LWS_WRITE_HTTP_HEADERS);
321 lws_plat_file_close(wsi, pss->fd);
325 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
327 lws_callback_on_writable(wsi);
331 /* if not, send a file the easy way */
332 if (!strncmp(in, "/cgit-data/", 11)) {
333 in = (char *)in + 11;
334 strcpy(buf, "/usr/share/cgit");
336 strcpy(buf, resource_path);
338 if (strcmp(in, "/")) {
339 if (*((const char *)in) != '/')
341 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
342 } else /* default file to serve */
343 strcat(buf, "/test.html");
344 buf[sizeof(buf) - 1] = '\0';
346 /* refuse to serve files we don't understand */
347 mimetype = get_mimetype(buf);
349 lwsl_err("Unknown mimetype for %s\n", buf);
350 lws_return_http_status(wsi,
351 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
355 /* demonstrates how to set a cookie on / */
357 other_headers = leaf_path;
358 p = (unsigned char *)leaf_path;
359 if (!strcmp((const char *)in, "/") &&
360 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
361 /* this isn't very unguessable but it'll do for us */
362 gettimeofday(&tv, NULL);
363 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
364 (unsigned int)tv.tv_sec,
365 (unsigned int)tv.tv_usec);
367 if (lws_add_http_header_by_name(wsi,
368 (unsigned char *)"set-cookie:",
369 (unsigned char *)b64, n, &p,
370 (unsigned char *)leaf_path + sizeof(leaf_path)))
373 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
375 "Strict-Transport-Security:",
377 "max-age=15768000 ; "
378 "includeSubDomains", 36, &p,
379 (unsigned char *)leaf_path +
382 n = (char *)p - leaf_path;
384 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
385 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
386 return -1; /* error or can't reuse connection: close the socket */
389 * notice that the sending of the file completes asynchronously,
390 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
395 case LWS_CALLBACK_HTTP_BODY:
396 strncpy(buf, in, 20);
401 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
402 (const char *)buf, (int)len);
406 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
407 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
408 /* the whole of the sent body arrived, close or reuse the connection */
409 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
412 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
415 case LWS_CALLBACK_HTTP_WRITEABLE:
416 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
418 if (pss->client_finished)
421 if (pss->fd == LWS_INVALID_FILE)
424 if (pss->reason_bf & 1) {
425 if (lws_cgi_write_split_stdout_headers(wsi) < 0)
428 pss->reason_bf &= ~1;
432 #ifndef LWS_NO_CLIENT
433 if (pss->reason_bf & 2) {
434 char *px = buf + LWS_PRE;
435 int lenx = sizeof(buf) - LWS_PRE;
437 * our sink is writeable and our source has something
438 * to read. So read a lump of source material of
439 * suitable size to send or what's available, whichever
442 pss->reason_bf &= ~2;
443 wsi1 = lws_get_child(wsi);
446 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
449 if (pss->client_finished)
455 * we can send more of whatever it is we were sending
459 /* we'd like the send this much */
460 n = sizeof(buffer) - LWS_PRE;
462 /* but if the peer told us he wants less, we can adapt */
463 m = lws_get_peer_write_allowance(wsi);
465 /* -1 means not using a protocol that has this info */
467 /* right now, peer can't handle anything */
470 if (m != -1 && m < n)
471 /* he couldn't handle that much */
474 n = lws_plat_file_read(wsi, pss->fd,
475 &amount, buffer + LWS_PRE, n);
476 /* problem reading, close conn */
478 lwsl_err("problem reading file\n");
482 /* sent it all, close conn */
486 * To support HTTP2, must take care about preamble space
488 * identification of when we send the last payload frame
489 * is handled by the library itself if you sent a
490 * content-length header
492 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
494 lwsl_err("write failed\n");
495 /* write failed, close conn */
498 if (m) /* while still active, extend timeout */
499 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
502 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
504 lws_callback_on_writable(wsi);
507 lws_plat_file_close(wsi, pss->fd);
508 pss->fd = LWS_INVALID_FILE;
512 lws_plat_file_close(wsi, pss->fd);
517 * callback for confirming to continue with client IP appear in
518 * protocol 0 callback since no websocket protocol has been agreed
519 * yet. You can just ignore this if you won't filter on client IP
520 * since the default unhandled callback return is 0 meaning let the
521 * connection continue.
523 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
524 /* if we returned non-zero from here, we kill the connection */
527 #ifndef LWS_NO_CLIENT
528 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
529 char ctype[64], ctlen = 0;
530 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
531 p = buffer + LWS_PRE;
532 end = p + sizeof(buffer) - LWS_PRE;
533 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
535 if (lws_add_http_header_by_token(lws_get_parent(wsi),
536 WSI_TOKEN_HTTP_SERVER,
537 (unsigned char *)"libwebsockets",
541 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
543 if (lws_add_http_header_by_token(lws_get_parent(wsi),
544 WSI_TOKEN_HTTP_CONTENT_TYPE,
545 (unsigned char *)ctype, ctlen, &p, end))
549 if (lws_add_http_header_content_length(lws_get_parent(wsi),
553 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
557 lwsl_info("%s\n", buffer + LWS_PRE);
559 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
560 p - (buffer + LWS_PRE),
561 LWS_WRITE_HTTP_HEADERS);
566 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
567 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
570 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
571 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
572 assert(lws_get_parent(wsi));
573 if (!lws_get_parent(wsi))
575 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
576 // wsi, lws_get_socket_fd(wsi),
577 // lws_get_parent(wsi),
578 // lws_get_socket_fd(lws_get_parent(wsi)), len);
579 pss1 = lws_wsi_user(lws_get_parent(wsi));
580 pss1->reason_bf |= 2;
581 lws_callback_on_writable(lws_get_parent(wsi));
583 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
584 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
585 assert(lws_get_parent(wsi));
586 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
587 len, LWS_WRITE_HTTP);
591 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
592 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
593 assert(lws_get_parent(wsi));
594 if (!lws_get_parent(wsi))
596 pss1 = lws_wsi_user(lws_get_parent(wsi));
597 pss1->client_finished = 1;
602 /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
604 * - POST data goes on subprocess stdin
605 * - subprocess stdout goes on http via writeable callback
606 * - subprocess stderr goes to the logs
608 case LWS_CALLBACK_CGI:
609 pss->args = *((struct lws_cgi_args *)in);
610 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
611 switch (pss->args.ch) { /* which of stdin/out/err ? */
613 /* TBD stdin rx flow control */
617 /* when writing to MASTER would not block */
618 lws_callback_on_writable(wsi);
621 n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
623 //lwsl_notice("stderr reads %d\n", n);
625 if (buf[n - 1] != '\n')
628 lwsl_notice("CGI-stderr: %s\n", buf);
634 case LWS_CALLBACK_CGI_TERMINATED:
635 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
636 /* because we sent on openended http, close the connection */
639 case LWS_CALLBACK_CGI_STDIN_DATA: /* POST body for stdin */
640 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
641 pss->args = *((struct lws_cgi_args *)in);
642 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
643 pss->args.data, pss->args.len);
644 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
645 if (n < pss->args.len)
646 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
652 * callbacks for managing the external poll() array appear in
653 * protocol 0 callback
656 case LWS_CALLBACK_LOCK_POLL:
658 * lock mutex to protect pollfd state
659 * called before any other POLL related callback
660 * if protecting wsi lifecycle change, len == 1
662 test_server_lock(len);
665 case LWS_CALLBACK_UNLOCK_POLL:
667 * unlock mutex to protect pollfd state when
668 * called after any other POLL related callback
669 * if protecting wsi lifecycle change, len == 1
671 test_server_unlock(len);
675 case LWS_CALLBACK_ADD_POLL_FD:
677 if (count_pollfds >= max_poll_elements) {
678 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
682 fd_lookup[pa->fd] = count_pollfds;
683 pollfds[count_pollfds].fd = pa->fd;
684 pollfds[count_pollfds].events = pa->events;
685 pollfds[count_pollfds++].revents = 0;
688 case LWS_CALLBACK_DEL_POLL_FD:
689 if (!--count_pollfds)
691 m = fd_lookup[pa->fd];
692 /* have the last guy take up the vacant slot */
693 pollfds[m] = pollfds[count_pollfds];
694 fd_lookup[pollfds[count_pollfds].fd] = m;
697 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
698 pollfds[fd_lookup[pa->fd]].events = pa->events;
702 case LWS_CALLBACK_GET_THREAD_ID:
704 * if you will call "lws_callback_on_writable"
705 * from a different thread, return the caller thread ID
706 * here so lws can use this information to work out if it
707 * should signal the poll() loop to exit and restart early
710 /* return pthread_getthreadid_np(); */
720 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
722 if (lws_http_transaction_completed(wsi))