add timeout between accept and negotiation
[platform/upstream/libwebsockets.git] / lib / handshake.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 /*
25  * -04 of the protocol (actually the 80th version) has a radically different
26  * handshake.  The 04 spec gives the following idea
27  *
28  *    The handshake from the client looks as follows:
29  *
30  *      GET /chat HTTP/1.1
31  *      Host: server.example.com
32  *      Upgrade: websocket
33  *      Connection: Upgrade
34  *      Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
35  *      Sec-WebSocket-Origin: http://example.com
36  *      Sec-WebSocket-Protocol: chat, superchat
37  *      Sec-WebSocket-Version: 4
38  *
39  *  The handshake from the server looks as follows:
40  *
41  *       HTTP/1.1 101 Switching Protocols
42  *       Upgrade: websocket
43  *       Connection: Upgrade
44  *       Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
45  *       Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
46  *       Sec-WebSocket-Protocol: chat
47  */
48
49 /*
50  * We have to take care about parsing because the headers may be split
51  * into multiple fragments.  They may contain unknown headers with arbitrary
52  * argument lengths.  So, we parse using a single-character at a time state
53  * machine that is completely independent of packet size.
54  */
55
56 LWS_VISIBLE int
57 libwebsocket_read(struct libwebsocket_context *context,
58                      struct libwebsocket *wsi, unsigned char *buf, size_t len)
59 {
60         size_t n;
61 #ifndef LWS_NO_SERVER
62         struct allocated_headers *ah;
63         char *uri_ptr = NULL;
64         int uri_len = 0;
65         char content_length_str[32];
66 #endif
67
68         switch (wsi->state) {
69
70         case WSI_STATE_HTTP_BODY:
71 #ifndef LWS_NO_SERVER
72 http_postbody:
73 #endif
74                 while (len--) {
75
76                         if (wsi->u.http.content_length_seen >= wsi->u.http.content_length)
77                                 break;
78
79                         wsi->u.http.post_buffer[wsi->u.http.body_index++] = *buf++;
80                         wsi->u.http.content_length_seen++;
81                         n = wsi->protocol->rx_buffer_size;
82                         if (!n)
83                                 n = LWS_MAX_SOCKET_IO_BUF;
84
85                         if (wsi->u.http.body_index != n &&
86                             wsi->u.http.content_length_seen != wsi->u.http.content_length)
87                                 continue;
88
89                         if (wsi->protocol->callback) {
90                                 n = wsi->protocol->callback(
91                                         wsi->protocol->owning_server, wsi,
92                                             LWS_CALLBACK_HTTP_BODY,
93                                             wsi->user_space, wsi->u.http.post_buffer,
94                                                         wsi->u.http.body_index);
95                                 wsi->u.http.body_index = 0;
96                                 if (n)
97                                         goto bail;
98                         }
99
100                         if (wsi->u.http.content_length_seen == wsi->u.http.content_length) {
101                                 /* he sent the content in time */
102                                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
103                                 n = wsi->protocol->callback(
104                                         wsi->protocol->owning_server, wsi,
105                                             LWS_CALLBACK_HTTP_BODY_COMPLETION,
106                                             wsi->user_space, NULL, 0);
107                                 wsi->u.http.body_index = 0;
108                                 if (n)
109                                         goto bail;
110                         }
111
112                 }
113
114                 /* 
115                  * we need to spill here so everything is seen in the case
116                  * there is no content-length
117                  */
118                 if (wsi->u.http.body_index && wsi->protocol->callback) {
119                         n = wsi->protocol->callback(
120                                 wsi->protocol->owning_server, wsi,
121                                     LWS_CALLBACK_HTTP_BODY,
122                                     wsi->user_space, wsi->u.http.post_buffer,
123                                                 wsi->u.http.body_index);
124                         wsi->u.http.body_index = 0;
125                         if (n)
126                                 goto bail;
127                 }
128                 break;
129
130         case WSI_STATE_HTTP_ISSUING_FILE:
131         case WSI_STATE_HTTP:
132                 wsi->state = WSI_STATE_HTTP_HEADERS;
133                 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
134                 wsi->u.hdr.lextable_pos = 0;
135                 /* fallthru */
136         case WSI_STATE_HTTP_HEADERS:
137
138                 lwsl_parser("issuing %d bytes to parser\n", (int)len);
139
140 #ifndef LWS_NO_CLIENT
141                 switch (wsi->mode) {
142                 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
143                 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
144                 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
145                 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
146                 case LWS_CONNMODE_WS_CLIENT:
147                         for (n = 0; n < len; n++)
148                                 if (libwebsocket_client_rx_sm(wsi, *buf++)) {
149                                         lwsl_info("client_rx_sm failed\n");
150                                         goto bail;
151                                 }
152                         return 0;
153                 default:
154                         break;
155                 }
156 #endif
157 #ifndef LWS_NO_SERVER
158                 /* LWS_CONNMODE_WS_SERVING */
159
160                 while (len--) {
161                         if (libwebsocket_parse(wsi, *buf++)) {
162                                 lwsl_info("libwebsocket_parse failed\n");
163                                 goto bail_nuke_ah;
164                         }
165
166                         if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
167                                 continue;
168
169                         lwsl_parser("libwebsocket_parse sees parsing complete\n");
170
171                         wsi->mode = LWS_CONNMODE_PRE_WS_SERVING_ACCEPT;
172                         libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
173
174                         /* is this websocket protocol or normal http 1.0? */
175
176                         if (!lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE) ||
177                                      !lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
178
179                                 /* it's not websocket.... shall we accept it as http? */
180
181                                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) &&
182                                     !lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
183                                         lwsl_warn("Missing URI in HTTP request\n");
184                                         goto bail_nuke_ah;
185                                 }
186
187                                 if (lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) &&
188                                     lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
189                                         lwsl_warn("GET and POST methods?\n");
190                                         goto bail_nuke_ah;
191                                 }
192
193                                 if (libwebsocket_ensure_user_space(wsi))
194                                         goto bail_nuke_ah;
195
196                                 if (lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) {
197                                         uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI);
198                                         uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI);
199                                         lwsl_info("HTTP GET request for '%s'\n",
200                                             lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
201
202                                 }
203                                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
204                                         lwsl_info("HTTP POST request for '%s'\n",
205                                            lws_hdr_simple_ptr(wsi, WSI_TOKEN_POST_URI));
206                                         uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_POST_URI);
207                                         uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI);
208                                 }
209
210                                 /*
211                                  * Hm we still need the headers so the
212                                  * callback can look at leaders like the URI, but we
213                                  * need to transition to http union state.... hold a
214                                  * copy of u.hdr.ah and deallocate afterwards
215                                  */
216                                 ah = wsi->u.hdr.ah;
217
218                                 /* union transition */
219                                 memset(&wsi->u, 0, sizeof(wsi->u));
220                                 wsi->mode = LWS_CONNMODE_HTTP_SERVING_ACCEPTED;
221                                 wsi->state = WSI_STATE_HTTP;
222                                 wsi->u.http.fd = -1;
223
224                                 /* expose it at the same offset as u.hdr */
225                                 wsi->u.http.ah = ah;
226
227                                 /* HTTP header had a content length? */
228
229                                 wsi->u.http.content_length = 0;
230                                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
231                                         wsi->u.http.content_length = 100 * 1024 * 1024;
232
233                                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
234                                         lws_hdr_copy(wsi, content_length_str,
235                                                         sizeof(content_length_str) - 1,
236                                                                         WSI_TOKEN_HTTP_CONTENT_LENGTH);
237                                         wsi->u.http.content_length = atoi(content_length_str);
238                                 }
239
240                                 if (wsi->u.http.content_length > 0) {
241                                         wsi->u.http.body_index = 0;
242                                         n = wsi->protocol->rx_buffer_size;
243                                         if (!n)
244                                                 n = LWS_MAX_SOCKET_IO_BUF;
245                                         wsi->u.http.post_buffer = malloc(n);
246                                         if (!wsi->u.http.post_buffer) {
247                                                 lwsl_err("Unable to allocate post buffer\n");
248                                                 n = -1;
249                                                 goto leave;
250                                         }
251                                 }
252
253                                 n = 0;
254                                 if (wsi->protocol->callback)
255                                         n = wsi->protocol->callback(context, wsi,
256                                                 LWS_CALLBACK_FILTER_HTTP_CONNECTION,
257                                                      wsi->user_space, uri_ptr, uri_len);
258
259                                 if (!n && wsi->protocol->callback)
260                                         n = wsi->protocol->callback(context, wsi,
261                                             LWS_CALLBACK_HTTP,
262                                             wsi->user_space, uri_ptr, uri_len);
263
264 leave:
265                                 /* now drop the header info we kept a pointer to */
266                                 if (ah)
267                                         free(ah);
268                                 /* not possible to continue to use past here */
269                                 wsi->u.http.ah = NULL;
270
271                                 if (n) {
272                                         lwsl_info("LWS_CALLBACK_HTTP closing\n");
273                                         goto bail; /* struct ah ptr already nuked */
274                                 }
275
276                                 /*
277                                  * if there is content supposed to be coming,
278                                  * put a timeout on it having arrived
279                                  */
280                                 libwebsocket_set_timeout(wsi,
281                                         PENDING_TIMEOUT_HTTP_CONTENT,
282                                                               AWAITING_TIMEOUT);
283
284                                 /*
285                                  * (if callback didn't start sending a file)
286                                  * deal with anything else as body, whether
287                                  * there was a content-length or not
288                                  */
289
290                                 if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE)
291                                         wsi->state = WSI_STATE_HTTP_BODY;
292                                 goto http_postbody;
293                         }
294
295                         if (!wsi->protocol)
296                                 lwsl_err("NULL protocol at libwebsocket_read\n");
297
298                         /*
299                          * It's websocket
300                          *
301                          * Make sure user side is happy about protocol
302                          */
303
304                         while (wsi->protocol->callback) {
305
306                                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL)) {
307                                         if (wsi->protocol->name == NULL)
308                                                 break;
309                                 } else
310                                         if (wsi->protocol->name && strcmp(
311                                                 lws_hdr_simple_ptr(wsi,
312                                                         WSI_TOKEN_PROTOCOL),
313                                                               wsi->protocol->name) == 0)
314                                                 break;
315
316                                 wsi->protocol++;
317                         }
318
319                         /* we didn't find a protocol he wanted? */
320
321                         if (wsi->protocol->callback == NULL) {
322                                 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL) ==
323                                                                                  NULL) {
324                                         lwsl_info("no protocol -> prot 0 handler\n");
325                                         wsi->protocol = &context->protocols[0];
326                                 } else {
327                                         lwsl_err("Req protocol %s not supported\n",
328                                            lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL));
329                                         goto bail_nuke_ah;
330                                 }
331                         }
332
333                         /* allocate wsi->user storage */
334                         if (libwebsocket_ensure_user_space(wsi))
335                                 goto bail_nuke_ah;
336
337                         /*
338                          * Give the user code a chance to study the request and
339                          * have the opportunity to deny it
340                          */
341
342                         if ((wsi->protocol->callback)(wsi->protocol->owning_server, wsi,
343                                         LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
344                                         wsi->user_space,
345                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
346                                 lwsl_warn("User code denied connection\n");
347                                 goto bail_nuke_ah;
348                         }
349
350
351                         /*
352                          * Perform the handshake according to the protocol version the
353                          * client announced
354                          */
355
356                         switch (wsi->ietf_spec_revision) {
357                         case 13:
358                                 lwsl_parser("lws_parse calling handshake_04\n");
359                                 if (handshake_0405(context, wsi)) {
360                                         lwsl_info("hs0405 has failed the connection\n");
361                                         goto bail_nuke_ah;
362                                 }
363                                 break;
364
365                         default:
366                                 lwsl_warn("Unknown client spec version %d\n",
367                                                                wsi->ietf_spec_revision);
368                                 goto bail_nuke_ah;
369                         }
370
371                         /* drop the header info -- no bail_nuke_ah after this */
372
373                         if (wsi->u.hdr.ah)
374                                 free(wsi->u.hdr.ah);
375
376                         wsi->mode = LWS_CONNMODE_WS_SERVING;
377
378                         /* union transition */
379                         memset(&wsi->u, 0, sizeof(wsi->u));
380                         wsi->u.ws.rxflow_change_to = LWS_RXFLOW_ALLOW;
381
382                         /*
383                          * create the frame buffer for this connection according to the
384                          * size mentioned in the protocol definition.  If 0 there, use
385                          * a big default for compatibility
386                          */
387
388                         n = wsi->protocol->rx_buffer_size;
389                         if (!n)
390                                 n = LWS_MAX_SOCKET_IO_BUF;
391                         n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING;
392                         wsi->u.ws.rx_user_buffer = malloc(n);
393                         if (!wsi->u.ws.rx_user_buffer) {
394                                 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
395                                 goto bail;
396                         }
397                         lwsl_info("Allocating RX buffer %d\n", n);
398
399                         if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,  &n, sizeof n)) {
400                                 lwsl_warn("Failed to set SNDBUF to %d", n);
401                                 goto bail;
402                         }
403
404                         lwsl_parser("accepted v%02d connection\n",
405                                                                wsi->ietf_spec_revision);
406                 } /* while all chars are handled */
407                 break;
408 #endif
409
410         case WSI_STATE_AWAITING_CLOSE_ACK:
411         case WSI_STATE_ESTABLISHED:
412 #ifndef LWS_NO_CLIENT
413                 switch (wsi->mode) {
414                 case LWS_CONNMODE_WS_CLIENT:
415                         for (n = 0; n < len; n++)
416                                 if (libwebsocket_client_rx_sm(
417                                                              wsi, *buf++) < 0) {
418                                         lwsl_info("client rx has bailed\n");
419                                         goto bail;
420                                 }
421
422                         return 0;
423                 default:
424                         break;
425                 }
426 #endif
427 #ifndef LWS_NO_SERVER
428                 /* LWS_CONNMODE_WS_SERVING */
429
430                 if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0) {
431                         lwsl_info("interpret_incoming_packet has bailed\n");
432                         goto bail;
433                 }
434 #endif
435                 break;
436         default:
437                 lwsl_err("libwebsocket_read: Unhandled state\n");
438                 break;
439         }
440
441         return 0;
442
443 #ifndef LWS_NO_SERVER
444 bail_nuke_ah:
445         /* drop the header info */
446         if (wsi->u.hdr.ah)
447                 free(wsi->u.hdr.ah);
448 #endif
449
450 bail:
451         lwsl_info("closing connection at libwebsocket_read bail:\n");
452
453         libwebsocket_close_and_free_session(context, wsi,
454                                                      LWS_CLOSE_STATUS_NOSTATUS);
455
456         return -1;
457 }