2 * Copyright 2016 IoT.bzh
3 * Author: José Bollo <jose.bollo@iot.bzh>
5 * Inspired by the work of
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 #include <microhttpd.h>
29 #include <openssl/sha.h>
31 #include <openssl/bio.h>
32 #include <openssl/evp.h>
37 #include "local-def.h"
39 #include "afb-req-itf.h"
40 #include "afb-method.h"
42 #include "afb-websock.h"
45 #include "utils-upoll.h"
47 /**************** WebSocket connection upgrade ****************************/
49 static const char websocket_s[] = "websocket";
50 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
51 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
52 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
53 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
54 static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
56 static void enc64(unsigned char *in, char *out)
58 static const char tob64[] =
59 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
60 "abcdefghijklmnopqrstuvwxyz"
62 out[0] = tob64[in[0] >> 2];
63 out[1] = tob64[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
64 out[2] = tob64[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
65 out[3] = tob64[in[2] & 0x3f];
68 static void make_accept_value(const char *key, char result[29])
70 unsigned char md[SHA_DIGEST_LENGTH+1];
71 size_t len = strlen(key);
72 char *buffer = alloca(len + sizeof websocket_guid - 1);
73 memcpy(buffer, key, len);
74 memcpy(buffer + len, websocket_guid, sizeof websocket_guid - 1);
75 SHA1((const unsigned char *)buffer, (unsigned long)(len + sizeof websocket_guid - 1), md);
76 assert(SHA_DIGEST_LENGTH == 20);
78 enc64(&md[0], &result[0]);
79 enc64(&md[3], &result[4]);
80 enc64(&md[6], &result[8]);
81 enc64(&md[9], &result[12]);
82 enc64(&md[12], &result[16]);
83 enc64(&md[15], &result[20]);
84 enc64(&md[18], &result[24]);
89 static int headerhas(const char *header, const char *needle)
91 static const char sep[] = " \t,";
96 header += strspn(header, sep);
99 len = strcspn(header, sep);
100 if (n == len && 0 == strncasecmp(needle, header, n))
106 int afb_websock_check(struct afb_hreq *hreq, int *later)
108 const char *connection, *upgrade, *key, *version, *protocols;
111 struct MHD_Response *response;
113 /* is an upgrade to websocket ? */
114 upgrade = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_UPGRADE);
115 if (upgrade == NULL || strcasecmp(upgrade, websocket_s))
118 /* is a connection for upgrade ? */
119 connection = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONNECTION);
120 if (connection == NULL || !headerhas (connection, MHD_HTTP_HEADER_UPGRADE))
124 if(hreq->method != afb_method_get || strcasecmp(hreq->version, MHD_HTTP_VERSION_1_1))
127 /* has a key and a version ? */
128 key = afb_hreq_get_header(hreq, sec_websocket_key_s);
129 version = afb_hreq_get_header(hreq, sec_websocket_version_s);
130 if (key == NULL || version == NULL)
133 /* is a supported version ? */
134 vernum = atoi(version);
136 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
137 MHD_add_response_header (response, sec_websocket_version_s, "13");
138 MHD_queue_response (hreq->connection, MHD_HTTP_BAD_REQUEST, response);
139 MHD_destroy_response (response);
144 /* is the protocol supported ? */
145 protocols = afb_hreq_get_header(hreq, sec_websocket_protocol_s);
147 /* send the accept connection */
148 make_accept_value(key, acceptval);
149 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
150 MHD_add_response_header (response, sec_websocket_accept_s, acceptval);
151 MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, MHD_HTTP_HEADER_UPGRADE);
152 MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, websocket_s);
153 MHD_queue_response (hreq->connection, MHD_HTTP_SWITCHING_PROTOCOLS, response);
154 MHD_destroy_response (response);
160 /**************** WebSocket handling ****************************/
162 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
163 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
164 static void aws_disconnect(struct afb_websock *ws);
165 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size);
166 static void aws_on_content(struct afb_websock *ws, int last, size_t size);
167 static void aws_on_readable(struct afb_websock *ws);
169 static struct websock_itf aws_itf = {
170 .writev = (void*)aws_writev,
171 .readv = (void*)aws_readv,
172 .disconnect = (void*)aws_disconnect,
176 .on_close = (void*)aws_on_close,
177 .on_text = (void*)aws_on_content,
178 .on_binary = (void*)aws_on_content,
179 .on_continue = (void*)aws_on_content
184 struct afb_websock *aws;
185 struct afb_wsreq *next;
186 struct json_object *id;
187 struct json_object *name;
188 struct json_object *token;
189 struct json_object *request;
195 struct MHD_Connection *connection;
198 struct AFB_clientCtx *context;
199 struct json_tokener *tokener;
200 struct afb_wsreq *requests;
203 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
204 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
205 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
206 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
207 static int wsreq_session_create(struct afb_wsreq *wsreq);
208 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh);
209 static void wsreq_session_close(struct afb_wsreq *wsreq);
211 static const struct afb_req_itf wsreq_itf = {
212 .get = (void*)wsreq_get,
213 .iterate = (void*)wsreq_iterate,
214 .fail = (void*)wsreq_fail,
215 .success = (void*)wsreq_success,
216 .session_create = (void*)wsreq_session_create,
217 .session_check = (void*)wsreq_session_check,
218 .session_close = (void*)wsreq_session_close
221 struct afb_websock *afb_websock_create(struct afb_hreq *hreq)
224 struct afb_websock *result;
226 fd = MHD_get_connection_info(hreq->connection,
227 MHD_CONNECTION_INFO_CONNECTION_FD)->connect_fd;
232 result = malloc(sizeof * result);
236 result->connection = hreq->connection;
238 result->context = ctxClientGet(afb_hreq_context(hreq));
239 if (result->context == NULL)
242 result->tokener = json_tokener_new();
243 if (result->tokener == NULL)
246 result->ws = websock_create(&aws_itf, result);
247 if (result->ws == NULL)
250 result->up = upoll_open(result->fd, result);
251 if (result->up == NULL)
254 upoll_on_readable(result->up, (void*)aws_on_readable);
255 upoll_on_hangup(result->up, (void*)aws_disconnect);
258 websock_destroy(result->ws);
260 json_tokener_free(result->tokener);
268 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
272 rc = writev(ws->fd, iov, iovcnt);
273 } while(rc == -1 && errno == EINTR);
277 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
281 rc = readv(ws->fd, iov, iovcnt);
282 } while(rc == -1 && errno == EINTR);
286 static void aws_disconnect(struct afb_websock *ws)
289 websock_destroy(ws->ws);
291 MHD_resume_connection (ws->connection);
292 ctxClientPut(ws->context);
293 json_tokener_free(ws->tokener);
297 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size)
302 static void aws_on_readable(struct afb_websock *ws)
304 websock_dispatch(ws->ws);
307 static int aws_handle_json(struct afb_websock *aws, struct json_object *obj)
311 struct json_object *type, *id, *name, *req, *token;
312 struct afb_wsreq *wsreq;
313 const char *api, *verb;
314 size_t lenapi, lenverb;
316 /* protocol inspired by http://www.gir.fr/ocppjs/ocpp_srpc_spec.shtml */
318 /* the object must be an array of 4 or 5 elements */
319 if (!json_object_is_type(obj, json_type_array))
321 count = json_object_array_length(obj);
322 if (count < 4 || count > 5)
325 /* get the 5 elements: type id name request token */
326 type = json_object_array_get_idx(obj, 0);
327 id = json_object_array_get_idx(obj, 1);
328 name = json_object_array_get_idx(obj, 2);
329 req = json_object_array_get_idx(obj, 3);
330 token = json_object_array_get_idx(obj, 4);
332 /* check the types: int string string object string */
333 if (!json_object_is_type(type, json_type_int))
335 if (!json_object_is_type(id, json_type_string))
337 if (!json_object_is_type(name, json_type_string))
339 if (!json_object_is_type(req, json_type_object))
341 if (token != NULL && !json_object_is_type(token, json_type_string))
344 /* the type is only 2 */
345 num = json_object_get_int(type);
349 /* checks the api/verb structure of name */
350 api = json_object_get_string(name);
351 for (lenapi = 0 ; api[lenapi] && api[lenapi] != '/' ; lenapi++);
352 if (!lenapi || !api[lenapi])
354 verb = &api[lenapi+1];
355 for (lenverb = 0 ; verb[lenverb] && verb[lenverb] != '/' ; lenverb++);
356 if (!lenverb || verb[lenverb])
359 /* allocates the request data */
360 wsreq = malloc(sizeof *wsreq);
364 /* fill and record the request */
366 wsreq->id = json_object_get(id);
367 wsreq->name = json_object_get(name);
368 wsreq->token = json_object_get(token);
369 wsreq->request = json_object_get(req);
370 wsreq->next = aws->requests;
371 aws->requests = wsreq;
372 json_object_put(obj);
376 rc = afb_apis_handle(r, aws->context, api, lenapi, verb, lenverb);
378 wsreq_fail(wsreq, "ail", "api not found");
382 json_object_put(obj);
386 static void aws_on_content(struct afb_websock *ws, int last, size_t size)
390 struct json_object *obj;
392 json_tokener_reset(ws->tokener);
394 rrc = websock_read(ws->ws, buffer,
395 size > sizeof buffer ? sizeof buffer : size);
397 websock_close(ws->ws);
401 obj = json_tokener_parse_ex(ws->tokener, buffer, (int)rrc);
403 if (!aws_handle_json(ws, obj)) {
404 websock_close(ws->ws);
407 } else if (json_tokener_get_error(ws->tokener) != json_tokener_continue) {
408 websock_close(ws->ws);
415 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
418 struct json_object *value;
420 if (json_object_object_get_ex(wsreq->request, name, &value)) {
422 arg.value = json_object_get_string(value);
432 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
435 struct json_object_iterator it = json_object_iter_begin(wsreq->request);
436 struct json_object_iterator end = json_object_iter_end(wsreq->request);
440 while(!json_object_iter_equal(&it, &end)) {
441 arg.name = json_object_iter_peek_name(&it);
442 arg.value = json_object_get_string(json_object_iter_peek_value(&it));
443 if (!iterator(closure, arg))
445 json_object_iter_next(&it);
449 static int wsreq_session_create(struct afb_wsreq *wsreq)
451 struct AFB_clientCtx *context = wsreq->aws->context;
452 if (context->created)
454 return wsreq_session_check(wsreq, 1);
457 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh)
460 struct AFB_clientCtx *context = wsreq->aws->context;
462 if (wsreq->token == NULL)
465 token = json_object_get_string(wsreq->token);
469 if (!ctxTokenCheck (context, token))
473 ctxTokenNew (context);
479 static void wsreq_session_close(struct afb_wsreq *wsreq)
481 struct AFB_clientCtx *context = wsreq->aws->context;
482 ctxClientClose(context);
486 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
488 json_object *root, *request, *reply;
491 /* builds the answering structure */
492 root = json_object_new_object();
493 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
494 request = json_object_new_object();
495 json_object_object_add(root, "request", request);
496 json_object_object_add(request, "status", json_object_new_string(status));
498 json_object_object_add(request, "info", json_object_new_string(info));
500 json_object_object_add(root, "response", resp);
503 reply = json_object_new_array();
504 json_object_array_add(reply, json_object_new_int(retcode));
505 json_object_array_add(reply, wsreq->id);
506 json_object_array_add(reply, root);
507 json_object_array_add(reply, json_object_new_string(wsreq->aws->context->token));
509 /* emits the reply */
510 message = json_object_to_json_string(reply);
511 websock_text(wsreq->aws->ws, message, strlen(message));
513 /* TODO eliminates the wsreq */
516 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
518 wsreq_reply(wsreq, 4, status, info, NULL);
521 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
523 wsreq_reply(wsreq, 3, "success", info, obj);