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