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