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