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