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>
33 #include "afb-req-itf.h"
34 #include "afb-method.h"
36 #include "afb-websock.h"
39 #include "utils-upoll.h"
41 /**************** WebSocket connection upgrade ****************************/
43 static const char websocket_s[] = "websocket";
44 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
45 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
46 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
47 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
48 static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
50 static void enc64(unsigned char *in, char *out)
52 static const char tob64[] =
53 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
54 "abcdefghijklmnopqrstuvwxyz"
56 out[0] = tob64[in[0] >> 2];
57 out[1] = tob64[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
58 out[2] = tob64[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
59 out[3] = tob64[in[2] & 0x3f];
62 static void make_accept_value(const char *key, char result[29])
64 unsigned char md[SHA_DIGEST_LENGTH+1];
65 size_t len = strlen(key);
66 char *buffer = alloca(len + sizeof websocket_guid - 1);
67 memcpy(buffer, key, len);
68 memcpy(buffer + len, websocket_guid, sizeof websocket_guid - 1);
69 SHA1((const unsigned char *)buffer, (unsigned long)(len + sizeof websocket_guid - 1), md);
70 assert(SHA_DIGEST_LENGTH == 20);
72 enc64(&md[0], &result[0]);
73 enc64(&md[3], &result[4]);
74 enc64(&md[6], &result[8]);
75 enc64(&md[9], &result[12]);
76 enc64(&md[12], &result[16]);
77 enc64(&md[15], &result[20]);
78 enc64(&md[18], &result[24]);
83 static int headerhas(const char *header, const char *needle)
85 static const char sep[] = " \t,";
90 header += strspn(header, sep);
93 len = strcspn(header, sep);
94 if (n == len && 0 == strncasecmp(needle, header, n))
100 int afb_websock_check(struct afb_hreq *hreq, int *later)
102 const char *connection, *upgrade, *key, *version, *protocols;
105 struct MHD_Response *response;
107 /* is an upgrade to websocket ? */
108 upgrade = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_UPGRADE);
109 if (upgrade == NULL || strcasecmp(upgrade, websocket_s))
112 /* is a connection for upgrade ? */
113 connection = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONNECTION);
114 if (connection == NULL || !headerhas (connection, MHD_HTTP_HEADER_UPGRADE))
118 if(hreq->method != afb_method_get || strcasecmp(hreq->version, MHD_HTTP_VERSION_1_1))
121 /* has a key and a version ? */
122 key = afb_hreq_get_header(hreq, sec_websocket_key_s);
123 version = afb_hreq_get_header(hreq, sec_websocket_version_s);
124 if (key == NULL || version == NULL)
127 /* is a supported version ? */
128 vernum = atoi(version);
130 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
131 MHD_add_response_header (response, sec_websocket_version_s, "13");
132 MHD_queue_response (hreq->connection, MHD_HTTP_BAD_REQUEST, response);
133 MHD_destroy_response (response);
138 /* is the protocol supported ? */
139 protocols = afb_hreq_get_header(hreq, sec_websocket_protocol_s);
141 /* send the accept connection */
142 make_accept_value(key, acceptval);
143 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
144 MHD_add_response_header (response, sec_websocket_accept_s, acceptval);
145 MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, MHD_HTTP_HEADER_UPGRADE);
146 MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, websocket_s);
147 MHD_queue_response (hreq->connection, MHD_HTTP_SWITCHING_PROTOCOLS, response);
148 MHD_destroy_response (response);
154 /**************** WebSocket handling ****************************/
156 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
157 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
158 static void aws_disconnect(struct afb_websock *ws);
159 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size);
160 static void aws_on_content(struct afb_websock *ws, int last, size_t size);
161 static void aws_on_readable(struct afb_websock *ws);
163 static struct websock_itf aws_itf = {
164 .writev = (void*)aws_writev,
165 .readv = (void*)aws_readv,
166 .disconnect = (void*)aws_disconnect,
170 .on_close = (void*)aws_on_close,
171 .on_text = (void*)aws_on_content,
172 .on_binary = (void*)aws_on_content,
173 .on_continue = (void*)aws_on_content,
174 .on_extension = NULL,
179 struct afb_websock *aws;
180 struct afb_wsreq *next;
181 struct json_object *id;
182 struct json_object *name;
183 struct json_object *token;
184 struct json_object *request;
190 struct MHD_Connection *connection;
193 struct AFB_clientCtx *context;
194 struct json_tokener *tokener;
195 struct afb_wsreq *requests;
198 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
199 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
200 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
201 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
202 static int wsreq_session_create(struct afb_wsreq *wsreq);
203 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh);
204 static void wsreq_session_close(struct afb_wsreq *wsreq);
206 static const struct afb_req_itf wsreq_itf = {
207 .get = (void*)wsreq_get,
208 .iterate = (void*)wsreq_iterate,
209 .fail = (void*)wsreq_fail,
210 .success = (void*)wsreq_success,
211 .session_create = (void*)wsreq_session_create,
212 .session_check = (void*)wsreq_session_check,
213 .session_close = (void*)wsreq_session_close
216 struct afb_websock *afb_websock_create(struct afb_hreq *hreq)
219 struct afb_websock *result;
221 fd = MHD_get_connection_info(hreq->connection,
222 MHD_CONNECTION_INFO_CONNECTION_FD)->connect_fd;
227 result = malloc(sizeof * result);
231 result->connection = hreq->connection;
233 result->context = ctxClientGet(afb_hreq_context(hreq));
234 if (result->context == NULL)
237 result->tokener = json_tokener_new();
238 if (result->tokener == NULL)
241 result->ws = websock_create_v13(&aws_itf, result);
242 if (result->ws == NULL)
245 result->up = upoll_open(result->fd, result);
246 if (result->up == NULL)
249 upoll_on_readable(result->up, (void*)aws_on_readable);
250 upoll_on_hangup(result->up, (void*)aws_disconnect);
253 websock_destroy(result->ws);
255 json_tokener_free(result->tokener);
257 ctxClientPut(result->context);
265 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
269 rc = writev(ws->fd, iov, iovcnt);
270 } while(rc == -1 && errno == EINTR);
274 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
278 rc = readv(ws->fd, iov, iovcnt);
279 } while(rc == -1 && errno == EINTR);
283 static void aws_disconnect(struct afb_websock *ws)
286 websock_destroy(ws->ws);
288 MHD_resume_connection (ws->connection);
289 ctxClientPut(ws->context);
290 json_tokener_free(ws->tokener);
294 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size)
299 static void aws_on_readable(struct afb_websock *ws)
301 websock_dispatch(ws->ws);
304 static int aws_handle_json(struct afb_websock *aws, struct json_object *obj)
308 struct json_object *type, *id, *name, *req, *token;
309 struct afb_wsreq *wsreq;
310 const char *api, *verb;
311 size_t lenapi, lenverb;
313 /* protocol inspired by http://www.gir.fr/ocppjs/ocpp_srpc_spec.shtml */
315 /* the object must be an array of 4 or 5 elements */
316 if (!json_object_is_type(obj, json_type_array))
318 count = json_object_array_length(obj);
319 if (count < 4 || count > 5)
322 /* get the 5 elements: type id name request token */
323 type = json_object_array_get_idx(obj, 0);
324 id = json_object_array_get_idx(obj, 1);
325 name = json_object_array_get_idx(obj, 2);
326 req = json_object_array_get_idx(obj, 3);
327 token = json_object_array_get_idx(obj, 4);
329 /* check the types: int string string object string */
330 if (!json_object_is_type(type, json_type_int))
332 if (!json_object_is_type(id, json_type_string))
334 if (!json_object_is_type(name, json_type_string))
336 if (!json_object_is_type(req, json_type_object))
338 if (token != NULL && !json_object_is_type(token, json_type_string))
341 /* the type is only 2 */
342 num = json_object_get_int(type);
346 /* checks the api/verb structure of name */
347 api = json_object_get_string(name);
348 for (lenapi = 0 ; api[lenapi] && api[lenapi] != '/' ; lenapi++);
349 if (!lenapi || !api[lenapi])
351 verb = &api[lenapi+1];
352 for (lenverb = 0 ; verb[lenverb] && verb[lenverb] != '/' ; lenverb++);
353 if (!lenverb || verb[lenverb])
356 /* allocates the request data */
357 wsreq = malloc(sizeof *wsreq);
361 /* fill and record the request */
363 wsreq->id = json_object_get(id);
364 wsreq->name = json_object_get(name);
365 wsreq->token = json_object_get(token);
366 wsreq->request = json_object_get(req);
367 wsreq->next = aws->requests;
368 aws->requests = wsreq;
369 json_object_put(obj);
373 afb_apis_call(r, aws->context, api, lenapi, verb, lenverb);
377 json_object_put(obj);
381 static void aws_on_content(struct afb_websock *ws, int last, size_t size)
385 struct json_object *obj;
387 json_tokener_reset(ws->tokener);
389 rrc = websock_read(ws->ws, buffer,
390 size > sizeof buffer ? sizeof buffer : size);
392 websock_close(ws->ws);
396 obj = json_tokener_parse_ex(ws->tokener, buffer, (int)rrc);
398 if (!aws_handle_json(ws, obj)) {
399 websock_close(ws->ws);
402 } else if (json_tokener_get_error(ws->tokener) != json_tokener_continue) {
403 websock_close(ws->ws);
409 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
412 struct json_object *value;
414 if (json_object_object_get_ex(wsreq->request, name, &value)) {
416 arg.value = json_object_get_string(value);
417 arg.size = strlen(arg.value);
427 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
430 struct json_object_iterator it = json_object_iter_begin(wsreq->request);
431 struct json_object_iterator end = json_object_iter_end(wsreq->request);
435 while(!json_object_iter_equal(&it, &end)) {
436 arg.name = json_object_iter_peek_name(&it);
437 arg.value = json_object_get_string(json_object_iter_peek_value(&it));
438 if (!iterator(closure, arg))
440 json_object_iter_next(&it);
444 static int wsreq_session_create(struct afb_wsreq *wsreq)
446 struct AFB_clientCtx *context = wsreq->aws->context;
447 if (context->created)
449 return wsreq_session_check(wsreq, 1);
452 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh)
455 struct AFB_clientCtx *context = wsreq->aws->context;
457 if (wsreq->token == NULL)
460 token = json_object_get_string(wsreq->token);
464 if (!ctxTokenCheck (context, token))
468 ctxTokenNew (context);
474 static void wsreq_session_close(struct afb_wsreq *wsreq)
476 struct AFB_clientCtx *context = wsreq->aws->context;
477 ctxClientClose(context);
481 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
483 json_object *root, *request, *reply;
486 /* builds the answering structure */
487 root = json_object_new_object();
488 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
489 request = json_object_new_object();
490 json_object_object_add(root, "request", request);
491 json_object_object_add(request, "status", json_object_new_string(status));
493 json_object_object_add(request, "info", json_object_new_string(info));
495 json_object_object_add(root, "response", resp);
498 reply = json_object_new_array();
499 json_object_array_add(reply, json_object_new_int(retcode));
500 json_object_array_add(reply, wsreq->id);
501 json_object_array_add(reply, root);
502 json_object_array_add(reply, json_object_new_string(wsreq->aws->context->token));
504 /* emits the reply */
505 message = json_object_to_json_string(reply);
506 websock_text(wsreq->aws->ws, message, strlen(message));
507 json_object_put(reply);
509 /* TODO eliminates the wsreq */
512 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
514 wsreq_reply(wsreq, 4, status, info, NULL);
517 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
519 wsreq_reply(wsreq, 3, "success", info, obj);