2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2014 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_ctx(wsi),
32 wsi->u.ws.frame_masking_nonce_04, 4);
34 lwsl_parser("Unable to read from random device %s %d\n",
35 SYSTEM_RANDOM_FILEPATH, n);
39 /* start masking from first byte of masking key buffer */
40 wsi->u.ws.frame_mask_index = 0;
47 LWS_VISIBLE void lwsl_hexdump(void *vbuf, size_t len)
49 unsigned char *buf = (unsigned char *)vbuf;
50 unsigned int n, m, start;
56 for (n = 0; n < len;) {
60 p += sprintf(p, "%04X: ", start);
62 for (m = 0; m < 16 && n < len; m++)
63 p += sprintf(p, "%02X ", buf[n++]);
69 for (m = 0; m < 16 && (start + m) < len; m++) {
70 if (buf[start + m] >= ' ' && buf[start + m] < 127)
71 *p++ = buf[start + m];
80 lwsl_debug("%s", line);
88 * notice this returns number of bytes consumed, or -1
91 int lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len)
93 struct lws_context *context = lws_get_ctx(wsi);
94 size_t real_len = len;
99 /* just ignore sends after we cleared the truncation buffer */
100 if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
101 !wsi->truncated_send_len)
104 if (wsi->truncated_send_len && (buf < wsi->truncated_send_malloc ||
105 buf > (wsi->truncated_send_malloc + wsi->truncated_send_len +
106 wsi->truncated_send_offset))) {
107 lwsl_err("****** %x Sending new, pending truncated ...\n", wsi);
111 m = lws_ext_callback_for_each_active(wsi,
112 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, &buf, len);
115 if (m) /* handled */ {
117 goto handle_truncated_send;
120 if (!lws_socket_is_valid(wsi->sock))
121 lwsl_warn("** error invalid sock but expected to send\n");
123 /* nope, send it on the socket directly */
124 lws_latency_pre(context, wsi);
125 n = lws_ssl_capable_write(wsi, buf, len);
126 lws_latency(context, wsi, "send lws_issue_raw", n, (unsigned int)n == len);
129 case LWS_SSL_CAPABLE_ERROR:
130 lwsl_err("%s: wsi %p: LWS_SSL_CAPABLE_ERROR\n", __func__, (void *)wsi);
131 /* we're going to close, let close know sends aren't possible */
132 wsi->socket_is_permanently_unusable = 1;
134 case LWS_SSL_CAPABLE_MORE_SERVICE:
135 /* nothing got sent, not fatal, retry the whole thing later */
140 handle_truncated_send:
142 * we were already handling a truncated send?
144 if (wsi->truncated_send_len) {
145 lwsl_info("***** %x partial send moved on by %d (vs %d)\n",
147 wsi->truncated_send_offset += n;
148 wsi->truncated_send_len -= n;
150 if (!wsi->truncated_send_len) {
151 lwsl_info("***** %x partial send completed\n", wsi);
152 /* done with it, but don't free it */
154 if (wsi->state == WSI_STATE_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(lws_get_ctx(wsi), 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("***** %x new partial sent %d from %d total\n",
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->truncated_send_malloc ||
192 real_len - n > wsi->truncated_send_allocation) {
193 lws_free(wsi->truncated_send_malloc);
195 wsi->truncated_send_allocation = real_len - n;
196 wsi->truncated_send_malloc = lws_malloc(real_len - n);
197 if (!wsi->truncated_send_malloc) {
198 lwsl_err("truncated send: unable to malloc %d\n",
203 wsi->truncated_send_offset = 0;
204 wsi->truncated_send_len = real_len - n;
205 memcpy(wsi->truncated_send_malloc, buf + n, real_len - n);
207 /* since something buffered, force it to get another chance to send */
208 lws_callback_on_writable(lws_get_ctx(wsi), wsi);
214 * lws_write() - Apply protocol then write data to client
215 * @wsi: Websocket instance (available from user callback)
216 * @buf: The data to send. For data being sent on a websocket
217 * connection (ie, not default http), this buffer MUST have
218 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
219 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
220 * in the buffer after (buf + len). This is so the protocol
221 * header and trailer data can be added in-situ.
222 * @len: Count of the data bytes in the payload starting from buf
223 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
224 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
225 * data on a websockets connection. Remember to allow the extra
226 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
229 * This function provides the way to issue data back to the client
230 * for both http and websocket protocols.
232 * In the case of sending using websocket protocol, be sure to allocate
233 * valid storage before and after buf as explained above. This scheme
234 * allows maximum efficiency of sending data and protocol in a single
235 * packet while not burdening the user code with any protocol knowledge.
237 * Return may be -1 for a fatal error needing connection close, or a
238 * positive number reflecting the amount of bytes actually sent. This
239 * can be less than the requested number of bytes due to OS memory
240 * pressure at any given time.
243 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf,
244 size_t len, enum lws_write_protocol protocol)
246 int masked7 = wsi->mode == LWS_CONNMODE_WS_CLIENT;
247 unsigned char is_masked_bit = 0;
248 unsigned char *dropmask = NULL;
249 struct lws_tokens eff_buf;
250 int post = 0, pre = 0, n;
251 size_t orig_len = len;
253 if (len == 0 && protocol != LWS_WRITE_CLOSE &&
254 protocol != LWS_WRITE_PING && protocol != LWS_WRITE_PONG) {
255 lwsl_warn("zero length lws_write attempt\n");
259 if (protocol == LWS_WRITE_HTTP ||
260 protocol == LWS_WRITE_HTTP_FINAL ||
261 protocol == LWS_WRITE_HTTP_HEADERS)
264 /* websocket protocol, either binary or text */
266 if (wsi->state != WSI_STATE_ESTABLISHED &&
267 !(wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY &&
268 protocol == LWS_WRITE_CLOSE))
271 /* if we are continuing a frame that already had its header done */
273 if (wsi->u.ws.inside_frame)
274 goto do_more_inside_frame;
276 wsi->u.ws.clean_buffer = 1;
279 * give a chance to the extensions to modify payload
280 * pre-TX mangling is not allowed to truncate
282 eff_buf.token = (char *)buf;
283 eff_buf.token_len = len;
288 case LWS_WRITE_CLOSE:
291 if (lws_ext_callback_for_each_active(wsi,
292 LWS_EXT_CALLBACK_PAYLOAD_TX, &eff_buf, 0) < 0)
297 * an extension did something we need to keep... for example, if
298 * compression extension, it has already updated its state according
299 * to this being issued
301 if ((char *)buf != eff_buf.token)
303 * extension recreated it:
304 * need to buffer this if not all sent
306 wsi->u.ws.clean_buffer = 0;
308 buf = (unsigned char *)eff_buf.token;
309 len = eff_buf.token_len;
311 switch (wsi->ietf_spec_revision) {
315 dropmask = &buf[0 - pre];
316 is_masked_bit = 0x80;
319 switch (protocol & 0xf) {
321 n = LWS_WS_OPCODE_07__TEXT_FRAME;
323 case LWS_WRITE_BINARY:
324 n = LWS_WS_OPCODE_07__BINARY_FRAME;
326 case LWS_WRITE_CONTINUATION:
327 n = LWS_WS_OPCODE_07__CONTINUATION;
330 case LWS_WRITE_CLOSE:
331 n = LWS_WS_OPCODE_07__CLOSE;
334 * 06+ has a 2-byte status code in network order
335 * we can do this because we demand post-buf
338 if (wsi->u.ws.close_reason) {
339 /* reason codes count as data bytes */
341 buf[0] = (unsigned char)(wsi->u.ws.close_reason >> 8);
342 buf[1] = (unsigned char)wsi->u.ws.close_reason;
347 n = LWS_WS_OPCODE_07__PING;
350 n = LWS_WS_OPCODE_07__PONG;
353 lwsl_warn("lws_write: unknown write opc / protocol\n");
357 if (!(protocol & LWS_WRITE_NO_FIN))
363 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
368 buf[-pre + 1] = 126 | is_masked_bit;
369 buf[-pre + 2] = (unsigned char)(len >> 8);
370 buf[-pre + 3] = (unsigned char)len;
374 buf[-pre + 1] = 127 | is_masked_bit;
376 buf[-pre + 2] = (len >> 56) & 0x7f;
377 buf[-pre + 3] = len >> 48;
378 buf[-pre + 4] = len >> 40;
379 buf[-pre + 5] = len >> 32;
386 buf[-pre + 6] = (unsigned char)(len >> 24);
387 buf[-pre + 7] = (unsigned char)(len >> 16);
388 buf[-pre + 8] = (unsigned char)(len >> 8);
389 buf[-pre + 9] = (unsigned char)len;
395 do_more_inside_frame:
398 * Deal with masking if we are in client -> server direction and
399 * the protocol demands it
402 if (wsi->mode == LWS_CONNMODE_WS_CLIENT) {
404 if (!wsi->u.ws.inside_frame)
405 if (lws_0405_frame_mask_generate(wsi)) {
406 lwsl_err("frame mask generation failed\n");
411 * in v7, just mask the payload
413 if (dropmask) { /* never set if already inside frame */
414 for (n = 4; n < (int)len + 4; n++)
415 dropmask[n] = dropmask[n] ^
416 wsi->u.ws.frame_masking_nonce_04[
417 (wsi->u.ws.frame_mask_index++) & 3];
419 /* copy the frame nonce into place */
420 memcpy(dropmask, wsi->u.ws.frame_masking_nonce_04, 4);
426 case LWS_WRITE_CLOSE:
427 /* lwsl_hexdump(&buf[-pre], len + post); */
429 case LWS_WRITE_HTTP_FINAL:
430 case LWS_WRITE_HTTP_HEADERS:
434 if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) {
435 unsigned char flags = 0;
437 n = LWS_HTTP2_FRAME_TYPE_DATA;
438 if (protocol == LWS_WRITE_HTTP_HEADERS) {
439 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
440 flags = LWS_HTTP2_FLAG_END_HEADERS;
441 if (wsi->u.http2.send_END_STREAM)
442 flags |= LWS_HTTP2_FLAG_END_STREAM;
445 if ((protocol == LWS_WRITE_HTTP || protocol == LWS_WRITE_HTTP_FINAL) && wsi->u.http.content_length) {
446 wsi->u.http.content_remain -= len;
447 lwsl_info("%s: content_remain = %lu\n", __func__, wsi->u.http.content_remain);
448 if (!wsi->u.http.content_remain) {
449 lwsl_info("%s: selecting final write mode\n", __func__);
450 protocol = LWS_WRITE_HTTP_FINAL;
454 if (protocol == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
455 lwsl_info("%s: setting END_STREAM\n", __func__);
456 flags |= LWS_HTTP2_FLAG_END_STREAM;
459 return lws_http2_frame_write(wsi, n, flags, wsi->u.http2.my_stream_id, len, buf);
462 return lws_issue_raw(wsi, (unsigned char *)buf - pre,
468 wsi->u.ws.inside_frame = 1;
471 * give any active extensions a chance to munge the buffer
472 * before send. We pass in a pointer to an lws_tokens struct
473 * prepared with the default buffer and content length that's in
474 * there. Rather than rewrite the default buffer, extensions
475 * that expect to grow the buffer can adapt .token to
476 * point to their own per-connection buffer in the extension
477 * user allocation. By default with no extensions or no
478 * extension callback handling, just the normal input buffer is
479 * used then so it is efficient.
481 * callback returns 1 in case it wants to spill more buffers
483 * This takes care of holding the buffer if send is incomplete, ie,
484 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
485 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
486 * return to the user code how much OF THE USER BUFFER was consumed.
489 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre + post);
493 if (n == (int)len + pre + post) {
494 /* everything in the buffer was handled (or rebuffered...) */
495 wsi->u.ws.inside_frame = 0;
500 * it is how many bytes of user buffer got sent... may be < orig_len
501 * in which case callback when writable has already been arranged
502 * and user code can call lws_write() again with the rest
506 return n - (pre + post);
509 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws_context *context,
512 unsigned long amount;
515 while (!lws_send_pipe_choked(wsi)) {
517 if (wsi->truncated_send_len) {
518 if (lws_issue_raw(wsi, wsi->truncated_send_malloc +
519 wsi->truncated_send_offset,
520 wsi->truncated_send_len) < 0) {
521 lwsl_info("%s: closing\n", __func__);
527 if (wsi->u.http.filepos == wsi->u.http.filelen)
530 if (lws_plat_file_read(wsi, wsi->u.http.fd, &amount,
531 context->service_buffer,
532 sizeof(context->service_buffer)) < 0)
533 return -1; /* caller will close */
537 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
539 wsi->u.http.filepos += n;
540 m = lws_write(wsi, context->service_buffer, n,
541 wsi->u.http.filepos == wsi->u.http.filelen ?
542 LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
547 /* adjust for what was not sent */
548 if (lws_plat_file_seek_cur(wsi,
555 if (!wsi->truncated_send_len &&
556 wsi->u.http.filepos == wsi->u.http.filelen) {
557 wsi->state = WSI_STATE_HTTP;
559 /* we might be in keepalive, so close it off here */
560 lws_plat_file_close(wsi, wsi->u.http.fd);
561 wsi->u.http.fd = LWS_INVALID_FILE;
563 if (wsi->protocol->callback)
564 /* ignore callback returned value */
565 user_callback_handle_rxflow(
566 wsi->protocol->callback, context, wsi,
567 LWS_CALLBACK_HTTP_FILE_COMPLETION,
568 wsi->user_space, NULL, 0);
569 return 1; /* >0 indicates completed */
573 lwsl_info("choked before able to send whole file (post)\n");
574 lws_callback_on_writable(context, wsi);
576 return 0; /* indicates further processing must be done */
581 lws_ssl_capable_read_no_ssl(struct lws_context *context,
582 struct lws *wsi, unsigned char *buf, int len)
588 n = recv(wsi->sock, (char *)buf, len, 0);
592 if (LWS_ERRNO == LWS_EAGAIN ||
593 LWS_ERRNO == LWS_EWOULDBLOCK ||
594 LWS_ERRNO == LWS_EINTR)
595 return LWS_SSL_CAPABLE_MORE_SERVICE;
597 lwsl_warn("error on reading from skt\n");
598 return LWS_SSL_CAPABLE_ERROR;
602 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
607 n = send(wsi->sock, (char *)buf, len, MSG_NOSIGNAL);
611 if (LWS_ERRNO == LWS_EAGAIN ||
612 LWS_ERRNO == LWS_EWOULDBLOCK ||
613 LWS_ERRNO == LWS_EINTR) {
614 if (LWS_ERRNO == LWS_EWOULDBLOCK)
615 lws_set_blocking_send(wsi);
617 return LWS_SSL_CAPABLE_MORE_SERVICE;
627 lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
628 return LWS_SSL_CAPABLE_ERROR;
632 lws_ssl_pending_no_ssl(struct lws *wsi)