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