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