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