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);
218 /* if a legal POST URL, let it continue and accept data */
219 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
222 /* check for the "send a big file by hand" example case */
224 if (!strcmp((const char *)in, "/leaf.jpg")) {
225 if (strlen(resource_path) > sizeof(leaf_path) - 10)
227 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
229 /* well, let's demonstrate how to send the hard way */
231 p = buffer + LWS_PRE;
232 end = p + sizeof(buffer) - LWS_PRE;
234 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
237 if (pss->fd == LWS_INVALID_FILE) {
238 lwsl_err("faild to open file %s\n", leaf_path);
243 * we will send a big jpeg file, but it could be
244 * anything. Set the Content-Type: appropriately
245 * so the browser knows what to do with it.
247 * Notice we use the APIs to build the header, which
248 * will do the right thing for HTTP 1/1.1 and HTTP2
249 * depending on what connection it happens to be working
252 if (lws_add_http_header_status(wsi, 200, &p, end))
254 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
255 (unsigned char *)"libwebsockets",
258 if (lws_add_http_header_by_token(wsi,
259 WSI_TOKEN_HTTP_CONTENT_TYPE,
260 (unsigned char *)"image/jpeg",
263 if (lws_add_http_header_content_length(wsi,
267 if (lws_finalize_http_header(wsi, &p, end))
271 * send the http headers...
272 * this won't block since it's the first payload sent
273 * on the connection since it was established
274 * (too small for partial)
276 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
277 * which also means you can't send body too in one step,
278 * this is mandated by changes in HTTP2
282 lwsl_info("%s\n", buffer + LWS_PRE);
284 n = lws_write(wsi, buffer + LWS_PRE,
285 p - (buffer + LWS_PRE),
286 LWS_WRITE_HTTP_HEADERS);
288 lws_plat_file_close(wsi, pss->fd);
292 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
294 lws_callback_on_writable(wsi);
298 /* if not, send a file the easy way */
299 if (!strncmp(in, "/cgit-data/", 11)) {
300 in = (char *)in + 11;
301 strcpy(buf, "/usr/share/cgit");
303 strcpy(buf, resource_path);
305 if (strcmp(in, "/")) {
306 if (*((const char *)in) != '/')
308 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
309 } else /* default file to serve */
310 strcat(buf, "/test.html");
311 buf[sizeof(buf) - 1] = '\0';
313 /* refuse to serve files we don't understand */
314 mimetype = get_mimetype(buf);
316 lwsl_err("Unknown mimetype for %s\n", buf);
317 lws_return_http_status(wsi,
318 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
322 /* demonstrates how to set a cookie on / */
324 other_headers = leaf_path;
325 p = (unsigned char *)leaf_path;
326 if (!strcmp((const char *)in, "/") &&
327 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
328 /* this isn't very unguessable but it'll do for us */
329 gettimeofday(&tv, NULL);
330 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
331 (unsigned int)tv.tv_sec,
332 (unsigned int)tv.tv_usec);
334 if (lws_add_http_header_by_name(wsi,
335 (unsigned char *)"set-cookie:",
336 (unsigned char *)b64, n, &p,
337 (unsigned char *)leaf_path + sizeof(leaf_path)))
340 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
342 "Strict-Transport-Security:",
344 "max-age=15768000 ; "
345 "includeSubDomains", 36, &p,
346 (unsigned char *)leaf_path +
349 n = (char *)p - leaf_path;
351 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
352 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
353 return -1; /* error or can't reuse connection: close the socket */
356 * notice that the sending of the file completes asynchronously,
357 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
362 case LWS_CALLBACK_HTTP_BODY:
363 strncpy(buf, in, 20);
368 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
369 (const char *)buf, (int)len);
373 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
374 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
375 /* the whole of the sent body arrived, close or reuse the connection */
376 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
379 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
382 case LWS_CALLBACK_HTTP_WRITEABLE:
383 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
385 if (pss->client_finished)
388 if (pss->fd == LWS_INVALID_FILE)
391 #ifndef LWS_NO_CLIENT
392 if (pss->reason_bf & 2) {
393 char *px = buf + LWS_PRE;
394 int lenx = sizeof(buf) - LWS_PRE;
396 * our sink is writeable and our source has something
397 * to read. So read a lump of source material of
398 * suitable size to send or what's available, whichever
401 pss->reason_bf &= ~2;
402 wsi1 = lws_get_child(wsi);
405 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
408 if (pss->client_finished)
414 * we can send more of whatever it is we were sending
418 /* we'd like the send this much */
419 n = sizeof(buffer) - LWS_PRE;
421 /* but if the peer told us he wants less, we can adapt */
422 m = lws_get_peer_write_allowance(wsi);
424 /* -1 means not using a protocol that has this info */
426 /* right now, peer can't handle anything */
429 if (m != -1 && m < n)
430 /* he couldn't handle that much */
433 n = lws_plat_file_read(wsi, pss->fd,
434 &amount, buffer + LWS_PRE, n);
435 /* problem reading, close conn */
437 lwsl_err("problem reading file\n");
441 /* sent it all, close conn */
445 * To support HTTP2, must take care about preamble space
447 * identification of when we send the last payload frame
448 * is handled by the library itself if you sent a
449 * content-length header
451 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
453 lwsl_err("write failed\n");
454 /* write failed, close conn */
457 if (m) /* while still active, extend timeout */
458 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
461 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
463 lws_callback_on_writable(wsi);
466 lws_plat_file_close(wsi, pss->fd);
467 pss->fd = LWS_INVALID_FILE;
471 lws_plat_file_close(wsi, pss->fd);
476 * callback for confirming to continue with client IP appear in
477 * protocol 0 callback since no websocket protocol has been agreed
478 * yet. You can just ignore this if you won't filter on client IP
479 * since the default unhandled callback return is 0 meaning let the
480 * connection continue.
482 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
483 /* if we returned non-zero from here, we kill the connection */
486 #ifndef LWS_NO_CLIENT
487 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
488 char ctype[64], ctlen = 0;
489 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
490 p = buffer + LWS_PRE;
491 end = p + sizeof(buffer) - LWS_PRE;
492 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
494 if (lws_add_http_header_by_token(lws_get_parent(wsi),
495 WSI_TOKEN_HTTP_SERVER,
496 (unsigned char *)"libwebsockets",
500 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
502 if (lws_add_http_header_by_token(lws_get_parent(wsi),
503 WSI_TOKEN_HTTP_CONTENT_TYPE,
504 (unsigned char *)ctype, ctlen, &p, end))
508 if (lws_add_http_header_content_length(lws_get_parent(wsi),
512 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
516 lwsl_info("%s\n", buffer + LWS_PRE);
518 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
519 p - (buffer + LWS_PRE),
520 LWS_WRITE_HTTP_HEADERS);
525 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
526 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
529 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
530 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
531 assert(lws_get_parent(wsi));
532 if (!lws_get_parent(wsi))
534 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
535 // wsi, lws_get_socket_fd(wsi),
536 // lws_get_parent(wsi),
537 // lws_get_socket_fd(lws_get_parent(wsi)), len);
538 pss1 = lws_wsi_user(lws_get_parent(wsi));
539 pss1->reason_bf |= 2;
540 lws_callback_on_writable(lws_get_parent(wsi));
542 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
543 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
544 assert(lws_get_parent(wsi));
545 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
546 len, LWS_WRITE_HTTP);
550 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
551 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
552 assert(lws_get_parent(wsi));
553 if (!lws_get_parent(wsi))
555 pss1 = lws_wsi_user(lws_get_parent(wsi));
556 pss1->client_finished = 1;
561 * callbacks for managing the external poll() array appear in
562 * protocol 0 callback
565 case LWS_CALLBACK_LOCK_POLL:
567 * lock mutex to protect pollfd state
568 * called before any other POLL related callback
569 * if protecting wsi lifecycle change, len == 1
571 test_server_lock(len);
574 case LWS_CALLBACK_UNLOCK_POLL:
576 * unlock mutex to protect pollfd state when
577 * called after any other POLL related callback
578 * if protecting wsi lifecycle change, len == 1
580 test_server_unlock(len);
584 case LWS_CALLBACK_ADD_POLL_FD:
586 if (count_pollfds >= max_poll_elements) {
587 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
591 fd_lookup[pa->fd] = count_pollfds;
592 pollfds[count_pollfds].fd = pa->fd;
593 pollfds[count_pollfds].events = pa->events;
594 pollfds[count_pollfds++].revents = 0;
597 case LWS_CALLBACK_DEL_POLL_FD:
598 if (!--count_pollfds)
600 m = fd_lookup[pa->fd];
601 /* have the last guy take up the vacant slot */
602 pollfds[m] = pollfds[count_pollfds];
603 fd_lookup[pollfds[count_pollfds].fd] = m;
606 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
607 pollfds[fd_lookup[pa->fd]].events = pa->events;
611 case LWS_CALLBACK_GET_THREAD_ID:
613 * if you will call "lws_callback_on_writable"
614 * from a different thread, return the caller thread ID
615 * here so lws can use this information to work out if it
616 * should signal the poll() loop to exit and restart early
619 /* return pthread_getthreadid_np(); */
629 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
631 if (lws_http_transaction_completed(wsi))