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