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