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