afb-client-demo: Fix bug that forbids interactive behaviour
[src/app-framework-binder.git] / src / main-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(void *closure, void *request, struct json_object *result, const char *error, const char *info);
45 static void on_pws_event_create(void *closure, const char *event_name, int event_id);
46 static void on_pws_event_remove(void *closure, const char *event_name, int event_id);
47 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id);
48 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id);
49 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data);
50 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data);
51
52 static void idle();
53 static int process_stdin();
54 static int on_stdin(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 = on_pws_reply,
69         .on_event_create = on_pws_event_create,
70         .on_event_remove = on_pws_event_remove,
71         .on_event_subscribe = on_pws_event_subscribe,
72         .on_event_unsubscribe = on_pws_event_unsubscribe,
73         .on_event_push = on_pws_event_push,
74         .on_event_broadcast = on_pws_event_broadcast,
75 };
76
77 /* global variables */
78 static struct afb_wsj1 *wsj1;
79 static struct afb_proto_ws *pws;
80 static int breakcon;
81 static int exonrep;
82 static int callcount;
83 static int human;
84 static int raw;
85 static int keeprun;
86 static int direct;
87 static int echo;
88 static int synchro;
89 static int usein;
90 static sd_event *loop;
91 static sd_event_source *evsrc;
92 static char *sessionid = "afb-client-demo";
93
94 /* print usage of the program */
95 static void usage(int status, char *arg0)
96 {
97         char *name = strrchr(arg0, '/');
98         name = name ? name + 1 : arg0;
99         fprintf(status ? stderr : stdout, "usage: %s [-H [-r]] [-b] [-e] uri [api verb [data]]\n", name);
100         fprintf(status ? stderr : stdout, "       %s -d [-H [-r]] [-b] [-e] uri [verb [data]]\n", name);
101         fprintf(status ? stderr : stdout, "\n"
102                 "allowed options\n"
103                 "  --break, -b         Break connection just after event/call has been emitted.\n"
104                 "  --direct, -d        Direct api\n"
105                 "  --echo, -e          Echo inputs\n"
106                 "  --help, -h          Display this help\n"
107                 "  --human, -H         Display human readable JSON\n"
108                 "  --raw, -r           Raw output (default)\n"
109                 "  --sync, -s          Synchronous: wait for answers\n"
110                 "  --keep-running, -k  Keep running until disconnect, even if input closed\n"
111                 "Example:\n"
112                 " %s --human 'localhost:1234/api?token=HELLO&uuid=magic' hello ping\n"
113                 "\n", name
114         );
115
116         exit(status);
117 }
118
119 /* entry function */
120 int main(int ac, char **av, char **env)
121 {
122         int rc;
123         char *a0;
124
125         /* get the program name */
126         a0 = av[0];
127
128         /* check options */
129         while (ac > 1 && av[1][0] == '-') {
130                 if (av[1][1] == '-') {
131                         /* long option */
132
133                         if (!strcmp(av[1], "--human")) /* request for human output */
134                                 human = 1;
135
136                         else if (!strcmp(av[1], "--raw")) /* request for raw output */
137                                 raw = 1;
138
139                         else if (!strcmp(av[1], "--direct")) /* request for direct api */
140                                 direct = 1;
141
142                         else if (!strcmp(av[1], "--break")) /* request to break connection */
143                                 breakcon = 1;
144
145                         else if (!strcmp(av[1], "--keep-running")) /* request to break connection */
146                                 keeprun = 1;
147
148                         else if (!strcmp(av[1], "--sync")) /* request to break connection */
149                                 synchro = 1;
150
151                         else if (!strcmp(av[1], "--echo")) /* request to echo inputs */
152                                 echo = 1;
153
154                         /* emit usage and exit */
155                         else
156                                 usage(!!strcmp(av[1], "--help"), a0);
157                 } else {
158                         /* short option(s) */
159                         for (rc = 1 ; av[1][rc] ; rc++)
160                                 switch (av[1][rc]) {
161                                 case 'H': human = 1; break;
162                                 case 'r': raw = 1; break;
163                                 case 'd': direct = 1; break;
164                                 case 'b': breakcon = 1; break;
165                                 case 'k': keeprun = 1; break;
166                                 case 's': synchro = 1; break;
167                                 case 'e': echo = 1; break;
168                                 default: usage(av[1][rc] != 'h', a0);
169                                 }
170                 }
171                 av++;
172                 ac--;
173         }
174
175         /* check the argument count */
176         if (ac != 2 && ac != 4 && ac != 5)
177                 usage(1, a0);
178
179         /* set raw by default */
180         if (!human)
181                 raw = 1;
182
183         /* get the default event loop */
184         rc = sd_event_default(&loop);
185         if (rc < 0) {
186                 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
187                 return 1;
188         }
189
190         /* connect the websocket wsj1 to the uri given by the first argument */
191         if (direct) {
192                 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
193                 if (pws == NULL) {
194                         fprintf(stderr, "connection to %s failed: %m\n", av[1]);
195                         return 1;
196                 }
197                 afb_proto_ws_on_hangup(pws, on_pws_hangup);
198         } else {
199                 wsj1 = afb_ws_client_connect_wsj1(loop, av[1], &wsj1_itf, NULL);
200                 if (wsj1 == NULL) {
201                         fprintf(stderr, "connection to %s failed: %m\n", av[1]);
202                         return 1;
203                 }
204         }
205
206         /* test the behaviour */
207         if (ac == 2) {
208                 /* get requests from stdin */
209                 usein = 1;
210                 fcntl(0, F_SETFL, O_NONBLOCK);
211                 if (sd_event_add_io(loop, &evsrc, 0, EPOLLIN, on_stdin, NULL) < 0)
212                         evsrc = NULL;
213         } else {
214                 /* the request is defined by the arguments */
215                 usein = 0;
216                 exonrep = !keeprun;
217                 if (direct)
218                         pws_call(av[2], av[3]);
219                 else
220                         wsj1_emit(av[2], av[3], av[4]);
221         }
222
223         /* loop until end */
224         idle();
225         return 0;
226 }
227
228 static void idle()
229 {
230         for(;;) {
231                 if (!usein) {
232                         if (!keeprun && !callcount)
233                                 exit(0);
234                         sd_event_run(loop, 30000000);
235                 }
236                 else if (!synchro || !callcount) {
237                         if (!process_stdin() && usein)
238                                 sd_event_run(loop, 100000);
239                 } else {
240                         sd_event_run(loop, 30000000);
241                 }
242         }
243 }
244
245 /* decrement the count of calls */
246 static void dec_callcount()
247 {
248         callcount--;
249         if (exonrep && !callcount)
250                 exit(0);
251 }
252
253 /* called when wsj1 hangsup */
254 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
255 {
256         printf("ON-HANGUP\n");
257         fflush(stdout);
258         exit(0);
259 }
260
261 /* called when wsj1 receives a method invocation */
262 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
263 {
264         int rc;
265         if (raw)
266                 printf("%s\n", afb_wsj1_msg_object_s(msg));
267         if (human)
268                 printf("ON-CALL %s/%s:\n%s\n", api, verb,
269                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
270                                                         JSON_C_TO_STRING_PRETTY));
271         fflush(stdout);
272         rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
273         if (rc < 0)
274                 fprintf(stderr, "replying failed: %m\n");
275 }
276
277 /* called when wsj1 receives an event */
278 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
279 {
280         if (raw)
281                 printf("%s\n", afb_wsj1_msg_object_s(msg));
282         if (human)
283                 printf("ON-EVENT %s:\n%s\n", event,
284                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
285                                                         JSON_C_TO_STRING_PRETTY));
286         fflush(stdout);
287 }
288
289 /* called when wsj1 receives a reply */
290 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
291 {
292         if (raw)
293                 printf("%s\n", afb_wsj1_msg_object_s(msg));
294         if (human)
295                 printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
296                                 afb_wsj1_msg_is_reply_ok(msg) ? "OK" : "ERROR",
297                                 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
298                                                         JSON_C_TO_STRING_PRETTY));
299         fflush(stdout);
300         free(closure);
301         dec_callcount();
302 }
303
304 /* makes a call */
305 static void wsj1_call(const char *api, const char *verb, const char *object)
306 {
307         static int num = 0;
308         char *key;
309         int rc;
310
311         /* allocates an id for the request */
312         rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
313
314         /* echo the command if asked */
315         if (echo)
316                 printf("SEND-CALL %s/%s %s\n", api, verb, object?:"null");
317
318         /* send the request */
319         callcount++;
320         rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
321         if (rc < 0) {
322                 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
323                 dec_callcount();
324         }
325 }
326
327 /* sends an event */
328 static void wsj1_event(const char *event, const char *object)
329 {
330         int rc;
331
332         /* echo the command if asked */
333         if (echo)
334                 printf("SEND-EVENT: %s %s\n", event, object?:"null");
335
336         rc = afb_wsj1_send_event_s(wsj1, event, object);
337         if (rc < 0)
338                 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
339 }
340
341 /* emits either a call (when api!='!') or an event */
342 static void wsj1_emit(const char *api, const char *verb, const char *object)
343 {
344         if (object == NULL || object[0] == 0)
345                 object = "null";
346
347         if (api[0] == '!' && api[1] == 0)
348                 wsj1_event(verb, object);
349         else
350                 wsj1_call(api, verb, object);
351         if (breakcon)
352                 exit(0);
353 }
354
355 /* process stdin */
356 static int process_stdin()
357 {
358         static size_t count = 0;
359         static char line[16384];
360         static char sep[] = " \t";
361         static char sepnl[] = " \t\n";
362
363         int result = 0;
364         ssize_t rc = 0;
365         size_t pos;
366
367         /* read the buffer */
368         while (sizeof line > count) {
369                 rc = read(0, line + count, sizeof line - count);
370                 if (rc >= 0 || errno != EINTR)
371                         break;
372         }
373         if (rc < 0) {
374                 if (errno == EAGAIN)
375                         return 0;
376                 fprintf(stderr, "read error: %m\n");
377                 exit(1);
378         }
379         if (rc == 0) {
380                 usein = count != 0;
381                 if (!usein && !keeprun) {
382                         if (!callcount)
383                                 exit(0);
384                         exonrep = 1;
385                 }
386         }
387         count += (size_t)rc;
388         if (synchro && callcount)
389                 return 0;
390
391         /* normalise the buffer content */
392         /* TODO: handle backspace \x7f ? */
393         /* process the lines */
394         pos = 0;
395         for(;;) {
396                 size_t i, api[2], verb[2], rest[2];
397                 i = pos;
398                 while(i < count && strchr(sep, line[i])) i++;
399                 api[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; api[1] = i;
400                 while(i < count && strchr(sep, line[i])) i++;
401                 if (direct) {
402                         verb[0] = api[0];
403                         verb[1] = api[1];
404                 } else {
405                         verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
406                         while(i < count && strchr(sep, line[i])) i++;
407                 }
408                 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
409                 if (i == count) break;
410                 line[i++] = 0;
411                 pos = i;
412                 if (api[0] == api[1]) {
413                         /* empty line */
414                 } else if (line[api[0]] == '#') {
415                         /* comment */
416                 } else if (verb[0] == verb[1]) {
417                         fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
418                 } else {
419                         line[api[1]] = line[verb[1]] = 0;
420                         if (direct)
421                                 pws_call(line + verb[0], line + rest[0]);
422                         else
423                                 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
424                         result = 1;
425                         break;
426                 }
427         }
428         count -= pos;
429         if (count == sizeof line) {
430                 fprintf(stderr, "overflow\n");
431                 exit(1);
432         }
433         if (count)
434                 memmove(line, line + pos, count);
435
436         return result;
437 }
438
439 /* called when something happens on stdin */
440 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure)
441 {
442         process_stdin();
443         if (!usein) {
444                 sd_event_source_unref(src);
445                 evsrc = NULL;
446         }
447         return 1;
448 }
449
450 static void on_pws_reply(void *closure, void *request, struct json_object *result, const char *error, const char *info)
451 {
452         error = error ?: "success";
453         if (raw) {
454                 /* TODO: transitionnal: fake the structured response */
455                 struct json_object *x = json_object_new_object(), *y = json_object_new_object();
456                 json_object_object_add(x, "jtype", json_object_new_string("afb-reply"));
457                 json_object_object_add(x, "request", y);
458                 json_object_object_add(y, "status", json_object_new_string(error));
459                 if (info)
460                         json_object_object_add(y, "info", json_object_new_string(info));
461                 if (result)
462                         json_object_object_add(x, "response", json_object_get(result));
463
464                 printf("%s\n", json_object_to_json_string(x));
465                 json_object_put(x);
466         }
467         if (human)
468                 printf("ON-REPLY %s: %s %s\n%s\n", (char*)request, error, info ?: "", json_object_to_json_string_ext(result, JSON_C_TO_STRING_PRETTY));
469         fflush(stdout);
470         free(request);
471         dec_callcount();
472 }
473
474 static void on_pws_event_create(void *closure, const char *event_name, int event_id)
475 {
476         printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
477         fflush(stdout);
478 }
479
480 static void on_pws_event_remove(void *closure, const char *event_name, int event_id)
481 {
482         printf("ON-EVENT-REMOVE: [%d:%s]\n", event_id, event_name);
483         fflush(stdout);
484 }
485
486 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
487 {
488         printf("ON-EVENT-SUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
489         fflush(stdout);
490 }
491
492 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
493 {
494         printf("ON-EVENT-UNSUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
495         fflush(stdout);
496 }
497
498 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
499 {
500         if (raw)
501                 printf("ON-EVENT-PUSH: [%d:%s]\n%s\n", event_id, event_name, json_object_to_json_string_ext(data, 0));
502         if (human)
503                 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));
504         fflush(stdout);
505 }
506
507 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data)
508 {
509         if (raw)
510                 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, 0));
511         if (human)
512                 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_PRETTY));
513         fflush(stdout);
514 }
515
516 /* makes a call */
517 static void pws_call(const char *verb, const char *object)
518 {
519         static int num = 0;
520         char *key;
521         int rc;
522         struct json_object *o;
523
524         /* allocates an id for the request */
525         rc = asprintf(&key, "%d:%s", ++num, verb);
526
527         /* echo the command if asked */
528         if (echo)
529                 printf("SEND-CALL: %s %s\n", verb, object?:"null");
530
531         /* send the request */
532         callcount++;
533         if (object == NULL || object[0] == 0 || !strcmp(object, "null"))
534                 o = NULL;
535         else {
536                 o = json_tokener_parse(object);
537                 if (!o)
538                         o = json_object_new_string(object);
539         }
540         rc = afb_proto_ws_client_call(pws, verb, o, sessionid, key, NULL);
541         json_object_put(o);
542         if (rc < 0) {
543                 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
544                 dec_callcount();
545         }
546         if (breakcon)
547                 exit(0);
548 }
549
550 /* called when pws hangsup */
551 static void on_pws_hangup(void *closure)
552 {
553         printf("ON-HANGUP\n");
554         fflush(stdout);
555         exit(0);
556 }