a784bdb79580809830c5ee7b08380ad8527b74f0
[src/app-framework-binder.git] / src / afb-client-demo.c
1 /*
2  * Copyright (C) 2015-2018 "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 breakcon;
83 static int exonrep;
84 static int callcount;
85 static int human;
86 static int raw;
87 static int direct;
88 static sd_event_source *evsrc;
89 static char *sessionid = "afb-client-demo";
90
91 /* print usage of the program */
92 static void usage(int status, char *arg0)
93 {
94         char *name = strrchr(arg0, '/');
95         name = name ? name + 1 : arg0;
96         fprintf(status ? stderr : stdout, "usage: %s [-H [-r]] [-b] uri [api verb [data]]\n", name);
97         fprintf(status ? stderr : stdout, "       %s -d [-H [-r]] [-b] uri [verb [data]]\n", name);
98         exit(status);
99 }
100
101 /* entry function */
102 int main(int ac, char **av, char **env)
103 {
104         int rc;
105         char *a0;
106         sd_event *loop;
107
108         /* get the program name */
109         a0 = av[0];
110
111         /* check options */
112         while (ac > 1 && av[1][0] == '-') {
113                 if (av[1][1] == '-') {
114                         /* long option */
115
116                         if (!strcmp(av[1], "--human")) /* request for human output */
117                                 human = 1;
118
119                         else if (!strcmp(av[1], "--raw")) /* request for raw output */
120                                 raw = 1;
121
122                         else if (!strcmp(av[1], "--direct")) /* request for direct api */
123                                 direct = 1;
124
125                         else if (!strcmp(av[1], "--break")) /* request to break connection */
126                                 breakcon = 1;
127
128                         /* emit usage and exit */
129                         else
130                                 usage(!!strcmp(av[1], "--help"), a0);
131                 } else {
132                         /* short option(s) */
133                         for (rc = 1 ; av[1][rc] ; rc++)
134                                 switch (av[1][rc]) {
135                                 case 'H': human = 1; break;
136                                 case 'r': raw = 1; break;
137                                 case 'd': direct = 1; break;
138                                 case 'b': breakcon = 1; break;
139                                 default: usage(av[1][rc] != 'h', a0);
140                                 }
141                 }
142                 av++;
143                 ac--;
144         }
145
146         /* check the argument count */
147         if (ac != 2 && ac != 4 && ac != 5)
148                 usage(1, a0);
149
150         /* set raw by default */
151         if (!human)
152                 raw = 1;
153
154         /* get the default event loop */
155         rc = sd_event_default(&loop);
156         if (rc < 0) {
157                 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
158                 return 1;
159         }
160
161         /* connect the websocket wsj1 to the uri given by the first argument */
162         if (direct) {
163                 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
164                 if (pws == NULL) {
165                         fprintf(stderr, "connection to %s failed: %m\n", av[1]);
166                         return 1;
167                 }
168                 afb_proto_ws_on_hangup(pws, on_pws_hangup);
169         } else {
170                 wsj1 = afb_ws_client_connect_wsj1(loop, av[1], &wsj1_itf, NULL);
171                 if (wsj1 == NULL) {
172                         fprintf(stderr, "connection to %s failed: %m\n", av[1]);
173                         return 1;
174                 }
175         }
176
177         /* test the behaviour */
178         if (ac == 2) {
179                 /* get requests from stdin */
180                 fcntl(0, F_SETFL, O_NONBLOCK);
181                 sd_event_add_io(loop, &evsrc, 0, EPOLLIN, io_event_callback, NULL);
182         } else {
183                 /* the request is defined by the arguments */
184                 exonrep = 1;
185                 if (direct)
186                         pws_call(av[2], av[3]);
187                 else
188                         wsj1_emit(av[2], av[3], av[4]);
189         }
190
191         /* loop until end */
192         for(;;)
193                 sd_event_run(loop, 30000000);
194         return 0;
195 }
196
197 /* decrement the count of calls */
198 static void dec_callcount()
199 {
200         callcount--;
201         if (exonrep && !callcount)
202                 exit(0);
203 }
204
205 /* called when wsj1 hangsup */
206 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
207 {
208         printf("ON-HANGUP\n");
209         fflush(stdout);
210         exit(0);
211 }
212
213 /* called when wsj1 receives a method invocation */
214 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
215 {
216         int rc;
217         if (raw)
218                 printf("ON-CALL %s/%s(%s)\n", api, verb, afb_wsj1_msg_object_s(msg));
219         if (human)
220                 printf("ON-CALL %s/%s:\n%s\n", api, verb,
221                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
222                                                         JSON_C_TO_STRING_PRETTY));
223         fflush(stdout);
224         rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
225         if (rc < 0)
226                 fprintf(stderr, "replying failed: %m\n");
227 }
228
229 /* called when wsj1 receives an event */
230 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
231 {
232         if (raw)
233                 printf("ON-EVENT %s(%s)\n", event, afb_wsj1_msg_object_s(msg));
234         if (human)
235                 printf("ON-EVENT %s:\n%s\n", event,
236                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
237                                                         JSON_C_TO_STRING_PRETTY));
238         fflush(stdout);
239 }
240
241 /* called when wsj1 receives a reply */
242 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
243 {
244         if (raw)
245                 printf("ON-REPLY %s: %s\n", (char*)closure, afb_wsj1_msg_object_s(msg));
246         if (human)
247                 printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
248                                 afb_wsj1_msg_is_reply_ok(msg) ? "OK" : "ERROR",
249                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
250                                                         JSON_C_TO_STRING_PRETTY));
251         fflush(stdout);
252         free(closure);
253         dec_callcount();
254 }
255
256 /* makes a call */
257 static void wsj1_call(const char *api, const char *verb, const char *object)
258 {
259         static int num = 0;
260         char *key;
261         int rc;
262
263         /* allocates an id for the request */
264         rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
265
266         /* send the request */
267         callcount++;
268         rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
269         if (rc < 0) {
270                 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
271                 dec_callcount();
272         }
273 }
274
275 /* sends an event */
276 static void wsj1_event(const char *event, const char *object)
277 {
278         int rc;
279
280         rc = afb_wsj1_send_event_s(wsj1, event, object);
281         if (rc < 0)
282                 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
283 }
284
285 /* emits either a call (when api!='!') or an event */
286 static void wsj1_emit(const char *api, const char *verb, const char *object)
287 {
288         if (object == NULL || object[0] == 0)
289                 object = "null";
290         if (api[0] == '!' && api[1] == 0)
291                 wsj1_event(verb, object);
292         else
293                 wsj1_call(api, verb, object);
294         if (breakcon)
295                 exit(0);
296 }
297
298 /* called when something happens on stdin */
299 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *closure)
300 {
301         static size_t count = 0;
302         static char line[16384];
303         static char sep[] = " \t";
304         static char sepnl[] = " \t\n";
305
306         ssize_t rc;
307         size_t pos;
308
309         /* read the buffer */
310         do { rc = read(0, line + count, sizeof line - count); } while (rc < 0 && errno == EINTR);
311         if (rc < 0) {
312                 fprintf(stderr, "read error: %m\n");
313                 exit(1);
314         }
315         if (rc == 0) {
316                 if (!callcount)
317                         exit(0);
318                 exonrep = 1;
319                 sd_event_source_unref(evsrc);
320         }
321         count += (size_t)rc;
322
323         /* normalise the buffer content */
324         /* TODO: handle backspace \x7f ? */
325
326         /* process the lines */
327         pos = 0;
328         for(;;) {
329                 size_t i, api[2], verb[2], rest[2];
330                 i = pos;
331                 while(i < count && strchr(sep, line[i])) i++;
332                 api[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; api[1] = i;
333                 while(i < count && strchr(sep, line[i])) i++;
334                 if (direct) {
335                         verb[0] = api[0];
336                         verb[1] = api[1];
337                 } else {
338                         verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
339                         while(i < count && strchr(sep, line[i])) i++;
340                 }
341                 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
342                 if (i == count) break;
343                 line[i++] = 0;
344                 if (api[0] == api[1]) {
345                         /* empty line */
346                 } else if (line[api[0]] == '#') {
347                         /* comment */
348                 } else if (verb[0] == verb[1]) {
349                         fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
350                 } else {
351                         line[api[1]] = line[verb[1]] = 0;
352                         if (direct)
353                                 pws_call(line + verb[0], line + rest[0]);
354                         else
355                                 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
356                 }
357                 pos = i;
358         }
359         count -= pos;
360         if (count == sizeof line) {
361                 fprintf(stderr, "overflow\n");
362                 exit(1);
363         }
364         if (count)
365                 memmove(line, line + pos, count);
366         return 1;
367 }
368
369 static void on_pws_reply_success(void *closure, void *request, struct json_object *result, const char *info)
370 {
371         if (raw)
372                 printf("ON-REPLY-SUCCESS %s: [%s] %s\n", (char*)request, info?:"", json_object_to_json_string(result));
373         if (human)
374                 printf("ON-REPLY-SUCCESS %s: %s\n%s\n", (char*)request, info?:"", json_object_to_json_string_ext(result, JSON_C_TO_STRING_PRETTY));
375         fflush(stdout);
376         free(request);
377         dec_callcount();
378 }
379
380 static void on_pws_reply_fail(void *closure, void *request, const char *status, const char *info)
381 {
382         printf("ON-REPLY-FAIL %s: %s [%s]\n", (char*)request, status?:"?", info?:"");
383         fflush(stdout);
384         free(request);
385         dec_callcount();
386 }
387
388 static void on_pws_event_create(void *closure, const char *event_name, int event_id)
389 {
390         printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
391         fflush(stdout);
392 }
393
394 static void on_pws_event_remove(void *closure, const char *event_name, int event_id)
395 {
396         printf("ON-EVENT-REMOVE: [%d:%s]\n", event_id, event_name);
397         fflush(stdout);
398 }
399
400 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
401 {
402         printf("ON-EVENT-SUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
403         fflush(stdout);
404 }
405
406 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
407 {
408         printf("ON-EVENT-UNSUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
409         fflush(stdout);
410 }
411
412 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
413 {
414         if (raw)
415                 printf("ON-EVENT-PUSH: [%d:%s] %s\n", event_id, event_name, json_object_to_json_string(data));
416         if (human)
417                 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));
418         fflush(stdout);
419 }
420
421 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data)
422 {
423         if (raw)
424                 printf("ON-EVENT-BROADCAST: [%s] %s\n", event_name, json_object_to_json_string(data));
425         if (human)
426                 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_PRETTY));
427         fflush(stdout);
428 }
429
430 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)
431 {
432         if (raw)
433                 printf("ON-SUBCALL %s: %s/%s %s\n", (char*)request, api, verb, json_object_to_json_string(args));
434         if (human)
435                 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));
436         afb_proto_ws_subcall_reply(subcall, 1, NULL);
437         fflush(stdout);
438 }
439
440 /* makes a call */
441 static void pws_call(const char *verb, const char *object)
442 {
443         static int num = 0;
444         char *key;
445         int rc;
446         struct json_object *o;
447
448         /* allocates an id for the request */
449         rc = asprintf(&key, "%d:%s", ++num, verb);
450
451         /* send the request */
452         callcount++;
453         if (object == NULL || object[0] == 0 || !strcmp(object, "null"))
454                 o = NULL;
455         else {
456                 o = json_tokener_parse(object);
457                 if (!o)
458                         o = json_object_new_string(object);
459         }
460         rc = afb_proto_ws_client_call(pws, verb, o, sessionid, key);
461         json_object_put(o);
462         if (rc < 0) {
463                 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
464                 dec_callcount();
465         }
466         if (breakcon)
467                 exit(0);
468 }
469
470 /* called when pws hangsup */
471 static void on_pws_hangup(void *closure)
472 {
473         printf("ON-HANGUP\n");
474         fflush(stdout);
475         exit(0);
476 }
477
478