libafbwsc: add function 'afb_ws_client_connect_api'
[src/app-framework-binder.git] / src / afb-client-demo.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author José Bollo <jose.bollo@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #define _GNU_SOURCE
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <errno.h>
30
31 #include <systemd/sd-event.h>
32 #include <json-c/json.h>
33
34 #include "afb-wsj1.h"
35 #include "afb-ws-client.h"
36 #include "afb-proto-ws.h"
37
38 /* declaration of functions */
39 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1);
40 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg);
41 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg);
42
43 static void on_pws_hangup(void *closure);
44 static void on_pws_reply_success(void *closure, void *request, struct json_object *result, const char *info);
45 static void on_pws_reply_fail(void *closure, void *request, const char *status, const char *info);
46 static void on_pws_event_create(void *closure, const char *event_name, int event_id);
47 static void on_pws_event_remove(void *closure, const char *event_name, int event_id);
48 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id);
49 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id);
50 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data);
51 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data);
52 static void on_pws_subcall(void *closure, struct afb_proto_ws_subcall *subcall, void *request, const char *api, const char *verb, struct json_object *args);
53
54 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *closure);
55
56 static void wsj1_emit(const char *api, const char *verb, const char *object);
57 static void pws_call(const char *verb, const char *object);
58
59 /* the callback interface for wsj1 */
60 static struct afb_wsj1_itf wsj1_itf = {
61         .on_hangup = on_wsj1_hangup,
62         .on_call = on_wsj1_call,
63         .on_event = on_wsj1_event
64 };
65
66 /* the callback interface for pws */
67 static struct afb_proto_ws_client_itf pws_itf = {
68         .on_reply_success = on_pws_reply_success,
69         .on_reply_fail = on_pws_reply_fail,
70         .on_event_create = on_pws_event_create,
71         .on_event_remove = on_pws_event_remove,
72         .on_event_subscribe = on_pws_event_subscribe,
73         .on_event_unsubscribe = on_pws_event_unsubscribe,
74         .on_event_push = on_pws_event_push,
75         .on_event_broadcast = on_pws_event_broadcast,
76         .on_subcall = on_pws_subcall,
77 };
78
79 /* global variables */
80 static struct afb_wsj1 *wsj1;
81 static struct afb_proto_ws *pws;
82 static int exonrep;
83 static int callcount;
84 static int human;
85 static int raw;
86 static int direct;
87 static sd_event_source *evsrc;
88 static char *sessionid = "afb-client-demo";
89
90 /* print usage of the program */
91 static void usage(int status, char *arg0)
92 {
93         char *name = strrchr(arg0, '/');
94         name = name ? name + 1 : arg0;
95         fprintf(status ? stderr : stdout, "usage: %s [-H [-r]] uri [api verb [data]]\n", name);
96         fprintf(status ? stderr : stdout, "       %s -d [-H [-r]] uri [verb [data]]\n", name);
97         exit(status);
98 }
99
100 /* entry function */
101 int main(int ac, char **av, char **env)
102 {
103         int rc;
104         char *a0;
105         sd_event *loop;
106
107         /* get the program name */
108         a0 = av[0];
109
110         /* check options */
111         while (ac > 1 && av[1][0] == '-') {
112                 if (av[1][1] == '-') {
113                         /* long option */
114
115                         if (!strcmp(av[1], "--human")) /* request for human output */
116                                 human = 1;
117
118                         else if (!strcmp(av[1], "--raw")) /* request for raw output */
119                                 raw = 1;
120
121                         else if (!strcmp(av[1], "--direct")) /* request for direct api */
122                                 direct = 1;
123
124                         /* emit usage and exit */
125                         else
126                                 usage(!!strcmp(av[1], "--help"), a0);
127                 } else {
128                         /* short option(s) */
129                         for (rc = 1 ; av[1][rc] ; rc++)
130                                 switch (av[1][rc]) {
131                                 case 'H': human = 1; break;
132                                 case 'r': raw = 1; break;
133                                 case 'd': direct = 1; break;
134                                 default: usage(av[1][rc] != 'h', a0);
135                                 }
136                 }
137                 av++;
138                 ac--;
139         }
140
141         /* check the argument count */
142         if (ac != 2 && ac != 4 && ac != 5)
143                 usage(1, a0);
144
145         /* set raw by default */
146         if (!human)
147                 raw = 1;
148
149         /* get the default event loop */
150         rc = sd_event_default(&loop);
151         if (rc < 0) {
152                 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
153                 return 1;
154         }
155
156         /* connect the websocket wsj1 to the uri given by the first argument */
157         if (direct) {
158                 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
159                 if (pws == NULL) {
160                         fprintf(stderr, "connection to %s failed: %m\n", av[1]);
161                         return 1;
162                 }
163                 afb_proto_ws_on_hangup(pws, on_pws_hangup);
164         } else {
165                 wsj1 = afb_ws_client_connect_wsj1(loop, av[1], &wsj1_itf, NULL);
166                 if (wsj1 == NULL) {
167                         fprintf(stderr, "connection to %s failed: %m\n", av[1]);
168                         return 1;
169                 }
170         }
171
172         /* test the behaviour */
173         if (ac == 2) {
174                 /* get requests from stdin */
175                 fcntl(0, F_SETFL, O_NONBLOCK);
176                 sd_event_add_io(loop, &evsrc, 0, EPOLLIN, io_event_callback, NULL);
177         } else {
178                 /* the request is defined by the arguments */
179                 exonrep = 1;
180                 if (direct)
181                         pws_call(av[2], av[3]);
182                 else
183                         wsj1_emit(av[2], av[3], av[4]);
184         }
185
186         /* loop until end */
187         for(;;)
188                 sd_event_run(loop, 30000000);
189         return 0;
190 }
191
192 /* decrement the count of calls */
193 static void dec_callcount()
194 {
195         callcount--;
196         if (exonrep && !callcount)
197                 exit(0);
198 }
199
200 /* called when wsj1 hangsup */
201 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
202 {
203         printf("ON-HANGUP\n");
204         fflush(stdout);
205         exit(0);
206 }
207
208 /* called when wsj1 receives a method invocation */
209 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
210 {
211         int rc;
212         if (raw)
213                 printf("ON-CALL %s/%s(%s)\n", api, verb, afb_wsj1_msg_object_s(msg));
214         if (human)
215                 printf("ON-CALL %s/%s:\n%s\n", api, verb,
216                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
217                                                         JSON_C_TO_STRING_PRETTY));
218         fflush(stdout);
219         rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
220         if (rc < 0)
221                 fprintf(stderr, "replying failed: %m\n");
222 }
223
224 /* called when wsj1 receives an event */
225 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
226 {
227         if (raw)
228                 printf("ON-EVENT %s(%s)\n", event, afb_wsj1_msg_object_s(msg));
229         if (human)
230                 printf("ON-EVENT %s:\n%s\n", event,
231                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
232                                                         JSON_C_TO_STRING_PRETTY));
233         fflush(stdout);
234 }
235
236 /* called when wsj1 receives a reply */
237 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
238 {
239         if (raw)
240                 printf("ON-REPLY %s: %s\n", (char*)closure, afb_wsj1_msg_object_s(msg));
241         if (human)
242                 printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
243                                 afb_wsj1_msg_is_reply_ok(msg) ? "OK" : "ERROR",
244                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
245                                                         JSON_C_TO_STRING_PRETTY));
246         fflush(stdout);
247         free(closure);
248         dec_callcount();
249 }
250
251 /* makes a call */
252 static void wsj1_call(const char *api, const char *verb, const char *object)
253 {
254         static int num = 0;
255         char *key;
256         int rc;
257
258         /* allocates an id for the request */
259         rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
260
261         /* send the request */
262         callcount++;
263         rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
264         if (rc < 0) {
265                 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
266                 dec_callcount();
267         }
268 }
269
270 /* sends an event */
271 static void wsj1_event(const char *event, const char *object)
272 {
273         int rc;
274
275         rc = afb_wsj1_send_event_s(wsj1, event, object);
276         if (rc < 0)
277                 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
278 }
279
280 /* emits either a call (when api!='!') or an event */
281 static void wsj1_emit(const char *api, const char *verb, const char *object)
282 {
283         if (object == NULL || object[0] == 0)
284                 object = "null";
285         if (api[0] == '!' && api[1] == 0)
286                 wsj1_event(verb, object);
287         else
288                 wsj1_call(api, verb, object);
289 }
290
291 /* called when something happens on stdin */
292 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *closure)
293 {
294         static size_t count = 0;
295         static char line[16384];
296         static char sep[] = " \t";
297         static char sepnl[] = " \t\n";
298
299         ssize_t rc;
300         size_t pos;
301
302         /* read the buffer */
303         do { rc = read(0, line + count, sizeof line - count); } while (rc < 0 && errno == EINTR);
304         if (rc < 0) {
305                 fprintf(stderr, "read error: %m\n");
306                 exit(1);
307         }
308         if (rc == 0) {
309                 if (!callcount)
310                         exit(0);
311                 exonrep = 1;
312                 sd_event_source_unref(evsrc);
313         }
314         count += (size_t)rc;
315
316         /* normalise the buffer content */
317         /* TODO: handle backspace \x7f ? */
318
319         /* process the lines */
320         pos = 0;
321         for(;;) {
322                 size_t i, api[2], verb[2], rest[2];
323                 i = pos;
324                 while(i < count && strchr(sep, line[i])) i++;
325                 api[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; api[1] = i;
326                 while(i < count && strchr(sep, line[i])) i++;
327                 if (direct) {
328                         verb[0] = api[0];
329                         verb[1] = api[1];
330                 } else {
331                         verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
332                         while(i < count && strchr(sep, line[i])) i++;
333                 }
334                 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
335                 if (i == count) break;
336                 line[i++] = 0;
337                 if (api[0] == api[1]) {
338                         /* empty line */
339                 } else if (line[api[0]] == '#') {
340                         /* comment */
341                 } else if (verb[0] == verb[1]) {
342                         fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
343                 } else {
344                         line[api[1]] = line[verb[1]] = 0;
345                         if (direct)
346                                 pws_call(line + verb[0], line + rest[0]);
347                         else
348                                 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
349                 }
350                 pos = i;
351         }
352         count -= pos;
353         if (count == sizeof line) {
354                 fprintf(stderr, "overflow\n");
355                 exit(1);
356         }
357         if (count)
358                 memmove(line, line + pos, count);
359         return 1;
360 }
361
362 static void on_pws_reply_success(void *closure, void *request, struct json_object *result, const char *info)
363 {
364         if (raw)
365                 printf("ON-REPLY-SUCCESS %s: [%s] %s\n", (char*)request, info?:"", json_object_to_json_string(result));
366         if (human)
367                 printf("ON-REPLY-SUCCESS %s: %s\n%s\n", (char*)request, info?:"", json_object_to_json_string_ext(result, JSON_C_TO_STRING_PRETTY));
368         fflush(stdout);
369         free(request);
370         dec_callcount();
371 }
372
373 static void on_pws_reply_fail(void *closure, void *request, const char *status, const char *info)
374 {
375         printf("ON-REPLY-FAIL %s: %s [%s]\n", (char*)request, status?:"?", info?:"");
376         fflush(stdout);
377         free(request);
378         dec_callcount();
379 }
380
381 static void on_pws_event_create(void *closure, const char *event_name, int event_id)
382 {
383         printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
384         fflush(stdout);
385 }
386
387 static void on_pws_event_remove(void *closure, const char *event_name, int event_id)
388 {
389         printf("ON-EVENT-REMOVE: [%d:%s]\n", event_id, event_name);
390         fflush(stdout);
391 }
392
393 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
394 {
395         printf("ON-EVENT-SUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
396         fflush(stdout);
397 }
398
399 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
400 {
401         printf("ON-EVENT-UNSUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
402         fflush(stdout);
403 }
404
405 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
406 {
407         if (raw)
408                 printf("ON-EVENT-PUSH: [%d:%s] %s\n", event_id, event_name, json_object_to_json_string(data));
409         if (human)
410                 printf("ON-EVENT-PUSH: [%d:%s]\n%s\n", event_id, event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_PRETTY));
411         fflush(stdout);
412 }
413
414 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data)
415 {
416         if (raw)
417                 printf("ON-EVENT-BROADCAST: [%s] %s\n", event_name, json_object_to_json_string(data));
418         if (human)
419                 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_PRETTY));
420         fflush(stdout);
421 }
422
423 static void on_pws_subcall(void *closure, struct afb_proto_ws_subcall *subcall, void *request, const char *api, const char *verb, struct json_object *args)
424 {
425         if (raw)
426                 printf("ON-SUBCALL %s: %s/%s %s\n", (char*)request, api, verb, json_object_to_json_string(args));
427         if (human)
428                 printf("ON-SUBCALL %s: %s/%s\n%s\n", (char*)request, api, verb, json_object_to_json_string_ext(args, JSON_C_TO_STRING_PRETTY));
429         afb_proto_ws_subcall_reply(subcall, 1, NULL);
430         fflush(stdout);
431 }
432
433 /* makes a call */
434 static void pws_call(const char *verb, const char *object)
435 {
436         static int num = 0;
437         char *key;
438         int rc;
439         struct json_object *o;
440
441         /* allocates an id for the request */
442         rc = asprintf(&key, "%d:%s", ++num, verb);
443
444         /* send the request */
445         callcount++;
446         if (object == NULL || object[0] == 0 || !strcmp(object, "null"))
447                 o = NULL;
448         else {
449                 o = json_tokener_parse(object);
450                 if (!o)
451                         o = json_object_new_string(object);
452         }
453         rc = afb_proto_ws_client_call(pws, verb, o, sessionid, key);
454         if (rc < 0) {
455                 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
456                 dec_callcount();
457         }
458 }
459
460 /* called when pws hangsup */
461 static void on_pws_hangup(void *closure)
462 {
463         printf("ON-HANGUP\n");
464         fflush(stdout);
465         exit(0);
466 }
467
468