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;
103 /* just ignore sends after we cleared the truncation buffer */
104 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
108 if (wsi->trunc_len && (buf < wsi->trunc_alloc ||
109 buf > (wsi->trunc_alloc + wsi->trunc_len +
110 wsi->trunc_offset))) {
111 lwsl_err("****** %x Sending new, pending truncated ...\n", wsi);
115 m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_DO_SEND, &buf, len);
118 if (m) /* handled */ {
120 goto handle_truncated_send;
123 if (!lws_socket_is_valid(wsi->sock))
124 lwsl_warn("** error invalid sock but expected to send\n");
126 /* nope, send it on the socket directly */
127 lws_latency_pre(context, wsi);
128 n = lws_ssl_capable_write(wsi, buf, len);
129 lws_latency(context, wsi, "send lws_issue_raw", n,
130 (unsigned int)n == len);
133 case LWS_SSL_CAPABLE_ERROR:
134 lwsl_err("%s: wsi %p: LWS_SSL_CAPABLE_ERROR\n", __func__,
136 /* we're going to close, let close know sends aren't possible */
137 wsi->socket_is_permanently_unusable = 1;
139 case LWS_SSL_CAPABLE_MORE_SERVICE:
140 /* nothing got sent, not fatal, retry the whole thing later */
145 handle_truncated_send:
147 * we were already handling a truncated send?
149 if (wsi->trunc_len) {
150 lwsl_info("%p partial adv %d (vs %d)\n", wsi, n, real_len);
151 wsi->trunc_offset += n;
154 if (!wsi->trunc_len) {
155 lwsl_info("***** %x partial send completed\n", wsi);
156 /* done with it, but don't free it */
158 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
159 lwsl_info("***** %x signalling to close now\n", wsi);
160 return -1; /* retry closing now */
163 /* always callback on writeable */
164 lws_callback_on_writable(wsi);
169 if ((unsigned int)n == real_len)
170 /* what we just sent went out cleanly */
174 * Newly truncated send. Buffer the remainder (it will get
175 * first priority next time the socket is writable)
177 lwsl_info("%p new partial sent %d from %d total\n", wsi, n, real_len);
180 * - if we still have a suitable malloc lying around, use it
181 * - or, if too small, reallocate it
182 * - or, if no buffer, create it
184 if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {
185 lws_free(wsi->trunc_alloc);
187 wsi->trunc_alloc_len = real_len - n;
188 wsi->trunc_alloc = lws_malloc(real_len - n);
189 if (!wsi->trunc_alloc) {
190 lwsl_err("truncated send: unable to malloc %d\n",
195 wsi->trunc_offset = 0;
196 wsi->trunc_len = real_len - n;
197 memcpy(wsi->trunc_alloc, buf + n, real_len - n);
199 /* since something buffered, force it to get another chance to send */
200 lws_callback_on_writable(wsi);
206 * lws_write() - Apply protocol then write data to client
207 * @wsi: Websocket instance (available from user callback)
208 * @buf: The data to send. For data being sent on a websocket
209 * connection (ie, not default http), this buffer MUST have
210 * LWS_PRE bytes valid BEFORE the pointer.
211 * This is so the protocol header data can be added in-situ.
212 * @len: Count of the data bytes in the payload starting from buf
213 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
214 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
215 * data on a websockets connection. Remember to allow the extra
216 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
219 * This function provides the way to issue data back to the client
220 * for both http and websocket protocols.
222 * In the case of sending using websocket protocol, be sure to allocate
223 * valid storage before and after buf as explained above. This scheme
224 * allows maximum efficiency of sending data and protocol in a single
225 * packet while not burdening the user code with any protocol knowledge.
227 * Return may be -1 for a fatal error needing connection close, or a
228 * positive number reflecting the amount of bytes actually sent. This
229 * can be less than the requested number of bytes due to OS memory
230 * pressure at any given time.
233 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len,
234 enum lws_write_protocol wp)
236 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
237 int masked7 = (wsi->mode == LWSCM_WS_CLIENT);
238 unsigned char is_masked_bit = 0;
239 unsigned char *dropmask = NULL;
240 struct lws_tokens eff_buf;
242 size_t orig_len = len;
244 if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) {
245 /* remove us from the list */
246 struct lws **w = &pt->tx_draining_ext_list;
247 lwsl_debug("%s: TX EXT DRAINING: Remove from list\n", __func__);
248 wsi->u.ws.tx_draining_ext = 0;
249 /* remove us from context draining ext list */
252 *w = wsi->u.ws.tx_draining_ext_list;
255 w = &((*w)->u.ws.tx_draining_ext_list);
257 wsi->u.ws.tx_draining_ext_list = NULL;
258 wp = (wsi->u.ws.tx_draining_stashed_wp & 0xc0) |
259 LWS_WRITE_CONTINUATION;
261 lwsl_ext("FORCED draining wp to 0x%02X\n", wp);
264 if (wp == LWS_WRITE_HTTP ||
265 wp == LWS_WRITE_HTTP_FINAL ||
266 wp == LWS_WRITE_HTTP_HEADERS)
269 /* if not in a state to send stuff, then just send nothing */
271 if (wsi->state != LWSS_ESTABLISHED &&
272 ((wsi->state != LWSS_RETURNED_CLOSE_ALREADY &&
273 wsi->state != LWSS_AWAITING_CLOSE_ACK) ||
274 wp != LWS_WRITE_CLOSE))
277 /* if we are continuing a frame that already had its header done */
279 if (wsi->u.ws.inside_frame) {
280 lwsl_debug("INSIDE FRAME\n");
281 goto do_more_inside_frame;
284 wsi->u.ws.clean_buffer = 1;
287 * give a chance to the extensions to modify payload
288 * the extension may decide to produce unlimited payload erratically
289 * (eg, compression extension), so we require only that if he produces
290 * something, it will be a complete fragment of the length known at
291 * the time (just the fragment length known), and if he has
292 * more we will come back next time he is writeable and allow him to
293 * produce more fragments until he's drained.
295 * This allows what is sent each time it is writeable to be limited to
296 * a size that can be sent without partial sends or blocking, allows
297 * interleaving of control frames and other connection service.
299 eff_buf.token = (char *)buf;
300 eff_buf.token_len = len;
305 case LWS_WRITE_CLOSE:
308 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &eff_buf, wp);
312 if (n && eff_buf.token_len) {
313 /* extension requires further draining */
314 wsi->u.ws.tx_draining_ext = 1;
315 wsi->u.ws.tx_draining_ext_list = pt->tx_draining_ext_list;
316 pt->tx_draining_ext_list = wsi;
317 /* we must come back to do more */
318 lws_callback_on_writable(wsi);
320 * keep a copy of the write type for the overall
321 * action that has provoked generation of these
322 * fragments, so the last guy can use its FIN state.
324 wsi->u.ws.tx_draining_stashed_wp = wp;
325 /* this is definitely not actually the last fragment
326 * because the extension asserted he has more coming
327 * So make sure this intermediate one doesn't go out
330 wp |= LWS_WRITE_NO_FIN;
333 if (eff_buf.token_len && wsi->u.ws.stashed_write_pending) {
334 wsi->u.ws.stashed_write_pending = 0;
335 wp = (wp &0xc0) | (int)wsi->u.ws.stashed_write_type;
340 * an extension did something we need to keep... for example, if
341 * compression extension, it has already updated its state according
342 * to this being issued
344 if ((char *)buf != eff_buf.token) {
346 * ext might eat it, but no have anything to issue yet
347 * in that case we have to follow his lead, but stash and
348 * replace the write type that was lost here the first time.
350 if (len && !eff_buf.token_len) {
351 if (!wsi->u.ws.stashed_write_pending)
352 wsi->u.ws.stashed_write_type = (char)wp & 0x3f;
353 wsi->u.ws.stashed_write_pending = 1;
357 * extension recreated it:
358 * need to buffer this if not all sent
360 wsi->u.ws.clean_buffer = 0;
363 buf = (unsigned char *)eff_buf.token;
364 len = eff_buf.token_len;
366 switch (wsi->ietf_spec_revision) {
370 dropmask = &buf[0 - pre];
371 is_masked_bit = 0x80;
376 n = LWSWSOPC_TEXT_FRAME;
378 case LWS_WRITE_BINARY:
379 n = LWSWSOPC_BINARY_FRAME;
381 case LWS_WRITE_CONTINUATION:
382 n = LWSWSOPC_CONTINUATION;
385 case LWS_WRITE_CLOSE:
395 lwsl_warn("lws_write: unknown write opc / wp\n");
399 if (!(wp & LWS_WRITE_NO_FIN))
405 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
410 buf[-pre + 1] = 126 | is_masked_bit;
411 buf[-pre + 2] = (unsigned char)(len >> 8);
412 buf[-pre + 3] = (unsigned char)len;
416 buf[-pre + 1] = 127 | is_masked_bit;
418 buf[-pre + 2] = (len >> 56) & 0x7f;
419 buf[-pre + 3] = len >> 48;
420 buf[-pre + 4] = len >> 40;
421 buf[-pre + 5] = len >> 32;
428 buf[-pre + 6] = (unsigned char)(len >> 24);
429 buf[-pre + 7] = (unsigned char)(len >> 16);
430 buf[-pre + 8] = (unsigned char)(len >> 8);
431 buf[-pre + 9] = (unsigned char)len;
437 do_more_inside_frame:
440 * Deal with masking if we are in client -> server direction and
445 if (!wsi->u.ws.inside_frame)
446 if (lws_0405_frame_mask_generate(wsi)) {
447 lwsl_err("frame mask generation failed\n");
452 * in v7, just mask the payload
454 if (dropmask) { /* never set if already inside frame */
455 for (n = 4; n < (int)len + 4; n++)
456 dropmask[n] = dropmask[n] ^ wsi->u.ws.mask[
457 (wsi->u.ws.mask_idx++) & 3];
459 /* copy the frame nonce into place */
460 memcpy(dropmask, wsi->u.ws.mask, 4);
466 case LWS_WRITE_CLOSE:
467 /* lwsl_hexdump(&buf[-pre], len); */
469 case LWS_WRITE_HTTP_FINAL:
470 case LWS_WRITE_HTTP_HEADERS:
474 if (wsi->mode == LWSCM_HTTP2_SERVING) {
475 unsigned char flags = 0;
477 n = LWS_HTTP2_FRAME_TYPE_DATA;
478 if (wp == LWS_WRITE_HTTP_HEADERS) {
479 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
480 flags = LWS_HTTP2_FLAG_END_HEADERS;
481 if (wsi->u.http2.send_END_STREAM)
482 flags |= LWS_HTTP2_FLAG_END_STREAM;
485 if ((wp == LWS_WRITE_HTTP ||
486 wp == LWS_WRITE_HTTP_FINAL) &&
487 wsi->u.http.content_length) {
488 wsi->u.http.content_remain -= len;
489 lwsl_info("%s: content_remain = %lu\n", __func__,
490 wsi->u.http.content_remain);
491 if (!wsi->u.http.content_remain) {
492 lwsl_info("%s: selecting final write mode\n", __func__);
493 wp = LWS_WRITE_HTTP_FINAL;
497 if (wp == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
498 lwsl_info("%s: setting END_STREAM\n", __func__);
499 flags |= LWS_HTTP2_FLAG_END_STREAM;
502 return lws_http2_frame_write(wsi, n, flags,
503 wsi->u.http2.my_stream_id, len, buf);
506 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
512 * give any active extensions a chance to munge the buffer
513 * before send. We pass in a pointer to an lws_tokens struct
514 * prepared with the default buffer and content length that's in
515 * there. Rather than rewrite the default buffer, extensions
516 * that expect to grow the buffer can adapt .token to
517 * point to their own per-connection buffer in the extension
518 * user allocation. By default with no extensions or no
519 * extension callback handling, just the normal input buffer is
520 * used then so it is efficient.
522 * callback returns 1 in case it wants to spill more buffers
524 * This takes care of holding the buffer if send is incomplete, ie,
525 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
526 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
527 * return to the user code how much OF THE USER BUFFER was consumed.
530 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
531 wsi->u.ws.inside_frame = 1;
535 if (n == (int)len + pre) {
536 /* everything in the buffer was handled (or rebuffered...) */
537 wsi->u.ws.inside_frame = 0;
542 * it is how many bytes of user buffer got sent... may be < orig_len
543 * in which case callback when writable has already been arranged
544 * and user code can call lws_write() again with the rest
551 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)
553 struct lws_context *context = wsi->context;
554 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
555 unsigned long amount;
558 while (!lws_send_pipe_choked(wsi)) {
559 if (wsi->trunc_len) {
560 if (lws_issue_raw(wsi, wsi->trunc_alloc +
562 wsi->trunc_len) < 0) {
563 lwsl_info("%s: closing\n", __func__);
569 if (wsi->u.http.filepos == wsi->u.http.filelen)
572 if (lws_plat_file_read(wsi, wsi->u.http.fd, &amount,
574 LWS_MAX_SOCKET_IO_BUF) < 0)
575 return -1; /* caller will close */
579 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
581 wsi->u.http.filepos += n;
582 m = lws_write(wsi, pt->serv_buf, n,
583 wsi->u.http.filepos == wsi->u.http.filelen ?
584 LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
589 /* adjust for what was not sent */
590 if (lws_plat_file_seek_cur(wsi, wsi->u.http.fd,
596 if (!wsi->trunc_len && wsi->u.http.filepos == wsi->u.http.filelen) {
597 wsi->state = LWSS_HTTP;
599 /* we might be in keepalive, so close it off here */
600 lws_plat_file_close(wsi, wsi->u.http.fd);
601 wsi->u.http.fd = LWS_INVALID_FILE;
603 if (wsi->protocol->callback)
604 /* ignore callback returned value */
605 user_callback_handle_rxflow(
606 wsi->protocol->callback, wsi,
607 LWS_CALLBACK_HTTP_FILE_COMPLETION,
608 wsi->user_space, NULL, 0);
609 return 1; /* >0 indicates completed */
613 lwsl_info("choked before able to send whole file (post)\n");
614 lws_callback_on_writable(wsi);
616 return 0; /* indicates further processing must be done */
621 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
625 n = recv(wsi->sock, (char *)buf, len, 0);
629 if (LWS_ERRNO == LWS_EAGAIN ||
630 LWS_ERRNO == LWS_EWOULDBLOCK ||
631 LWS_ERRNO == LWS_EINTR)
632 return LWS_SSL_CAPABLE_MORE_SERVICE;
634 lwsl_warn("error on reading from skt\n");
635 return LWS_SSL_CAPABLE_ERROR;
639 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
644 n = send(wsi->sock, (char *)buf, len, MSG_NOSIGNAL);
648 if (LWS_ERRNO == LWS_EAGAIN ||
649 LWS_ERRNO == LWS_EWOULDBLOCK ||
650 LWS_ERRNO == LWS_EINTR) {
651 if (LWS_ERRNO == LWS_EWOULDBLOCK)
652 lws_set_blocking_send(wsi);
654 return LWS_SSL_CAPABLE_MORE_SERVICE;
664 lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
665 return LWS_SSL_CAPABLE_ERROR;
669 lws_ssl_pending_no_ssl(struct lws *wsi)