websocket: accept empty protocol
[src/app-framework-binder.git] / src / afb-websock.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  * Author: José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <assert.h>
22 #include <errno.h>
23 #include <string.h>
24
25 #include <openssl/sha.h>
26 #include <microhttpd.h>
27
28 #include "afb-method.h"
29 #include "afb-context.h"
30 #include "afb-hreq.h"
31 #include "afb-websock.h"
32 #include "afb-ws-json1.h"
33
34 /**************** WebSocket connection upgrade ****************************/
35
36 static const char websocket_s[] = "websocket";
37 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
38 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
39 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
40 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
41 static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
42
43 static void enc64(unsigned char *in, char *out)
44 {
45         static const char tob64[] =
46                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
47                 "abcdefghijklmnopqrstuvwxyz"
48                 "0123456789+/";
49         out[0] = tob64[in[0] >> 2];
50         out[1] = tob64[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
51         out[2] = tob64[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
52         out[3] = tob64[in[2] & 0x3f];
53 }
54
55 static void make_accept_value(const char *key, char result[29])
56 {
57         unsigned char md[SHA_DIGEST_LENGTH+1];
58         size_t len = strlen(key);
59         char *buffer = alloca(len + sizeof websocket_guid - 1);
60         memcpy(buffer, key, len);
61         memcpy(buffer + len, websocket_guid, sizeof websocket_guid - 1);
62         SHA1((const unsigned char *)buffer, (unsigned long)(len + sizeof websocket_guid - 1), md);
63         assert(SHA_DIGEST_LENGTH == 20);
64         md[20] = 0;
65         enc64(&md[0], &result[0]);
66         enc64(&md[3], &result[4]);
67         enc64(&md[6], &result[8]);
68         enc64(&md[9], &result[12]);
69         enc64(&md[12], &result[16]);
70         enc64(&md[15], &result[20]);
71         enc64(&md[18], &result[24]);
72         result[27] = '=';
73         result[28] = 0;
74 }
75
76 static const char vseparators[] = " \t,";
77
78 static int headerhas(const char *header, const char *needle)
79 {
80         size_t len, n;
81
82         n = strlen(needle);
83         for(;;) {
84                 header += strspn(header, vseparators);
85                 if (!*header)
86                         return 0;
87                 len = strcspn(header, vseparators);
88                 if (n == len && 0 == strncasecmp(needle, header, n))
89                         return 1;
90                 header += len;
91         }
92 }
93
94 struct protodef
95 {
96         const char *name;
97         void *(*create)(int fd, void *context, void (*cleanup)(void*), void *cleanup_closure);
98 };
99
100 static const struct protodef *search_proto(const struct protodef *protodefs, const char *protocols)
101 {
102         int i;
103         size_t len;
104
105         if (protocols == NULL) {
106                 /* return NULL; */
107                 return protodefs != NULL && protodefs->name != NULL ? protodefs : NULL;
108         }
109         for(;;) {
110                 protocols += strspn(protocols, vseparators);
111                 if (!*protocols)
112                         return NULL;
113                 len = strcspn(protocols, vseparators);
114                 for (i = 0 ; protodefs[i].name != NULL ; i++)
115                         if (!strncasecmp(protodefs[i].name, protocols, len)
116                          && !protodefs[i].name[len])
117                                 return &protodefs[i];
118                 protocols += len;
119         }
120 }
121
122 static int check_websocket_upgrade(struct MHD_Connection *con, const struct protodef *protodefs, void *context, void **websock)
123 {
124         const union MHD_ConnectionInfo *info;
125         struct MHD_Response *response;
126         const char *connection, *upgrade, *key, *version, *protocols;
127         char acceptval[29];
128         int vernum;
129         const struct protodef *proto;
130         void *ws;
131
132         /* is an upgrade to websocket ? */
133         upgrade = MHD_lookup_connection_value(con, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE);
134         if (upgrade == NULL || strcasecmp(upgrade, websocket_s))
135                 return 0;
136
137         /* is a connection for upgrade ? */
138         connection = MHD_lookup_connection_value(con, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION);
139         if (connection == NULL
140          || !headerhas (connection, MHD_HTTP_HEADER_UPGRADE))
141                 return 0;
142
143         /* has a key and a version ? */
144         key = MHD_lookup_connection_value(con, MHD_HEADER_KIND, sec_websocket_key_s);
145         version = MHD_lookup_connection_value(con, MHD_HEADER_KIND, sec_websocket_version_s);
146         if (key == NULL || version == NULL)
147                 return 0;
148
149         /* is a supported version ? */
150         vernum = atoi(version);
151         if (vernum != 13) {
152                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
153                 MHD_add_response_header(response, sec_websocket_version_s, "13");
154                 MHD_queue_response(con, MHD_HTTP_UPGRADE_REQUIRED, response);
155                 MHD_destroy_response(response);
156                 return 1;
157         }
158
159         /* is the protocol supported ? */
160         protocols = MHD_lookup_connection_value(con, MHD_HEADER_KIND, sec_websocket_protocol_s);
161         proto = search_proto(protodefs, protocols);
162         if (proto == NULL) {
163                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
164                 MHD_queue_response(con, MHD_HTTP_PRECONDITION_FAILED, response);
165                 MHD_destroy_response(response);
166                 return 1;
167         }
168
169         /* create the web socket */
170         info = MHD_get_connection_info(con, MHD_CONNECTION_INFO_CONNECTION_FD);
171         if (info == NULL) {
172                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
173                 MHD_queue_response(con, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
174                 MHD_destroy_response(response);
175                 return 1;
176         }
177         ws = proto->create(info->connect_fd, context, (void*)MHD_resume_connection, con);
178         if (ws == NULL) {
179                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
180                 MHD_queue_response(con, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
181                 MHD_destroy_response(response);
182                 return 1;
183         }
184
185         /* send the accept connection */
186         make_accept_value(key, acceptval);
187         response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
188         MHD_add_response_header(response, sec_websocket_accept_s, acceptval);
189         MHD_add_response_header(response, sec_websocket_protocol_s, proto->name);
190         MHD_add_response_header(response, MHD_HTTP_HEADER_CONNECTION, MHD_HTTP_HEADER_UPGRADE);
191         MHD_add_response_header(response, MHD_HTTP_HEADER_UPGRADE, websocket_s);
192         MHD_queue_response(con, MHD_HTTP_SWITCHING_PROTOCOLS, response);
193         MHD_destroy_response(response);
194
195         *websock = ws;
196         return 1;
197 }
198
199 static const struct protodef protodefs[] = {
200         { "x-afb-ws-json1",     (void*)afb_ws_json1_create },
201         { NULL, NULL }
202 };
203
204 int afb_websock_check_upgrade(struct afb_hreq *hreq)
205 {
206         void *ws;
207         int rc;
208
209         /* is a get ? */
210         if (hreq->method != afb_method_get
211          || strcasecmp(hreq->version, MHD_HTTP_VERSION_1_1))
212                 return 0;
213
214         ws = NULL;
215         rc = check_websocket_upgrade(hreq->connection, protodefs, &hreq->context, &ws);
216         if (rc == 1) {
217                 hreq->replied = 1;
218                 if (ws != NULL)
219                         hreq->upgrade = 1;
220         }
221         return rc;
222 }
223