coding-style-cleanups.patch
[profile/ivi/libwebsockets.git] / lib / parsers.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 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 const struct lws_tokens lws_tokens[WSI_TOKEN_COUNT] = {
25         { "GET ", 4 },
26         { "Host:", 5 },
27         { "Connection:", 11 },
28         { "Sec-WebSocket-Key1:", 19 },
29         { "Sec-WebSocket-Key2:", 19 },
30         { "Sec-WebSocket-Protocol:", 23 },
31         { "Upgrade:", 8 },
32         { "Origin:", 7 },
33         { "Sec-WebSocket-Draft:", 20 },
34         { "\x0d\x0a", 2 },
35 };
36
37 int libwebsocket_parse(struct libwebsocket *wsi, unsigned char c)
38 {
39         int n;
40
41         switch (wsi->parser_state) {
42         case WSI_TOKEN_GET_URI:
43         case WSI_TOKEN_HOST:
44         case WSI_TOKEN_CONNECTION:
45         case WSI_TOKEN_KEY1:
46         case WSI_TOKEN_KEY2:
47         case WSI_TOKEN_PROTOCOL:
48         case WSI_TOKEN_UPGRADE:
49         case WSI_TOKEN_ORIGIN:
50         case WSI_TOKEN_DRAFT:
51         case WSI_TOKEN_CHALLENGE:
52
53                 debug("WSI_TOKEN_(%d) '%c'\n", wsi->parser_state, c);
54
55                 /* collect into malloc'd buffers */
56                 /* optional space swallow */
57                 if (!wsi->utf8_token[wsi->parser_state].token_len && c == ' ')
58                         break;
59
60                 /* special case space terminator for get-uri */
61                 if (wsi->parser_state == WSI_TOKEN_GET_URI && c == ' ') {
62                         wsi->utf8_token[wsi->parser_state].token[
63                            wsi->utf8_token[wsi->parser_state].token_len] = '\0';
64                         wsi->parser_state = WSI_TOKEN_SKIPPING;
65                         break;
66                 }
67
68                 /* allocate appropriate memory */
69                 if (wsi->utf8_token[wsi->parser_state].token_len ==
70                                                    wsi->current_alloc_len - 1) {
71                         /* need to extend */
72                         wsi->current_alloc_len += LWS_ADDITIONAL_HDR_ALLOC;
73                         if (wsi->current_alloc_len >= LWS_MAX_HEADER_LEN) {
74                                 /* it's waaay to much payload, fail it */
75                                 strcpy(wsi->utf8_token[wsi->parser_state].token,
76                                    "!!! Length exceeded maximum supported !!!");
77                                 wsi->parser_state = WSI_TOKEN_SKIPPING;
78                                 break;
79                         }
80                         wsi->utf8_token[wsi->parser_state].token =
81                                realloc(wsi->utf8_token[wsi->parser_state].token,
82                                                         wsi->current_alloc_len);
83                 }
84
85                 /* bail at EOL */
86                 if (wsi->parser_state != WSI_TOKEN_CHALLENGE && c == '\x0d') {
87                         wsi->utf8_token[wsi->parser_state].token[
88                            wsi->utf8_token[wsi->parser_state].token_len] = '\0';
89                         wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
90                         break;
91                 }
92
93                 wsi->utf8_token[wsi->parser_state].token[
94                             wsi->utf8_token[wsi->parser_state].token_len++] = c;
95
96                 /* special payload limiting */
97                 if (wsi->parser_state == WSI_TOKEN_CHALLENGE &&
98                             wsi->utf8_token[wsi->parser_state].token_len == 8) {
99                         debug("Setting WSI_PARSING_COMPLETE\n");
100                         wsi->parser_state = WSI_PARSING_COMPLETE;
101                         break;
102                 }
103
104                 break;
105
106                 /* collecting and checking a name part */
107         case WSI_TOKEN_NAME_PART:
108                 debug("WSI_TOKEN_NAME_PART '%c'\n", c);
109
110                 if (wsi->name_buffer_pos == sizeof(wsi->name_buffer) - 1) {
111                         /* name bigger than we can handle, skip until next */
112                         wsi->parser_state = WSI_TOKEN_SKIPPING;
113                         break;
114                 }
115                 wsi->name_buffer[wsi->name_buffer_pos++] = c;
116                 wsi->name_buffer[wsi->name_buffer_pos] = '\0';
117
118                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
119                         if (wsi->name_buffer_pos != lws_tokens[n].token_len)
120                                 continue;
121                         if (strcmp(lws_tokens[n].token, wsi->name_buffer))
122                                 continue;
123                         debug("known hdr '%s'\n", wsi->name_buffer);
124                         wsi->parser_state = WSI_TOKEN_GET_URI + n;
125                         wsi->current_alloc_len = LWS_INITIAL_HDR_ALLOC;
126                         wsi->utf8_token[wsi->parser_state].token =
127                                                  malloc(wsi->current_alloc_len);
128                         wsi->utf8_token[wsi->parser_state].token_len = 0;
129                         n = WSI_TOKEN_COUNT;
130                 }
131
132                 /* colon delimiter means we just don't know this name */
133
134                 if (wsi->parser_state == WSI_TOKEN_NAME_PART && c == ':') {
135                         debug("skipping unknown header '%s'\n",
136                                                               wsi->name_buffer);
137                         wsi->parser_state = WSI_TOKEN_SKIPPING;
138                         break;
139                 }
140
141                 /* don't look for payload when it can just be http headers */
142
143                 if (wsi->parser_state == WSI_TOKEN_CHALLENGE &&
144                                 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len) {
145                         /* they're HTTP headers, not websocket upgrade! */
146                         debug("Setting WSI_PARSING_COMPLETE "
147                                                          "from http headers\n");
148                         wsi->parser_state = WSI_PARSING_COMPLETE;
149                 }
150                 break;
151
152                 /* skipping arg part of a name we didn't recognize */
153         case WSI_TOKEN_SKIPPING:
154                 debug("WSI_TOKEN_SKIPPING '%c'\n", c);
155                 if (c == '\x0d')
156                         wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
157                 break;
158         case WSI_TOKEN_SKIPPING_SAW_CR:
159                 debug("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
160                 if (c == '\x0a')
161                         wsi->parser_state = WSI_TOKEN_NAME_PART;
162                 else
163                         wsi->parser_state = WSI_TOKEN_SKIPPING;
164                 wsi->name_buffer_pos = 0;
165                 break;
166                 /* we're done, ignore anything else */
167         case WSI_PARSING_COMPLETE:
168                 debug("WSI_PARSING_COMPLETE '%c'\n", c);
169                 break;
170
171         default:        /* keep gcc happy */
172                 break;
173         }
174
175         return 0;
176 }
177
178
179 static int libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
180 {
181         int n;
182         unsigned char buf[2];
183
184         switch (wsi->lws_rx_parse_state) {
185         case LWS_RXPS_NEW:
186
187                 switch (wsi->ietf_spec_revision) {
188                 /* Firefox 4.0b6 likes this as of 30 Oct */
189                 case 76:
190                         if (c == 0xff)
191                                 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
192                         break;
193                 case 0:
194                         break;
195                 }
196
197                 if (c == 0) {
198                         wsi->lws_rx_parse_state = LWS_RXPS_EAT_UNTIL_76_FF;
199                         wsi->rx_user_buffer_head = 0;
200                 }
201                 break;
202         case LWS_RXPS_EAT_UNTIL_76_FF:
203                 if (c == 0xff) {
204                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
205                         goto issue;
206                 }
207                 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
208                                               (wsi->rx_user_buffer_head++)] = c;
209
210                 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
211                         break;
212 issue:
213                 if (wsi->protocol->callback)
214                         wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
215                           wsi->user_space,
216                           &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
217                           wsi->rx_user_buffer_head);
218                 wsi->rx_user_buffer_head = 0;
219                 break;
220         case LWS_RXPS_SEEN_76_FF:
221                 if (c)
222                         break;
223
224                 debug("Seen that client is requesting "
225                                 "a v76 close, sending ack\n");
226                 buf[0] = 0xff;
227                 buf[1] = 0;
228                 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
229                 if (n < 0) {
230                         fprintf(stderr, "ERROR writing to socket");
231                         return -1;
232                 }
233                 debug("  v76 close ack sent, server closing skt\n");
234                 /* returning < 0 will get it closed in parent */
235                 return -1;
236
237         case LWS_RXPS_PULLING_76_LENGTH:
238                 break;
239         case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
240                 break;
241         }
242
243         return 0;
244 }
245
246 int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi,
247                                                  unsigned char *buf, size_t len)
248 {
249         int n;
250
251 #ifdef DEBUG
252         fprintf(stderr, "received %d byte packet\n", (int)len);
253         for (n = 0; n < len; n++)
254                 fprintf(stderr, "%02X ", buf[n]);
255         fprintf(stderr, "\n");
256 #endif
257         /* let the rx protocol state machine have as much as it needs */
258
259         n = 0;
260         while (wsi->lws_rx_parse_state !=
261                              LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED && n < len)
262                 if (libwebsocket_rx_sm(wsi, buf[n++]) < 0)
263                         return -1;
264
265         return -0;
266 }
267
268
269
270 /**
271  * libwebsocket_write() - Apply protocol then write data to client
272  * @wsi:        Websocket instance (available from user callback)
273  * @buf:        The data to send.  For data being sent on a websocket
274  *              connection (ie, not default http), this buffer MUST have
275  *              LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
276  *              and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
277  *              in the buffer after (buf + len).  This is so the protocol
278  *              header and trailer data can be added in-situ.
279  * @len:        Count of the data bytes in the payload starting from buf
280  * @protocol:   Use LWS_WRITE_HTTP to reply to an http connection, and one
281  *              of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
282  *              data on a websockets connection.  Remember to allow the extra
283  *              bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
284  *              are used.
285  *
286  *      This function provides the way to issue data back to the client
287  *      for both http and websocket protocols.
288  *
289  *      In the case of sending using websocket protocol, be sure to allocate
290  *      valid storage before and after buf as explained above.  This scheme
291  *      allows maximum efficiency of sending data and protocol in a single
292  *      packet while not burdening the user code with any protocol knowledge.
293  */
294
295 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
296                           size_t len, enum libwebsocket_write_protocol protocol)
297 {
298         int n;
299         int pre = 0;
300         int post = 0;
301         unsigned int shift = 7;
302
303         if (protocol == LWS_WRITE_HTTP)
304                 goto send_raw;
305
306         /* websocket protocol, either binary or text */
307
308         if (wsi->state != WSI_STATE_ESTABLISHED)
309                 return -1;
310
311         switch (wsi->ietf_spec_revision) {
312         /* chrome likes this as of 30 Oct */
313         /* Firefox 4.0b6 likes this as of 30 Oct */
314         case 76:
315                 if (protocol == LWS_WRITE_BINARY) {
316                         /* in binary mode we send 7-bit used length blocks */
317                         pre = 1;
318                         while (len & (127 << shift)) {
319                                 pre++;
320                                 shift += 7;
321                         }
322                         n = 0;
323                         shift -= 7;
324                         while (shift >= 0) {
325                                 if (shift)
326                                         buf[0 - pre + n] =
327                                                   ((len >> shift) & 127) | 0x80;
328                                 else
329                                         buf[0 - pre + n] =
330                                                   ((len >> shift) & 127);
331                                 n++;
332                                 shift -= 7;
333                         }
334                         break;
335                 }
336
337                 /* frame type = text, length-free spam mode */
338
339                 buf[-1] = 0;
340                 buf[len] = 0xff; /* EOT marker */
341                 pre = 1;
342                 post = 1;
343                 break;
344
345         case 0:
346                 buf[-9] = 0xff;
347 #if defined __LP64__
348                         buf[-8] = len >> 56;
349                         buf[-7] = len >> 48;
350                         buf[-6] = len >> 40;
351                         buf[-5] = len >> 32;
352 #else
353                         buf[-8] = 0;
354                         buf[-7] = 0;
355                         buf[-6] = 0;
356                         buf[-5] = 0;
357 #endif
358                 buf[-4] = len >> 24;
359                 buf[-3] = len >> 16;
360                 buf[-2] = len >> 8;
361                 buf[-1] = len;
362                 pre = 9;
363                 break;
364
365         /* just an unimplemented spec right now apparently */
366         case 2:
367                 n = 4; /* text */
368                 if (protocol == LWS_WRITE_BINARY)
369                         n = 5; /* binary */
370                 if (len < 126) {
371                         buf[-2] = n;
372                         buf[-1] = len;
373                         pre = 2;
374                 } else {
375                         if (len < 65536) {
376                                 buf[-4] = n;
377                                 buf[-3] = 126;
378                                 buf[-2] = len >> 8;
379                                 buf[-1] = len;
380                                 pre = 4;
381                         } else {
382                                 buf[-10] = n;
383                                 buf[-9] = 127;
384 #if defined __LP64__
385                                         buf[-8] = (len >> 56) & 0x7f;
386                                         buf[-7] = len >> 48;
387                                         buf[-6] = len >> 40;
388                                         buf[-5] = len >> 32;
389 #else
390                                         buf[-8] = 0;
391                                         buf[-7] = 0;
392                                         buf[-6] = 0;
393                                         buf[-5] = 0;
394 #endif
395                                 buf[-4] = len >> 24;
396                                 buf[-3] = len >> 16;
397                                 buf[-2] = len >> 8;
398                                 buf[-1] = len;
399                                 pre = 10;
400                         }
401                 }
402                 break;
403         }
404
405 #if 0
406         for (n = 0; n < (len + pre + post); n++)
407                 fprintf(stderr, "%02X ", buf[n - pre]);
408
409         fprintf(stderr, "\n");
410 #endif
411
412 send_raw:
413 #ifdef LWS_OPENSSL_SUPPORT
414         if (use_ssl) {
415                 n = SSL_write(wsi->ssl, buf - pre, len + pre + post);
416                 if (n < 0) {
417                         fprintf(stderr, "ERROR writing to socket");
418                         return -1;
419                 }
420         } else {
421 #endif
422                 n = send(wsi->sock, buf - pre, len + pre + post, 0);
423                 if (n < 0) {
424                         fprintf(stderr, "ERROR writing to socket");
425                         return -1;
426                 }
427 #ifdef LWS_OPENSSL_SUPPORT
428         }
429 #endif
430         debug("written %d bytes to client\n", (int)len);
431
432         return 0;
433 }
434
435
436 /**
437  * libwebsockets_serve_http_file() - Send a file back to the client using http
438  * @wsi:                Websocket instance (available from user callback)
439  * @file:               The file to issue over http
440  * @content_type:       The http content type, eg, text/html
441  *
442  *      This function is intended to be called from the callback in response
443  *      to http requests from the client.  It allows the callback to issue
444  *      local files down the http link in a single step.
445  */
446
447 int libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
448                                                        const char *content_type)
449 {
450         int fd;
451         struct stat stat;
452         char buf[512];
453         char *p = buf;
454         int n;
455
456         fd = open(file, O_RDONLY);
457         if (fd < 1) {
458                 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
459                         "Server: libwebsockets\x0d\x0a"
460                         "\x0d\x0a"
461                 );
462                 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
463                                                                 LWS_WRITE_HTTP);
464
465                 return -1;
466         }
467
468         fstat(fd, &stat);
469         p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
470                         "Server: libwebsockets\x0d\x0a"
471                         "Content-Type: %s\x0d\x0a"
472                         "Content-Length: %u\x0d\x0a"
473                         "\x0d\x0a", content_type, (unsigned int)stat.st_size);
474
475         libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
476
477         n = 1;
478         while (n > 0) {
479                 n = read(fd, buf, 512);
480                 libwebsocket_write(wsi, (unsigned char *)buf, n,
481                                                                 LWS_WRITE_HTTP);
482         }
483
484         close(fd);
485
486         return 0;
487 }