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