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_nonce[0] = 0;
29 wsi->u.ws.mask_nonce[1] = 0;
30 wsi->u.ws.mask_nonce[2] = 0;
31 wsi->u.ws.mask_nonce[3] = 0;
34 /* fetch the per-frame nonce */
36 n = lws_get_random(lws_get_context(wsi), wsi->u.ws.mask_nonce, 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.frame_mask_index = 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_wsi_active_exts(wsi,
116 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, &buf, len);
119 if (m) /* handled */ {
121 goto handle_truncated_send;
124 if (!lws_socket_is_valid(wsi->sock))
125 lwsl_warn("** error invalid sock but expected to send\n");
127 /* nope, send it on the socket directly */
128 lws_latency_pre(context, wsi);
129 n = lws_ssl_capable_write(wsi, buf, len);
130 lws_latency(context, wsi, "send lws_issue_raw", n,
131 (unsigned int)n == len);
134 case LWS_SSL_CAPABLE_ERROR:
135 lwsl_err("%s: wsi %p: LWS_SSL_CAPABLE_ERROR\n", __func__,
137 /* we're going to close, let close know sends aren't possible */
138 wsi->socket_is_permanently_unusable = 1;
140 case LWS_SSL_CAPABLE_MORE_SERVICE:
141 /* nothing got sent, not fatal, retry the whole thing later */
146 handle_truncated_send:
148 * we were already handling a truncated send?
150 if (wsi->trunc_len) {
151 lwsl_info("%p partial adv %d (vs %d)\n", wsi, n, real_len);
152 wsi->trunc_offset += n;
155 if (!wsi->trunc_len) {
156 lwsl_info("***** %x partial send completed\n", wsi);
157 /* done with it, but don't free it */
159 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
160 lwsl_info("***** %x signalling to close now\n", wsi);
161 return -1; /* retry closing now */
164 /* always callback on writeable */
165 lws_callback_on_writable(wsi);
170 if ((unsigned int)n == real_len)
171 /* what we just sent went out cleanly */
175 * Newly truncated send. Buffer the remainder (it will get
176 * first priority next time the socket is writable)
178 lwsl_info("%p new partial sent %d from %d total\n", wsi, n, real_len);
181 * - if we still have a suitable malloc lying around, use it
182 * - or, if too small, reallocate it
183 * - or, if no buffer, create it
185 if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {
186 lws_free(wsi->trunc_alloc);
188 wsi->trunc_alloc_len = real_len - n;
189 wsi->trunc_alloc = lws_malloc(real_len - n);
190 if (!wsi->trunc_alloc) {
191 lwsl_err("truncated send: unable to malloc %d\n",
196 wsi->trunc_offset = 0;
197 wsi->trunc_len = real_len - n;
198 memcpy(wsi->trunc_alloc, buf + n, real_len - n);
200 /* since something buffered, force it to get another chance to send */
201 lws_callback_on_writable(wsi);
207 * lws_write() - Apply protocol then write data to client
208 * @wsi: Websocket instance (available from user callback)
209 * @buf: The data to send. For data being sent on a websocket
210 * connection (ie, not default http), this buffer MUST have
211 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer.
212 * This is so the protocol header data can be added in-situ.
213 * @len: Count of the data bytes in the payload starting from buf
214 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
215 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
216 * data on a websockets connection. Remember to allow the extra
217 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
220 * This function provides the way to issue data back to the client
221 * for both http and websocket protocols.
223 * In the case of sending using websocket protocol, be sure to allocate
224 * valid storage before and after buf as explained above. This scheme
225 * allows maximum efficiency of sending data and protocol in a single
226 * packet while not burdening the user code with any protocol knowledge.
228 * Return may be -1 for a fatal error needing connection close, or a
229 * positive number reflecting the amount of bytes actually sent. This
230 * can be less than the requested number of bytes due to OS memory
231 * pressure at any given time.
234 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf,
235 size_t len, enum lws_write_protocol protocol)
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 (protocol == LWS_WRITE_HTTP ||
245 protocol == LWS_WRITE_HTTP_FINAL ||
246 protocol == LWS_WRITE_HTTP_HEADERS)
249 /* websocket protocol, either binary or text */
251 if (wsi->state != LWSS_ESTABLISHED &&
252 !(wsi->state == LWSS_RETURNED_CLOSE_ALREADY &&
253 protocol == LWS_WRITE_CLOSE))
256 /* if we are continuing a frame that already had its header done */
258 if (wsi->u.ws.inside_frame) {
259 lwsl_debug("INSIDE FRAME\n");
260 goto do_more_inside_frame;
263 wsi->u.ws.clean_buffer = 1;
266 * give a chance to the extensions to modify payload
267 * pre-TX mangling is not allowed to truncate
269 eff_buf.token = (char *)buf;
270 eff_buf.token_len = len;
272 switch ((int)protocol) {
275 case LWS_WRITE_CLOSE:
278 if (lws_ext_cb_wsi_active_exts(wsi, LWS_EXT_CALLBACK_PAYLOAD_TX,
284 * an extension did something we need to keep... for example, if
285 * compression extension, it has already updated its state according
286 * to this being issued
288 if ((char *)buf != eff_buf.token)
290 * extension recreated it:
291 * need to buffer this if not all sent
293 wsi->u.ws.clean_buffer = 0;
295 buf = (unsigned char *)eff_buf.token;
296 len = eff_buf.token_len;
298 switch (wsi->ietf_spec_revision) {
302 dropmask = &buf[0 - pre];
303 is_masked_bit = 0x80;
306 switch (protocol & 0xf) {
308 n = LWSWSOPC_TEXT_FRAME;
310 case LWS_WRITE_BINARY:
311 n = LWSWSOPC_BINARY_FRAME;
313 case LWS_WRITE_CONTINUATION:
314 n = LWSWSOPC_CONTINUATION;
317 case LWS_WRITE_CLOSE:
327 lwsl_warn("lws_write: unknown write opc / protocol\n");
331 if (!(protocol & LWS_WRITE_NO_FIN))
337 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
342 buf[-pre + 1] = 126 | is_masked_bit;
343 buf[-pre + 2] = (unsigned char)(len >> 8);
344 buf[-pre + 3] = (unsigned char)len;
348 buf[-pre + 1] = 127 | is_masked_bit;
350 buf[-pre + 2] = (len >> 56) & 0x7f;
351 buf[-pre + 3] = len >> 48;
352 buf[-pre + 4] = len >> 40;
353 buf[-pre + 5] = len >> 32;
360 buf[-pre + 6] = (unsigned char)(len >> 24);
361 buf[-pre + 7] = (unsigned char)(len >> 16);
362 buf[-pre + 8] = (unsigned char)(len >> 8);
363 buf[-pre + 9] = (unsigned char)len;
369 do_more_inside_frame:
372 * Deal with masking if we are in client -> server direction and
373 * the protocol demands it
376 if (wsi->mode == LWSCM_WS_CLIENT) {
377 if (!wsi->u.ws.inside_frame)
378 if (lws_0405_frame_mask_generate(wsi)) {
379 lwsl_err("frame mask generation failed\n");
384 * in v7, just mask the payload
386 if (dropmask) { /* never set if already inside frame */
387 for (n = 4; n < (int)len + 4; n++)
388 dropmask[n] = dropmask[n] ^
389 wsi->u.ws.mask_nonce[
390 (wsi->u.ws.frame_mask_index++) & 3];
392 /* copy the frame nonce into place */
393 memcpy(dropmask, wsi->u.ws.mask_nonce, 4);
398 switch ((int)protocol) {
399 case LWS_WRITE_CLOSE:
400 /* lwsl_hexdump(&buf[-pre], len); */
402 case LWS_WRITE_HTTP_FINAL:
403 case LWS_WRITE_HTTP_HEADERS:
407 if (wsi->mode == LWSCM_HTTP2_SERVING) {
408 unsigned char flags = 0;
410 n = LWS_HTTP2_FRAME_TYPE_DATA;
411 if (protocol == LWS_WRITE_HTTP_HEADERS) {
412 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
413 flags = LWS_HTTP2_FLAG_END_HEADERS;
414 if (wsi->u.http2.send_END_STREAM)
415 flags |= LWS_HTTP2_FLAG_END_STREAM;
418 if ((protocol == LWS_WRITE_HTTP ||
419 protocol == LWS_WRITE_HTTP_FINAL) &&
420 wsi->u.http.content_length) {
421 wsi->u.http.content_remain -= len;
422 lwsl_info("%s: content_remain = %lu\n", __func__,
423 wsi->u.http.content_remain);
424 if (!wsi->u.http.content_remain) {
425 lwsl_info("%s: selecting final write mode\n", __func__);
426 protocol = LWS_WRITE_HTTP_FINAL;
430 if (protocol == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
431 lwsl_info("%s: setting END_STREAM\n", __func__);
432 flags |= LWS_HTTP2_FLAG_END_STREAM;
435 return lws_http2_frame_write(wsi, n, flags,
436 wsi->u.http2.my_stream_id, len, buf);
439 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
444 wsi->u.ws.inside_frame = 1;
447 * give any active extensions a chance to munge the buffer
448 * before send. We pass in a pointer to an lws_tokens struct
449 * prepared with the default buffer and content length that's in
450 * there. Rather than rewrite the default buffer, extensions
451 * that expect to grow the buffer can adapt .token to
452 * point to their own per-connection buffer in the extension
453 * user allocation. By default with no extensions or no
454 * extension callback handling, just the normal input buffer is
455 * used then so it is efficient.
457 * callback returns 1 in case it wants to spill more buffers
459 * This takes care of holding the buffer if send is incomplete, ie,
460 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
461 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
462 * return to the user code how much OF THE USER BUFFER was consumed.
465 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
469 if (n == (int)len + pre) {
470 /* everything in the buffer was handled (or rebuffered...) */
471 wsi->u.ws.inside_frame = 0;
476 * it is how many bytes of user buffer got sent... may be < orig_len
477 * in which case callback when writable has already been arranged
478 * and user code can call lws_write() again with the rest
485 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)
487 struct lws_context *context = wsi->context;
488 unsigned long amount;
491 while (!lws_send_pipe_choked(wsi)) {
492 if (wsi->trunc_len) {
493 if (lws_issue_raw(wsi, wsi->trunc_alloc +
495 wsi->trunc_len) < 0) {
496 lwsl_info("%s: closing\n", __func__);
502 if (wsi->u.http.filepos == wsi->u.http.filelen)
505 if (lws_plat_file_read(wsi, wsi->u.http.fd, &amount,
507 sizeof(context->serv_buf)) < 0)
508 return -1; /* caller will close */
512 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
514 wsi->u.http.filepos += n;
515 m = lws_write(wsi, context->serv_buf, n,
516 wsi->u.http.filepos == wsi->u.http.filelen ?
517 LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
522 /* adjust for what was not sent */
523 if (lws_plat_file_seek_cur(wsi, wsi->u.http.fd,
529 if (!wsi->trunc_len && wsi->u.http.filepos == wsi->u.http.filelen) {
530 wsi->state = LWSS_HTTP;
532 /* we might be in keepalive, so close it off here */
533 lws_plat_file_close(wsi, wsi->u.http.fd);
534 wsi->u.http.fd = LWS_INVALID_FILE;
536 if (wsi->protocol->callback)
537 /* ignore callback returned value */
538 user_callback_handle_rxflow(
539 wsi->protocol->callback, wsi,
540 LWS_CALLBACK_HTTP_FILE_COMPLETION,
541 wsi->user_space, NULL, 0);
542 return 1; /* >0 indicates completed */
546 lwsl_info("choked before able to send whole file (post)\n");
547 lws_callback_on_writable(wsi);
549 return 0; /* indicates further processing must be done */
554 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
558 n = recv(wsi->sock, (char *)buf, len, 0);
562 if (LWS_ERRNO == LWS_EAGAIN ||
563 LWS_ERRNO == LWS_EWOULDBLOCK ||
564 LWS_ERRNO == LWS_EINTR)
565 return LWS_SSL_CAPABLE_MORE_SERVICE;
567 lwsl_warn("error on reading from skt\n");
568 return LWS_SSL_CAPABLE_ERROR;
572 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
577 n = send(wsi->sock, (char *)buf, len, MSG_NOSIGNAL);
581 if (LWS_ERRNO == LWS_EAGAIN ||
582 LWS_ERRNO == LWS_EWOULDBLOCK ||
583 LWS_ERRNO == LWS_EINTR) {
584 if (LWS_ERRNO == LWS_EWOULDBLOCK)
585 lws_set_blocking_send(wsi);
587 return LWS_SSL_CAPABLE_MORE_SERVICE;
597 lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
598 return LWS_SSL_CAPABLE_ERROR;
602 lws_ssl_pending_no_ssl(struct lws *wsi)