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