2 * Copyright (C) 2016 "IoT.bzh"
3 * Author: José Bollo <jose.bollo@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
26 #include <sys/types.h>
27 #include <sys/socket.h>
33 /**************** WebSocket handshake ****************************/
35 static const char *compkeys[32] = {
36 "lYKr2sn9+ILcLpkqdrE2VQ==", "G5J7ncQnmS/MubIYcqKWM+E6k8I=",
37 "gjN6eOU/6Yy7dBTJ+EaQSw==", "P5QzN7mRt4DeRWxKdG7s4/NCEwk=",
38 "ziLin6OQ0/a1+cGaI9Mupg==", "yvpxcFJAGam6huL77vz34CdShyU=",
39 "KMfd2bHKah0U5mk2Kg/LIg==", "lyYxfDP5YunhkBF+nAWb/w6K4yg=",
40 "fQ/ISF1mNCPRMyAj3ucqNg==", "91YY1EUelb4eMU24Z8WHhJ9cHmc=",
41 "RHlfiVVE1lM1AJnErI8dFg==", "UdZQc0JaihQJV5ETCZ84Av88pxQ=",
42 "NVy3L2ujXN7v3KEJwK92ww==", "+dE7iITxhExjBtf06VYNWChHqx8=",
43 "cCNAgttlgELfbDDIfhujww==", "W2JiswqbTAXx5u84EtjbtqAW2Bg=",
44 "K+oQvEDWJP+WXzRS5BJDFw==", "szgW10a9AuD+HtfS4ylaqWfzWAs=",
45 "nmg43S4DpVaxye+oQv9KTw==", "8XK74jB9xFfTzzl0wTqW04k3tPE=",
46 "LIqZ23sEppbF4YJR9LQ4/w==", "f8lJBQEbR8QmmvPHZpA0smlIeeA=",
47 "WY1vvvY2j/3V9DAGW3ZZcA==", "lROlE4vL4cjU1Vnk6rISc9gVKN0=",
48 "Ia+dgHnA9QaBrbxuqh4wgQ==", "GiGjxFdSaF0EGTl2cjvFsVmJnfM=",
49 "MfpIVG082jFTV7SxTNNijQ==", "f5I2h53hBsT5ES3EHhnxAJ2nqsw=",
50 "kFumnAw5d/WctG0yAUHPiQ==", "aQQmOjoABl7mrbliTPS1bOkndOs=",
51 "MHiEc+Qc8w/SJ3zMHEM8pA==", "FVCxLBmoil3gY0jSX3aNJ6kR/t4="
54 static const char websocket_s[] = "websocket";
55 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
56 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
57 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
58 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
60 static const char vseparators[] = " \t,";
62 /* get randomly a pair of key/accept value */
63 static void getkeypair(const char **key, const char **ack)
68 r = (r & 15) + (r >> 4);
74 /* joins the strings using the separator */
75 static char *strjoin(int count, const char **strings, const char *separ)
81 /* creates the count if needed */
83 for(count = 0 ; strings[count] != NULL ; count++);
85 /* compute the length of the result */
89 length = (unsigned)(count - 1) * strlen(separ);
90 for (idx = 0 ; idx < count ; idx ++)
91 length += strlen(strings[idx]);
94 /* allocates the result */
95 result = malloc(length + 1);
99 /* create the result */
101 iter = stpcpy(result, strings[idx = 0]);
102 while (++idx < count)
103 iter = stpcpy(stpcpy(iter, separ), strings[idx]);
104 // assert(iter - result == length);
111 /* creates the http message for the request */
112 static int make_request(char **request, const char *path, const char *host, const char *key, const char *protocols)
114 int rc = asprintf(request,
115 "GET %s HTTP/1.1\r\n"
117 "Upgrade: websocket\r\n"
118 "Connection: Upgrade\r\n"
119 "Sec-WebSocket-Version: 13\r\n"
120 "Sec-WebSocket-Key: %s\r\n"
121 "Sec-WebSocket-Protocol: %s\r\n"
122 "Content-Length: 0\r\n"
137 /* create the request and send it to fd, returns the expected accept string */
138 static const char *send_request(int fd, const char **protocols, const char *path, const char *host)
140 const char *key, *ack;
141 char *protolist, *request;
144 /* make the list of accepted protocols */
145 protolist = strjoin(-1, protocols, ", ");
146 if (protolist == NULL)
149 /* create the request */
150 getkeypair(&key, &ack);
151 length = make_request(&request, path, host, key, protolist);
156 /* send the request */
157 do { rc = (int)write(fd, request, length); } while(rc < 0 && errno == EINTR);
159 return rc < 0 ? NULL : ack;
162 /* read a line not efficiently but without buffering */
163 static int receive_line(int fd, char *line, int size)
165 int rc, length = 0, cr = 0;
167 if (length >= size) {
171 do { rc = (int)read(fd, line + length, 1); } while (rc < 0 && errno == EINTR);
174 if (line[length] == '\r')
176 else if (cr != 0 && line[length] == '\n') {
186 static inline int isheader(const char *head, size_t klen, const char *key)
188 return strncasecmp(head, key, klen) == 0 && key[klen] == 0;
191 /* receives and scan the response */
192 static int receive_response(int fd, const char **protocols, const char *ack)
194 char line[4096], *it;
195 int rc, haserr, result = -1;
198 /* check the header line to be something like: "HTTP/1.1 101 Switching Protocols" */
199 rc = receive_line(fd, line, (int)sizeof(line));
202 len = strcspn(line, " ");
203 if (len != 8 || 0 != strncmp(line, "HTTP/1.1", 8))
206 len = strspn(it, " ");
210 len = strcspn(it, " ");
211 if (len != 3 || 0 != strncmp(it, "101", 3))
214 /* reads the rest of the response until empty line */
218 rc = receive_line(fd, line, (int)sizeof(line));
223 len = strcspn(line, ": ");
224 if (len != 0 && line[len] == ':') {
225 /* checks the headers values */
227 it += strspn(it, " ,");
228 it[strcspn(it, " ,")] = 0;
229 if (isheader(line, len, "Sec-WebSocket-Accept")) {
230 if (strcmp(it, ack) != 0)
232 } else if (isheader(line, len, "Sec-WebSocket-Protocol")) {
234 while(protocols[result] != NULL && strcmp(it, protocols[result]) != 0)
236 } else if (isheader(line, len, "Upgrade")) {
237 if (strcmp(it, "websocket") != 0)
239 } else if (isheader(line, len, "Content-Length")) {
245 /* skips the remaining of the message */
246 while (clen >= sizeof line) {
247 while (read(fd, line, sizeof line) < 0 && errno == EINTR);
251 while (read(fd, line, len) < 0 && errno == EINTR);
253 if (haserr != 0 || result < 0)
257 errno = ECONNABORTED;
262 static int negociate(int fd, const char **protocols, const char *path, const char *host)
264 const char *ack = send_request(fd, protocols, path, host);
265 return ack == NULL ? -1 : receive_response(fd, protocols, ack);
268 /* tiny parse a "standard" websock uri ws://host:port/path... */
269 static int parse_uri(const char *uri, char **host, char **service, const char **path)
275 if (strncmp(uri, "ws://", 5) == 0)
280 hlen = strcspn(h, ":/");
285 /* the port (optional) */
288 plen = strcspn(p, "/");
301 /* make the result */
302 *host = strndup(h, hlen);
304 *service = plen ? strndup(p, plen) : strdup("http");
305 if (*service != NULL) {
323 static const char *proto_json1[2] = { "x-afb-ws-json1", NULL };
325 struct afb_wsj1 *afb_ws_client_connect_wsj1(const char *uri, struct afb_wsj1_itf *itf, void *closure)
328 char *host, *service, xhost[32];
330 struct addrinfo hint, *rai, *iai;
331 struct afb_wsj1 *result;
334 rc = parse_uri(uri, &host, &service, &path);
339 memset(&hint, 0, sizeof hint);
340 hint.ai_family = AF_INET;
341 hint.ai_socktype = SOCK_STREAM;
342 rc = getaddrinfo(host, service, &hint, &rai);
353 while (iai != NULL) {
354 struct sockaddr_in *a = (struct sockaddr_in*)(iai->ai_addr);
355 unsigned char *ipv4 = (unsigned char*)&(a->sin_addr.s_addr);
356 unsigned char *port = (unsigned char*)&(a->sin_port);
357 sprintf(xhost, "%d.%d.%d.%d:%d",
358 (int)ipv4[0], (int)ipv4[1], (int)ipv4[2], (int)ipv4[3],
359 (((int)port[0]) << 8)|(int)port[1]);
360 fd = socket(iai->ai_family, iai->ai_socktype, iai->ai_protocol);
362 rc = connect(fd, iai->ai_addr, iai->ai_addrlen);
364 rc = negociate(fd, proto_json1, path, xhost);
366 result = afb_wsj1_create(fd, itf, closure);
367 if (result != NULL) {
368 fcntl(fd, F_SETFL, O_NONBLOCK);
382 /* compute the queried path */
383 static char *makequery(const char *path, const char *uuid, const char *token)
392 rc = asprintf(&result, "/%s", path);
394 rc = asprintf(&result, "/%s?x-afb-token=%s", path, token);
397 rc = asprintf(&result, "/%s?x-afb-uuid=%s", path, uuid);
399 rc = asprintf(&result, "/%s?x-afb-uuid=%s&x-afb-token=%s", path, uuid, token);