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 *wsi, enum lws_callback_reasons reason, void *user,
114 void *in, size_t len)
116 struct per_session_data__http *pss =
117 (struct per_session_data__http *)user;
118 static unsigned char buffer[4096];
119 unsigned long amount, file_len;
120 char leaf_path[1024];
121 const char *mimetype;
131 struct lws_pollargs *pa = (struct lws_pollargs *)in;
135 case LWS_CALLBACK_HTTP:
137 dump_handshake_info(wsi);
139 /* dump the individual URI Arg parameters */
141 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
142 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
143 lwsl_info("URI Arg %d: %s\n", ++n, buf);
147 lws_return_http_status(wsi,
148 HTTP_STATUS_BAD_REQUEST, NULL);
152 /* this example server has no concept of directories */
153 if (strchr((const char *)in + 1, '/')) {
154 lws_return_http_status(wsi,
155 HTTP_STATUS_FORBIDDEN, NULL);
159 /* if a legal POST URL, let it continue and accept data */
160 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
163 /* check for the "send a big file by hand" example case */
165 if (!strcmp((const char *)in, "/leaf.jpg")) {
166 if (strlen(resource_path) > sizeof(leaf_path) - 10)
168 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
170 /* well, let's demonstrate how to send the hard way */
172 p = buffer + LWS_SEND_BUFFER_PRE_PADDING;
173 end = p + sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
175 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
178 if (pss->fd == LWS_INVALID_FILE)
182 * we will send a big jpeg file, but it could be
183 * anything. Set the Content-Type: appropriately
184 * so the browser knows what to do with it.
186 * Notice we use the APIs to build the header, which
187 * will do the right thing for HTTP 1/1.1 and HTTP2
188 * depending on what connection it happens to be working
191 if (lws_add_http_header_status(wsi, 200, &p, end))
193 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
194 (unsigned char *)"libwebsockets",
197 if (lws_add_http_header_by_token(wsi,
198 WSI_TOKEN_HTTP_CONTENT_TYPE,
199 (unsigned char *)"image/jpeg",
202 if (lws_add_http_header_content_length(wsi,
206 if (lws_finalize_http_header(wsi, &p, end))
210 * send the http headers...
211 * this won't block since it's the first payload sent
212 * on the connection since it was established
213 * (too small for partial)
215 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
216 * which also means you can't send body too in one step,
217 * this is mandated by changes in HTTP2
220 n = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
221 p - (buffer + LWS_SEND_BUFFER_PRE_PADDING),
222 LWS_WRITE_HTTP_HEADERS);
225 lws_plat_file_close(wsi, pss->fd);
229 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
231 lws_callback_on_writable(wsi);
235 /* if not, send a file the easy way */
236 strcpy(buf, resource_path);
237 if (strcmp(in, "/")) {
238 if (*((const char *)in) != '/')
240 strncat(buf, in, sizeof(buf) - strlen(resource_path));
241 } else /* default file to serve */
242 strcat(buf, "/test.html");
243 buf[sizeof(buf) - 1] = '\0';
245 /* refuse to serve files we don't understand */
246 mimetype = get_mimetype(buf);
248 lwsl_err("Unknown mimetype for %s\n", buf);
249 lws_return_http_status(wsi,
250 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
254 /* demonstrates how to set a cookie on / */
256 other_headers = NULL;
258 if (!strcmp((const char *)in, "/") &&
259 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
260 /* this isn't very unguessable but it'll do for us */
261 gettimeofday(&tv, NULL);
262 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
263 (unsigned int)tv.tv_sec,
264 (unsigned int)tv.tv_usec);
266 p = (unsigned char *)leaf_path;
268 if (lws_add_http_header_by_name(wsi,
269 (unsigned char *)"set-cookie:",
270 (unsigned char *)b64, n, &p,
271 (unsigned char *)leaf_path + sizeof(leaf_path)))
273 n = (char *)p - leaf_path;
274 other_headers = leaf_path;
277 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
278 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
279 return -1; /* error or can't reuse connection: close the socket */
282 * notice that the sending of the file completes asynchronously,
283 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
289 case LWS_CALLBACK_HTTP_BODY:
290 strncpy(buf, in, 20);
295 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
296 (const char *)buf, (int)len);
300 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
301 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
302 /* the whole of the sent body arrived, close or reuse the connection */
303 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
306 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
309 case LWS_CALLBACK_HTTP_WRITEABLE:
311 * we can send more of whatever it is we were sending
314 /* we'd like the send this much */
315 n = sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
317 /* but if the peer told us he wants less, we can adapt */
318 m = lws_get_peer_write_allowance(wsi);
320 /* -1 means not using a protocol that has this info */
322 /* right now, peer can't handle anything */
325 if (m != -1 && m < n)
326 /* he couldn't handle that much */
329 n = lws_plat_file_read(wsi, pss->fd,
331 LWS_SEND_BUFFER_PRE_PADDING, n);
332 /* problem reading, close conn */
336 /* sent it all, close conn */
340 * To support HTTP2, must take care about preamble space
342 * identification of when we send the last payload frame
343 * is handled by the library itself if you sent a
344 * content-length header
346 m = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
349 /* write failed, close conn */
353 * http2 won't do this
356 /* partial write, adjust */
357 if (lws_plat_file_seek_cur(wsi, pss->fd, m - n) ==
361 if (m) /* while still active, extend timeout */
363 PENDING_TIMEOUT_HTTP_CONTENT, 5);
365 /* if we have indigestion, let him clear it
366 * before eating more */
367 if (lws_partial_buffered(wsi))
370 } while (!lws_send_pipe_choked(wsi));
373 lws_callback_on_writable(wsi);
376 /* true if still partial pending */
377 if (lws_partial_buffered(wsi)) {
378 lws_callback_on_writable(wsi);
381 lws_plat_file_close(wsi, pss->fd);
385 lws_plat_file_close(wsi, pss->fd);
389 * callback for confirming to continue with client IP appear in
390 * protocol 0 callback since no websocket protocol has been agreed
391 * yet. You can just ignore this if you won't filter on client IP
392 * since the default uhandled callback return is 0 meaning let the
393 * connection continue.
395 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
397 /* if we returned non-zero from here, we kill the connection */
401 * callbacks for managing the external poll() array appear in
402 * protocol 0 callback
405 case LWS_CALLBACK_LOCK_POLL:
407 * lock mutex to protect pollfd state
408 * called before any other POLL related callback
409 * if protecting wsi lifecycle change, len == 1
411 test_server_lock(len);
414 case LWS_CALLBACK_UNLOCK_POLL:
416 * unlock mutex to protect pollfd state when
417 * called after any other POLL related callback
418 * if protecting wsi lifecycle change, len == 1
420 test_server_unlock(len);
424 case LWS_CALLBACK_ADD_POLL_FD:
426 if (count_pollfds >= max_poll_elements) {
427 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
431 fd_lookup[pa->fd] = count_pollfds;
432 pollfds[count_pollfds].fd = pa->fd;
433 pollfds[count_pollfds].events = pa->events;
434 pollfds[count_pollfds++].revents = 0;
437 case LWS_CALLBACK_DEL_POLL_FD:
438 if (!--count_pollfds)
440 m = fd_lookup[pa->fd];
441 /* have the last guy take up the vacant slot */
442 pollfds[m] = pollfds[count_pollfds];
443 fd_lookup[pollfds[count_pollfds].fd] = m;
446 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
447 pollfds[fd_lookup[pa->fd]].events = pa->events;
451 case LWS_CALLBACK_GET_THREAD_ID:
453 * if you will call "lws_callback_on_writable"
454 * from a different thread, return the caller thread ID
455 * here so lws can use this information to work out if it
456 * should signal the poll() loop to exit and restart early
459 /* return pthread_getthreadid_np(); */
469 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
471 if (lws_http_transaction_completed(wsi))