9f72443e058f0910e0565f8770308016e2d3f85d
[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[0] = 0;
29         wsi->u.ws.mask[1] = 0;
30         wsi->u.ws.mask[2] = 0;
31         wsi->u.ws.mask[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, 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.mask_idx = 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         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
99         size_t real_len = len;
100         unsigned int n;
101         int m;
102
103         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_WRITE, 1);
104
105         if (!len)
106                 return 0;
107         /* just ignore sends after we cleared the truncation buffer */
108         if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
109             !wsi->trunc_len)
110                 return len;
111
112         if (wsi->trunc_len && (buf < wsi->trunc_alloc ||
113             buf > (wsi->trunc_alloc + wsi->trunc_len + wsi->trunc_offset))) {
114                 char dump[20];
115                 strncpy(dump, (char *)buf, sizeof(dump) - 1);
116                 dump[sizeof(dump) - 1] = '\0';
117 #if defined(LWS_WITH_ESP8266)
118                 lwsl_err("****** %p: Sending new %lu (%s), pending truncated ...\n",
119                          wsi, (unsigned long)len, dump);
120 #else
121                 lwsl_err("****** %p: Sending new %lu (%s), pending truncated ...\n"
122                          "       It's illegal to do an lws_write outside of\n"
123                          "       the writable callback: fix your code",
124                          wsi, (unsigned long)len, dump);
125 #endif
126                 assert(0);
127
128                 return -1;
129         }
130
131         m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_DO_SEND, &buf, len);
132         if (m < 0)
133                 return -1;
134         if (m) /* handled */ {
135                 n = m;
136                 goto handle_truncated_send;
137         }
138
139         if (!lws_socket_is_valid(wsi->desc.sockfd))
140                 lwsl_warn("** error invalid sock but expected to send\n");
141
142         /* limit sending */
143         if (wsi->protocol->tx_packet_size)
144                 n = wsi->protocol->tx_packet_size;
145         else {
146                 n = wsi->protocol->rx_buffer_size;
147                 if (!n)
148                         n = context->pt_serv_buf_size;
149         }
150         n += LWS_PRE + 4;
151         if (n > len)
152                 n = len;
153 #if defined(LWS_WITH_ESP8266)   
154         if (wsi->pending_send_completion) {
155                 n = 0;
156                 goto handle_truncated_send;
157         }
158 #endif
159
160         /* nope, send it on the socket directly */
161         lws_latency_pre(context, wsi);
162         n = lws_ssl_capable_write(wsi, buf, n);
163         lws_latency(context, wsi, "send lws_issue_raw", n, n == len);
164
165         //lwsl_notice("lws_ssl_capable_write: %d\n", n);
166
167         switch (n) {
168         case LWS_SSL_CAPABLE_ERROR:
169                 /* we're going to close, let close know sends aren't possible */
170                 wsi->socket_is_permanently_unusable = 1;
171                 return -1;
172         case LWS_SSL_CAPABLE_MORE_SERVICE:
173                 /* nothing got sent, not fatal, retry the whole thing later */
174                 n = 0;
175                 break;
176         }
177
178 handle_truncated_send:
179         /*
180          * we were already handling a truncated send?
181          */
182         if (wsi->trunc_len) {
183                 lwsl_info("%p partial adv %d (vs %ld)\n", wsi, n, (long)real_len);
184                 wsi->trunc_offset += n;
185                 wsi->trunc_len -= n;
186
187                 if (!wsi->trunc_len) {
188                         lwsl_info("***** %p partial send completed\n", wsi);
189                         /* done with it, but don't free it */
190                         n = real_len;
191                         if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
192                                 lwsl_info("***** %p signalling to close now\n", wsi);
193                                 return -1; /* retry closing now */
194                         }
195                 }
196                 /* always callback on writeable */
197                 lws_callback_on_writable(wsi);
198
199                 return n;
200         }
201
202         if ((unsigned int)n == real_len)
203                 /* what we just sent went out cleanly */
204                 return n;
205
206         /*
207          * Newly truncated send.  Buffer the remainder (it will get
208          * first priority next time the socket is writable)
209          */
210         lwsl_debug("%p new partial sent %d from %lu total\n", wsi, n,
211                     (unsigned long)real_len);
212
213         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITE_PARTIALS, 1);
214         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, n);
215
216         /*
217          *  - if we still have a suitable malloc lying around, use it
218          *  - or, if too small, reallocate it
219          *  - or, if no buffer, create it
220          */
221         if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {
222                 lws_free(wsi->trunc_alloc);
223
224                 wsi->trunc_alloc_len = real_len - n;
225                 wsi->trunc_alloc = lws_malloc(real_len - n);
226                 if (!wsi->trunc_alloc) {
227                         lwsl_err("truncated send: unable to malloc %lu\n",
228                                  (unsigned long)(real_len - n));
229                         return -1;
230                 }
231         }
232         wsi->trunc_offset = 0;
233         wsi->trunc_len = real_len - n;
234         memcpy(wsi->trunc_alloc, buf + n, real_len - n);
235
236         /* since something buffered, force it to get another chance to send */
237         lws_callback_on_writable(wsi);
238
239         return real_len;
240 }
241
242 LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len,
243                           enum lws_write_protocol wp)
244 {
245         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
246         int masked7 = (wsi->mode == LWSCM_WS_CLIENT);
247         unsigned char is_masked_bit = 0;
248         unsigned char *dropmask = NULL;
249         struct lws_tokens eff_buf;
250         int pre = 0, n;
251         size_t orig_len = len;
252
253         if (wsi->parent_carries_io) {
254                 struct lws_write_passthru pas;
255
256                 pas.buf = buf;
257                 pas.len = len;
258                 pas.wp = wp;
259                 pas.wsi = wsi;
260
261                 if (wsi->parent->protocol->callback(wsi->parent,
262                                 LWS_CALLBACK_CHILD_WRITE_VIA_PARENT,
263                                 wsi->parent->user_space,
264                                 (void *)&pas, 0))
265                         return 1;
266
267                 return len;
268         }
269
270         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_LWS_WRITE, 1);
271
272         if ((int)len < 0) {
273                 lwsl_err("%s: suspicious len int %d, ulong %lu\n", __func__,
274                                 (int)len, (unsigned long)len);
275                 return -1;
276         }
277
278         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_WRITE, len);
279
280 #ifdef LWS_WITH_ACCESS_LOG
281         wsi->access_log.sent += len;
282 #endif
283         if (wsi->vhost)
284                 wsi->vhost->conn_stats.tx += len;
285
286         if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) {
287                 /* remove us from the list */
288                 struct lws **w = &pt->tx_draining_ext_list;
289                 lwsl_debug("%s: TX EXT DRAINING: Remove from list\n", __func__);
290                 wsi->u.ws.tx_draining_ext = 0;
291                 /* remove us from context draining ext list */
292                 while (*w) {
293                         if (*w == wsi) {
294                                 *w = wsi->u.ws.tx_draining_ext_list;
295                                 break;
296                         }
297                         w = &((*w)->u.ws.tx_draining_ext_list);
298                 }
299                 wsi->u.ws.tx_draining_ext_list = NULL;
300                 wp = (wsi->u.ws.tx_draining_stashed_wp & 0xc0) |
301                                 LWS_WRITE_CONTINUATION;
302
303                 lwsl_ext("FORCED draining wp to 0x%02X\n", wp);
304         }
305
306         lws_restart_ws_ping_pong_timer(wsi);
307
308         if (wp == LWS_WRITE_HTTP ||
309             wp == LWS_WRITE_HTTP_FINAL ||
310             wp == LWS_WRITE_HTTP_HEADERS)
311                 goto send_raw;
312
313         /* if not in a state to send stuff, then just send nothing */
314
315         if (wsi->state != LWSS_ESTABLISHED &&
316             ((wsi->state != LWSS_RETURNED_CLOSE_ALREADY &&
317               wsi->state != LWSS_AWAITING_CLOSE_ACK) ||
318                             wp != LWS_WRITE_CLOSE))
319                 return 0;
320
321         /* if we are continuing a frame that already had its header done */
322
323         if (wsi->u.ws.inside_frame) {
324                 lwsl_debug("INSIDE FRAME\n");
325                 goto do_more_inside_frame;
326         }
327
328         wsi->u.ws.clean_buffer = 1;
329
330         /*
331          * give a chance to the extensions to modify payload
332          * the extension may decide to produce unlimited payload erratically
333          * (eg, compression extension), so we require only that if he produces
334          * something, it will be a complete fragment of the length known at
335          * the time (just the fragment length known), and if he has
336          * more we will come back next time he is writeable and allow him to
337          * produce more fragments until he's drained.
338          *
339          * This allows what is sent each time it is writeable to be limited to
340          * a size that can be sent without partial sends or blocking, allows
341          * interleaving of control frames and other connection service.
342          */
343         eff_buf.token = (char *)buf;
344         eff_buf.token_len = len;
345
346         switch ((int)wp) {
347         case LWS_WRITE_PING:
348         case LWS_WRITE_PONG:
349         case LWS_WRITE_CLOSE:
350                 break;
351         default:
352                 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &eff_buf, wp);
353                 if (n < 0)
354                         return -1;
355
356                 if (n && eff_buf.token_len) {
357                         /* extension requires further draining */
358                         wsi->u.ws.tx_draining_ext = 1;
359                         wsi->u.ws.tx_draining_ext_list = pt->tx_draining_ext_list;
360                         pt->tx_draining_ext_list = wsi;
361                         /* we must come back to do more */
362                         lws_callback_on_writable(wsi);
363                         /*
364                          * keep a copy of the write type for the overall
365                          * action that has provoked generation of these
366                          * fragments, so the last guy can use its FIN state.
367                          */
368                         wsi->u.ws.tx_draining_stashed_wp = wp;
369                         /* this is definitely not actually the last fragment
370                          * because the extension asserted he has more coming
371                          * So make sure this intermediate one doesn't go out
372                          * with a FIN.
373                          */
374                         wp |= LWS_WRITE_NO_FIN;
375                 }
376
377                 if (eff_buf.token_len && wsi->u.ws.stashed_write_pending) {
378                         wsi->u.ws.stashed_write_pending = 0;
379                         wp = (wp &0xc0) | (int)wsi->u.ws.stashed_write_type;
380                 }
381         }
382
383         /*
384          * an extension did something we need to keep... for example, if
385          * compression extension, it has already updated its state according
386          * to this being issued
387          */
388         if ((char *)buf != eff_buf.token) {
389                 /*
390                  * ext might eat it, but no have anything to issue yet
391                  * in that case we have to follow his lead, but stash and
392                  * replace the write type that was lost here the first time.
393                  */
394                 if (len && !eff_buf.token_len) {
395                         if (!wsi->u.ws.stashed_write_pending)
396                                 wsi->u.ws.stashed_write_type = (char)wp & 0x3f;
397                         wsi->u.ws.stashed_write_pending = 1;
398                         return len;
399                 }
400                 /*
401                  * extension recreated it:
402                  * need to buffer this if not all sent
403                  */
404                 wsi->u.ws.clean_buffer = 0;
405         }
406
407         buf = (unsigned char *)eff_buf.token;
408         len = eff_buf.token_len;
409
410         switch (wsi->ietf_spec_revision) {
411         case 13:
412                 if (masked7) {
413                         pre += 4;
414                         dropmask = &buf[0 - pre];
415                         is_masked_bit = 0x80;
416                 }
417
418                 switch (wp & 0xf) {
419                 case LWS_WRITE_TEXT:
420                         n = LWSWSOPC_TEXT_FRAME;
421                         break;
422                 case LWS_WRITE_BINARY:
423                         n = LWSWSOPC_BINARY_FRAME;
424                         break;
425                 case LWS_WRITE_CONTINUATION:
426                         n = LWSWSOPC_CONTINUATION;
427                         break;
428
429                 case LWS_WRITE_CLOSE:
430                         n = LWSWSOPC_CLOSE;
431                         break;
432                 case LWS_WRITE_PING:
433                         n = LWSWSOPC_PING;
434                         break;
435                 case LWS_WRITE_PONG:
436                         n = LWSWSOPC_PONG;
437                         break;
438                 default:
439                         lwsl_warn("lws_write: unknown write opc / wp\n");
440                         return -1;
441                 }
442
443                 if (!(wp & LWS_WRITE_NO_FIN))
444                         n |= 1 << 7;
445
446                 if (len < 126) {
447                         pre += 2;
448                         buf[-pre] = n;
449                         buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
450                 } else {
451                         if (len < 65536) {
452                                 pre += 4;
453                                 buf[-pre] = n;
454                                 buf[-pre + 1] = 126 | is_masked_bit;
455                                 buf[-pre + 2] = (unsigned char)(len >> 8);
456                                 buf[-pre + 3] = (unsigned char)len;
457                         } else {
458                                 pre += 10;
459                                 buf[-pre] = n;
460                                 buf[-pre + 1] = 127 | is_masked_bit;
461 #if defined __LP64__
462                                         buf[-pre + 2] = (len >> 56) & 0x7f;
463                                         buf[-pre + 3] = len >> 48;
464                                         buf[-pre + 4] = len >> 40;
465                                         buf[-pre + 5] = len >> 32;
466 #else
467                                         buf[-pre + 2] = 0;
468                                         buf[-pre + 3] = 0;
469                                         buf[-pre + 4] = 0;
470                                         buf[-pre + 5] = 0;
471 #endif
472                                 buf[-pre + 6] = (unsigned char)(len >> 24);
473                                 buf[-pre + 7] = (unsigned char)(len >> 16);
474                                 buf[-pre + 8] = (unsigned char)(len >> 8);
475                                 buf[-pre + 9] = (unsigned char)len;
476                         }
477                 }
478                 break;
479         }
480
481 do_more_inside_frame:
482
483         /*
484          * Deal with masking if we are in client -> server direction and
485          * the wp demands it
486          */
487
488         if (masked7) {
489                 if (!wsi->u.ws.inside_frame)
490                         if (lws_0405_frame_mask_generate(wsi)) {
491                                 lwsl_err("frame mask generation failed\n");
492                                 return -1;
493                         }
494
495                 /*
496                  * in v7, just mask the payload
497                  */
498                 if (dropmask) { /* never set if already inside frame */
499                         for (n = 4; n < (int)len + 4; n++)
500                                 dropmask[n] = dropmask[n] ^ wsi->u.ws.mask[
501                                         (wsi->u.ws.mask_idx++) & 3];
502
503                         /* copy the frame nonce into place */
504                         memcpy(dropmask, wsi->u.ws.mask, 4);
505                 }
506         }
507
508 send_raw:
509         switch ((int)wp) {
510         case LWS_WRITE_CLOSE:
511 /*              lwsl_hexdump(&buf[-pre], len); */
512         case LWS_WRITE_HTTP:
513         case LWS_WRITE_HTTP_FINAL:
514         case LWS_WRITE_HTTP_HEADERS:
515         case LWS_WRITE_PONG:
516         case LWS_WRITE_PING:
517 #ifdef LWS_USE_HTTP2
518                 if (wsi->mode == LWSCM_HTTP2_SERVING) {
519                         unsigned char flags = 0;
520
521                         n = LWS_HTTP2_FRAME_TYPE_DATA;
522                         if (wp == LWS_WRITE_HTTP_HEADERS) {
523                                 n = LWS_HTTP2_FRAME_TYPE_HEADERS;
524                                 flags = LWS_HTTP2_FLAG_END_HEADERS;
525                                 if (wsi->u.http2.send_END_STREAM)
526                                         flags |= LWS_HTTP2_FLAG_END_STREAM;
527                         }
528
529                         if ((wp == LWS_WRITE_HTTP ||
530                              wp == LWS_WRITE_HTTP_FINAL) &&
531                             wsi->u.http.content_length) {
532                                 wsi->u.http.content_remain -= len;
533                                 lwsl_info("%s: content_remain = %llu\n", __func__,
534                                           (unsigned long long)wsi->u.http.content_remain);
535                                 if (!wsi->u.http.content_remain) {
536                                         lwsl_info("%s: selecting final write mode\n", __func__);
537                                         wp = LWS_WRITE_HTTP_FINAL;
538                                 }
539                         }
540
541                         if (wp == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) {
542                                 lwsl_info("%s: setting END_STREAM\n", __func__);
543                                 flags |= LWS_HTTP2_FLAG_END_STREAM;
544                         }
545
546                         return lws_http2_frame_write(wsi, n, flags,
547                                         wsi->u.http2.my_stream_id, len, buf);
548                 }
549 #endif
550                 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
551         default:
552                 break;
553         }
554
555         /*
556          * give any active extensions a chance to munge the buffer
557          * before send.  We pass in a pointer to an lws_tokens struct
558          * prepared with the default buffer and content length that's in
559          * there.  Rather than rewrite the default buffer, extensions
560          * that expect to grow the buffer can adapt .token to
561          * point to their own per-connection buffer in the extension
562          * user allocation.  By default with no extensions or no
563          * extension callback handling, just the normal input buffer is
564          * used then so it is efficient.
565          *
566          * callback returns 1 in case it wants to spill more buffers
567          *
568          * This takes care of holding the buffer if send is incomplete, ie,
569          * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with
570          * the buffer).  If wsi->u.ws.clean_buffer is 1, it will instead
571          * return to the user code how much OF THE USER BUFFER was consumed.
572          */
573
574         n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
575         wsi->u.ws.inside_frame = 1;
576         if (n <= 0)
577                 return n;
578
579         if (n == (int)len + pre) {
580                 /* everything in the buffer was handled (or rebuffered...) */
581                 wsi->u.ws.inside_frame = 0;
582                 return orig_len;
583         }
584
585         /*
586          * it is how many bytes of user buffer got sent... may be < orig_len
587          * in which case callback when writable has already been arranged
588          * and user code can call lws_write() again with the rest
589          * later.
590          */
591
592         return n - pre;
593 }
594
595 LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)
596 {
597         struct lws_context *context = wsi->context;
598         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
599         struct lws_process_html_args args;
600         lws_filepos_t amount, poss;
601         unsigned char *p;
602 #if defined(LWS_WITH_RANGES)
603         unsigned char finished = 0;
604 #endif
605         int n, m;
606
607         // lwsl_notice("%s (trunc len %d)\n", __func__, wsi->trunc_len);
608
609         while (wsi->http2_substream || !lws_send_pipe_choked(wsi)) {
610
611                 if (wsi->trunc_len) {
612                         if (lws_issue_raw(wsi, wsi->trunc_alloc +
613                                           wsi->trunc_offset,
614                                           wsi->trunc_len) < 0) {
615                                 lwsl_info("%s: closing\n", __func__);
616                                 goto file_had_it;
617                         }
618                         continue;
619                 }
620
621                 if (wsi->u.http.filepos == wsi->u.http.filelen)
622                         goto all_sent;
623
624                 n = 0;
625
626                 p = pt->serv_buf;
627
628 #if defined(LWS_WITH_RANGES)
629                 if (wsi->u.http.range.count_ranges && !wsi->u.http.range.inside) {
630
631                         lwsl_notice("%s: doing range start %llu\n", __func__, wsi->u.http.range.start);
632
633                         if ((long long)lws_vfs_file_seek_cur(wsi->u.http.fop_fd,
634                                                    wsi->u.http.range.start -
635                                                    wsi->u.http.filepos) < 0)
636                                 goto file_had_it;
637
638                         wsi->u.http.filepos = wsi->u.http.range.start;
639
640                         if (wsi->u.http.range.count_ranges > 1) {
641                                 n =  lws_snprintf((char *)p, context->pt_serv_buf_size,
642                                         "_lws\x0d\x0a"
643                                         "Content-Type: %s\x0d\x0a"
644                                         "Content-Range: bytes %llu-%llu/%llu\x0d\x0a"
645                                         "\x0d\x0a",
646                                         wsi->u.http.multipart_content_type,
647                                         wsi->u.http.range.start,
648                                         wsi->u.http.range.end,
649                                         wsi->u.http.range.extent);
650                                 p += n;
651                         }
652
653                         wsi->u.http.range.budget = wsi->u.http.range.end -
654                                                    wsi->u.http.range.start + 1;
655                         wsi->u.http.range.inside = 1;
656                 }
657 #endif
658
659                 poss = context->pt_serv_buf_size - n;
660
661                 /*
662                  * if there is a hint about how much we will do well to send at one time,
663                  * restrict ourselves to only trying to send that.
664                  */
665                 if (wsi->protocol->tx_packet_size && poss > wsi->protocol->tx_packet_size)
666                         poss = wsi->protocol->tx_packet_size;
667
668 #if defined(LWS_WITH_RANGES)
669                 if (wsi->u.http.range.count_ranges) {
670                         if (wsi->u.http.range.count_ranges > 1)
671                                 poss -= 7; /* allow for final boundary */
672                         if (poss > wsi->u.http.range.budget)
673                                 poss = wsi->u.http.range.budget;
674                 }
675 #endif
676                 if (wsi->sending_chunked) {
677                         /* we need to drop the chunk size in here */
678                         p += 10;
679                         /* allow for the chunk to grow by 128 in translation */
680                         poss -= 10 + 128;
681                 }
682
683                 if (lws_vfs_file_read(wsi->u.http.fop_fd, &amount, p, poss) < 0)
684                         goto file_had_it; /* caller will close */
685                 
686                 //lwsl_notice("amount %ld\n", amount);
687
688                 if (wsi->sending_chunked)
689                         n = (int)amount;
690                 else
691                         n = (p - pt->serv_buf) + (int)amount;
692                 if (n) {
693                         lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
694                                         context->timeout_secs);
695
696                         if (wsi->sending_chunked) {
697                                 args.p = (char *)p;
698                                 args.len = n;
699                                 args.max_len = (unsigned int)poss + 128;
700                                 args.final = wsi->u.http.filepos + n ==
701                                              wsi->u.http.filelen;
702                                 if (user_callback_handle_rxflow(
703                                      wsi->vhost->protocols[(int)wsi->protocol_interpret_idx].callback, wsi,
704                                      LWS_CALLBACK_PROCESS_HTML,
705                                      wsi->user_space, &args, 0) < 0)
706                                         goto file_had_it;
707                                 n = args.len;
708                                 p = (unsigned char *)args.p;
709                         } else
710                                 p = pt->serv_buf;
711
712 #if defined(LWS_WITH_RANGES)
713                         if (wsi->u.http.range.send_ctr + 1 ==
714                                 wsi->u.http.range.count_ranges && // last range
715                             wsi->u.http.range.count_ranges > 1 && // was 2+ ranges (ie, multipart)
716                             wsi->u.http.range.budget - amount == 0) {// final part
717                                 n += lws_snprintf((char *)pt->serv_buf + n, 6,
718                                         "_lws\x0d\x0a"); // append trailing boundary
719                                 lwsl_debug("added trailing boundary\n");
720                         }
721 #endif
722                         m = lws_write(wsi, p, n,
723                                       wsi->u.http.filepos == wsi->u.http.filelen ?
724                                         LWS_WRITE_HTTP_FINAL :
725                                         LWS_WRITE_HTTP
726                                 );
727                         if (m < 0)
728                                 goto file_had_it;
729
730                         wsi->u.http.filepos += amount;
731
732 #if defined(LWS_WITH_RANGES)
733                         if (wsi->u.http.range.count_ranges >= 1) {
734                                 wsi->u.http.range.budget -= amount;
735                                 if (wsi->u.http.range.budget == 0) {
736                                         lwsl_notice("range budget exhausted\n");
737                                         wsi->u.http.range.inside = 0;
738                                         wsi->u.http.range.send_ctr++;
739
740                                         if (lws_ranges_next(&wsi->u.http.range) < 1) {
741                                                 finished = 1;
742                                                 goto all_sent;
743                                         }
744                                 }
745                         }
746 #endif
747
748                         if (m != n) {
749                                 /* adjust for what was not sent */
750                                 if (lws_vfs_file_seek_cur(wsi->u.http.fop_fd,
751                                                            m - n) ==
752                                                              (unsigned long)-1)
753                                         goto file_had_it;
754                         }
755                 }
756 all_sent:
757                 if ((!wsi->trunc_len && wsi->u.http.filepos == wsi->u.http.filelen)
758 #if defined(LWS_WITH_RANGES)
759                     || finished)
760 #else
761                 )
762 #endif
763                      {
764                         wsi->state = LWSS_HTTP;
765                         /* we might be in keepalive, so close it off here */
766                         lws_vfs_file_close(&wsi->u.http.fop_fd);
767                         
768                         lwsl_debug("file completed\n");
769
770                         if (wsi->protocol->callback)
771                                 /* ignore callback returned value */
772                                 if (user_callback_handle_rxflow(
773                                      wsi->protocol->callback, wsi,
774                                      LWS_CALLBACK_HTTP_FILE_COMPLETION,
775                                      wsi->user_space, NULL, 0) < 0)
776                                         return -1;
777
778                         return 1;  /* >0 indicates completed */
779                 }
780         }
781
782         lws_callback_on_writable(wsi);
783
784         return 0; /* indicates further processing must be done */
785
786 file_had_it:
787         lws_vfs_file_close(&wsi->u.http.fop_fd);
788
789         return -1;
790 }
791
792 #if LWS_POSIX
793 LWS_VISIBLE int
794 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
795 {
796         struct lws_context *context = wsi->context;
797         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
798         int n;
799
800         lws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1);
801
802         n = recv(wsi->desc.sockfd, (char *)buf, len, 0);
803         if (n >= 0) {
804                 if (wsi->vhost)
805                         wsi->vhost->conn_stats.rx += n;
806                 lws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n);
807                 lws_restart_ws_ping_pong_timer(wsi);
808                 return n;
809         }
810 #if LWS_POSIX
811         if (LWS_ERRNO == LWS_EAGAIN ||
812             LWS_ERRNO == LWS_EWOULDBLOCK ||
813             LWS_ERRNO == LWS_EINTR)
814                 return LWS_SSL_CAPABLE_MORE_SERVICE;
815 #endif
816         lwsl_notice("error on reading from skt : %d\n", LWS_ERRNO);
817         return LWS_SSL_CAPABLE_ERROR;
818 }
819
820 LWS_VISIBLE int
821 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
822 {
823         int n = 0;
824
825 #if LWS_POSIX
826         n = send(wsi->desc.sockfd, (char *)buf, len, MSG_NOSIGNAL);
827 //      lwsl_info("%s: sent len %d result %d", __func__, len, n);
828         if (n >= 0)
829                 return n;
830
831         if (LWS_ERRNO == LWS_EAGAIN ||
832             LWS_ERRNO == LWS_EWOULDBLOCK ||
833             LWS_ERRNO == LWS_EINTR) {
834                 if (LWS_ERRNO == LWS_EWOULDBLOCK) {
835                         lws_set_blocking_send(wsi);
836                 }
837
838                 return LWS_SSL_CAPABLE_MORE_SERVICE;
839         }
840 #else
841         (void)n;
842         (void)wsi;
843         (void)buf;
844         (void)len;
845         // !!!
846 #endif
847
848         lwsl_debug("ERROR writing len %d to skt fd %d err %d / errno %d\n", len, wsi->desc.sockfd, n, LWS_ERRNO);
849         return LWS_SSL_CAPABLE_ERROR;
850 }
851 #endif
852 LWS_VISIBLE int
853 lws_ssl_pending_no_ssl(struct lws *wsi)
854 {
855         (void)wsi;
856 #if defined(LWS_WITH_ESP32)
857         return 100;
858 #else
859         return 0;
860 #endif
861 }