2 * libwebsockets web server application
4 * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU 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 * General Public License for more details.
16 * You should have received a copy of the GNU General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23 /* http server gets files from this path */
24 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
25 char *resource_path = LOCAL_RESOURCE_PATH;
30 * We take a strict whitelist approach to stop ../ attacks
37 const char * get_mimetype(const char *file)
44 if (!strcmp(&file[n - 4], ".ico"))
45 return "image/x-icon";
47 if (!strcmp(&file[n - 4], ".png"))
50 if (!strcmp(&file[n - 4], ".jpg"))
53 if (!strcmp(&file[n - 5], ".html"))
56 if (!strcmp(&file[n - 4], ".css"))
62 /* this protocol server (always the first one) handles HTTP,
64 * Some misc callbacks that aren't associated with a protocol also turn up only
65 * here on the first protocol server.
68 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
71 struct per_session_data__http *pss =
72 (struct per_session_data__http *)user;
73 unsigned char buffer[4096 + LWS_PRE];
74 unsigned long amount, file_len, sent;
82 struct per_session_data__http *pss1;
89 struct lws_pollargs *pa = (struct lws_pollargs *)in;
92 // lwsl_err("%s: reason %d\n", __func__, reason);
95 case LWS_CALLBACK_HTTP:
98 char name[100], rip[50];
99 lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
100 sizeof(name), rip, sizeof(rip));
101 sprintf(buf, "%s (%s)", name, rip);
102 lwsl_notice("HTTP connect from %s\n", buf);
106 lws_return_http_status(wsi,
107 HTTP_STATUS_BAD_REQUEST, NULL);
111 #ifndef LWS_NO_CLIENT
112 if (!strncmp(in, "/proxytest", 10)) {
113 struct lws_client_connect_info i;
114 char *rootpath = "/";
115 const char *p = (const char *)in;
117 if (lws_get_child(wsi))
120 pss->client_finished = 0;
121 memset(&i,0, sizeof(i));
122 i.context = lws_get_context(wsi);
123 i.address = "git.libwebsockets.org";
125 i.ssl_connection = 0;
127 i.path = (char *)in + 10;
130 i.host = "git.libwebsockets.org";
134 i.uri_replace_from = "git.libwebsockets.org/";
135 i.uri_replace_to = "/proxytest/";
136 if (!lws_client_connect_via_info(&i)) {
137 lwsl_err("proxy connect fail\n");
148 /* this example server has no concept of directories */
149 if (strchr((const char *)in + 1, '/')) {
150 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
155 /* if a legal POST URL, let it continue and accept data */
156 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
159 /* check for the "send a big file by hand" example case */
160 lwsl_notice("%s\n", in);
161 if (!strcmp((const char *)in, "/leaf.jpg")) {
162 if (strlen(resource_path) > sizeof(leaf_path) - 10)
164 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
166 /* well, let's demonstrate how to send the hard way */
168 p = buffer + LWS_PRE;
169 end = p + sizeof(buffer) - LWS_PRE;
171 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
174 if (pss->fd == LWS_INVALID_FILE) {
175 lwsl_err("faild to open file %s\n", leaf_path);
180 * we will send a big jpeg file, but it could be
181 * anything. Set the Content-Type: appropriately
182 * so the browser knows what to do with it.
184 * Notice we use the APIs to build the header, which
185 * will do the right thing for HTTP 1/1.1 and HTTP2
186 * depending on what connection it happens to be working
189 if (lws_add_http_header_status(wsi, 200, &p, end))
191 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
192 (unsigned char *)"libwebsockets",
195 if (lws_add_http_header_by_token(wsi,
196 WSI_TOKEN_HTTP_CONTENT_TYPE,
197 (unsigned char *)"image/jpeg",
200 if (lws_add_http_header_content_length(wsi,
204 if (lws_finalize_http_header(wsi, &p, end))
208 * send the http headers...
209 * this won't block since it's the first payload sent
210 * on the connection since it was established
211 * (too small for partial)
213 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
214 * which also means you can't send body too in one step,
215 * this is mandated by changes in HTTP2
219 lwsl_info("%s\n", buffer + LWS_PRE);
221 n = lws_write(wsi, buffer + LWS_PRE,
222 p - (buffer + LWS_PRE),
223 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 if (!strncmp(in, "/cgit-data/", 11)) {
237 in = (char *)in + 11;
238 strcpy(buf, "/usr/share/cgit");
240 strcpy(buf, resource_path);
242 if (strcmp(in, "/")) {
243 if (*((const char *)in) != '/')
245 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
246 } else /* default file to serve */
247 strcat(buf, "/test.html");
248 buf[sizeof(buf) - 1] = '\0';
250 /* refuse to serve files we don't understand */
251 mimetype = get_mimetype(buf);
253 lwsl_err("Unknown mimetype for %s\n", buf);
254 lws_return_http_status(wsi,
255 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
259 /* demonstrates how to set a cookie on / */
261 other_headers = leaf_path;
262 p = (unsigned char *)leaf_path;
263 if (!strcmp((const char *)in, "/") &&
264 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
265 /* this isn't very unguessable but it'll do for us */
266 gettimeofday(&tv, NULL);
267 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
268 (unsigned int)tv.tv_sec,
269 (unsigned int)tv.tv_usec);
271 if (lws_add_http_header_by_name(wsi,
272 (unsigned char *)"set-cookie:",
273 (unsigned char *)b64, n, &p,
274 (unsigned char *)leaf_path + sizeof(leaf_path)))
277 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
279 "Strict-Transport-Security:",
281 "max-age=15768000 ; "
282 "includeSubDomains", 36, &p,
283 (unsigned char *)leaf_path +
286 n = (char *)p - leaf_path;
288 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
289 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
290 return -1; /* error or can't reuse connection: close the socket */
293 * notice that the sending of the file completes asynchronously,
294 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
299 case LWS_CALLBACK_HTTP_BODY:
300 strncpy(buf, in, 20);
305 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
306 (const char *)buf, (int)len);
310 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
311 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
312 /* the whole of the sent body arrived, close or reuse the connection */
313 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
316 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
319 case LWS_CALLBACK_HTTP_WRITEABLE:
320 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
322 if (pss->client_finished)
325 if (pss->fd == LWS_INVALID_FILE)
328 if (pss->reason_bf & 1) {
329 if (lws_cgi_write_split_stdout_headers(wsi) < 0)
332 pss->reason_bf &= ~1;
336 #ifndef LWS_NO_CLIENT
337 if (pss->reason_bf & 2) {
338 char *px = buf + LWS_PRE;
339 int lenx = sizeof(buf) - LWS_PRE;
341 * our sink is writeable and our source has something
342 * to read. So read a lump of source material of
343 * suitable size to send or what's available, whichever
346 pss->reason_bf &= ~2;
347 wsi1 = lws_get_child(wsi);
350 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
353 if (pss->client_finished)
359 * we can send more of whatever it is we were sending
363 /* we'd like the send this much */
364 n = sizeof(buffer) - LWS_PRE;
366 /* but if the peer told us he wants less, we can adapt */
367 m = lws_get_peer_write_allowance(wsi);
369 /* -1 means not using a protocol that has this info */
371 /* right now, peer can't handle anything */
374 if (m != -1 && m < n)
375 /* he couldn't handle that much */
378 n = lws_plat_file_read(wsi, pss->fd,
379 &amount, buffer + LWS_PRE, n);
380 /* problem reading, close conn */
382 lwsl_err("problem reading file\n");
386 /* sent it all, close conn */
390 * To support HTTP2, must take care about preamble space
392 * identification of when we send the last payload frame
393 * is handled by the library itself if you sent a
394 * content-length header
396 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
398 lwsl_err("write failed\n");
399 /* write failed, close conn */
402 if (m) /* while still active, extend timeout */
403 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
406 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
408 lws_callback_on_writable(wsi);
411 lws_plat_file_close(wsi, pss->fd);
412 pss->fd = LWS_INVALID_FILE;
416 lws_plat_file_close(wsi, pss->fd);
421 * callback for confirming to continue with client IP appear in
422 * protocol 0 callback since no websocket protocol has been agreed
423 * yet. You can just ignore this if you won't filter on client IP
424 * since the default unhandled callback return is 0 meaning let the
425 * connection continue.
427 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
428 /* if we returned non-zero from here, we kill the connection */
431 #ifndef LWS_NO_CLIENT
432 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
433 char ctype[64], ctlen = 0;
434 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
435 p = buffer + LWS_PRE;
436 end = p + sizeof(buffer) - LWS_PRE;
437 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
439 if (lws_add_http_header_by_token(lws_get_parent(wsi),
440 WSI_TOKEN_HTTP_SERVER,
441 (unsigned char *)"libwebsockets",
445 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
447 if (lws_add_http_header_by_token(lws_get_parent(wsi),
448 WSI_TOKEN_HTTP_CONTENT_TYPE,
449 (unsigned char *)ctype, ctlen, &p, end))
453 if (lws_add_http_header_content_length(lws_get_parent(wsi),
457 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
461 lwsl_info("%s\n", buffer + LWS_PRE);
463 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
464 p - (buffer + LWS_PRE),
465 LWS_WRITE_HTTP_HEADERS);
470 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
471 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
474 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
475 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
476 assert(lws_get_parent(wsi));
477 if (!lws_get_parent(wsi))
479 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
480 // wsi, lws_get_socket_fd(wsi),
481 // lws_get_parent(wsi),
482 // lws_get_socket_fd(lws_get_parent(wsi)), len);
483 pss1 = lws_wsi_user(lws_get_parent(wsi));
484 pss1->reason_bf |= 2;
485 lws_callback_on_writable(lws_get_parent(wsi));
487 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
488 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
489 assert(lws_get_parent(wsi));
490 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
491 len, LWS_WRITE_HTTP);
495 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
496 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
497 assert(lws_get_parent(wsi));
498 if (!lws_get_parent(wsi))
500 pss1 = lws_wsi_user(lws_get_parent(wsi));
501 pss1->client_finished = 1;
506 /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
508 * - POST data goes on subprocess stdin
509 * - subprocess stdout goes on http via writeable callback
510 * - subprocess stderr goes to the logs
512 case LWS_CALLBACK_CGI:
513 pss->args = *((struct lws_cgi_args *)in);
514 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
515 switch (pss->args.ch) { /* which of stdin/out/err ? */
517 /* TBD stdin rx flow control */
521 /* when writing to MASTER would not block */
522 lws_callback_on_writable(wsi);
525 n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
527 //lwsl_notice("stderr reads %d\n", n);
529 if (buf[n - 1] != '\n')
532 lwsl_notice("CGI-stderr: %s\n", buf);
538 case LWS_CALLBACK_CGI_TERMINATED:
539 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
540 /* because we sent on openended http, close the connection */
543 case LWS_CALLBACK_CGI_STDIN_DATA: /* POST body for stdin */
544 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
545 pss->args = *((struct lws_cgi_args *)in);
546 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
547 pss->args.data, pss->args.len);
548 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
549 if (n < pss->args.len)
550 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
556 * callbacks for managing the external poll() array appear in
557 * protocol 0 callback
560 case LWS_CALLBACK_LOCK_POLL:
562 * lock mutex to protect pollfd state
563 * called before any other POLL related callback
564 * if protecting wsi lifecycle change, len == 1
566 test_server_lock(len);
569 case LWS_CALLBACK_UNLOCK_POLL:
571 * unlock mutex to protect pollfd state when
572 * called after any other POLL related callback
573 * if protecting wsi lifecycle change, len == 1
575 test_server_unlock(len);
579 case LWS_CALLBACK_ADD_POLL_FD:
581 if (count_pollfds >= max_poll_elements) {
582 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
586 fd_lookup[pa->fd] = count_pollfds;
587 pollfds[count_pollfds].fd = pa->fd;
588 pollfds[count_pollfds].events = pa->events;
589 pollfds[count_pollfds++].revents = 0;
592 case LWS_CALLBACK_DEL_POLL_FD:
593 if (!--count_pollfds)
595 m = fd_lookup[pa->fd];
596 /* have the last guy take up the vacant slot */
597 pollfds[m] = pollfds[count_pollfds];
598 fd_lookup[pollfds[count_pollfds].fd] = m;
601 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
602 pollfds[fd_lookup[pa->fd]].events = pa->events;
606 case LWS_CALLBACK_GET_THREAD_ID:
608 * if you will call "lws_callback_on_writable"
609 * from a different thread, return the caller thread ID
610 * here so lws can use this information to work out if it
611 * should signal the poll() loop to exit and restart early
614 /* return pthread_getthreadid_np(); */
624 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
626 if (lws_http_transaction_completed(wsi))