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