deprecate no_buffer_all_partials
[platform/upstream/libwebsockets.git] / lib / output.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 static int
25 libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi)
26 {
27         int n;
28
29         /* fetch the per-frame nonce */
30
31         n = libwebsockets_get_random(wsi->protocol->owning_server,
32                                            wsi->u.ws.frame_masking_nonce_04, 4);
33         if (n != 4) {
34                 lwsl_parser("Unable to read from random device %s %d\n",
35                                                      SYSTEM_RANDOM_FILEPATH, n);
36                 return 1;
37         }
38
39         /* start masking from first byte of masking key buffer */
40         wsi->u.ws.frame_mask_index = 0;
41
42         return 0;
43 }
44
45 #ifdef _DEBUG
46
47 LWS_VISIBLE void lwsl_hexdump(void *vbuf, size_t len)
48 {
49         int n;
50         int m;
51         int start;
52         unsigned char *buf = (unsigned char *)vbuf;
53         char line[80];
54         char *p;
55
56         lwsl_parser("\n");
57
58         for (n = 0; n < len;) {
59                 start = n;
60                 p = line;
61
62                 p += sprintf(p, "%04X: ", start);
63
64                 for (m = 0; m < 16 && n < len; m++)
65                         p += sprintf(p, "%02X ", buf[n++]);
66                 while (m++ < 16)
67                         p += sprintf(p, "   ");
68
69                 p += sprintf(p, "   ");
70
71                 for (m = 0; m < 16 && (start + m) < len; m++) {
72                         if (buf[start + m] >= ' ' && buf[start + m] < 127)
73                                 *p++ = buf[start + m];
74                         else
75                                 *p++ = '.';
76                 }
77                 while (m++ < 16)
78                         *p++ = ' ';
79
80                 *p++ = '\n';
81                 *p = '\0';
82                 lwsl_debug("%s", line);
83         }
84         lwsl_debug("\n");
85 }
86
87 #endif
88
89 /*
90  * notice this returns number of bytes consumed, or -1
91  */
92
93 int lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len)
94 {
95         struct libwebsocket_context *context = wsi->protocol->owning_server;
96         int n;
97         size_t real_len = len;
98         int m;
99         
100         if (!len)
101                 return 0;
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)
105                 return len;
106
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);
112                 assert(0);
113         }
114
115         m = lws_ext_callback_for_each_active(wsi,
116                         LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, &buf, len);
117         if (m < 0)
118                 return -1;
119         if (m) /* handled */ {
120                 n = m;
121                 goto handle_truncated_send;
122         }
123         if (wsi->sock < 0)
124                 lwsl_warn("** error invalid sock but expected to send\n");
125
126         /*
127          * nope, send it on the socket directly
128          */
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);
132
133         switch (n) {
134         case LWS_SSL_CAPABLE_ERROR:
135                 return -1;
136         case LWS_SSL_CAPABLE_MORE_SERVICE:
137                 /* nothing got sent, not fatal, retry the whole thing later */
138                 n = 0;
139                 break;
140         }
141
142 handle_truncated_send:
143         /*
144          * we were already handling a truncated send?
145          */
146         if (wsi->truncated_send_len) {
147                 lwsl_info("***** %x partial send moved on by %d (vs %d)\n",
148                                                              wsi, n, real_len);
149                 wsi->truncated_send_offset += n;
150                 wsi->truncated_send_len -= n;
151
152                 if (!wsi->truncated_send_len) {
153                         lwsl_info("***** %x partial send completed\n", wsi);
154                         /* done with it, but don't free it */
155                         n = real_len;
156                         if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
157                                 lwsl_info("***** %x signalling to close now\n", wsi);
158                                 return -1; /* retry closing now */
159                         }
160                 }
161                 /* always callback on writeable */
162                 libwebsocket_callback_on_writable(
163                                              wsi->protocol->owning_server, wsi);
164
165                 return n;
166         }
167
168         if (n == real_len)
169                 /* what we just sent went out cleanly */
170                 return n;
171
172         if (n && wsi->u.ws.clean_buffer)
173                 /*
174                  * This buffer unaffected by extension rewriting.
175                  * It means the user code is expected to deal with
176                  * partial sends.  (lws knows the header was already
177                  * sent, so on next send will just resume sending
178                  * payload)
179                  */
180                  return n;
181
182         /*
183          * Newly truncated send.  Buffer the remainder (it will get
184          * first priority next time the socket is writable)
185          */
186         lwsl_info("***** %x new partial sent %d from %d total\n",
187                                                       wsi, n, real_len);
188
189         /*
190          *  - if we still have a suitable malloc lying around, use it
191          *  - or, if too small, reallocate it
192          *  - or, if no buffer, create it
193          */
194         if (!wsi->truncated_send_malloc ||
195                         real_len - n > wsi->truncated_send_allocation) {
196                 if (wsi->truncated_send_malloc)
197                         free(wsi->truncated_send_malloc);
198
199                 wsi->truncated_send_allocation = real_len - n;
200                 wsi->truncated_send_malloc = malloc(real_len - n);
201                 if (!wsi->truncated_send_malloc) {
202                         lwsl_err("truncated send: unable to malloc %d\n",
203                                                           real_len - n);
204                         return -1;
205                 }
206         }
207         wsi->truncated_send_offset = 0;
208         wsi->truncated_send_len = real_len - n;
209         memcpy(wsi->truncated_send_malloc, buf + n, real_len - n);
210
211         /* since something buffered, force it to get another chance to send */
212         libwebsocket_callback_on_writable(wsi->protocol->owning_server, wsi);
213
214         return real_len;
215 }
216
217 /**
218  * libwebsocket_write() - Apply protocol then write data to client
219  * @wsi:        Websocket instance (available from user callback)
220  * @buf:        The data to send.  For data being sent on a websocket
221  *              connection (ie, not default http), this buffer MUST have
222  *              LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
223  *              and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
224  *              in the buffer after (buf + len).  This is so the protocol
225  *              header and trailer data can be added in-situ.
226  * @len:        Count of the data bytes in the payload starting from buf
227  * @protocol:   Use LWS_WRITE_HTTP to reply to an http connection, and one
228  *              of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
229  *              data on a websockets connection.  Remember to allow the extra
230  *              bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
231  *              are used.
232  *
233  *      This function provides the way to issue data back to the client
234  *      for both http and websocket protocols.
235  *
236  *      In the case of sending using websocket protocol, be sure to allocate
237  *      valid storage before and after buf as explained above.  This scheme
238  *      allows maximum efficiency of sending data and protocol in a single
239  *      packet while not burdening the user code with any protocol knowledge.
240  *
241  *      Return may be -1 for a fatal error needing connection close, or a
242  *      positive number reflecting the amount of bytes actually sent.  This
243  *      can be less than the requested number of bytes due to OS memory
244  *      pressure at any given time.
245  */
246
247 LWS_VISIBLE int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
248                           size_t len, enum libwebsocket_write_protocol protocol)
249 {
250         int n;
251         int pre = 0;
252         int post = 0;
253         int masked7 = wsi->mode == LWS_CONNMODE_WS_CLIENT;
254         unsigned char *dropmask = NULL;
255         unsigned char is_masked_bit = 0;
256         size_t orig_len = len;
257         struct lws_tokens eff_buf;
258
259         if (len == 0 && protocol != LWS_WRITE_CLOSE &&
260                      protocol != LWS_WRITE_PING && protocol != LWS_WRITE_PONG) {
261                 lwsl_warn("zero length libwebsocket_write attempt\n");
262                 return 0;
263         }
264
265         if (protocol == LWS_WRITE_HTTP)
266                 goto send_raw;
267
268         /* websocket protocol, either binary or text */
269
270         if (wsi->state != WSI_STATE_ESTABLISHED)
271                 return -1;
272
273         /* if we are continuing a frame that already had its header done */
274
275         if (wsi->u.ws.inside_frame)
276                 goto do_more_inside_frame;
277
278         wsi->u.ws.clean_buffer = 1;
279
280         /*
281          * give a chance to the extensions to modify payload
282          * pre-TX mangling is not allowed to truncate
283          */
284         eff_buf.token = (char *)buf;
285         eff_buf.token_len = len;
286
287         switch (protocol) {
288         case LWS_WRITE_PING:
289         case LWS_WRITE_PONG:
290         case LWS_WRITE_CLOSE:
291                 break;
292         default:
293                 if (lws_ext_callback_for_each_active(wsi,
294                                LWS_EXT_CALLBACK_PAYLOAD_TX, &eff_buf, 0) < 0)
295                         return -1;
296         }
297
298         /*
299          * an extension did something we need to keep... for example, if
300          * compression extension, it has already updated its state according
301          * to this being issued
302          */
303         if ((char *)buf != eff_buf.token)
304                 /*
305                  * extension recreated it:
306                  * need to buffer this if not all sent
307                  */
308                 wsi->u.ws.clean_buffer = 0;
309
310         buf = (unsigned char *)eff_buf.token;
311         len = eff_buf.token_len;
312
313         switch (wsi->ietf_spec_revision) {
314         case 13:
315
316                 if (masked7) {
317                         pre += 4;
318                         dropmask = &buf[0 - pre];
319                         is_masked_bit = 0x80;
320                 }
321
322                 switch (protocol & 0xf) {
323                 case LWS_WRITE_TEXT:
324                         n = LWS_WS_OPCODE_07__TEXT_FRAME;
325                         break;
326                 case LWS_WRITE_BINARY:
327                         n = LWS_WS_OPCODE_07__BINARY_FRAME;
328                         break;
329                 case LWS_WRITE_CONTINUATION:
330                         n = LWS_WS_OPCODE_07__CONTINUATION;
331                         break;
332
333                 case LWS_WRITE_CLOSE:
334                         n = LWS_WS_OPCODE_07__CLOSE;
335
336                         /*
337                          * 06+ has a 2-byte status code in network order
338                          * we can do this because we demand post-buf
339                          */
340
341                         if (wsi->u.ws.close_reason) {
342                                 /* reason codes count as data bytes */
343                                 buf -= 2;
344                                 buf[0] = wsi->u.ws.close_reason >> 8;
345                                 buf[1] = wsi->u.ws.close_reason;
346                                 len += 2;
347                         }
348                         break;
349                 case LWS_WRITE_PING:
350                         n = LWS_WS_OPCODE_07__PING;
351                         break;
352                 case LWS_WRITE_PONG:
353                         n = LWS_WS_OPCODE_07__PONG;
354                         break;
355                 default:
356                         lwsl_warn("lws_write: unknown write opc / protocol\n");
357                         return -1;
358                 }
359
360                 if (!(protocol & LWS_WRITE_NO_FIN))
361                         n |= 1 << 7;
362
363                 if (len < 126) {
364                         pre += 2;
365                         buf[-pre] = n;
366                         buf[-pre + 1] = len | is_masked_bit;
367                 } else {
368                         if (len < 65536) {
369                                 pre += 4;
370                                 buf[-pre] = n;
371                                 buf[-pre + 1] = 126 | is_masked_bit;
372                                 buf[-pre + 2] = len >> 8;
373                                 buf[-pre + 3] = len;
374                         } else {
375                                 pre += 10;
376                                 buf[-pre] = n;
377                                 buf[-pre + 1] = 127 | is_masked_bit;
378 #if defined __LP64__
379                                         buf[-pre + 2] = (len >> 56) & 0x7f;
380                                         buf[-pre + 3] = len >> 48;
381                                         buf[-pre + 4] = len >> 40;
382                                         buf[-pre + 5] = len >> 32;
383 #else
384                                         buf[-pre + 2] = 0;
385                                         buf[-pre + 3] = 0;
386                                         buf[-pre + 4] = 0;
387                                         buf[-pre + 5] = 0;
388 #endif
389                                 buf[-pre + 6] = len >> 24;
390                                 buf[-pre + 7] = len >> 16;
391                                 buf[-pre + 8] = len >> 8;
392                                 buf[-pre + 9] = len;
393                         }
394                 }
395                 break;
396         }
397
398 do_more_inside_frame:
399
400         /*
401          * Deal with masking if we are in client -> server direction and
402          * the protocol demands it
403          */
404
405         if (wsi->mode == LWS_CONNMODE_WS_CLIENT) {
406
407                 if (!wsi->u.ws.inside_frame)
408                         if (libwebsocket_0405_frame_mask_generate(wsi)) {
409                                 lwsl_err("frame mask generation failed\n");
410                                 return -1;
411                         }
412
413                 /*
414                  * in v7, just mask the payload
415                  */
416                 if (dropmask) { /* never set if already inside frame */
417                         for (n = 4; n < (int)len + 4; n++)
418                                 dropmask[n] = dropmask[n] ^
419                                 wsi->u.ws.frame_masking_nonce_04[
420                                         (wsi->u.ws.frame_mask_index++) & 3];
421
422                         /* copy the frame nonce into place */
423                         memcpy(dropmask, wsi->u.ws.frame_masking_nonce_04, 4);
424                 }
425         }
426
427 send_raw:
428         switch (protocol) {
429         case LWS_WRITE_CLOSE:
430 /*              lwsl_hexdump(&buf[-pre], len + post); */
431         case LWS_WRITE_HTTP:
432         case LWS_WRITE_PONG:
433         case LWS_WRITE_PING:
434                 return lws_issue_raw(wsi, (unsigned char *)buf - pre,
435                                                               len + pre + post);
436         default:
437                 break;
438         }
439
440         wsi->u.ws.inside_frame = 1;
441
442         /*
443          * give any active extensions a chance to munge the buffer
444          * before send.  We pass in a pointer to an lws_tokens struct
445          * prepared with the default buffer and content length that's in
446          * there.  Rather than rewrite the default buffer, extensions
447          * that expect to grow the buffer can adapt .token to
448          * point to their own per-connection buffer in the extension
449          * user allocation.  By default with no extensions or no
450          * extension callback handling, just the normal input buffer is
451          * used then so it is efficient.
452          *
453          * callback returns 1 in case it wants to spill more buffers
454          *
455          * This takes care of holding the buffer if send is incomplete, ie,
456          * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
457          * the buffer).  If wsi->u.ws.clean_buffer is 1, it will instead
458          * return to the user code how much OF THE USER BUFFER was consumed.
459          */
460
461         n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre + post);
462         if (n <= 0)
463                 return n;
464
465         if (n == len + pre + post) {
466                 /* everything in the buffer was handled (or rebuffered...) */
467                 wsi->u.ws.inside_frame = 0;
468                 return orig_len;
469         }
470
471         /*
472          * it is how many bytes of user buffer got sent... may be < orig_len
473          * in which case callback when writable has already been arranged
474          * and user code can call libwebsocket_write() again with the rest
475          * later.
476          */
477
478         return n - (pre + post);
479 }
480
481 LWS_VISIBLE int libwebsockets_serve_http_file_fragment(
482                 struct libwebsocket_context *context, struct libwebsocket *wsi)
483 {
484         int n;
485         int m;
486
487         while (!lws_send_pipe_choked(wsi)) {
488
489                 if (wsi->truncated_send_len) {
490                         if (lws_issue_raw(wsi, wsi->truncated_send_malloc +
491                                         wsi->truncated_send_offset,
492                                                        wsi->truncated_send_len) < 0) {
493                                 lwsl_info("closing from libwebsockets_serve_http_file_fragment\n");
494                                 return -1;
495                         }
496                         continue;
497                 }
498
499                 if (wsi->u.http.filepos == wsi->u.http.filelen)
500                         goto all_sent;
501
502                 compatible_file_read(n, wsi->u.http.fd, context->service_buffer,
503                                                sizeof(context->service_buffer));
504                 if (n < 0)
505                         return -1; /* caller will close */
506                 if (n) {
507                         m = libwebsocket_write(wsi, context->service_buffer, n,
508                                                                 LWS_WRITE_HTTP);
509                         if (m < 0)
510                                 return -1;
511
512                         wsi->u.http.filepos += m;
513                         if (m != n)
514                                 /* adjust for what was not sent */
515                                 compatible_file_seek_cur(wsi->u.http.fd, m - n);
516                 }
517 all_sent:
518                 if (!wsi->truncated_send_len &&
519                                 wsi->u.http.filepos == wsi->u.http.filelen) {
520                         wsi->state = WSI_STATE_HTTP;
521
522                         if (wsi->protocol->callback)
523                                 /* ignore callback returned value */
524                                 user_callback_handle_rxflow(
525                                         wsi->protocol->callback, context, wsi,
526                                         LWS_CALLBACK_HTTP_FILE_COMPLETION,
527                                         wsi->user_space, NULL, 0);
528                         return 1;  /* >0 indicates completed */
529                 }
530         }
531
532         lwsl_info("choked before able to send whole file (post)\n");
533         libwebsocket_callback_on_writable(context, wsi);
534
535         return 0; /* indicates further processing must be done */
536 }
537
538 LWS_VISIBLE int
539 lws_ssl_capable_read_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len)
540 {
541         int n;
542
543         n = recv(wsi->sock, buf, len, 0);
544         if (n >= 0)
545                 return n;
546
547         lwsl_warn("error on reading from skt\n");
548         return LWS_SSL_CAPABLE_ERROR;
549 }
550
551 LWS_VISIBLE int
552 lws_ssl_capable_write_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len)
553 {
554         int n;
555         
556         n = send(wsi->sock, buf, len, 0);
557         if (n >= 0)
558                 return n;
559
560         if (LWS_ERRNO == LWS_EAGAIN ||
561             LWS_ERRNO == LWS_EWOULDBLOCK ||
562             LWS_ERRNO == LWS_EINTR) {
563                 if (LWS_ERRNO == LWS_EWOULDBLOCK)
564                         lws_set_blocking_send(wsi);
565
566                 return LWS_SSL_CAPABLE_MORE_SERVICE;
567         }
568         lwsl_debug("ERROR writing len %d to skt %d\n", len, n);
569         return LWS_SSL_CAPABLE_ERROR;
570 }