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)
29 /* fetch the per-frame nonce */
31 n = lws_get_random(lws_get_context(wsi), wsi->u.ws.mask_nonce, 4);
33 lwsl_parser("Unable to read from random device %s %d\n",
34 SYSTEM_RANDOM_FILEPATH, n);
38 /* start masking from first byte of masking key buffer */
39 wsi->u.ws.frame_mask_index = 0;
46 LWS_VISIBLE void lwsl_hexdump(void *vbuf, size_t len)
48 unsigned char *buf = (unsigned char *)vbuf;
49 unsigned int n, m, start;
55 for (n = 0; n < len;) {
59 p += sprintf(p, "%04X: ", start);
61 for (m = 0; m < 16 && n < len; m++)
62 p += sprintf(p, "%02X ", buf[n++]);
68 for (m = 0; m < 16 && (start + m) < len; m++) {
69 if (buf[start + m] >= ' ' && buf[start + m] < 127)
70 *p++ = buf[start + m];
79 lwsl_debug("%s", line);
87 * notice this returns number of bytes consumed, or -1
90 int lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len)
92 struct lws_context *context = lws_get_context(wsi);
93 size_t real_len = len;
98 /* just ignore sends after we cleared the truncation buffer */
99 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
103 if (wsi->trunc_len && (buf < wsi->trunc_alloc ||
104 buf > (wsi->trunc_alloc + wsi->trunc_len +
105 wsi->trunc_offset))) {
106 lwsl_err("****** %x Sending new, pending truncated ...\n", wsi);
110 m = lws_ext_cb_wsi_active_exts(wsi,
111 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, &buf, len);
114 if (m) /* handled */ {
116 goto handle_truncated_send;
119 if (!lws_socket_is_valid(wsi->sock))
120 lwsl_warn("** error invalid sock but expected to send\n");
122 /* nope, send it on the socket directly */
123 lws_latency_pre(context, wsi);
124 n = lws_ssl_capable_write(wsi, buf, len);
125 lws_latency(context, wsi, "send lws_issue_raw", n,
126 (unsigned int)n == len);
129 case LWS_SSL_CAPABLE_ERROR:
130 lwsl_err("%s: wsi %p: LWS_SSL_CAPABLE_ERROR\n", __func__,
132 /* we're going to close, let close know sends aren't possible */
133 wsi->socket_is_permanently_unusable = 1;
135 case LWS_SSL_CAPABLE_MORE_SERVICE:
136 /* nothing got sent, not fatal, retry the whole thing later */
141 handle_truncated_send:
143 * we were already handling a truncated send?
145 if (wsi->trunc_len) {
146 lwsl_info("%p partial adv %d (vs %d)\n", wsi, n, real_len);
147 wsi->trunc_offset += n;
150 if (!wsi->trunc_len) {
151 lwsl_info("***** %x partial send completed\n", wsi);
152 /* done with it, but don't free it */
154 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
155 lwsl_info("***** %x signalling to close now\n", wsi);
156 return -1; /* retry closing now */
159 /* always callback on writeable */
160 lws_callback_on_writable(wsi);
165 if ((unsigned int)n == real_len)
166 /* what we just sent went out cleanly */
169 if (n && wsi->u.ws.clean_buffer)
171 * This buffer unaffected by extension rewriting.
172 * It means the user code is expected to deal with
173 * partial sends. (lws knows the header was already
174 * sent, so on next send will just resume sending
180 * Newly truncated send. Buffer the remainder (it will get
181 * first priority next time the socket is writable)
183 lwsl_info("%p new partial sent %d from %d total\n", wsi, n, real_len);
186 * - if we still have a suitable malloc lying around, use it
187 * - or, if too small, reallocate it
188 * - or, if no buffer, create it
190 if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {
191 lws_free(wsi->trunc_alloc);
193 wsi->trunc_alloc_len = real_len - n;
194 wsi->trunc_alloc = lws_malloc(real_len - n);
195 if (!wsi->trunc_alloc) {
196 lwsl_err("truncated send: unable to malloc %d\n",
201 wsi->trunc_offset = 0;
202 wsi->trunc_len = real_len - n;
203 memcpy(wsi->trunc_alloc, buf + n, real_len - n);
205 /* since something buffered, force it to get another chance to send */
206 lws_callback_on_writable(wsi);
212 * lws_write() - Apply protocol then write data to client
213 * @wsi: Websocket instance (available from user callback)
214 * @buf: The data to send. For data being sent on a websocket
215 * connection (ie, not default http), this buffer MUST have
216 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
217 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
218 * in the buffer after (buf + len). This is so the protocol
219 * header and trailer data can be added in-situ.
220 * @len: Count of the data bytes in the payload starting from buf
221 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
222 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
223 * data on a websockets connection. Remember to allow the extra
224 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
227 * This function provides the way to issue data back to the client
228 * for both http and websocket protocols.
230 * In the case of sending using websocket protocol, be sure to allocate
231 * valid storage before and after buf as explained above. This scheme
232 * allows maximum efficiency of sending data and protocol in a single
233 * packet while not burdening the user code with any protocol knowledge.
235 * Return may be -1 for a fatal error needing connection close, or a
236 * positive number reflecting the amount of bytes actually sent. This
237 * can be less than the requested number of bytes due to OS memory
238 * pressure at any given time.
241 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf,
242 size_t len, enum lws_write_protocol protocol)
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 (len == 0 && protocol != LWS_WRITE_CLOSE &&
252 protocol != LWS_WRITE_PING && protocol != LWS_WRITE_PONG) {
253 lwsl_warn("zero length lws_write attempt\n");
257 if (protocol == LWS_WRITE_HTTP ||
258 protocol == LWS_WRITE_HTTP_FINAL ||
259 protocol == LWS_WRITE_HTTP_HEADERS)
262 /* websocket protocol, either binary or text */
264 if (wsi->state != LWSS_ESTABLISHED &&
265 !(wsi->state == LWSS_RETURNED_CLOSE_ALREADY &&
266 protocol == LWS_WRITE_CLOSE))
269 /* if we are continuing a frame that already had its header done */
271 if (wsi->u.ws.inside_frame)
272 goto do_more_inside_frame;
274 wsi->u.ws.clean_buffer = 1;
277 * give a chance to the extensions to modify payload
278 * pre-TX mangling is not allowed to truncate
280 eff_buf.token = (char *)buf;
281 eff_buf.token_len = len;
286 case LWS_WRITE_CLOSE:
289 if (lws_ext_cb_wsi_active_exts(wsi, LWS_EXT_CALLBACK_PAYLOAD_TX,
295 * an extension did something we need to keep... for example, if
296 * compression extension, it has already updated its state according
297 * to this being issued
299 if ((char *)buf != eff_buf.token)
301 * extension recreated it:
302 * need to buffer this if not all sent
304 wsi->u.ws.clean_buffer = 0;
306 buf = (unsigned char *)eff_buf.token;
307 len = eff_buf.token_len;
309 switch (wsi->ietf_spec_revision) {
313 dropmask = &buf[0 - pre];
314 is_masked_bit = 0x80;
317 switch (protocol & 0xf) {
319 n = LWSWSOPC_TEXT_FRAME;
321 case LWS_WRITE_BINARY:
322 n = LWSWSOPC_BINARY_FRAME;
324 case LWS_WRITE_CONTINUATION:
325 n = LWSWSOPC_CONTINUATION;
328 case LWS_WRITE_CLOSE:
332 * 06+ has a 2-byte status code in network order
333 * we can do this because we demand post-buf
336 if (wsi->u.ws.close_reason) {
337 /* reason codes count as data bytes */
338 buf[0] = (unsigned char)(wsi->u.ws.close_reason >> 8);
339 buf[1] = (unsigned char)wsi->u.ws.close_reason;
350 lwsl_warn("lws_write: unknown write opc / protocol\n");
354 if (!(protocol & LWS_WRITE_NO_FIN))
360 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
365 buf[-pre + 1] = 126 | is_masked_bit;
366 buf[-pre + 2] = (unsigned char)(len >> 8);
367 buf[-pre + 3] = (unsigned char)len;
371 buf[-pre + 1] = 127 | is_masked_bit;
373 buf[-pre + 2] = (len >> 56) & 0x7f;
374 buf[-pre + 3] = len >> 48;
375 buf[-pre + 4] = len >> 40;
376 buf[-pre + 5] = len >> 32;
383 buf[-pre + 6] = (unsigned char)(len >> 24);
384 buf[-pre + 7] = (unsigned char)(len >> 16);
385 buf[-pre + 8] = (unsigned char)(len >> 8);
386 buf[-pre + 9] = (unsigned char)len;
392 do_more_inside_frame:
395 * Deal with masking if we are in client -> server direction and
396 * the protocol demands it
399 if (wsi->mode == LWSCM_WS_CLIENT) {
400 if (!wsi->u.ws.inside_frame)
401 if (lws_0405_frame_mask_generate(wsi)) {
402 lwsl_err("frame mask generation failed\n");
407 * in v7, just mask the payload
409 if (dropmask) { /* never set if already inside frame */
410 for (n = 4; n < (int)len + 4; n++)
411 dropmask[n] = dropmask[n] ^
412 wsi->u.ws.mask_nonce[
413 (wsi->u.ws.frame_mask_index++) & 3];
415 /* copy the frame nonce into place */
416 memcpy(dropmask, wsi->u.ws.mask_nonce, 4);
422 case LWS_WRITE_CLOSE:
423 /* lwsl_hexdump(&buf[-pre], len); */
425 case LWS_WRITE_HTTP_FINAL:
426 case LWS_WRITE_HTTP_HEADERS:
430 if (wsi->mode == LWSCM_HTTP2_SERVING) {
431 unsigned char flags = 0;
433 n = LWS_HTTP2_FRAME_TYPE_DATA;
434 if (protocol == LWS_WRITE_HTTP_HEADERS) {
435 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
436 flags = LWS_HTTP2_FLAG_END_HEADERS;
437 if (wsi->u.http2.send_END_STREAM)
438 flags |= LWS_HTTP2_FLAG_END_STREAM;
441 if ((protocol == LWS_WRITE_HTTP ||
442 protocol == LWS_WRITE_HTTP_FINAL) &&
443 wsi->u.http.content_length) {
444 wsi->u.http.content_remain -= len;
445 lwsl_info("%s: content_remain = %lu\n", __func__,
446 wsi->u.http.content_remain);
447 if (!wsi->u.http.content_remain) {
448 lwsl_info("%s: selecting final write mode\n", __func__);
449 protocol = LWS_WRITE_HTTP_FINAL;
453 if (protocol == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
454 lwsl_info("%s: setting END_STREAM\n", __func__);
455 flags |= LWS_HTTP2_FLAG_END_STREAM;
458 return lws_http2_frame_write(wsi, n, flags,
459 wsi->u.http2.my_stream_id, len, buf);
462 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
467 wsi->u.ws.inside_frame = 1;
470 * give any active extensions a chance to munge the buffer
471 * before send. We pass in a pointer to an lws_tokens struct
472 * prepared with the default buffer and content length that's in
473 * there. Rather than rewrite the default buffer, extensions
474 * that expect to grow the buffer can adapt .token to
475 * point to their own per-connection buffer in the extension
476 * user allocation. By default with no extensions or no
477 * extension callback handling, just the normal input buffer is
478 * used then so it is efficient.
480 * callback returns 1 in case it wants to spill more buffers
482 * This takes care of holding the buffer if send is incomplete, ie,
483 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
484 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
485 * return to the user code how much OF THE USER BUFFER was consumed.
488 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
492 if (n == (int)len + pre) {
493 /* everything in the buffer was handled (or rebuffered...) */
494 wsi->u.ws.inside_frame = 0;
499 * it is how many bytes of user buffer got sent... may be < orig_len
500 * in which case callback when writable has already been arranged
501 * and user code can call lws_write() again with the rest
508 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)
510 struct lws_context *context = wsi->context;
511 unsigned long amount;
514 while (!lws_send_pipe_choked(wsi)) {
515 if (wsi->trunc_len) {
516 if (lws_issue_raw(wsi, wsi->trunc_alloc +
518 wsi->trunc_len) < 0) {
519 lwsl_info("%s: closing\n", __func__);
525 if (wsi->u.http.filepos == wsi->u.http.filelen)
528 if (lws_plat_file_read(wsi, wsi->u.http.fd, &amount,
530 sizeof(context->serv_buf)) < 0)
531 return -1; /* caller will close */
535 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
537 wsi->u.http.filepos += n;
538 m = lws_write(wsi, context->serv_buf, n,
539 wsi->u.http.filepos == wsi->u.http.filelen ?
540 LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
545 /* adjust for what was not sent */
546 if (lws_plat_file_seek_cur(wsi, wsi->u.http.fd,
552 if (!wsi->trunc_len && wsi->u.http.filepos == wsi->u.http.filelen) {
553 wsi->state = LWSS_HTTP;
555 /* we might be in keepalive, so close it off here */
556 lws_plat_file_close(wsi, wsi->u.http.fd);
557 wsi->u.http.fd = LWS_INVALID_FILE;
559 if (wsi->protocol->callback)
560 /* ignore callback returned value */
561 user_callback_handle_rxflow(
562 wsi->protocol->callback, wsi,
563 LWS_CALLBACK_HTTP_FILE_COMPLETION,
564 wsi->user_space, NULL, 0);
565 return 1; /* >0 indicates completed */
569 lwsl_info("choked before able to send whole file (post)\n");
570 lws_callback_on_writable(wsi);
572 return 0; /* indicates further processing must be done */
577 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
581 n = recv(wsi->sock, (char *)buf, len, 0);
585 if (LWS_ERRNO == LWS_EAGAIN ||
586 LWS_ERRNO == LWS_EWOULDBLOCK ||
587 LWS_ERRNO == LWS_EINTR)
588 return LWS_SSL_CAPABLE_MORE_SERVICE;
590 lwsl_warn("error on reading from skt\n");
591 return LWS_SSL_CAPABLE_ERROR;
595 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
600 n = send(wsi->sock, (char *)buf, len, MSG_NOSIGNAL);
604 if (LWS_ERRNO == LWS_EAGAIN ||
605 LWS_ERRNO == LWS_EWOULDBLOCK ||
606 LWS_ERRNO == LWS_EINTR) {
607 if (LWS_ERRNO == LWS_EWOULDBLOCK)
608 lws_set_blocking_send(wsi);
610 return LWS_SSL_CAPABLE_MORE_SERVICE;
620 lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
621 return LWS_SSL_CAPABLE_ERROR;
625 lws_ssl_pending_no_ssl(struct lws *wsi)