2 * libwebsockets-test-server - libwebsockets test implementation
4 * Copyright (C) 2010-2015 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 #include "test-server.h"
24 * This demo server shows how to use libwebsockets for one or more
25 * websocket protocols in the same server
27 * It defines the following websocket protocols:
29 * dumb-increment-protocol: once the socket is opened, an incrementing
30 * ascii string is sent down it every 50ms.
31 * If you send "reset\n" on the websocket, then
32 * the incrementing number is reset to 0.
34 * lws-mirror-protocol: copies any received packet to every connection also
35 * using this protocol, including the sender
42 PROTOCOL_DUMB_INCREMENT,
50 * We take a strict whitelist approach to stop ../ attacks
58 * this is just an example of parsing handshake headers, you don't need this
59 * in your code unless you will filter allowing connections by the header
63 dump_handshake_info(struct lws *wsi)
67 const unsigned char *c;
70 c = lws_token_to_string(n);
76 if (!lws_hdr_total_length(wsi, n)) {
81 lws_hdr_copy(wsi, buf, sizeof buf, n);
83 fprintf(stderr, " %s = %s\n", (char *)c, buf);
88 const char * get_mimetype(const char *file)
95 if (!strcmp(&file[n - 4], ".ico"))
96 return "image/x-icon";
98 if (!strcmp(&file[n - 4], ".png"))
101 if (!strcmp(&file[n - 5], ".html"))
107 /* this protocol server (always the first one) handles HTTP,
109 * Some misc callbacks that aren't associated with a protocol also turn up only
110 * here on the first protocol server.
113 int callback_http(struct lws_context *context, struct lws *wsi,
114 enum lws_callback_reasons reason, void *user,
115 void *in, size_t len)
117 struct per_session_data__http *pss =
118 (struct per_session_data__http *)user;
119 static unsigned char buffer[4096];
120 unsigned long amount, file_len;
121 char leaf_path[1024];
122 const char *mimetype;
132 struct lws_pollargs *pa = (struct lws_pollargs *)in;
136 case LWS_CALLBACK_HTTP:
138 dump_handshake_info(wsi);
140 /* dump the individual URI Arg parameters */
144 m = lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
145 WSI_TOKEN_HTTP_URI_ARGS, n);
149 lwsl_info("URI Arg %d: %s\n", n, buf);
153 lws_return_http_status(context, wsi,
154 HTTP_STATUS_BAD_REQUEST, NULL);
158 /* this example server has no concept of directories */
159 if (strchr((const char *)in + 1, '/')) {
160 lws_return_http_status(context, wsi,
161 HTTP_STATUS_FORBIDDEN, NULL);
165 /* if a legal POST URL, let it continue and accept data */
166 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
169 /* check for the "send a big file by hand" example case */
171 if (!strcmp((const char *)in, "/leaf.jpg")) {
172 if (strlen(resource_path) > sizeof(leaf_path) - 10)
174 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
176 /* well, let's demonstrate how to send the hard way */
178 p = buffer + LWS_SEND_BUFFER_PRE_PADDING;
179 end = p + sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
181 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
184 if (pss->fd == LWS_INVALID_FILE)
188 * we will send a big jpeg file, but it could be
189 * anything. Set the Content-Type: appropriately
190 * so the browser knows what to do with it.
192 * Notice we use the APIs to build the header, which
193 * will do the right thing for HTTP 1/1.1 and HTTP2
194 * depending on what connection it happens to be working
197 if (lws_add_http_header_status(context, wsi, 200, &p, end))
199 if (lws_add_http_header_by_token(context, wsi,
200 WSI_TOKEN_HTTP_SERVER,
201 (unsigned char *)"libwebsockets",
204 if (lws_add_http_header_by_token(context, wsi,
205 WSI_TOKEN_HTTP_CONTENT_TYPE,
206 (unsigned char *)"image/jpeg",
209 if (lws_add_http_header_content_length(context, wsi,
213 if (lws_finalize_http_header(context, wsi, &p, end))
217 * send the http headers...
218 * this won't block since it's the first payload sent
219 * on the connection since it was established
220 * (too small for partial)
222 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
223 * which also means you can't send body too in one step,
224 * this is mandated by changes in HTTP2
227 n = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
228 p - (buffer + LWS_SEND_BUFFER_PRE_PADDING),
229 LWS_WRITE_HTTP_HEADERS);
232 lws_plat_file_close(wsi, pss->fd);
236 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
238 lws_callback_on_writable(context, wsi);
242 /* if not, send a file the easy way */
243 strcpy(buf, resource_path);
244 if (strcmp(in, "/")) {
245 if (*((const char *)in) != '/')
247 strncat(buf, in, sizeof(buf) - strlen(resource_path));
248 } else /* default file to serve */
249 strcat(buf, "/test.html");
250 buf[sizeof(buf) - 1] = '\0';
252 /* refuse to serve files we don't understand */
253 mimetype = get_mimetype(buf);
255 lwsl_err("Unknown mimetype for %s\n", buf);
256 lws_return_http_status(context, wsi,
257 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
261 /* demostrates how to set a cookie on / */
263 other_headers = NULL;
265 if (!strcmp((const char *)in, "/") &&
266 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
267 /* this isn't very unguessable but it'll do for us */
268 gettimeofday(&tv, NULL);
269 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
270 (unsigned int)tv.tv_sec,
271 (unsigned int)tv.tv_usec);
273 p = (unsigned char *)leaf_path;
275 if (lws_add_http_header_by_name(context, wsi,
276 (unsigned char *)"set-cookie:",
277 (unsigned char *)b64, n, &p,
278 (unsigned char *)leaf_path + sizeof(leaf_path)))
280 n = (char *)p - leaf_path;
281 other_headers = leaf_path;
284 n = lws_serve_http_file(context, wsi, buf,
285 mimetype, other_headers, n);
286 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
287 return -1; /* error or can't reuse connection: close the socket */
290 * notice that the sending of the file completes asynchronously,
291 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
297 case LWS_CALLBACK_HTTP_BODY:
298 strncpy(buf, in, 20);
303 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
304 (const char *)buf, (int)len);
308 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
309 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
310 /* the whole of the sent body arrived, close or reuse the connection */
311 lws_return_http_status(context, wsi,
312 HTTP_STATUS_OK, NULL);
315 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
318 case LWS_CALLBACK_HTTP_WRITEABLE:
320 * we can send more of whatever it is we were sending
323 /* we'd like the send this much */
324 n = sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
326 /* but if the peer told us he wants less, we can adapt */
327 m = lws_get_peer_write_allowance(wsi);
329 /* -1 means not using a protocol that has this info */
331 /* right now, peer can't handle anything */
334 if (m != -1 && m < n)
335 /* he couldn't handle that much */
338 n = lws_plat_file_read(wsi, pss->fd,
340 LWS_SEND_BUFFER_PRE_PADDING, n);
341 /* problem reading, close conn */
345 /* sent it all, close conn */
349 * To support HTTP2, must take care about preamble space
351 * identification of when we send the last payload frame
352 * is handled by the library itself if you sent a
353 * content-length header
355 m = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
358 /* write failed, close conn */
362 * http2 won't do this
365 /* partial write, adjust */
366 if (lws_plat_file_seek_cur(wsi, pss->fd, m - n) ==
370 if (m) /* while still active, extend timeout */
372 PENDING_TIMEOUT_HTTP_CONTENT, 5);
374 /* if we have indigestion, let him clear it
375 * before eating more */
376 if (lws_partial_buffered(wsi))
379 } while (!lws_send_pipe_choked(wsi));
382 lws_callback_on_writable(context, wsi);
385 /* true if still partial pending */
386 if (lws_partial_buffered(wsi)) {
387 lws_callback_on_writable(context, wsi);
390 lws_plat_file_close(wsi, pss->fd);
394 lws_plat_file_close(wsi, pss->fd);
398 * callback for confirming to continue with client IP appear in
399 * protocol 0 callback since no websocket protocol has been agreed
400 * yet. You can just ignore this if you won't filter on client IP
401 * since the default uhandled callback return is 0 meaning let the
402 * connection continue.
404 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
406 /* if we returned non-zero from here, we kill the connection */
410 * callbacks for managing the external poll() array appear in
411 * protocol 0 callback
414 case LWS_CALLBACK_LOCK_POLL:
416 * lock mutex to protect pollfd state
417 * called before any other POLL related callback
418 * if protecting wsi lifecycle change, len == 1
420 test_server_lock(len);
423 case LWS_CALLBACK_UNLOCK_POLL:
425 * unlock mutex to protect pollfd state when
426 * called after any other POLL related callback
427 * if protecting wsi lifecycle change, len == 1
429 test_server_unlock(len);
433 case LWS_CALLBACK_ADD_POLL_FD:
435 if (count_pollfds >= max_poll_elements) {
436 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
440 fd_lookup[pa->fd] = count_pollfds;
441 pollfds[count_pollfds].fd = pa->fd;
442 pollfds[count_pollfds].events = pa->events;
443 pollfds[count_pollfds++].revents = 0;
446 case LWS_CALLBACK_DEL_POLL_FD:
447 if (!--count_pollfds)
449 m = fd_lookup[pa->fd];
450 /* have the last guy take up the vacant slot */
451 pollfds[m] = pollfds[count_pollfds];
452 fd_lookup[pollfds[count_pollfds].fd] = m;
455 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
456 pollfds[fd_lookup[pa->fd]].events = pa->events;
460 case LWS_CALLBACK_GET_THREAD_ID:
462 * if you will call "lws_callback_on_writable"
463 * from a different thread, return the caller thread ID
464 * here so lws can use this information to work out if it
465 * should signal the poll() loop to exit and restart early
468 /* return pthread_getthreadid_np(); */
478 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
480 if (lws_http_transaction_completed(wsi))