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);
156 if (!strncmp(in, "/cgitest", 8)) {
157 static char *cmd[] = {
160 INSTALL_DATADIR"/libwebsockets-test-server/lws-cgi-test.sh",
161 // "/var/www/cgi-bin/cgit",
165 lwsl_notice("%s: cgitest\n", __func__);
166 n = lws_cgi(wsi, cmd, 8, 5);
168 lwsl_err("%s: cgi failed\n");
171 p = buffer + LWS_PRE;
172 end = p + sizeof(buffer) - LWS_PRE;
174 if (lws_add_http_header_status(wsi, 200, &p, end))
176 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
177 (unsigned char *)"close", 5, &p, end))
179 n = lws_write(wsi, buffer + LWS_PRE,
180 p - (buffer + LWS_PRE),
181 LWS_WRITE_HTTP_HEADERS);
183 /* the cgi starts by outputting headers, we can't
184 * finalize the headers until we see the end of that
191 /* if a legal POST URL, let it continue and accept data */
192 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
195 /* check for the "send a big file by hand" example case */
196 lwsl_notice("%s\n", in);
197 if (!strcmp((const char *)in, "/leaf.jpg")) {
198 if (strlen(resource_path) > sizeof(leaf_path) - 10)
200 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
202 /* well, let's demonstrate how to send the hard way */
204 p = buffer + LWS_PRE;
205 end = p + sizeof(buffer) - LWS_PRE;
207 pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
210 if (pss->fd == LWS_INVALID_FILE) {
211 lwsl_err("faild to open file %s\n", leaf_path);
216 * we will send a big jpeg file, but it could be
217 * anything. Set the Content-Type: appropriately
218 * so the browser knows what to do with it.
220 * Notice we use the APIs to build the header, which
221 * will do the right thing for HTTP 1/1.1 and HTTP2
222 * depending on what connection it happens to be working
225 if (lws_add_http_header_status(wsi, 200, &p, end))
227 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
228 (unsigned char *)"libwebsockets",
231 if (lws_add_http_header_by_token(wsi,
232 WSI_TOKEN_HTTP_CONTENT_TYPE,
233 (unsigned char *)"image/jpeg",
236 if (lws_add_http_header_content_length(wsi,
240 if (lws_finalize_http_header(wsi, &p, end))
244 * send the http headers...
245 * this won't block since it's the first payload sent
246 * on the connection since it was established
247 * (too small for partial)
249 * Notice they are sent using LWS_WRITE_HTTP_HEADERS
250 * which also means you can't send body too in one step,
251 * this is mandated by changes in HTTP2
255 lwsl_info("%s\n", buffer + LWS_PRE);
257 n = lws_write(wsi, buffer + LWS_PRE,
258 p - (buffer + LWS_PRE),
259 LWS_WRITE_HTTP_HEADERS);
261 lws_plat_file_close(wsi, pss->fd);
265 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
267 lws_callback_on_writable(wsi);
271 /* if not, send a file the easy way */
272 if (!strncmp(in, "/cgit-data/", 11)) {
273 in = (char *)in + 11;
274 strcpy(buf, "/usr/share/cgit");
276 strcpy(buf, resource_path);
278 if (strcmp(in, "/")) {
279 if (*((const char *)in) != '/')
281 strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
282 } else /* default file to serve */
283 strcat(buf, "/test.html");
284 buf[sizeof(buf) - 1] = '\0';
286 /* refuse to serve files we don't understand */
287 mimetype = get_mimetype(buf);
289 lwsl_err("Unknown mimetype for %s\n", buf);
290 lws_return_http_status(wsi,
291 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
295 /* demonstrates how to set a cookie on / */
297 other_headers = leaf_path;
298 p = (unsigned char *)leaf_path;
299 if (!strcmp((const char *)in, "/") &&
300 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
301 /* this isn't very unguessable but it'll do for us */
302 gettimeofday(&tv, NULL);
303 n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
304 (unsigned int)tv.tv_sec,
305 (unsigned int)tv.tv_usec);
307 if (lws_add_http_header_by_name(wsi,
308 (unsigned char *)"set-cookie:",
309 (unsigned char *)b64, n, &p,
310 (unsigned char *)leaf_path + sizeof(leaf_path)))
313 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
315 "Strict-Transport-Security:",
317 "max-age=15768000 ; "
318 "includeSubDomains", 36, &p,
319 (unsigned char *)leaf_path +
322 n = (char *)p - leaf_path;
324 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
325 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
326 return -1; /* error or can't reuse connection: close the socket */
329 * notice that the sending of the file completes asynchronously,
330 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
335 case LWS_CALLBACK_HTTP_BODY:
336 strncpy(buf, in, 20);
341 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
342 (const char *)buf, (int)len);
346 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
347 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
348 /* the whole of the sent body arrived, close or reuse the connection */
349 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
352 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
355 case LWS_CALLBACK_HTTP_WRITEABLE:
356 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
358 if (pss->client_finished)
361 if (pss->fd == LWS_INVALID_FILE)
364 if (pss->reason_bf & 1) {
365 if (lws_cgi_write_split_stdout_headers(wsi) < 0)
368 pss->reason_bf &= ~1;
372 #ifndef LWS_NO_CLIENT
373 if (pss->reason_bf & 2) {
374 char *px = buf + LWS_PRE;
375 int lenx = sizeof(buf) - LWS_PRE;
377 * our sink is writeable and our source has something
378 * to read. So read a lump of source material of
379 * suitable size to send or what's available, whichever
382 pss->reason_bf &= ~2;
383 wsi1 = lws_get_child(wsi);
386 if (lws_http_client_read(wsi1, &px, &lenx) < 0)
389 if (pss->client_finished)
395 * we can send more of whatever it is we were sending
399 /* we'd like the send this much */
400 n = sizeof(buffer) - LWS_PRE;
402 /* but if the peer told us he wants less, we can adapt */
403 m = lws_get_peer_write_allowance(wsi);
405 /* -1 means not using a protocol that has this info */
407 /* right now, peer can't handle anything */
410 if (m != -1 && m < n)
411 /* he couldn't handle that much */
414 n = lws_plat_file_read(wsi, pss->fd,
415 &amount, buffer + LWS_PRE, n);
416 /* problem reading, close conn */
418 lwsl_err("problem reading file\n");
422 /* sent it all, close conn */
426 * To support HTTP2, must take care about preamble space
428 * identification of when we send the last payload frame
429 * is handled by the library itself if you sent a
430 * content-length header
432 m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
434 lwsl_err("write failed\n");
435 /* write failed, close conn */
438 if (m) /* while still active, extend timeout */
439 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
442 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
444 lws_callback_on_writable(wsi);
447 lws_plat_file_close(wsi, pss->fd);
448 pss->fd = LWS_INVALID_FILE;
452 lws_plat_file_close(wsi, pss->fd);
457 * callback for confirming to continue with client IP appear in
458 * protocol 0 callback since no websocket protocol has been agreed
459 * yet. You can just ignore this if you won't filter on client IP
460 * since the default unhandled callback return is 0 meaning let the
461 * connection continue.
463 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
464 /* if we returned non-zero from here, we kill the connection */
467 #ifndef LWS_NO_CLIENT
468 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
469 char ctype[64], ctlen = 0;
470 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
471 p = buffer + LWS_PRE;
472 end = p + sizeof(buffer) - LWS_PRE;
473 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
475 if (lws_add_http_header_by_token(lws_get_parent(wsi),
476 WSI_TOKEN_HTTP_SERVER,
477 (unsigned char *)"libwebsockets",
481 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
483 if (lws_add_http_header_by_token(lws_get_parent(wsi),
484 WSI_TOKEN_HTTP_CONTENT_TYPE,
485 (unsigned char *)ctype, ctlen, &p, end))
489 if (lws_add_http_header_content_length(lws_get_parent(wsi),
493 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
497 lwsl_info("%s\n", buffer + LWS_PRE);
499 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
500 p - (buffer + LWS_PRE),
501 LWS_WRITE_HTTP_HEADERS);
506 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
507 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
510 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
511 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
512 assert(lws_get_parent(wsi));
513 if (!lws_get_parent(wsi))
515 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d, len %d\n",
516 // wsi, lws_get_socket_fd(wsi),
517 // lws_get_parent(wsi),
518 // lws_get_socket_fd(lws_get_parent(wsi)), len);
519 pss1 = lws_wsi_user(lws_get_parent(wsi));
520 pss1->reason_bf |= 2;
521 lws_callback_on_writable(lws_get_parent(wsi));
523 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
524 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
525 assert(lws_get_parent(wsi));
526 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
527 len, LWS_WRITE_HTTP);
531 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
532 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
533 assert(lws_get_parent(wsi));
534 if (!lws_get_parent(wsi))
536 pss1 = lws_wsi_user(lws_get_parent(wsi));
537 pss1->client_finished = 1;
542 /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
544 * - POST data goes on subprocess stdin
545 * - subprocess stdout goes on http via writeable callback
546 * - subprocess stderr goes to the logs
548 case LWS_CALLBACK_CGI:
549 pss->args = *((struct lws_cgi_args *)in);
550 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
551 switch (pss->args.ch) { /* which of stdin/out/err ? */
553 /* TBD stdin rx flow control */
557 /* when writing to MASTER would not block */
558 lws_callback_on_writable(wsi);
561 n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
563 //lwsl_notice("stderr reads %d\n", n);
565 if (buf[n - 1] != '\n')
568 lwsl_notice("CGI-stderr: %s\n", buf);
574 case LWS_CALLBACK_CGI_TERMINATED:
575 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
576 /* because we sent on openended http, close the connection */
579 case LWS_CALLBACK_CGI_STDIN_DATA: /* POST body for stdin */
580 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
581 pss->args = *((struct lws_cgi_args *)in);
582 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
583 pss->args.data, pss->args.len);
584 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
585 if (n < pss->args.len)
586 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
592 * callbacks for managing the external poll() array appear in
593 * protocol 0 callback
596 case LWS_CALLBACK_LOCK_POLL:
598 * lock mutex to protect pollfd state
599 * called before any other POLL related callback
600 * if protecting wsi lifecycle change, len == 1
602 test_server_lock(len);
605 case LWS_CALLBACK_UNLOCK_POLL:
607 * unlock mutex to protect pollfd state when
608 * called after any other POLL related callback
609 * if protecting wsi lifecycle change, len == 1
611 test_server_unlock(len);
615 case LWS_CALLBACK_ADD_POLL_FD:
617 if (count_pollfds >= max_poll_elements) {
618 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
622 fd_lookup[pa->fd] = count_pollfds;
623 pollfds[count_pollfds].fd = pa->fd;
624 pollfds[count_pollfds].events = pa->events;
625 pollfds[count_pollfds++].revents = 0;
628 case LWS_CALLBACK_DEL_POLL_FD:
629 if (!--count_pollfds)
631 m = fd_lookup[pa->fd];
632 /* have the last guy take up the vacant slot */
633 pollfds[m] = pollfds[count_pollfds];
634 fd_lookup[pollfds[count_pollfds].fd] = m;
637 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
638 pollfds[fd_lookup[pa->fd]].events = pa->events;
642 case LWS_CALLBACK_GET_THREAD_ID:
644 * if you will call "lws_callback_on_writable"
645 * from a different thread, return the caller thread ID
646 * here so lws can use this information to work out if it
647 * should signal the poll() loop to exit and restart early
650 /* return pthread_getthreadid_np(); */
660 /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
662 if (lws_http_transaction_completed(wsi))