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;
103 if (wsi->truncated_send_len && (buf < wsi->truncated_send_malloc ||
104 buf > (wsi->truncated_send_malloc +
105 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 lwsl_warn("** error invalid sock but expected to send\n");
123 * nope, send it on the socket directly
125 lws_latency_pre(context, wsi);
127 n = lws_ssl_capable_write(wsi, buf, len);
128 lws_latency(context, wsi, "send lws_issue_raw", n, n == len);
130 case LWS_SSL_CAPABLE_ERROR:
132 case LWS_SSL_CAPABLE_MORE_SERVICE:
134 goto handle_truncated_send;
137 handle_truncated_send:
139 * already handling a truncated send?
141 if (wsi->truncated_send_len) {
142 lwsl_info("***** %x partial send moved on by %d (vs %d)\n",
144 wsi->truncated_send_offset += n;
145 wsi->truncated_send_len -= n;
147 if (!wsi->truncated_send_len) {
148 lwsl_info("***** %x partial send completed\n", wsi);
149 /* done with it, but don't free it */
152 libwebsocket_callback_on_writable(
153 wsi->protocol->owning_server, wsi);
159 if (n && wsi->u.ws.clean_buffer)
161 * This buffer unaffected by extension rewriting.
162 * It means the user code is expected to deal with
163 * partial sends. (lws knows the header was already
164 * sent, so on next send will just resume sending
170 * Newly truncated send. Buffer the remainder (it will get
171 * first priority next time the socket is writable)
173 lwsl_info("***** %x new partial sent %d from %d total\n",
177 * - if we still have a suitable malloc lying around, use it
178 * - or, if too small, reallocate it
179 * - or, if no buffer, create it
181 if (!wsi->truncated_send_malloc ||
182 real_len - n > wsi->truncated_send_allocation) {
183 if (wsi->truncated_send_malloc)
184 free(wsi->truncated_send_malloc);
186 wsi->truncated_send_allocation = real_len - n;
187 wsi->truncated_send_malloc = malloc(real_len - n);
188 if (!wsi->truncated_send_malloc) {
190 "truncated send: unable to malloc %d\n",
195 wsi->truncated_send_offset = 0;
196 wsi->truncated_send_len = real_len - n;
197 memcpy(wsi->truncated_send_malloc, buf + n, real_len - n);
199 libwebsocket_callback_on_writable(
200 wsi->protocol->owning_server, wsi);
209 * libwebsocket_write() - Apply protocol then write data to client
210 * @wsi: Websocket instance (available from user callback)
211 * @buf: The data to send. For data being sent on a websocket
212 * connection (ie, not default http), this buffer MUST have
213 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
214 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
215 * in the buffer after (buf + len). This is so the protocol
216 * header and trailer data can be added in-situ.
217 * @len: Count of the data bytes in the payload starting from buf
218 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
219 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
220 * data on a websockets connection. Remember to allow the extra
221 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
224 * This function provides the way to issue data back to the client
225 * for both http and websocket protocols.
227 * In the case of sending using websocket protocol, be sure to allocate
228 * valid storage before and after buf as explained above. This scheme
229 * allows maximum efficiency of sending data and protocol in a single
230 * packet while not burdening the user code with any protocol knowledge.
232 * Return may be -1 for a fatal error needing connection close, or a
233 * positive number reflecting the amount of bytes actually sent. This
234 * can be less than the requested number of bytes due to OS memory
235 * pressure at any given time.
238 LWS_VISIBLE int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
239 size_t len, enum libwebsocket_write_protocol protocol)
244 int masked7 = wsi->mode == LWS_CONNMODE_WS_CLIENT;
245 unsigned char *dropmask = NULL;
246 unsigned char is_masked_bit = 0;
247 size_t orig_len = len;
248 struct lws_tokens eff_buf;
250 if (len == 0 && protocol != LWS_WRITE_CLOSE &&
251 protocol != LWS_WRITE_PING && protocol != LWS_WRITE_PONG) {
252 lwsl_warn("zero length libwebsocket_write attempt\n");
256 if (protocol == LWS_WRITE_HTTP)
259 /* websocket protocol, either binary or text */
261 if (wsi->state != WSI_STATE_ESTABLISHED)
264 /* if we are continuing a frame that already had its header done */
266 if (wsi->u.ws.inside_frame)
267 goto do_more_inside_frame;
269 /* if he wants all partials buffered, never have a clean_buffer */
270 wsi->u.ws.clean_buffer = !wsi->protocol->no_buffer_all_partial_tx;
273 * give a chance to the extensions to modify payload
274 * pre-TX mangling is not allowed to truncate
276 eff_buf.token = (char *)buf;
277 eff_buf.token_len = len;
282 case LWS_WRITE_CLOSE:
285 if (lws_ext_callback_for_each_active(wsi,
286 LWS_EXT_CALLBACK_PAYLOAD_TX, &eff_buf, 0) < 0)
291 * an extension did something we need to keep... for example, if
292 * compression extension, it has already updated its state according
293 * to this being issued
295 if ((char *)buf != eff_buf.token)
297 * extension recreated it:
298 * need to buffer this if not all sent
300 wsi->u.ws.clean_buffer = 0;
302 buf = (unsigned char *)eff_buf.token;
303 len = eff_buf.token_len;
305 switch (wsi->ietf_spec_revision) {
310 dropmask = &buf[0 - pre];
311 is_masked_bit = 0x80;
314 switch (protocol & 0xf) {
316 n = LWS_WS_OPCODE_07__TEXT_FRAME;
318 case LWS_WRITE_BINARY:
319 n = LWS_WS_OPCODE_07__BINARY_FRAME;
321 case LWS_WRITE_CONTINUATION:
322 n = LWS_WS_OPCODE_07__CONTINUATION;
325 case LWS_WRITE_CLOSE:
326 n = LWS_WS_OPCODE_07__CLOSE;
329 * 06+ has a 2-byte status code in network order
330 * we can do this because we demand post-buf
333 if (wsi->u.ws.close_reason) {
334 /* reason codes count as data bytes */
336 buf[0] = wsi->u.ws.close_reason >> 8;
337 buf[1] = wsi->u.ws.close_reason;
342 n = LWS_WS_OPCODE_07__PING;
345 n = LWS_WS_OPCODE_07__PONG;
348 lwsl_warn("lws_write: unknown write opc / protocol\n");
352 if (!(protocol & LWS_WRITE_NO_FIN))
358 buf[-pre + 1] = len | is_masked_bit;
363 buf[-pre + 1] = 126 | is_masked_bit;
364 buf[-pre + 2] = len >> 8;
369 buf[-pre + 1] = 127 | is_masked_bit;
371 buf[-pre + 2] = (len >> 56) & 0x7f;
372 buf[-pre + 3] = len >> 48;
373 buf[-pre + 4] = len >> 40;
374 buf[-pre + 5] = len >> 32;
381 buf[-pre + 6] = len >> 24;
382 buf[-pre + 7] = len >> 16;
383 buf[-pre + 8] = len >> 8;
390 do_more_inside_frame:
393 * Deal with masking if we are in client -> server direction and
394 * the protocol demands it
397 if (wsi->mode == LWS_CONNMODE_WS_CLIENT) {
399 if (!wsi->u.ws.inside_frame)
400 if (libwebsocket_0405_frame_mask_generate(wsi)) {
401 lwsl_err("frame mask generation failed\n");
406 * in v7, just mask the payload
408 if (dropmask) { /* never set if already inside frame */
409 for (n = 4; n < (int)len + 4; n++)
410 dropmask[n] = dropmask[n] ^
411 wsi->u.ws.frame_masking_nonce_04[
412 (wsi->u.ws.frame_mask_index++) & 3];
414 /* copy the frame nonce into place */
415 memcpy(dropmask, wsi->u.ws.frame_masking_nonce_04, 4);
421 case LWS_WRITE_CLOSE:
422 /* lwsl_hexdump(&buf[-pre], len + post); */
426 return lws_issue_raw(wsi, (unsigned char *)buf - pre,
432 wsi->u.ws.inside_frame = 1;
435 * give any active extensions a chance to munge the buffer
436 * before send. We pass in a pointer to an lws_tokens struct
437 * prepared with the default buffer and content length that's in
438 * there. Rather than rewrite the default buffer, extensions
439 * that expect to grow the buffer can adapt .token to
440 * point to their own per-connection buffer in the extension
441 * user allocation. By default with no extensions or no
442 * extension callback handling, just the normal input buffer is
443 * used then so it is efficient.
445 * callback returns 1 in case it wants to spill more buffers
447 * This takes care of holding the buffer if send is incomplete, ie,
448 * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
449 * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead
450 * return to the user code how much OF THE USER BUFFER was consumed.
453 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre + post);
457 if (n == len + pre + post) {
458 /* everything in the buffer was handled (or rebuffered...) */
459 wsi->u.ws.inside_frame = 0;
464 * it is how many bytes of user buffer got sent... may be < orig_len
465 * in which case callback when writable has already been arranged
466 * and user code can call libwebsocket_write() again with the rest
470 return n - (pre + post);
473 LWS_VISIBLE int libwebsockets_serve_http_file_fragment(
474 struct libwebsocket_context *context, struct libwebsocket *wsi)
479 while (!lws_send_pipe_choked(wsi)) {
481 if (wsi->truncated_send_len) {
482 lws_issue_raw(wsi, wsi->truncated_send_malloc +
483 wsi->truncated_send_offset,
484 wsi->truncated_send_len);
488 if (wsi->u.http.filepos == wsi->u.http.filelen)
491 compatible_file_read(n, wsi->u.http.fd, context->service_buffer,
492 sizeof(context->service_buffer));
494 return -1; /* caller will close */
496 m = libwebsocket_write(wsi, context->service_buffer, n,
501 wsi->u.http.filepos += m;
503 /* adjust for what was not sent */
504 compatible_file_seek_cur(wsi->u.http.fd, m - n);
507 if (!wsi->truncated_send_len &&
508 wsi->u.http.filepos == wsi->u.http.filelen) {
509 wsi->state = WSI_STATE_HTTP;
511 if (wsi->protocol->callback)
512 /* ignore callback returned value */
513 user_callback_handle_rxflow(
514 wsi->protocol->callback, context, wsi,
515 LWS_CALLBACK_HTTP_FILE_COMPLETION,
516 wsi->user_space, NULL, 0);
517 return 1; /* >0 indicates completed */
521 lwsl_info("choked before able to send whole file (post)\n");
522 libwebsocket_callback_on_writable(context, wsi);
524 return 0; /* indicates further processing must be done */
528 lws_ssl_capable_read_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len)
532 n = recv(wsi->sock, buf, len, 0);
534 lwsl_warn("error on reading from skt\n");
535 return LWS_SSL_CAPABLE_ERROR;
542 lws_ssl_capable_write_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len)
546 n = send(wsi->sock, buf, len, MSG_NOSIGNAL);
548 if (LWS_ERRNO == LWS_EAGAIN ||
549 LWS_ERRNO == LWS_EWOULDBLOCK ||
550 LWS_ERRNO == LWS_EINTR) {
551 if (LWS_ERRNO == LWS_EWOULDBLOCK)
552 lws_set_blocking_send(wsi);
553 return LWS_SSL_CAPABLE_MORE_SERVICE;
555 lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
556 return LWS_SSL_CAPABLE_ERROR;