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 +
111 wsi->trunc_offset))) {
112 lwsl_err("****** %x Sending new, pending truncated ...\n", wsi);
118 m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_DO_SEND, &buf, len);
121 if (m) /* handled */ {
123 goto handle_truncated_send;
126 if (!lws_socket_is_valid(wsi->sock))
127 lwsl_warn("** error invalid sock but expected to send\n");
130 n = wsi->protocol->rx_buffer_size;
132 n = LWS_MAX_SOCKET_IO_BUF;
136 /* nope, send it on the socket directly */
137 lws_latency_pre(context, wsi);
138 n = lws_ssl_capable_write(wsi, buf, n);
139 lws_latency(context, wsi, "send lws_issue_raw", n, n == len);
142 case LWS_SSL_CAPABLE_ERROR:
143 /* we're going to close, let close know sends aren't possible */
144 wsi->socket_is_permanently_unusable = 1;
146 case LWS_SSL_CAPABLE_MORE_SERVICE:
147 /* nothing got sent, not fatal, retry the whole thing later */
152 handle_truncated_send:
154 * we were already handling a truncated send?
156 if (wsi->trunc_len) {
157 lwsl_info("%p partial adv %d (vs %d)\n", wsi, n, real_len);
158 wsi->trunc_offset += n;
161 if (!wsi->trunc_len) {
162 lwsl_info("***** %x partial send completed\n", wsi);
163 /* done with it, but don't free it */
165 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
166 lwsl_info("***** %x signalling to close now\n", wsi);
167 return -1; /* retry closing now */
170 /* always callback on writeable */
171 lws_callback_on_writable(wsi);
176 if ((unsigned int)n == real_len)
177 /* what we just sent went out cleanly */
181 * Newly truncated send. Buffer the remainder (it will get
182 * first priority next time the socket is writable)
184 lwsl_info("%p new partial sent %d from %d total\n", wsi, n, real_len);
187 * - if we still have a suitable malloc lying around, use it
188 * - or, if too small, reallocate it
189 * - or, if no buffer, create it
191 if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {
192 lws_free(wsi->trunc_alloc);
194 wsi->trunc_alloc_len = real_len - n;
195 wsi->trunc_alloc = lws_malloc(real_len - n);
196 if (!wsi->trunc_alloc) {
197 lwsl_err("truncated send: unable to malloc %d\n",
202 wsi->trunc_offset = 0;
203 wsi->trunc_len = real_len - n;
204 memcpy(wsi->trunc_alloc, buf + n, real_len - n);
206 /* since something buffered, force it to get another chance to send */
207 lws_callback_on_writable(wsi);
213 * lws_write() - Apply protocol then write data to client
214 * @wsi: Websocket instance (available from user callback)
215 * @buf: The data to send. For data being sent on a websocket
216 * connection (ie, not default http), this buffer MUST have
217 * LWS_PRE bytes valid BEFORE the pointer.
218 * This is so the protocol header data can be added in-situ.
219 * @len: Count of the data bytes in the payload starting from buf
220 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
221 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
222 * data on a websockets connection. Remember to allow the extra
223 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
226 * This function provides the way to issue data back to the client
227 * for both http and websocket protocols.
229 * In the case of sending using websocket protocol, be sure to allocate
230 * valid storage before and after buf as explained above. This scheme
231 * allows maximum efficiency of sending data and protocol in a single
232 * packet while not burdening the user code with any protocol knowledge.
234 * Return may be -1 for a fatal error needing connection close, or a
235 * positive number reflecting the amount of bytes actually sent. This
236 * can be less than the requested number of bytes due to OS memory
237 * pressure at any given time.
240 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len,
241 enum lws_write_protocol wp)
243 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
244 int masked7 = (wsi->mode == LWSCM_WS_CLIENT);
245 unsigned char is_masked_bit = 0;
246 unsigned char *dropmask = NULL;
247 struct lws_tokens eff_buf;
249 size_t orig_len = len;
251 if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) {
252 /* remove us from the list */
253 struct lws **w = &pt->tx_draining_ext_list;
254 lwsl_debug("%s: TX EXT DRAINING: Remove from list\n", __func__);
255 wsi->u.ws.tx_draining_ext = 0;
256 /* remove us from context draining ext list */
259 *w = wsi->u.ws.tx_draining_ext_list;
262 w = &((*w)->u.ws.tx_draining_ext_list);
264 wsi->u.ws.tx_draining_ext_list = NULL;
265 wp = (wsi->u.ws.tx_draining_stashed_wp & 0xc0) |
266 LWS_WRITE_CONTINUATION;
268 lwsl_ext("FORCED draining wp to 0x%02X\n", wp);
271 if (wp == LWS_WRITE_HTTP ||
272 wp == LWS_WRITE_HTTP_FINAL ||
273 wp == LWS_WRITE_HTTP_HEADERS)
276 /* if not in a state to send stuff, then just send nothing */
278 if (wsi->state != LWSS_ESTABLISHED &&
279 ((wsi->state != LWSS_RETURNED_CLOSE_ALREADY &&
280 wsi->state != LWSS_AWAITING_CLOSE_ACK) ||
281 wp != LWS_WRITE_CLOSE))
284 /* if we are continuing a frame that already had its header done */
286 if (wsi->u.ws.inside_frame) {
287 lwsl_debug("INSIDE FRAME\n");
288 goto do_more_inside_frame;
291 wsi->u.ws.clean_buffer = 1;
294 * give a chance to the extensions to modify payload
295 * the extension may decide to produce unlimited payload erratically
296 * (eg, compression extension), so we require only that if he produces
297 * something, it will be a complete fragment of the length known at
298 * the time (just the fragment length known), and if he has
299 * more we will come back next time he is writeable and allow him to
300 * produce more fragments until he's drained.
302 * This allows what is sent each time it is writeable to be limited to
303 * a size that can be sent without partial sends or blocking, allows
304 * interleaving of control frames and other connection service.
306 eff_buf.token = (char *)buf;
307 eff_buf.token_len = len;
312 case LWS_WRITE_CLOSE:
315 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &eff_buf, wp);
319 if (n && eff_buf.token_len) {
320 /* extension requires further draining */
321 wsi->u.ws.tx_draining_ext = 1;
322 wsi->u.ws.tx_draining_ext_list = pt->tx_draining_ext_list;
323 pt->tx_draining_ext_list = wsi;
324 /* we must come back to do more */
325 lws_callback_on_writable(wsi);
327 * keep a copy of the write type for the overall
328 * action that has provoked generation of these
329 * fragments, so the last guy can use its FIN state.
331 wsi->u.ws.tx_draining_stashed_wp = wp;
332 /* this is definitely not actually the last fragment
333 * because the extension asserted he has more coming
334 * So make sure this intermediate one doesn't go out
337 wp |= LWS_WRITE_NO_FIN;
340 if (eff_buf.token_len && wsi->u.ws.stashed_write_pending) {
341 wsi->u.ws.stashed_write_pending = 0;
342 wp = (wp &0xc0) | (int)wsi->u.ws.stashed_write_type;
347 * an extension did something we need to keep... for example, if
348 * compression extension, it has already updated its state according
349 * to this being issued
351 if ((char *)buf != eff_buf.token) {
353 * ext might eat it, but no have anything to issue yet
354 * in that case we have to follow his lead, but stash and
355 * replace the write type that was lost here the first time.
357 if (len && !eff_buf.token_len) {
358 if (!wsi->u.ws.stashed_write_pending)
359 wsi->u.ws.stashed_write_type = (char)wp & 0x3f;
360 wsi->u.ws.stashed_write_pending = 1;
364 * extension recreated it:
365 * need to buffer this if not all sent
367 wsi->u.ws.clean_buffer = 0;
370 buf = (unsigned char *)eff_buf.token;
371 len = eff_buf.token_len;
373 switch (wsi->ietf_spec_revision) {
377 dropmask = &buf[0 - pre];
378 is_masked_bit = 0x80;
383 n = LWSWSOPC_TEXT_FRAME;
385 case LWS_WRITE_BINARY:
386 n = LWSWSOPC_BINARY_FRAME;
388 case LWS_WRITE_CONTINUATION:
389 n = LWSWSOPC_CONTINUATION;
392 case LWS_WRITE_CLOSE:
402 lwsl_warn("lws_write: unknown write opc / wp\n");
406 if (!(wp & LWS_WRITE_NO_FIN))
412 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
417 buf[-pre + 1] = 126 | is_masked_bit;
418 buf[-pre + 2] = (unsigned char)(len >> 8);
419 buf[-pre + 3] = (unsigned char)len;
423 buf[-pre + 1] = 127 | is_masked_bit;
425 buf[-pre + 2] = (len >> 56) & 0x7f;
426 buf[-pre + 3] = len >> 48;
427 buf[-pre + 4] = len >> 40;
428 buf[-pre + 5] = len >> 32;
435 buf[-pre + 6] = (unsigned char)(len >> 24);
436 buf[-pre + 7] = (unsigned char)(len >> 16);
437 buf[-pre + 8] = (unsigned char)(len >> 8);
438 buf[-pre + 9] = (unsigned char)len;
444 do_more_inside_frame:
447 * Deal with masking if we are in client -> server direction and
452 if (!wsi->u.ws.inside_frame)
453 if (lws_0405_frame_mask_generate(wsi)) {
454 lwsl_err("frame mask generation failed\n");
459 * in v7, just mask the payload
461 if (dropmask) { /* never set if already inside frame */
462 for (n = 4; n < (int)len + 4; n++)
463 dropmask[n] = dropmask[n] ^ wsi->u.ws.mask[
464 (wsi->u.ws.mask_idx++) & 3];
466 /* copy the frame nonce into place */
467 memcpy(dropmask, wsi->u.ws.mask, 4);
473 case LWS_WRITE_CLOSE:
474 /* lwsl_hexdump(&buf[-pre], len); */
476 case LWS_WRITE_HTTP_FINAL:
477 case LWS_WRITE_HTTP_HEADERS:
481 if (wsi->mode == LWSCM_HTTP2_SERVING) {
482 unsigned char flags = 0;
484 n = LWS_HTTP2_FRAME_TYPE_DATA;
485 if (wp == LWS_WRITE_HTTP_HEADERS) {
486 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
487 flags = LWS_HTTP2_FLAG_END_HEADERS;
488 if (wsi->u.http2.send_END_STREAM)
489 flags |= LWS_HTTP2_FLAG_END_STREAM;
492 if ((wp == LWS_WRITE_HTTP ||
493 wp == LWS_WRITE_HTTP_FINAL) &&
494 wsi->u.http.content_length) {
495 wsi->u.http.content_remain -= len;
496 lwsl_info("%s: content_remain = %lu\n", __func__,
497 wsi->u.http.content_remain);
498 if (!wsi->u.http.content_remain) {
499 lwsl_info("%s: selecting final write mode\n", __func__);
500 wp = LWS_WRITE_HTTP_FINAL;
504 if (wp == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
505 lwsl_info("%s: setting END_STREAM\n", __func__);
506 flags |= LWS_HTTP2_FLAG_END_STREAM;
509 return lws_http2_frame_write(wsi, n, flags,
510 wsi->u.http2.my_stream_id, len, buf);
513 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
519 * give any active extensions a chance to munge the buffer
520 * before send. We pass in a pointer to an lws_tokens struct
521 * prepared with the default buffer and content length that's in
522 * there. Rather than rewrite the default buffer, extensions
523 * that expect to grow the buffer can adapt .token to
524 * point to their own per-connection buffer in the extension
525 * user allocation. By default with no extensions or no
526 * extension callback handling, just the normal input buffer is
527 * used then so it is efficient.
529 * callback returns 1 in case it wants to spill more buffers
531 * This takes care of holding the buffer if send is incomplete, ie,
532 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
533 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
534 * return to the user code how much OF THE USER BUFFER was consumed.
537 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
538 wsi->u.ws.inside_frame = 1;
542 if (n == (int)len + pre) {
543 /* everything in the buffer was handled (or rebuffered...) */
544 wsi->u.ws.inside_frame = 0;
549 * it is how many bytes of user buffer got sent... may be < orig_len
550 * in which case callback when writable has already been arranged
551 * and user code can call lws_write() again with the rest
558 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)
560 struct lws_context *context = wsi->context;
561 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
562 unsigned long amount;
565 while (wsi->http2_substream || !lws_send_pipe_choked(wsi)) {
566 if (wsi->trunc_len) {
567 if (lws_issue_raw(wsi, wsi->trunc_alloc +
569 wsi->trunc_len) < 0) {
570 lwsl_info("%s: closing\n", __func__);
576 if (wsi->u.http.filepos == wsi->u.http.filelen)
579 if (lws_plat_file_read(wsi, wsi->u.http.fd, &amount,
581 LWS_MAX_SOCKET_IO_BUF) < 0)
582 return -1; /* caller will close */
586 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
587 context->timeout_secs);
588 wsi->u.http.filepos += n;
589 m = lws_write(wsi, pt->serv_buf, n,
590 wsi->u.http.filepos == wsi->u.http.filelen ?
591 LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
596 /* adjust for what was not sent */
597 if (lws_plat_file_seek_cur(wsi, wsi->u.http.fd,
603 if (!wsi->trunc_len && wsi->u.http.filepos == wsi->u.http.filelen) {
604 wsi->state = LWSS_HTTP;
605 /* we might be in keepalive, so close it off here */
606 lws_plat_file_close(wsi, wsi->u.http.fd);
607 wsi->u.http.fd = LWS_INVALID_FILE;
609 if (wsi->protocol->callback)
610 /* ignore callback returned value */
611 if (user_callback_handle_rxflow(
612 wsi->protocol->callback, wsi,
613 LWS_CALLBACK_HTTP_FILE_COMPLETION,
614 wsi->user_space, NULL, 0) < 0)
616 return 1; /* >0 indicates completed */
620 lwsl_info("choked before able to send whole file (post)\n");
621 lws_callback_on_writable(wsi);
623 return 0; /* indicates further processing must be done */
628 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
632 n = recv(wsi->sock, (char *)buf, len, 0);
636 if (LWS_ERRNO == LWS_EAGAIN ||
637 LWS_ERRNO == LWS_EWOULDBLOCK ||
638 LWS_ERRNO == LWS_EINTR)
639 return LWS_SSL_CAPABLE_MORE_SERVICE;
641 lwsl_warn("error on reading from skt\n");
642 return LWS_SSL_CAPABLE_ERROR;
646 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
651 n = send(wsi->sock, (char *)buf, len, MSG_NOSIGNAL);
652 // lwsl_info("%s: sent len %d result %d", __func__, len, n);
656 if (LWS_ERRNO == LWS_EAGAIN ||
657 LWS_ERRNO == LWS_EWOULDBLOCK ||
658 LWS_ERRNO == LWS_EINTR) {
659 if (LWS_ERRNO == LWS_EWOULDBLOCK)
660 lws_set_blocking_send(wsi);
662 return LWS_SSL_CAPABLE_MORE_SERVICE;
672 lwsl_debug("ERROR writing len %d to skt fd %d err %d / errno %d\n", len, wsi->sock, n, LWS_ERRNO);
673 return LWS_SSL_CAPABLE_ERROR;
677 lws_ssl_pending_no_ssl(struct lws *wsi)