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