favor new names at entry for token and uuid
[src/app-framework-binder.git] / src / afb-ws-client.c
1 /*
2  * Copyright (C) 2016 "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 <stdio.h>
22 #include <unistd.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netdb.h>
29 #include <fcntl.h>
30
31 #include "afb-wsj1.h"
32
33 /**************** WebSocket handshake ****************************/
34
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="
52 };
53
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";
59
60 static const char vseparators[] = " \t,";
61
62 /* get randomly a pair of key/accept value */
63 static void getkeypair(const char **key, const char **ack)
64 {
65         int r;
66         r = rand();
67         while (r > 15)
68                 r = (r & 15) + (r >> 4);
69         r = (r & 15) << 1;
70         *key = compkeys[r];
71         *ack = compkeys[r+1];
72 }
73
74 /* joins the strings using the separator */
75 static char *strjoin(int count, const char **strings, const char *separ)
76 {
77         char *result, *iter;
78         size_t length;
79         int idx;
80
81         /* creates the count if needed */
82         if (count < 0)
83                 for(count = 0 ; strings[count] != NULL ; count++);
84
85         /* compute the length of the result */
86         if (count == 0)
87                 length = 0;
88         else {
89                 length = (unsigned)(count - 1) * strlen(separ);
90                 for (idx = 0 ; idx < count ; idx ++)
91                         length += strlen(strings[idx]);
92         }
93
94         /* allocates the result */
95         result = malloc(length + 1);
96         if (result == NULL)
97                 errno = ENOMEM;
98         else {
99                 /* create the result */
100                 if (count != 0) {
101                         iter = stpcpy(result, strings[idx = 0]);
102                         while (++idx < count)
103                                 iter = stpcpy(stpcpy(iter, separ), strings[idx]);
104                         // assert(iter - result == length);
105                 }
106                 result[length] = 0;
107         }
108         return result;
109 }
110
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)
113 {
114         int rc = asprintf(request, 
115                         "GET %s HTTP/1.1\r\n"
116                         "Host: %s\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"
123                         "\r\n"
124                         , path
125                         , host
126                         , key
127                         , protocols
128                 );
129         if (rc < 0) {
130                 errno = ENOMEM;
131                 *request = NULL;
132                 return -1;
133         }
134         return rc;
135 }
136
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)
139 {
140         const char *key, *ack;
141         char *protolist, *request;
142         int length, rc;
143
144         /* make the list of accepted protocols */
145         protolist = strjoin(-1, protocols, ", ");
146         if (protolist == NULL)
147                 return NULL;
148
149         /* create the request */
150         getkeypair(&key, &ack);
151         length = make_request(&request, path, host, key, protolist);
152         free(protolist);
153         if (length < 0)
154                 return NULL;
155
156         /* send the request */
157         do { rc = (int)write(fd, request, length); } while(rc < 0 && errno == EINTR);
158         free(request);
159         return rc < 0 ? NULL : ack;
160 }
161
162 /* read a line not efficiently but without buffering */
163 static int receive_line(int fd, char *line, int size)
164 {
165         int rc, length = 0, cr = 0;
166         for(;;) {
167                 if (length >= size) {
168                         errno = EFBIG;
169                         return -1;
170                 }
171                 do { rc = (int)read(fd, line + length, 1); } while (rc < 0 && errno == EINTR);
172                 if (rc < 0)
173                         return -1;
174                 if (line[length] == '\r')
175                         cr = 1;
176                 else if (cr != 0 && line[length] == '\n') {
177                         line[--length] = 0;
178                         return length;
179                 } else
180                         cr = 0;
181                 length++;
182         }
183 }
184
185 /* check a header */
186 static inline int isheader(const char *head, size_t klen, const char *key)
187 {
188         return strncasecmp(head, key, klen) == 0 && key[klen] == 0;
189 }
190
191 /* receives and scan the response */
192 static int receive_response(int fd, const char **protocols, const char *ack)
193 {
194         char line[4096], *it;
195         int rc, haserr, result = -1;
196         size_t len, clen;
197
198         /* check the header line to be something like: "HTTP/1.1 101 Switching Protocols" */
199         rc = receive_line(fd, line, (int)sizeof(line));
200         if (rc < 0)
201                 goto error;
202         len = strcspn(line, " ");
203         if (len != 8 || 0 != strncmp(line, "HTTP/1.1", 8))
204                 goto abort;
205         it = line + len;
206         len = strspn(it, " ");
207         if (len == 0)
208                 goto abort;
209         it += len;
210         len = strcspn(it, " ");
211         if (len != 3 || 0 != strncmp(it, "101", 3))
212                 goto abort;
213
214         /* reads the rest of the response until empty line */
215         clen = 0;
216         haserr = 0;
217         for(;;) {
218                 rc = receive_line(fd, line, (int)sizeof(line));
219                 if (rc < 0)
220                         goto error;
221                 if (rc == 0)
222                         break;
223                 len = strcspn(line, ": ");
224                 if (len != 0 && line[len] == ':') {
225                         /* checks the headers values */
226                         it = line + len + 1;
227                         it += strspn(it, " ,");
228                         it[strcspn(it, " ,")] = 0;
229                         if (isheader(line, len, "Sec-WebSocket-Accept")) {
230                                 if (strcmp(it, ack) != 0)
231                                         haserr = 1;
232                         } else if (isheader(line, len, "Sec-WebSocket-Protocol")) {
233                                 result = 0;
234                                 while(protocols[result] != NULL && strcmp(it, protocols[result]) != 0)
235                                         result++;
236                         } else if (isheader(line, len, "Upgrade")) {
237                                 if (strcmp(it, "websocket") != 0)
238                                         haserr = 1;
239                         } else if (isheader(line, len, "Content-Length")) {
240                                 clen = atol(it);
241                         }
242                 }
243         }
244
245         /* skips the remaining of the message */
246         while (clen >= sizeof line) {
247                 while (read(fd, line, sizeof line) < 0 && errno == EINTR);
248                 clen -= sizeof line;
249         }
250         if (clen > 0) {
251                 while (read(fd, line, len) < 0 && errno == EINTR);
252         }
253         if (haserr != 0 || result < 0)
254                 goto abort;
255         return result;
256 abort:
257         errno = ECONNABORTED;
258 error:
259         return -1;
260 }
261
262 static int negociate(int fd, const char **protocols, const char *path, const char *host)
263 {
264         const char *ack = send_request(fd, protocols, path, host);
265         return ack == NULL ? -1 : receive_response(fd, protocols, ack);
266 }
267
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)
270 {
271         const char *h, *p;
272         size_t hlen, plen;
273
274         /* the scheme */
275         if (strncmp(uri, "ws://", 5) == 0)
276                 uri += 5;
277
278         /* the host */
279         h = uri;
280         hlen = strcspn(h, ":/");
281         if (hlen == 0)
282                 goto invalid;
283         uri += hlen;
284
285         /* the port (optional) */
286         if (*uri == ':') {
287                 p = ++uri;
288                 plen = strcspn(p, "/");
289                 if (plen == 0)
290                         goto invalid;
291                 uri += plen;
292         } else {
293                 p = NULL;
294                 plen = 0;
295         }
296
297         /* the path */
298         if (*uri != '/')
299                 goto invalid;
300
301         /* make the result */
302         *host = strndup(h, hlen);
303         if (*host != NULL) {
304                 *service = plen ? strndup(p, plen) : strdup("http");
305                 if (*service != NULL) {
306                         *path = uri;
307                         return 0;
308                 }
309                 free(*host);
310         }
311         errno = ENOMEM;
312         goto error;
313 invalid:
314         errno = EINVAL;
315 error:
316         return -1;
317         
318 }
319
320
321
322
323 static const char *proto_json1[2] = { "x-afb-ws-json1", NULL };
324
325 struct afb_wsj1 *afb_ws_client_connect_wsj1(const char *uri, struct afb_wsj1_itf *itf, void *closure)
326 {
327         int rc, fd;
328         char *host, *service, xhost[32];
329         const char *path;
330         struct addrinfo hint, *rai, *iai;
331         struct afb_wsj1 *result;
332
333         /* scan the uri */
334         rc = parse_uri(uri, &host, &service, &path);
335         if (rc < 0)
336                 return NULL;
337
338         /* get addr */
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);
343         free(host);
344         free(service);
345         if (rc != 0) {
346                 errno = EINVAL;
347                 return NULL;
348         }
349
350         /* get the socket */
351         result = NULL;
352         iai = 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);
361                 if (fd >= 0) {
362                         rc = connect(fd, iai->ai_addr, iai->ai_addrlen);
363                         if (rc == 0) {
364                                 rc = negociate(fd, proto_json1, path, xhost);
365                                 if (rc == 0) {
366                                         result = afb_wsj1_create(fd, itf, closure);
367                                         if (result != NULL) {
368                                                 fcntl(fd, F_SETFL, O_NONBLOCK);
369                                                 break;
370                                         }
371                                 }
372                         }
373                         close(fd);
374                 }
375                 iai = iai->ai_next;
376         }
377         freeaddrinfo(rai);
378         return result;
379 }
380
381 #if 0
382 /* compute the queried path */
383 static char *makequery(const char *path, const char *uuid, const char *token)
384 {
385         char *result;
386         int rc;
387
388         while(*path == '/')
389                 path++;
390         if (uuid == NULL) {
391                 if (token == NULL)
392                         rc = asprintf(&result, "/%s", path);
393                 else
394                         rc = asprintf(&result, "/%s?x-afb-token=%s", path, token);
395         } else {
396                 if (token == NULL)
397                         rc = asprintf(&result, "/%s?x-afb-uuid=%s", path, uuid);
398                 else
399                         rc = asprintf(&result, "/%s?x-afb-uuid=%s&x-afb-token=%s", path, uuid, token);
400         }
401         if (rc < 0) {
402                 errno = ENOMEM;
403                 return NULL;
404         }
405         return result;
406 }
407 #endif
408
409