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