994d87dfb8506612f17618b56748eb385f0fa80d
[profile/ivi/libwebsockets.git] / lib / output.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2013 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 #ifdef WIN32
25 #include <io.h>
26 #endif
27
28 static int
29 libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi)
30 {
31         char buf[4 + 20];
32         int n;
33
34         /* fetch the per-frame nonce */
35
36         n = libwebsockets_get_random(wsi->protocol->owning_server,
37                                                 wsi->frame_masking_nonce_04, 4);
38         if (n != 4) {
39                 lwsl_parser("Unable to read from random device %s %d\n",
40                                                      SYSTEM_RANDOM_FILEPATH, n);
41                 return 1;
42         }
43
44         /* start masking from first byte of masking key buffer */
45         wsi->frame_mask_index = 0;
46
47         if (wsi->ietf_spec_revision != 4)
48                 return 0;
49
50         /* 04 only does SHA-1 more complex key */
51
52         /*
53          * the frame key is the frame nonce (4 bytes) followed by the
54          * connection masking key, hashed by SHA1
55          */
56
57         memcpy(buf, wsi->frame_masking_nonce_04, 4);
58
59         memcpy(buf + 4, wsi->masking_key_04, 20);
60
61         /* concatenate the nonce with the connection key then hash it */
62
63         SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
64
65         return 0;
66 }
67
68
69 void lws_stderr_hexdump(unsigned char *buf, size_t len)
70 {
71         int n;
72         int m;
73         int start;
74
75         lwsl_parser("\n");
76
77         for (n = 0; n < len;) {
78                 start = n;
79
80                 lwsl_debug("%04X: ", start);
81
82                 for (m = 0; m < 16 && n < len; m++)
83                         lwsl_debug("%02X ", buf[n++]);
84                 while (m++ < 16)
85                         lwsl_debug("   ");
86
87                 lwsl_debug("   ");
88
89                 for (m = 0; m < 16 && (start + m) < len; m++) {
90                         if (buf[start + m] >= ' ' && buf[start + m] <= 127)
91                                 lwsl_debug("%c", buf[start + m]);
92                         else
93                                 lwsl_debug(".");
94                 }
95                 while (m++ < 16)
96                         lwsl_debug(" ");
97
98                 lwsl_debug("\n");
99         }
100         lwsl_debug("\n");
101 }
102
103 int lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len)
104 {
105         int n;
106         int m;
107
108         /*
109          * one of the extensions is carrying our data itself?  Like mux?
110          */
111
112         for (n = 0; n < wsi->count_active_extensions; n++) {
113                 /*
114                  * there can only be active extensions after handshake completed
115                  * so we can rely on protocol being set already in here
116                  */
117                 m = wsi->active_extensions[n]->callback(
118                                 wsi->protocol->owning_server,
119                                 wsi->active_extensions[n], wsi,
120                                 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND,
121                                      wsi->active_extensions_user[n], &buf, len);
122                 if (m < 0) {
123                         lwsl_ext("Extension reports fatal error\n");
124                         return -1;
125                 }
126                 if (m) /* handled */ {
127 /*                      lwsl_ext("ext sent it\n"); */
128                         return 0;
129                 }
130         }
131
132         if (!wsi->sock)
133                 lwsl_warn("** error 0 sock but expected to send\n");
134
135         /*
136          * nope, send it on the socket directly
137          */
138
139 #if 0
140         lwsl_debug("  TX: ");
141         lws_stderr_hexdump(buf, len);
142 #endif
143
144 #ifdef LWS_OPENSSL_SUPPORT
145         if (wsi->ssl) {
146                 n = SSL_write(wsi->ssl, buf, len);
147                 if (n < 0) {
148                         lwsl_debug("ERROR writing to socket\n");
149                         return -1;
150                 }
151         } else {
152 #endif
153                 n = send(wsi->sock, buf, len, MSG_NOSIGNAL);
154                 if (n < 0) {
155                         lwsl_debug("ERROR writing to socket\n");
156                         return -1;
157                 }
158 #ifdef LWS_OPENSSL_SUPPORT
159         }
160 #endif
161         return 0;
162 }
163
164 int
165 lws_issue_raw_ext_access(struct libwebsocket *wsi,
166                                                  unsigned char *buf, size_t len)
167 {
168         int ret;
169         struct lws_tokens eff_buf;
170         int m;
171         int n;
172
173         eff_buf.token = (char *)buf;
174         eff_buf.token_len = len;
175
176         /*
177          * while we have original buf to spill ourselves, or extensions report
178          * more in their pipeline
179          */
180
181         ret = 1;
182         while (ret == 1) {
183
184                 /* default to nobody has more to spill */
185
186                 ret = 0;
187
188                 /* show every extension the new incoming data */
189
190                 for (n = 0; n < wsi->count_active_extensions; n++) {
191                         m = wsi->active_extensions[n]->callback(
192                                         wsi->protocol->owning_server,
193                                         wsi->active_extensions[n], wsi,
194                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
195                                    wsi->active_extensions_user[n], &eff_buf, 0);
196                         if (m < 0) {
197                                 lwsl_ext("Extension: fatal error\n");
198                                 return -1;
199                         }
200                         if (m)
201                                 /*
202                                  * at least one extension told us he has more
203                                  * to spill, so we will go around again after
204                                  */
205                                 ret = 1;
206                 }
207
208                 /* assuming they left us something to send, send it */
209
210                 if (eff_buf.token_len)
211                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
212                                                             eff_buf.token_len))
213                                 return -1;
214
215                 lwsl_parser("written %d bytes to client\n", eff_buf.token_len);
216
217                 /* no extension has more to spill */
218
219                 if (!ret)
220                         break;
221
222                 /* we used up what we had */
223
224                 eff_buf.token = NULL;
225                 eff_buf.token_len = 0;
226
227                 /*
228                  * Did that leave the pipe choked?
229                  */
230
231                 if (!lws_send_pipe_choked(wsi))
232                         /* no we could add more */
233                         continue;
234
235                 lwsl_debug("choked\n");
236
237                 /*
238                  * Yes, he's choked.  Don't spill the rest now get a callback
239                  * when he is ready to send and take care of it there
240                  */
241                 libwebsocket_callback_on_writable(
242                                              wsi->protocol->owning_server, wsi);
243                 wsi->extension_data_pending = 1;
244                 ret = 0;
245         }
246
247         return 0;
248 }
249
250 /**
251  * libwebsocket_write() - Apply protocol then write data to client
252  * @wsi:        Websocket instance (available from user callback)
253  * @buf:        The data to send.  For data being sent on a websocket
254  *              connection (ie, not default http), this buffer MUST have
255  *              LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
256  *              and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
257  *              in the buffer after (buf + len).  This is so the protocol
258  *              header and trailer data can be added in-situ.
259  * @len:        Count of the data bytes in the payload starting from buf
260  * @protocol:   Use LWS_WRITE_HTTP to reply to an http connection, and one
261  *              of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
262  *              data on a websockets connection.  Remember to allow the extra
263  *              bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
264  *              are used.
265  *
266  *      This function provides the way to issue data back to the client
267  *      for both http and websocket protocols.
268  *
269  *      In the case of sending using websocket protocol, be sure to allocate
270  *      valid storage before and after buf as explained above.  This scheme
271  *      allows maximum efficiency of sending data and protocol in a single
272  *      packet while not burdening the user code with any protocol knowledge.
273  */
274
275 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
276                           size_t len, enum libwebsocket_write_protocol protocol)
277 {
278         int n;
279         int pre = 0;
280         int post = 0;
281         int shift = 7;
282         int masked7 = wsi->mode == LWS_CONNMODE_WS_CLIENT &&
283                                                   wsi->xor_mask != xor_no_mask;
284         unsigned char *dropmask = NULL;
285         unsigned char is_masked_bit = 0;
286         struct lws_tokens eff_buf;
287         int m;
288
289         if (len == 0 && protocol != LWS_WRITE_CLOSE) {
290                 lwsl_warn("zero length libwebsocket_write attempt\n");
291                 return 0;
292         }
293
294         if (protocol == LWS_WRITE_HTTP)
295                 goto send_raw;
296
297         /* websocket protocol, either binary or text */
298
299         if (wsi->state != WSI_STATE_ESTABLISHED)
300                 return -1;
301
302         /* give a change to the extensions to modify payload */
303         eff_buf.token = (char *)buf;
304         eff_buf.token_len = len;
305
306         for (n = 0; n < wsi->count_active_extensions; n++) {
307                 m = wsi->active_extensions[n]->callback(
308                         wsi->protocol->owning_server,
309                         wsi->active_extensions[n], wsi,
310                         LWS_EXT_CALLBACK_PAYLOAD_TX,
311                         wsi->active_extensions_user[n], &eff_buf, 0);
312                 if (m < 0)
313                         return -1;
314         }
315
316         buf = (unsigned char *)eff_buf.token;
317         len = eff_buf.token_len;
318
319         switch (wsi->ietf_spec_revision) {
320         /* chrome likes this as of 30 Oct 2010 */
321         /* Firefox 4.0b6 likes this as of 30 Oct 2010 */
322         case 0:
323                 if ((protocol & 0xf) == LWS_WRITE_BINARY) {
324                         /* in binary mode we send 7-bit used length blocks */
325                         pre = 1;
326                         while (len & (127 << shift)) {
327                                 pre++;
328                                 shift += 7;
329                         }
330                         n = 0;
331                         shift -= 7;
332                         while (shift >= 0) {
333                                 if (shift)
334                                         buf[0 - pre + n] =
335                                                   ((len >> shift) & 127) | 0x80;
336                                 else
337                                         buf[0 - pre + n] =
338                                                   ((len >> shift) & 127);
339                                 n++;
340                                 shift -= 7;
341                         }
342                         break;
343                 }
344
345                 /* frame type = text, length-free spam mode */
346
347                 pre = 1;
348                 buf[-pre] = 0;
349                 buf[len] = 0xff; /* EOT marker */
350                 post = 1;
351                 break;
352
353         case 7:
354         case 8:
355         case 13:
356                 if (masked7) {
357                         pre += 4;
358                         dropmask = &buf[0 - pre];
359                         is_masked_bit = 0x80;
360                 }
361                 /* fallthru */
362         case 4:
363         case 5:
364         case 6:
365                 switch (protocol & 0xf) {
366                 case LWS_WRITE_TEXT:
367                         if (wsi->ietf_spec_revision < 7)
368                                 n = LWS_WS_OPCODE_04__TEXT_FRAME;
369                         else
370                                 n = LWS_WS_OPCODE_07__TEXT_FRAME;
371                         break;
372                 case LWS_WRITE_BINARY:
373                         if (wsi->ietf_spec_revision < 7)
374                                 n = LWS_WS_OPCODE_04__BINARY_FRAME;
375                         else
376                                 n = LWS_WS_OPCODE_07__BINARY_FRAME;
377                         break;
378                 case LWS_WRITE_CONTINUATION:
379                         if (wsi->ietf_spec_revision < 7)
380                                 n = LWS_WS_OPCODE_04__CONTINUATION;
381                         else
382                                 n = LWS_WS_OPCODE_07__CONTINUATION;
383                         break;
384
385                 case LWS_WRITE_CLOSE:
386                         if (wsi->ietf_spec_revision < 7)
387                                 n = LWS_WS_OPCODE_04__CLOSE;
388                         else
389                                 n = LWS_WS_OPCODE_07__CLOSE;
390
391                         /*
392                          * v5 mandates the first byte of close packet
393                          * in both client and server directions
394                          */
395
396                         switch (wsi->ietf_spec_revision) {
397                         case 0:
398                         case 4:
399                                 break;
400                         case 5:
401                                 /* we can do this because we demand post-buf */
402
403                                 if (len < 1)
404                                         len = 1;
405
406                                 switch (wsi->mode) {
407                                 case LWS_CONNMODE_WS_SERVING:
408                                         /*
409                                         lwsl_debug("LWS_WRITE_CLOSE S\n");
410                                         */
411                                         buf[0] = 'S';
412                                         break;
413                                 case LWS_CONNMODE_WS_CLIENT:
414                                         /*
415                                         lwsl_debug("LWS_WRITE_CLOSE C\n");
416                                         */
417                                         buf[0] = 'C';
418                                         break;
419                                 default:
420                                         break;
421                                 }
422                                 break;
423                         default:
424                                 /*
425                                  * 06 has a 2-byte status code in network order
426                                  * we can do this because we demand post-buf
427                                  */
428
429                                 if (wsi->close_reason) {
430                                         /* reason codes count as data bytes */
431                                         buf -= 2;
432                                         buf[0] = wsi->close_reason >> 8;
433                                         buf[1] = wsi->close_reason;
434                                         len += 2;
435                                 }
436                                 break;
437                         }
438                         break;
439                 case LWS_WRITE_PING:
440                         if (wsi->ietf_spec_revision < 7)
441                                 n = LWS_WS_OPCODE_04__PING;
442                         else
443                                 n = LWS_WS_OPCODE_07__PING;
444
445                         wsi->pings_vs_pongs++;
446                         break;
447                 case LWS_WRITE_PONG:
448                         if (wsi->ietf_spec_revision < 7)
449                                 n = LWS_WS_OPCODE_04__PONG;
450                         else
451                                 n = LWS_WS_OPCODE_07__PONG;
452                         break;
453                 default:
454                         lwsl_warn("libwebsocket_write: unknown write "
455                                                          "opcode / protocol\n");
456                         return -1;
457                 }
458
459                 if (!(protocol & LWS_WRITE_NO_FIN))
460                         n |= 1 << 7;
461
462                 if (len < 126) {
463                         pre += 2;
464                         buf[-pre] = n;
465                         buf[-pre + 1] = len | is_masked_bit;
466                 } else {
467                         if (len < 65536) {
468                                 pre += 4;
469                                 buf[-pre] = n;
470                                 buf[-pre + 1] = 126 | is_masked_bit;
471                                 buf[-pre + 2] = len >> 8;
472                                 buf[-pre + 3] = len;
473                         } else {
474                                 pre += 10;
475                                 buf[-pre] = n;
476                                 buf[-pre + 1] = 127 | is_masked_bit;
477 #if defined __LP64__
478                                         buf[-pre + 2] = (len >> 56) & 0x7f;
479                                         buf[-pre + 3] = len >> 48;
480                                         buf[-pre + 4] = len >> 40;
481                                         buf[-pre + 5] = len >> 32;
482 #else
483                                         buf[-pre + 2] = 0;
484                                         buf[-pre + 3] = 0;
485                                         buf[-pre + 4] = 0;
486                                         buf[-pre + 5] = 0;
487 #endif
488                                 buf[-pre + 6] = len >> 24;
489                                 buf[-pre + 7] = len >> 16;
490                                 buf[-pre + 8] = len >> 8;
491                                 buf[-pre + 9] = len;
492                         }
493                 }
494                 break;
495         }
496
497         /*
498          * Deal with masking if we are in client -> server direction and
499          * the protocol demands it
500          */
501
502         if (wsi->mode == LWS_CONNMODE_WS_CLIENT &&
503                                                  wsi->ietf_spec_revision >= 4) {
504
505                 /*
506                  * this is only useful for security tests where it's required
507                  * to control the raw packet payload content
508                  */
509
510                 if (!(protocol & LWS_WRITE_CLIENT_IGNORE_XOR_MASK) &&
511                                                 wsi->xor_mask != xor_no_mask) {
512
513                         if (libwebsocket_0405_frame_mask_generate(wsi)) {
514                                 lwsl_err("libwebsocket_write: "
515                                               "frame mask generation failed\n");
516                                 return 1;
517                         }
518
519
520                         if (wsi->ietf_spec_revision < 7)
521                                 /*
522                                  * use the XOR masking against everything we
523                                  * send past the frame key
524                                  */
525                                 for (n = -pre; n < ((int)len + post); n++)
526                                         buf[n] = wsi->xor_mask(wsi, buf[n]);
527                         else
528                                 /*
529                                  * in v7, just mask the payload
530                                  */
531                                 for (n = 0; n < (int)len; n++)
532                                         dropmask[n + 4] =
533                                            wsi->xor_mask(wsi, dropmask[n + 4]);
534
535
536                         if (wsi->ietf_spec_revision < 7) {
537                                 /* make space for the frame nonce in clear */
538                                 pre += 4;
539
540                                 dropmask = &buf[0 - pre];
541                         }
542
543                         if (dropmask)
544                                 /* copy the frame nonce into place */
545                                 memcpy(dropmask,
546                                                wsi->frame_masking_nonce_04, 4);
547
548                 } else {
549                         if (wsi->ietf_spec_revision < 7) {
550
551                                 /* make space for the frame nonce in clear */
552                                 pre += 4;
553
554                                 buf[0 - pre] = 0;
555                                 buf[1 - pre] = 0;
556                                 buf[2 - pre] = 0;
557                                 buf[3 - pre] = 0;
558                         } else {
559                                 if (dropmask && wsi->xor_mask != xor_no_mask) {
560                                         dropmask[0] = 0;
561                                         dropmask[1] = 0;
562                                         dropmask[2] = 0;
563                                         dropmask[3] = 0;
564                                 }
565                         }
566                 }
567
568         }
569
570 send_raw:
571
572 #if 0
573         lwsl_debug("send %ld: ", len + post);
574         for (n = -pre; n < ((int)len + post); n++)
575                 lwsl_debug("%02X ", buf[n]);
576
577         lwsl_debug("\n");
578 #endif
579
580         if (protocol == LWS_WRITE_HTTP) {
581                 if (lws_issue_raw(wsi, (unsigned char *)buf - pre,
582                                                               len + pre + post))
583                         return -1;
584
585                 return 0;
586         }
587
588         /*
589          * give any active extensions a chance to munge the buffer
590          * before send.  We pass in a pointer to an lws_tokens struct
591          * prepared with the default buffer and content length that's in
592          * there.  Rather than rewrite the default buffer, extensions
593          * that expect to grow the buffer can adapt .token to
594          * point to their own per-connection buffer in the extension
595          * user allocation.  By default with no extensions or no
596          * extension callback handling, just the normal input buffer is
597          * used then so it is efficient.
598          *
599          * callback returns 1 in case it wants to spill more buffers
600          */
601
602         return lws_issue_raw_ext_access(wsi, buf - pre, len + pre + post);
603 }
604
605
606 /**
607  * libwebsockets_serve_http_file() - Send a file back to the client using http
608  * @context:            libwebsockets context
609  * @wsi:                Websocket instance (available from user callback)
610  * @file:               The file to issue over http
611  * @content_type:       The http content type, eg, text/html
612  *
613  *      This function is intended to be called from the callback in response
614  *      to http requests from the client.  It allows the callback to issue
615  *      local files down the http link in a single step.
616  */
617
618 int libwebsockets_serve_http_file(struct libwebsocket_context *context,
619                         struct libwebsocket *wsi, const char *file,
620                                                        const char *content_type)
621 {
622         int fd;
623         struct stat stat_buf;
624         char buf[1400];
625         char *p = buf;
626         int n, m;
627
628         strncpy(wsi->filepath, file, sizeof wsi->filepath);
629         wsi->filepath[sizeof(wsi->filepath) - 1] = '\0';
630
631 #ifdef WIN32
632         fd = open(wsi->filepath, O_RDONLY | _O_BINARY);
633 #else
634         fd = open(wsi->filepath, O_RDONLY);
635 #endif
636         if (fd < 1) {
637                 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
638                         "Server: libwebsockets\x0d\x0a"
639                         "\x0d\x0a"
640                 );
641                 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
642                                                                 LWS_WRITE_HTTP);
643
644                 return -1;
645         }
646
647         fstat(fd, &stat_buf);
648         wsi->filelen = stat_buf.st_size;
649         p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
650                         "Server: libwebsockets\x0d\x0a"
651                         "Content-Type: %s\x0d\x0a"
652                         "Content-Length: %u\x0d\x0a"
653                         "\x0d\x0a", content_type,
654                                         (unsigned int)stat_buf.st_size);
655
656         n = libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
657         if (n) {
658                 close(fd);
659                 return n;
660         }
661
662         wsi->filepos = 0;
663         wsi->state = WSI_STATE_HTTP_ISSUING_FILE;
664
665         while (!lws_send_pipe_choked(wsi)) {
666
667                 n = read(fd, buf, sizeof buf);
668                 if (n > 0) {
669                         wsi->filepos += n;
670                         m = libwebsocket_write(wsi, (unsigned char *)buf, n, LWS_WRITE_HTTP);
671                         if (m) {
672                                 close(fd);
673                                 return m;
674                         }
675                 }
676
677                 if (n < 0) {
678                         close(fd);
679                         return -1;
680                 }
681
682                 if (n < sizeof(buf) || wsi->filepos == wsi->filelen) {
683                         /* oh, we were able to finish here! */
684                         wsi->state = WSI_STATE_HTTP;
685                         close(fd);
686
687                         if (wsi->protocol->callback(context, wsi, LWS_CALLBACK_HTTP_FILE_COMPLETION, wsi->user_space,
688                                                         wsi->filepath, wsi->filepos))
689                                 libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
690
691                         return 0;
692                 }
693         }
694
695         /* we choked, no worries schedule service for the rest of it */
696
697         libwebsocket_callback_on_writable(context, wsi);
698
699         close(fd);
700
701         return 0;
702 }
703
704 int libwebsockets_serve_http_file_fragment(struct libwebsocket_context *context,
705                                                         struct libwebsocket *wsi)
706 {
707         int fd;
708         int ret = 0;
709         char buf[1400];
710         int n;
711
712 #ifdef WIN32
713         fd = open(wsi->filepath, O_RDONLY | _O_BINARY);
714 #else
715         fd = open(wsi->filepath, O_RDONLY);
716 #endif
717         if (fd < 1)
718                 return -1;
719
720         lseek(fd, wsi->filepos, SEEK_SET);
721
722         while (!lws_send_pipe_choked(wsi)) {
723                 n = read(fd, buf, sizeof buf);
724                 if (n > 0) {
725                         libwebsocket_write(wsi, (unsigned char *)buf, n, LWS_WRITE_HTTP);
726                         wsi->filepos += n;
727                 }
728
729                 if (n < 0) {
730                         close(fd);
731                         return -1;
732                 }
733
734                 if (n < sizeof(buf) || wsi->filepos == wsi->filelen) {
735                         wsi->state = WSI_STATE_HTTP;
736                         close(fd);
737                         return 0;
738                 }
739         }
740
741         libwebsocket_callback_on_writable(context, wsi);
742
743         close(fd);
744
745         return ret;
746 }
747
748