2 * libwebsockets - small server side websockets and web server 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,
22 #include "private-libwebsockets.h"
25 lws_0405_frame_mask_generate(struct lws *wsi)
28 wsi->u.ws.mask[0] = 0;
29 wsi->u.ws.mask[1] = 0;
30 wsi->u.ws.mask[2] = 0;
31 wsi->u.ws.mask[3] = 0;
34 /* fetch the per-frame nonce */
36 n = lws_get_random(lws_get_context(wsi), wsi->u.ws.mask, 4);
38 lwsl_parser("Unable to read from random device %s %d\n",
39 SYSTEM_RANDOM_FILEPATH, n);
43 /* start masking from first byte of masking key buffer */
44 wsi->u.ws.mask_idx = 0;
51 LWS_VISIBLE void lwsl_hexdump(void *vbuf, size_t len)
53 unsigned char *buf = (unsigned char *)vbuf;
54 unsigned int n, m, start;
60 for (n = 0; n < len;) {
64 p += sprintf(p, "%04X: ", start);
66 for (m = 0; m < 16 && n < len; m++)
67 p += sprintf(p, "%02X ", buf[n++]);
73 for (m = 0; m < 16 && (start + m) < len; m++) {
74 if (buf[start + m] >= ' ' && buf[start + m] < 127)
75 *p++ = buf[start + m];
84 lwsl_debug("%s", line);
92 * notice this returns number of bytes consumed, or -1
95 int lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len)
97 struct lws_context *context = lws_get_context(wsi);
98 size_t real_len = len;
104 /* just ignore sends after we cleared the truncation buffer */
105 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
109 if (wsi->trunc_len && (buf < wsi->trunc_alloc ||
110 buf > (wsi->trunc_alloc + wsi->trunc_len + wsi->trunc_offset))) {
112 strncpy(dump, (char *)buf, sizeof(dump) - 1);
113 dump[sizeof(dump) - 1] = '\0';
114 #if defined(LWS_WITH_ESP8266)
115 lwsl_err("****** %p: Sending new %lu (%s), pending truncated ...\n",
116 wsi, (unsigned long)len, dump);
118 lwsl_err("****** %p: Sending new %lu (%s), pending truncated ...\n"
119 " It's illegal to do an lws_write outside of\n"
120 " the writable callback: fix your code",
121 wsi, (unsigned long)len, dump);
128 m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_DO_SEND, &buf, len);
131 if (m) /* handled */ {
133 goto handle_truncated_send;
136 if (!lws_socket_is_valid(wsi->desc.sockfd))
137 lwsl_warn("** error invalid sock but expected to send\n");
140 if (wsi->protocol->tx_packet_size)
141 n = wsi->protocol->tx_packet_size;
143 n = wsi->protocol->rx_buffer_size;
145 n = context->pt_serv_buf_size;
150 #if defined(LWS_WITH_ESP8266)
151 if (wsi->pending_send_completion) {
153 goto handle_truncated_send;
157 /* nope, send it on the socket directly */
158 lws_latency_pre(context, wsi);
159 n = lws_ssl_capable_write(wsi, buf, n);
160 lws_latency(context, wsi, "send lws_issue_raw", n, n == len);
162 //lwsl_notice("lws_ssl_capable_write: %d\n", n);
165 case LWS_SSL_CAPABLE_ERROR:
166 /* we're going to close, let close know sends aren't possible */
167 wsi->socket_is_permanently_unusable = 1;
169 case LWS_SSL_CAPABLE_MORE_SERVICE:
170 /* nothing got sent, not fatal, retry the whole thing later */
175 handle_truncated_send:
177 * we were already handling a truncated send?
179 if (wsi->trunc_len) {
180 lwsl_info("%p partial adv %d (vs %ld)\n", wsi, n, (long)real_len);
181 wsi->trunc_offset += n;
184 if (!wsi->trunc_len) {
185 lwsl_info("***** %p partial send completed\n", wsi);
186 /* done with it, but don't free it */
188 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
189 lwsl_info("***** %p signalling to close now\n", wsi);
190 return -1; /* retry closing now */
193 /* always callback on writeable */
194 lws_callback_on_writable(wsi);
199 if ((unsigned int)n == real_len)
200 /* what we just sent went out cleanly */
204 * Newly truncated send. Buffer the remainder (it will get
205 * first priority next time the socket is writable)
207 lwsl_debug("%p new partial sent %d from %lu total\n", wsi, n,
208 (unsigned long)real_len);
211 * - if we still have a suitable malloc lying around, use it
212 * - or, if too small, reallocate it
213 * - or, if no buffer, create it
215 if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {
216 lws_free(wsi->trunc_alloc);
218 wsi->trunc_alloc_len = real_len - n;
219 wsi->trunc_alloc = lws_malloc(real_len - n);
220 if (!wsi->trunc_alloc) {
221 lwsl_err("truncated send: unable to malloc %lu\n",
222 (unsigned long)(real_len - n));
226 wsi->trunc_offset = 0;
227 wsi->trunc_len = real_len - n;
228 memcpy(wsi->trunc_alloc, buf + n, real_len - n);
230 /* since something buffered, force it to get another chance to send */
231 lws_callback_on_writable(wsi);
236 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len,
237 enum lws_write_protocol wp)
239 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
240 int masked7 = (wsi->mode == LWSCM_WS_CLIENT);
241 unsigned char is_masked_bit = 0;
242 unsigned char *dropmask = NULL;
243 struct lws_tokens eff_buf;
245 size_t orig_len = len;
248 lwsl_err("%s: suspicious len int %d, ulong %lu\n", __func__,
249 (int)len, (unsigned long)len);
253 #ifdef LWS_WITH_ACCESS_LOG
254 wsi->access_log.sent += len;
257 wsi->vhost->conn_stats.tx += len;
259 if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) {
260 /* remove us from the list */
261 struct lws **w = &pt->tx_draining_ext_list;
262 lwsl_debug("%s: TX EXT DRAINING: Remove from list\n", __func__);
263 wsi->u.ws.tx_draining_ext = 0;
264 /* remove us from context draining ext list */
267 *w = wsi->u.ws.tx_draining_ext_list;
270 w = &((*w)->u.ws.tx_draining_ext_list);
272 wsi->u.ws.tx_draining_ext_list = NULL;
273 wp = (wsi->u.ws.tx_draining_stashed_wp & 0xc0) |
274 LWS_WRITE_CONTINUATION;
276 lwsl_ext("FORCED draining wp to 0x%02X\n", wp);
279 lws_restart_ws_ping_pong_timer(wsi);
281 if (wp == LWS_WRITE_HTTP ||
282 wp == LWS_WRITE_HTTP_FINAL ||
283 wp == LWS_WRITE_HTTP_HEADERS)
286 /* if not in a state to send stuff, then just send nothing */
288 if (wsi->state != LWSS_ESTABLISHED &&
289 ((wsi->state != LWSS_RETURNED_CLOSE_ALREADY &&
290 wsi->state != LWSS_AWAITING_CLOSE_ACK) ||
291 wp != LWS_WRITE_CLOSE))
294 /* if we are continuing a frame that already had its header done */
296 if (wsi->u.ws.inside_frame) {
297 lwsl_debug("INSIDE FRAME\n");
298 goto do_more_inside_frame;
301 wsi->u.ws.clean_buffer = 1;
304 * give a chance to the extensions to modify payload
305 * the extension may decide to produce unlimited payload erratically
306 * (eg, compression extension), so we require only that if he produces
307 * something, it will be a complete fragment of the length known at
308 * the time (just the fragment length known), and if he has
309 * more we will come back next time he is writeable and allow him to
310 * produce more fragments until he's drained.
312 * This allows what is sent each time it is writeable to be limited to
313 * a size that can be sent without partial sends or blocking, allows
314 * interleaving of control frames and other connection service.
316 eff_buf.token = (char *)buf;
317 eff_buf.token_len = len;
322 case LWS_WRITE_CLOSE:
325 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &eff_buf, wp);
329 if (n && eff_buf.token_len) {
330 /* extension requires further draining */
331 wsi->u.ws.tx_draining_ext = 1;
332 wsi->u.ws.tx_draining_ext_list = pt->tx_draining_ext_list;
333 pt->tx_draining_ext_list = wsi;
334 /* we must come back to do more */
335 lws_callback_on_writable(wsi);
337 * keep a copy of the write type for the overall
338 * action that has provoked generation of these
339 * fragments, so the last guy can use its FIN state.
341 wsi->u.ws.tx_draining_stashed_wp = wp;
342 /* this is definitely not actually the last fragment
343 * because the extension asserted he has more coming
344 * So make sure this intermediate one doesn't go out
347 wp |= LWS_WRITE_NO_FIN;
350 if (eff_buf.token_len && wsi->u.ws.stashed_write_pending) {
351 wsi->u.ws.stashed_write_pending = 0;
352 wp = (wp &0xc0) | (int)wsi->u.ws.stashed_write_type;
357 * an extension did something we need to keep... for example, if
358 * compression extension, it has already updated its state according
359 * to this being issued
361 if ((char *)buf != eff_buf.token) {
363 * ext might eat it, but no have anything to issue yet
364 * in that case we have to follow his lead, but stash and
365 * replace the write type that was lost here the first time.
367 if (len && !eff_buf.token_len) {
368 if (!wsi->u.ws.stashed_write_pending)
369 wsi->u.ws.stashed_write_type = (char)wp & 0x3f;
370 wsi->u.ws.stashed_write_pending = 1;
374 * extension recreated it:
375 * need to buffer this if not all sent
377 wsi->u.ws.clean_buffer = 0;
380 buf = (unsigned char *)eff_buf.token;
381 len = eff_buf.token_len;
383 switch (wsi->ietf_spec_revision) {
387 dropmask = &buf[0 - pre];
388 is_masked_bit = 0x80;
393 n = LWSWSOPC_TEXT_FRAME;
395 case LWS_WRITE_BINARY:
396 n = LWSWSOPC_BINARY_FRAME;
398 case LWS_WRITE_CONTINUATION:
399 n = LWSWSOPC_CONTINUATION;
402 case LWS_WRITE_CLOSE:
412 lwsl_warn("lws_write: unknown write opc / wp\n");
416 if (!(wp & LWS_WRITE_NO_FIN))
422 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
427 buf[-pre + 1] = 126 | is_masked_bit;
428 buf[-pre + 2] = (unsigned char)(len >> 8);
429 buf[-pre + 3] = (unsigned char)len;
433 buf[-pre + 1] = 127 | is_masked_bit;
435 buf[-pre + 2] = (len >> 56) & 0x7f;
436 buf[-pre + 3] = len >> 48;
437 buf[-pre + 4] = len >> 40;
438 buf[-pre + 5] = len >> 32;
445 buf[-pre + 6] = (unsigned char)(len >> 24);
446 buf[-pre + 7] = (unsigned char)(len >> 16);
447 buf[-pre + 8] = (unsigned char)(len >> 8);
448 buf[-pre + 9] = (unsigned char)len;
454 do_more_inside_frame:
457 * Deal with masking if we are in client -> server direction and
462 if (!wsi->u.ws.inside_frame)
463 if (lws_0405_frame_mask_generate(wsi)) {
464 lwsl_err("frame mask generation failed\n");
469 * in v7, just mask the payload
471 if (dropmask) { /* never set if already inside frame */
472 for (n = 4; n < (int)len + 4; n++)
473 dropmask[n] = dropmask[n] ^ wsi->u.ws.mask[
474 (wsi->u.ws.mask_idx++) & 3];
476 /* copy the frame nonce into place */
477 memcpy(dropmask, wsi->u.ws.mask, 4);
483 case LWS_WRITE_CLOSE:
484 /* lwsl_hexdump(&buf[-pre], len); */
486 case LWS_WRITE_HTTP_FINAL:
487 case LWS_WRITE_HTTP_HEADERS:
491 if (wsi->mode == LWSCM_HTTP2_SERVING) {
492 unsigned char flags = 0;
494 n = LWS_HTTP2_FRAME_TYPE_DATA;
495 if (wp == LWS_WRITE_HTTP_HEADERS) {
496 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
497 flags = LWS_HTTP2_FLAG_END_HEADERS;
498 if (wsi->u.http2.send_END_STREAM)
499 flags |= LWS_HTTP2_FLAG_END_STREAM;
502 if ((wp == LWS_WRITE_HTTP ||
503 wp == LWS_WRITE_HTTP_FINAL) &&
504 wsi->u.http.content_length) {
505 wsi->u.http.content_remain -= len;
506 lwsl_info("%s: content_remain = %lu\n", __func__,
507 (unsigned long)wsi->u.http.content_remain);
508 if (!wsi->u.http.content_remain) {
509 lwsl_info("%s: selecting final write mode\n", __func__);
510 wp = LWS_WRITE_HTTP_FINAL;
514 if (wp == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
515 lwsl_info("%s: setting END_STREAM\n", __func__);
516 flags |= LWS_HTTP2_FLAG_END_STREAM;
519 return lws_http2_frame_write(wsi, n, flags,
520 wsi->u.http2.my_stream_id, len, buf);
523 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
529 * give any active extensions a chance to munge the buffer
530 * before send. We pass in a pointer to an lws_tokens struct
531 * prepared with the default buffer and content length that's in
532 * there. Rather than rewrite the default buffer, extensions
533 * that expect to grow the buffer can adapt .token to
534 * point to their own per-connection buffer in the extension
535 * user allocation. By default with no extensions or no
536 * extension callback handling, just the normal input buffer is
537 * used then so it is efficient.
539 * callback returns 1 in case it wants to spill more buffers
541 * This takes care of holding the buffer if send is incomplete, ie,
542 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
543 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
544 * return to the user code how much OF THE USER BUFFER was consumed.
547 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
548 wsi->u.ws.inside_frame = 1;
552 if (n == (int)len + pre) {
553 /* everything in the buffer was handled (or rebuffered...) */
554 wsi->u.ws.inside_frame = 0;
559 * it is how many bytes of user buffer got sent... may be < orig_len
560 * in which case callback when writable has already been arranged
561 * and user code can call lws_write() again with the rest
568 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)
570 struct lws_context *context = wsi->context;
571 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
572 struct lws_process_html_args args;
573 lws_filepos_t amount, poss;
575 #if defined(LWS_WITH_RANGES)
576 unsigned char finished = 0;
580 // lwsl_notice("%s (trunc len %d)\n", __func__, wsi->trunc_len);
582 while (wsi->http2_substream || !lws_send_pipe_choked(wsi)) {
584 if (wsi->trunc_len) {
585 if (lws_issue_raw(wsi, wsi->trunc_alloc +
587 wsi->trunc_len) < 0) {
588 lwsl_info("%s: closing\n", __func__);
594 if (wsi->u.http.filepos == wsi->u.http.filelen)
601 #if defined(LWS_WITH_RANGES)
602 if (wsi->u.http.range.count_ranges && !wsi->u.http.range.inside) {
604 lwsl_notice("%s: doing range start %llu\n", __func__, wsi->u.http.range.start);
606 if ((long)lws_vfs_file_seek_cur(wsi->u.http.fop_fd,
607 wsi->u.http.range.start -
608 wsi->u.http.filepos) < 0)
611 wsi->u.http.filepos = wsi->u.http.range.start;
613 if (wsi->u.http.range.count_ranges > 1) {
614 n = lws_snprintf((char *)p, context->pt_serv_buf_size,
616 "Content-Type: %s\x0d\x0a"
617 "Content-Range: bytes %llu-%llu/%llu\x0d\x0a"
619 wsi->u.http.multipart_content_type,
620 wsi->u.http.range.start,
621 wsi->u.http.range.end,
622 wsi->u.http.range.extent);
626 wsi->u.http.range.budget = wsi->u.http.range.end -
627 wsi->u.http.range.start + 1;
628 wsi->u.http.range.inside = 1;
632 poss = context->pt_serv_buf_size - n;
635 * if there is a hint about how much we will do well to send at one time,
636 * restrict ourselves to only trying to send that.
638 if (wsi->protocol->tx_packet_size && poss > wsi->protocol->tx_packet_size)
639 poss = wsi->protocol->tx_packet_size;
641 #if defined(LWS_WITH_RANGES)
642 if (wsi->u.http.range.count_ranges) {
643 if (wsi->u.http.range.count_ranges > 1)
644 poss -= 7; /* allow for final boundary */
645 if (poss > wsi->u.http.range.budget)
646 poss = wsi->u.http.range.budget;
649 if (wsi->sending_chunked) {
650 /* we need to drop the chunk size in here */
652 /* allow for the chunk to grow by 128 in translation */
656 if (lws_vfs_file_read(wsi->u.http.fop_fd, &amount, p, poss) < 0)
657 goto file_had_it; /* caller will close */
659 //lwsl_notice("amount %ld\n", amount);
661 if (wsi->sending_chunked)
664 n = (p - pt->serv_buf) + (int)amount;
666 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
667 context->timeout_secs);
669 if (wsi->sending_chunked) {
672 args.max_len = poss + 128;
673 args.final = wsi->u.http.filepos + n ==
675 if (user_callback_handle_rxflow(
676 wsi->vhost->protocols[(int)wsi->protocol_interpret_idx].callback, wsi,
677 LWS_CALLBACK_PROCESS_HTML,
678 wsi->user_space, &args, 0) < 0)
681 p = (unsigned char *)args.p;
685 #if defined(LWS_WITH_RANGES)
686 if (wsi->u.http.range.send_ctr + 1 ==
687 wsi->u.http.range.count_ranges && // last range
688 wsi->u.http.range.count_ranges > 1 && // was 2+ ranges (ie, multipart)
689 wsi->u.http.range.budget - amount == 0) {// final part
690 n += lws_snprintf((char *)pt->serv_buf + n, 6,
691 "_lws\x0d\x0a"); // append trailing boundary
692 lwsl_debug("added trailing boundary\n");
695 m = lws_write(wsi, p, n,
696 wsi->u.http.filepos == wsi->u.http.filelen ?
697 LWS_WRITE_HTTP_FINAL :
703 wsi->u.http.filepos += amount;
705 #if defined(LWS_WITH_RANGES)
706 if (wsi->u.http.range.count_ranges >= 1) {
707 wsi->u.http.range.budget -= amount;
708 if (wsi->u.http.range.budget == 0) {
709 lwsl_notice("range budget exhausted\n");
710 wsi->u.http.range.inside = 0;
711 wsi->u.http.range.send_ctr++;
713 if (lws_ranges_next(&wsi->u.http.range) < 1) {
722 /* adjust for what was not sent */
723 if (lws_vfs_file_seek_cur(wsi->u.http.fop_fd,
730 if ((!wsi->trunc_len && wsi->u.http.filepos == wsi->u.http.filelen)
731 #if defined(LWS_WITH_RANGES)
737 wsi->state = LWSS_HTTP;
738 /* we might be in keepalive, so close it off here */
739 lws_vfs_file_close(&wsi->u.http.fop_fd);
741 lwsl_debug("file completed\n");
743 if (wsi->protocol->callback)
744 /* ignore callback returned value */
745 if (user_callback_handle_rxflow(
746 wsi->protocol->callback, wsi,
747 LWS_CALLBACK_HTTP_FILE_COMPLETION,
748 wsi->user_space, NULL, 0) < 0)
751 return 1; /* >0 indicates completed */
755 lws_callback_on_writable(wsi);
757 return 0; /* indicates further processing must be done */
760 lws_vfs_file_close(&wsi->u.http.fop_fd);
767 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
771 n = recv(wsi->desc.sockfd, (char *)buf, len, 0);
774 wsi->vhost->conn_stats.rx += n;
775 lws_restart_ws_ping_pong_timer(wsi);
779 if (LWS_ERRNO == LWS_EAGAIN ||
780 LWS_ERRNO == LWS_EWOULDBLOCK ||
781 LWS_ERRNO == LWS_EINTR)
782 return LWS_SSL_CAPABLE_MORE_SERVICE;
784 lwsl_notice("error on reading from skt : %d\n", LWS_ERRNO);
785 return LWS_SSL_CAPABLE_ERROR;
789 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
794 n = send(wsi->desc.sockfd, (char *)buf, len, MSG_NOSIGNAL);
795 // lwsl_info("%s: sent len %d result %d", __func__, len, n);
799 if (LWS_ERRNO == LWS_EAGAIN ||
800 LWS_ERRNO == LWS_EWOULDBLOCK ||
801 LWS_ERRNO == LWS_EINTR) {
802 if (LWS_ERRNO == LWS_EWOULDBLOCK) {
803 lws_set_blocking_send(wsi);
806 return LWS_SSL_CAPABLE_MORE_SERVICE;
816 lwsl_debug("ERROR writing len %d to skt fd %d err %d / errno %d\n", len, wsi->desc.sockfd, n, LWS_ERRNO);
817 return LWS_SSL_CAPABLE_ERROR;
821 lws_ssl_pending_no_ssl(struct lws *wsi)
824 #if defined(LWS_WITH_ESP32)