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 libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi)
29 /* fetch the per-frame nonce */
31 n = libwebsockets_get_random(wsi->protocol->owning_server,
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)
52 unsigned char *buf = (unsigned char *)vbuf;
58 for (n = 0; n < len;) {
62 p += sprintf(p, "%04X: ", start);
64 for (m = 0; m < 16 && n < len; m++)
65 p += sprintf(p, "%02X ", buf[n++]);
71 for (m = 0; m < 16 && (start + m) < len; m++) {
72 if (buf[start + m] >= ' ' && buf[start + m] < 127)
73 *p++ = buf[start + m];
82 lwsl_debug("%s", line);
90 * notice this returns number of bytes consumed, or -1
93 int lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len)
95 struct libwebsocket_context *context = wsi->protocol->owning_server;
97 size_t real_len = len;
102 /* just ignore sends after we cleared the truncation buffer */
103 if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
104 !wsi->truncated_send_len)
107 if (wsi->truncated_send_len && (buf < wsi->truncated_send_malloc ||
108 buf > (wsi->truncated_send_malloc +
109 wsi->truncated_send_len +
110 wsi->truncated_send_offset))) {
111 lwsl_err("****** %x Sending new, pending truncated ...\n", wsi);
115 m = lws_ext_callback_for_each_active(wsi,
116 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, &buf, len);
119 if (m) /* handled */ {
121 goto handle_truncated_send;
124 lwsl_warn("** error invalid sock but expected to send\n");
127 * nope, send it on the socket directly
129 lws_latency_pre(context, wsi);
130 n = lws_ssl_capable_write(wsi, buf, len);
131 lws_latency(context, wsi, "send lws_issue_raw", n, n == len);
134 case LWS_SSL_CAPABLE_ERROR:
135 /* we're going to close, let close know sends aren't possible */
136 wsi->socket_is_permanently_unusable = 1;
138 case LWS_SSL_CAPABLE_MORE_SERVICE:
139 /* nothing got sent, not fatal, retry the whole thing later */
144 handle_truncated_send:
146 * we were already handling a truncated send?
148 if (wsi->truncated_send_len) {
149 lwsl_info("***** %x partial send moved on by %d (vs %d)\n",
151 wsi->truncated_send_offset += n;
152 wsi->truncated_send_len -= n;
154 if (!wsi->truncated_send_len) {
155 lwsl_info("***** %x partial send completed\n", wsi);
156 /* done with it, but don't free it */
158 if (wsi->state == WSI_STATE_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 libwebsocket_callback_on_writable(
165 wsi->protocol->owning_server, wsi);
171 /* what we just sent went out cleanly */
174 if (n && wsi->u.ws.clean_buffer)
176 * This buffer unaffected by extension rewriting.
177 * It means the user code is expected to deal with
178 * partial sends. (lws knows the header was already
179 * sent, so on next send will just resume sending
185 * Newly truncated send. Buffer the remainder (it will get
186 * first priority next time the socket is writable)
188 lwsl_info("***** %x new partial sent %d from %d total\n",
192 * - if we still have a suitable malloc lying around, use it
193 * - or, if too small, reallocate it
194 * - or, if no buffer, create it
196 if (!wsi->truncated_send_malloc ||
197 real_len - n > wsi->truncated_send_allocation) {
198 if (wsi->truncated_send_malloc)
199 free(wsi->truncated_send_malloc);
201 wsi->truncated_send_allocation = real_len - n;
202 wsi->truncated_send_malloc = malloc(real_len - n);
203 if (!wsi->truncated_send_malloc) {
204 lwsl_err("truncated send: unable to malloc %d\n",
209 wsi->truncated_send_offset = 0;
210 wsi->truncated_send_len = real_len - n;
211 memcpy(wsi->truncated_send_malloc, buf + n, real_len - n);
213 /* since something buffered, force it to get another chance to send */
214 libwebsocket_callback_on_writable(wsi->protocol->owning_server, wsi);
220 * libwebsocket_write() - Apply protocol then write data to client
221 * @wsi: Websocket instance (available from user callback)
222 * @buf: The data to send. For data being sent on a websocket
223 * connection (ie, not default http), this buffer MUST have
224 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
225 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
226 * in the buffer after (buf + len). This is so the protocol
227 * header and trailer data can be added in-situ.
228 * @len: Count of the data bytes in the payload starting from buf
229 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
230 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
231 * data on a websockets connection. Remember to allow the extra
232 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
235 * This function provides the way to issue data back to the client
236 * for both http and websocket protocols.
238 * In the case of sending using websocket protocol, be sure to allocate
239 * valid storage before and after buf as explained above. This scheme
240 * allows maximum efficiency of sending data and protocol in a single
241 * packet while not burdening the user code with any protocol knowledge.
243 * Return may be -1 for a fatal error needing connection close, or a
244 * positive number reflecting the amount of bytes actually sent. This
245 * can be less than the requested number of bytes due to OS memory
246 * pressure at any given time.
249 LWS_VISIBLE int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
250 size_t len, enum libwebsocket_write_protocol protocol)
255 int masked7 = wsi->mode == LWS_CONNMODE_WS_CLIENT;
256 unsigned char *dropmask = NULL;
257 unsigned char is_masked_bit = 0;
258 size_t orig_len = len;
259 struct lws_tokens eff_buf;
261 if (len == 0 && protocol != LWS_WRITE_CLOSE &&
262 protocol != LWS_WRITE_PING && protocol != LWS_WRITE_PONG) {
263 lwsl_warn("zero length libwebsocket_write attempt\n");
267 if (protocol == LWS_WRITE_HTTP ||
268 protocol == LWS_WRITE_HTTP_FINAL ||
269 protocol == LWS_WRITE_HTTP_HEADERS)
272 /* websocket protocol, either binary or text */
274 if (wsi->state != WSI_STATE_ESTABLISHED)
277 /* if we are continuing a frame that already had its header done */
279 if (wsi->u.ws.inside_frame)
280 goto do_more_inside_frame;
282 wsi->u.ws.clean_buffer = 1;
285 * give a chance to the extensions to modify payload
286 * pre-TX mangling is not allowed to truncate
288 eff_buf.token = (char *)buf;
289 eff_buf.token_len = len;
294 case LWS_WRITE_CLOSE:
297 if (lws_ext_callback_for_each_active(wsi,
298 LWS_EXT_CALLBACK_PAYLOAD_TX, &eff_buf, 0) < 0)
303 * an extension did something we need to keep... for example, if
304 * compression extension, it has already updated its state according
305 * to this being issued
307 if ((char *)buf != eff_buf.token)
309 * extension recreated it:
310 * need to buffer this if not all sent
312 wsi->u.ws.clean_buffer = 0;
314 buf = (unsigned char *)eff_buf.token;
315 len = eff_buf.token_len;
317 switch (wsi->ietf_spec_revision) {
322 dropmask = &buf[0 - pre];
323 is_masked_bit = 0x80;
326 switch (protocol & 0xf) {
328 n = LWS_WS_OPCODE_07__TEXT_FRAME;
330 case LWS_WRITE_BINARY:
331 n = LWS_WS_OPCODE_07__BINARY_FRAME;
333 case LWS_WRITE_CONTINUATION:
334 n = LWS_WS_OPCODE_07__CONTINUATION;
337 case LWS_WRITE_CLOSE:
338 n = LWS_WS_OPCODE_07__CLOSE;
341 * 06+ has a 2-byte status code in network order
342 * we can do this because we demand post-buf
345 if (wsi->u.ws.close_reason) {
346 /* reason codes count as data bytes */
348 buf[0] = wsi->u.ws.close_reason >> 8;
349 buf[1] = wsi->u.ws.close_reason;
354 n = LWS_WS_OPCODE_07__PING;
357 n = LWS_WS_OPCODE_07__PONG;
360 lwsl_warn("lws_write: unknown write opc / protocol\n");
364 if (!(protocol & LWS_WRITE_NO_FIN))
370 buf[-pre + 1] = len | is_masked_bit;
375 buf[-pre + 1] = 126 | is_masked_bit;
376 buf[-pre + 2] = len >> 8;
381 buf[-pre + 1] = 127 | is_masked_bit;
383 buf[-pre + 2] = (len >> 56) & 0x7f;
384 buf[-pre + 3] = len >> 48;
385 buf[-pre + 4] = len >> 40;
386 buf[-pre + 5] = len >> 32;
393 buf[-pre + 6] = len >> 24;
394 buf[-pre + 7] = len >> 16;
395 buf[-pre + 8] = len >> 8;
402 do_more_inside_frame:
405 * Deal with masking if we are in client -> server direction and
406 * the protocol demands it
409 if (wsi->mode == LWS_CONNMODE_WS_CLIENT) {
411 if (!wsi->u.ws.inside_frame)
412 if (libwebsocket_0405_frame_mask_generate(wsi)) {
413 lwsl_err("frame mask generation failed\n");
418 * in v7, just mask the payload
420 if (dropmask) { /* never set if already inside frame */
421 for (n = 4; n < (int)len + 4; n++)
422 dropmask[n] = dropmask[n] ^
423 wsi->u.ws.frame_masking_nonce_04[
424 (wsi->u.ws.frame_mask_index++) & 3];
426 /* copy the frame nonce into place */
427 memcpy(dropmask, wsi->u.ws.frame_masking_nonce_04, 4);
433 case LWS_WRITE_CLOSE:
434 /* lwsl_hexdump(&buf[-pre], len + post); */
436 case LWS_WRITE_HTTP_FINAL:
437 case LWS_WRITE_HTTP_HEADERS:
441 if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) {
442 unsigned char flags = 0;
444 n = LWS_HTTP2_FRAME_TYPE_DATA;
445 if (protocol == LWS_WRITE_HTTP_HEADERS) {
446 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
447 flags = LWS_HTTP2_FLAG_END_HEADERS;
450 if ((protocol == LWS_WRITE_HTTP || protocol == LWS_WRITE_HTTP_FINAL) && wsi->u.http.content_length) {
451 wsi->u.http.content_remain -= len;
452 lwsl_info("%s: content_remain = %lu\n", __func__, wsi->u.http.content_remain);
453 if (!wsi->u.http.content_remain) {
454 lwsl_info("%s: selecting final write mode\n", __func__);
455 protocol = LWS_WRITE_HTTP_FINAL;
459 if ((protocol == LWS_WRITE_HTTP_FINAL || protocol == LWS_WRITE_HTTP_HEADERS) && wsi->u.http2.END_STREAM) {
460 lwsl_info("%s: setting END_STREAM\n", __func__);
461 flags |= LWS_HTTP2_FLAG_END_STREAM;
464 return lws_http2_frame_write(wsi, n, flags, wsi->u.http2.my_stream_id, len, buf);
467 return lws_issue_raw(wsi, (unsigned char *)buf - pre,
473 wsi->u.ws.inside_frame = 1;
476 * give any active extensions a chance to munge the buffer
477 * before send. We pass in a pointer to an lws_tokens struct
478 * prepared with the default buffer and content length that's in
479 * there. Rather than rewrite the default buffer, extensions
480 * that expect to grow the buffer can adapt .token to
481 * point to their own per-connection buffer in the extension
482 * user allocation. By default with no extensions or no
483 * extension callback handling, just the normal input buffer is
484 * used then so it is efficient.
486 * callback returns 1 in case it wants to spill more buffers
488 * This takes care of holding the buffer if send is incomplete, ie,
489 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
490 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
491 * return to the user code how much OF THE USER BUFFER was consumed.
494 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre + post);
498 if (n == len + pre + post) {
499 /* everything in the buffer was handled (or rebuffered...) */
500 wsi->u.ws.inside_frame = 0;
505 * it is how many bytes of user buffer got sent... may be < orig_len
506 * in which case callback when writable has already been arranged
507 * and user code can call libwebsocket_write() again with the rest
511 return n - (pre + post);
514 LWS_VISIBLE int libwebsockets_serve_http_file_fragment(
515 struct libwebsocket_context *context, struct libwebsocket *wsi)
520 while (!lws_send_pipe_choked(wsi)) {
522 if (wsi->truncated_send_len) {
523 if (lws_issue_raw(wsi, wsi->truncated_send_malloc +
524 wsi->truncated_send_offset,
525 wsi->truncated_send_len) < 0) {
526 lwsl_info("closing from libwebsockets_serve_http_file_fragment\n");
532 if (wsi->u.http.filepos == wsi->u.http.filelen)
535 compatible_file_read(n, wsi->u.http.fd, context->service_buffer,
536 sizeof(context->service_buffer));
538 return -1; /* caller will close */
540 wsi->u.http.filepos += n;
541 m = libwebsocket_write(wsi, context->service_buffer, n,
542 wsi->u.http.filepos == wsi->u.http.filelen ? LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
547 /* adjust for what was not sent */
548 compatible_file_seek_cur(wsi->u.http.fd, m - n);
551 if (!wsi->truncated_send_len &&
552 wsi->u.http.filepos == wsi->u.http.filelen) {
553 wsi->state = WSI_STATE_HTTP;
555 if (wsi->protocol->callback)
556 /* ignore callback returned value */
557 user_callback_handle_rxflow(
558 wsi->protocol->callback, context, wsi,
559 LWS_CALLBACK_HTTP_FILE_COMPLETION,
560 wsi->user_space, NULL, 0);
561 return 1; /* >0 indicates completed */
565 lwsl_info("choked before able to send whole file (post)\n");
566 libwebsocket_callback_on_writable(context, wsi);
568 return 0; /* indicates further processing must be done */
572 lws_ssl_capable_read_no_ssl(struct libwebsocket_context *context,
573 struct libwebsocket *wsi, unsigned char *buf, int len)
577 n = recv(wsi->sock, buf, len, 0);
581 lwsl_warn("error on reading from skt\n");
582 return LWS_SSL_CAPABLE_ERROR;
586 lws_ssl_capable_write_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len)
590 n = send(wsi->sock, buf, len, 0);
594 if (LWS_ERRNO == LWS_EAGAIN ||
595 LWS_ERRNO == LWS_EWOULDBLOCK ||
596 LWS_ERRNO == LWS_EINTR) {
597 if (LWS_ERRNO == LWS_EWOULDBLOCK)
598 lws_set_blocking_send(wsi);
600 return LWS_SSL_CAPABLE_MORE_SERVICE;
602 lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
603 return LWS_SSL_CAPABLE_ERROR;