73bb3c5e75f94ea94027336f481f303d47c2137f
[src/app-framework-binder.git] / src / afb-websock.c
1 /*
2  * Copyright (C) 2016-2019 "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 #include "afb-fdev.h"
34 #include "fdev.h"
35
36 /**************** WebSocket connection upgrade ****************************/
37
38 static const char websocket_s[] = "websocket";
39 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
40 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
41 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
42 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
43 static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
44
45 static void enc64(unsigned char *in, char *out)
46 {
47         static const char tob64[] =
48                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
49                 "abcdefghijklmnopqrstuvwxyz"
50                 "0123456789+/";
51         out[0] = tob64[in[0] >> 2];
52         out[1] = tob64[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
53         out[2] = tob64[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
54         out[3] = tob64[in[2] & 0x3f];
55 }
56
57 static void make_accept_value(const char *key, char result[29])
58 {
59         unsigned char md[SHA_DIGEST_LENGTH+1];
60         size_t len = strlen(key);
61         char *buffer = alloca(len + sizeof websocket_guid - 1);
62         memcpy(buffer, key, len);
63         memcpy(buffer + len, websocket_guid, sizeof websocket_guid - 1);
64         SHA1((const unsigned char *)buffer, (unsigned long)(len + sizeof websocket_guid - 1), md);
65         assert(SHA_DIGEST_LENGTH == 20);
66         md[20] = 0;
67         enc64(&md[0], &result[0]);
68         enc64(&md[3], &result[4]);
69         enc64(&md[6], &result[8]);
70         enc64(&md[9], &result[12]);
71         enc64(&md[12], &result[16]);
72         enc64(&md[15], &result[20]);
73         enc64(&md[18], &result[24]);
74         result[27] = '=';
75         result[28] = 0;
76 }
77
78 static const char vseparators[] = " \t,";
79
80 static int headerhas(const char *header, const char *needle)
81 {
82         size_t len, n;
83
84         n = strlen(needle);
85         for(;;) {
86                 header += strspn(header, vseparators);
87                 if (!*header)
88                         return 0;
89                 len = strcspn(header, vseparators);
90                 if (n == len && 0 == strncasecmp(needle, header, n))
91                         return 1;
92                 header += len;
93         }
94 }
95
96 struct protodef
97 {
98         const char *name;
99         void *(*create)(struct fdev *fdev, struct afb_apiset *apiset, struct afb_context *context, void (*cleanup)(void*), void *cleanup_closure);
100 };
101
102 static const struct protodef *search_proto(const struct protodef *protodefs, const char *protocols)
103 {
104         int i;
105         size_t len;
106
107         if (protocols == NULL) {
108                 /* return NULL; */
109                 return protodefs != NULL && protodefs->name != NULL ? protodefs : NULL;
110         }
111         for(;;) {
112                 protocols += strspn(protocols, vseparators);
113                 if (!*protocols)
114                         return NULL;
115                 len = strcspn(protocols, vseparators);
116                 for (i = 0 ; protodefs[i].name != NULL ; i++)
117                         if (!strncasecmp(protodefs[i].name, protocols, len)
118                          && !protodefs[i].name[len])
119                                 return &protodefs[i];
120                 protocols += len;
121         }
122 }
123
124 struct memo_websocket {
125         const struct protodef *proto;
126         struct afb_hreq *hreq;
127         struct afb_apiset *apiset;
128 };
129
130 static void close_websocket(void *closure)
131 {
132         struct MHD_UpgradeResponseHandle *urh = closure;
133         MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE);
134 }
135
136 static void upgrade_to_websocket(
137                         void *cls,
138                         struct MHD_Connection *connection,
139                         void *con_cls,
140                         const char *extra_in,
141                         size_t extra_in_size,
142                         MHD_socket sock,
143                         struct MHD_UpgradeResponseHandle *urh)
144 {
145         struct memo_websocket *memo = cls;
146         void *ws;
147         struct fdev *fdev;
148
149         fdev = afb_fdev_create(sock);
150         if (!fdev) {
151                 /* TODO */
152                 close_websocket(urh);
153         } else {
154                 fdev_set_autoclose(fdev, 0);
155                 ws = memo->proto->create(fdev, memo->apiset, &memo->hreq->xreq.context, close_websocket, urh);
156                 if (ws == NULL) {
157                         /* TODO */
158                         close_websocket(urh);
159                 }
160         }
161 #if MHD_VERSION <= 0x00095900
162         afb_hreq_unref(memo->hreq);
163 #endif
164         free(memo);
165 }
166
167 static int check_websocket_upgrade(struct MHD_Connection *con, const struct protodef *protodefs, struct afb_hreq *hreq, struct afb_apiset *apiset)
168 {
169         struct memo_websocket *memo;
170         struct MHD_Response *response;
171         const char *connection, *upgrade, *key, *version, *protocols;
172         char acceptval[29];
173         int vernum;
174         const struct protodef *proto;
175
176         /* is an upgrade to websocket ? */
177         upgrade = MHD_lookup_connection_value(con, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE);
178         if (upgrade == NULL || strcasecmp(upgrade, websocket_s))
179                 return 0;
180
181         /* is a connection for upgrade ? */
182         connection = MHD_lookup_connection_value(con, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION);
183         if (connection == NULL
184          || !headerhas (connection, MHD_HTTP_HEADER_UPGRADE))
185                 return 0;
186
187         /* has a key and a version ? */
188         key = MHD_lookup_connection_value(con, MHD_HEADER_KIND, sec_websocket_key_s);
189         version = MHD_lookup_connection_value(con, MHD_HEADER_KIND, sec_websocket_version_s);
190         if (key == NULL || version == NULL)
191                 return 0;
192
193         /* is a supported version ? */
194         vernum = atoi(version);
195         if (vernum != 13) {
196                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
197                 MHD_add_response_header(response, sec_websocket_version_s, "13");
198                 MHD_queue_response(con, MHD_HTTP_UPGRADE_REQUIRED, response);
199                 MHD_destroy_response(response);
200                 return 1;
201         }
202
203         /* is the protocol supported ? */
204         protocols = MHD_lookup_connection_value(con, MHD_HEADER_KIND, sec_websocket_protocol_s);
205         proto = search_proto(protodefs, protocols);
206         if (proto == NULL) {
207                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
208                 MHD_queue_response(con, MHD_HTTP_PRECONDITION_FAILED, response);
209                 MHD_destroy_response(response);
210                 return 1;
211         }
212
213         /* record context */
214         memo = malloc(sizeof *memo);
215         if (memo == NULL) {
216                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
217                 MHD_queue_response(con, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
218                 MHD_destroy_response(response);
219                 return 1;
220         }
221         memo->proto = proto;
222         memo->hreq = hreq;
223         memo->apiset = apiset;
224
225         /* send the accept connection */
226         response = MHD_create_response_for_upgrade(upgrade_to_websocket, memo);
227         make_accept_value(key, acceptval);
228         MHD_add_response_header(response, sec_websocket_accept_s, acceptval);
229         MHD_add_response_header(response, sec_websocket_protocol_s, proto->name);
230         MHD_add_response_header(response, MHD_HTTP_HEADER_UPGRADE, websocket_s);
231         MHD_queue_response(con, MHD_HTTP_SWITCHING_PROTOCOLS, response);
232         MHD_destroy_response(response);
233
234         return 1;
235 }
236
237 static const struct protodef protodefs[] = {
238         { "x-afb-ws-json1",     (void*)afb_ws_json1_create },
239         { NULL, NULL }
240 };
241
242 int afb_websock_check_upgrade(struct afb_hreq *hreq, struct afb_apiset *apiset)
243 {
244         int rc;
245
246         /* is a get ? */
247         if (hreq->method != afb_method_get
248          || strcasecmp(hreq->version, MHD_HTTP_VERSION_1_1))
249                 return 0;
250
251         rc = check_websocket_upgrade(hreq->connection, protodefs, hreq, apiset);
252         if (rc == 1) {
253                 hreq->replied = 1;
254         }
255         return rc;
256 }
257