2 * Copyright (C) 2015-2019 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author José Bollo <jose.bollo@iot.bzh>
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
28 #include <sys/types.h>
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
38 #include "afb-ws-client.h"
39 #include "afb-proto-ws.h"
51 /* declaration of functions */
52 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1);
53 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg);
54 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg);
56 static void on_pws_hangup(void *closure);
57 static void on_pws_reply(void *closure, void *request, struct json_object *result, const char *error, const char *info);
58 static void on_pws_event_create(void *closure, const char *event_name, int event_id);
59 static void on_pws_event_remove(void *closure, const char *event_name, int event_id);
60 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id);
61 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id);
62 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data);
63 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data, const afb_proto_ws_uuid_t uuid, uint8_t hop);
66 static int process_stdin();
67 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure);
69 static void wsj1_emit(const char *api, const char *verb, const char *object);
70 static void pws_call(const char *verb, const char *object);
72 /* the callback interface for wsj1 */
73 static struct afb_wsj1_itf wsj1_itf = {
74 .on_hangup = on_wsj1_hangup,
75 .on_call = on_wsj1_call,
76 .on_event = on_wsj1_event
79 /* the callback interface for pws */
80 static struct afb_proto_ws_client_itf pws_itf = {
81 .on_reply = on_pws_reply,
82 .on_event_create = on_pws_event_create,
83 .on_event_remove = on_pws_event_remove,
84 .on_event_subscribe = on_pws_event_subscribe,
85 .on_event_unsubscribe = on_pws_event_unsubscribe,
86 .on_event_push = on_pws_event_push,
87 .on_event_broadcast = on_pws_event_broadcast,
90 /* global variables */
91 static struct afb_wsj1 *wsj1;
92 static struct afb_proto_ws *pws;
103 static sd_event *loop;
104 static sd_event_source *evsrc;
105 static char *sessionid = "afb-client-demo";
106 static int exitcode = 0;
108 /* print usage of the program */
109 static void usage(int status, char *arg0)
111 char *name = strrchr(arg0, '/');
112 name = name ? name + 1 : arg0;
113 fprintf(status ? stderr : stdout, "usage: %s [-H [-r]] [-b] [-e] uri [api verb [data]]\n", name);
114 fprintf(status ? stderr : stdout, " %s -d [-H [-r]] [-b] [-e] uri [verb [data]]\n", name);
115 fprintf(status ? stderr : stdout, "\n"
117 " --break, -b Break connection just after event/call has been emitted.\n"
118 " --direct, -d Direct api\n"
119 " --echo, -e Echo inputs\n"
120 " --help, -h Display this help\n"
121 " --human, -H Display human readable JSON\n"
122 " --raw, -r Raw output (default)\n"
123 " --sync, -s Synchronous: wait for answers (like -p 1)\n"
124 " --keep-running, -k Keep running until disconnect, even if input closed\n"
125 " --pipe, -p COUNT Allow to pipe COUNT requests\n"
127 " %s --human 'localhost:1234/api?token=HELLO&uuid=magic' hello ping\n"
135 int main(int ac, char **av, char **env)
140 /* get the program name */
144 while (ac > 1 && (an = av[1])[0] == '-') {
148 if (!strcmp(an, "--human")) /* request for human output */
151 else if (!strcmp(an, "--raw")) /* request for raw output */
154 else if (!strcmp(an, "--direct")) /* request for direct api */
157 else if (!strcmp(an, "--break")) /* request to break connection */
160 else if (!strcmp(an, "--keep-running")) /* request to break connection */
163 else if (!strcmp(an, "--sync")) /* request to break connection */
166 else if (!strcmp(an, "--echo")) /* request to echo inputs */
169 else if (!strcmp(an, "--pipe") && av[2] && atoi(av[2]) > 0) {
170 synchro = atoi(av[2]);
175 /* emit usage and exit */
177 usage(strcmp(an, "--help") ? Exit_Bad_Arg : Exit_Success, a0);
179 /* short option(s) */
180 for (rc = 1 ; an[rc] ; rc++)
182 case 'H': human = 1; break;
183 case 'r': raw = 1; break;
184 case 'd': direct = 1; break;
185 case 'b': breakcon = 1; break;
186 case 'k': keeprun = 1; break;
187 case 's': synchro = 1; break;
188 case 'e': echo = 1; break;
189 case 'p': if (av[2] && atoi(av[2]) > 0) { synchro = atoi(av[2]); av++; ac--; break; } /*@fallthrough@*/
190 default: usage(an[rc] != 'h' ? Exit_Bad_Arg : Exit_Success, a0);
197 /* check the argument count */
198 if (ac != 2 && ac != 4 && ac != 5)
201 /* set raw by default */
205 /* get the default event loop */
206 rc = sd_event_default(&loop);
208 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
212 /* connect the websocket wsj1 to the uri given by the first argument */
214 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
216 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
217 return Exit_Cant_Connect;
219 afb_proto_ws_on_hangup(pws, on_pws_hangup);
221 wsj1 = afb_ws_client_connect_wsj1(loop, av[1], &wsj1_itf, NULL);
223 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
224 return Exit_Cant_Connect;
228 /* test the behaviour */
230 /* get requests from stdin */
232 fcntl(0, F_SETFL, O_NONBLOCK);
233 if (sd_event_add_io(loop, &evsrc, 0, EPOLLIN, on_stdin, NULL) < 0)
236 /* the request is defined by the arguments */
240 pws_call(av[2], av[3]);
242 wsj1_emit(av[2], av[3], av[4]);
254 if (!keeprun && !callcount)
256 sd_event_run(loop, 30000000);
258 else if (!synchro || callcount < synchro) {
259 if (!process_stdin() && usein)
260 sd_event_run(loop, 100000);
262 sd_event_run(loop, 30000000);
267 /* decrement the count of calls */
268 static void dec_callcount()
271 if (exonrep && !callcount)
275 /* called when wsj1 hangsup */
276 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
278 printf("ON-HANGUP\n");
283 /* called when wsj1 receives a method invocation */
284 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
288 printf("%s\n", afb_wsj1_msg_object_s(msg));
290 printf("ON-CALL %s/%s:\n%s\n", api, verb,
291 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
292 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
294 rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
296 fprintf(stderr, "replying failed: %m\n");
299 /* called when wsj1 receives an event */
300 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
303 printf("%s\n", afb_wsj1_msg_object_s(msg));
305 printf("ON-EVENT %s:\n%s\n", event,
306 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
307 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
311 /* called when wsj1 receives a reply */
312 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
314 int iserror = !afb_wsj1_msg_is_reply_ok(msg);
315 exitcode = iserror ? Exit_Error : Exit_Success;
317 printf("%s\n", afb_wsj1_msg_object_s(msg));
319 printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
320 iserror ? "ERROR" : "OK",
321 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
322 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
329 static void wsj1_call(const char *api, const char *verb, const char *object)
335 /* allocates an id for the request */
336 rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
338 /* echo the command if asked */
340 printf("SEND-CALL %s/%s %s\n", api, verb, object?:"null");
342 /* send the request */
344 rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
346 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
352 static void wsj1_event(const char *event, const char *object)
356 /* echo the command if asked */
358 printf("SEND-EVENT: %s %s\n", event, object?:"null");
360 rc = afb_wsj1_send_event_s(wsj1, event, object);
362 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
365 /* emits either a call (when api!='!') or an event */
366 static void wsj1_emit(const char *api, const char *verb, const char *object)
368 if (object == NULL || object[0] == 0)
371 if (api[0] == '!' && api[1] == 0)
372 wsj1_event(verb, object);
374 wsj1_call(api, verb, object);
380 static int process_stdin()
382 static size_t count = 0;
383 static char line[16384];
384 static char sep[] = " \t";
385 static char sepnl[] = " \t\n";
391 /* read the buffer */
392 while (sizeof line > count) {
393 rc = read(0, line + count, sizeof line - count);
394 if (rc >= 0 || errno != EINTR)
400 fprintf(stderr, "read error: %m\n");
401 exit(Exit_Input_Fail);
405 if (!usein && !keeprun) {
412 if (synchro && callcount >= synchro)
415 /* normalise the buffer content */
416 /* TODO: handle backspace \x7f ? */
417 /* process the lines */
420 size_t i, api[2], verb[2], rest[2];
422 while(i < count && strchr(sep, line[i])) i++;
423 api[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; api[1] = i;
424 while(i < count && strchr(sep, line[i])) i++;
429 verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
430 while(i < count && strchr(sep, line[i])) i++;
432 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
433 if (i == count) break;
436 if (api[0] == api[1]) {
438 } else if (line[api[0]] == '#') {
440 } else if (verb[0] == verb[1]) {
441 fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
443 line[api[1]] = line[verb[1]] = 0;
445 pws_call(line + verb[0], line + rest[0]);
447 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
453 if (count == sizeof line) {
454 fprintf(stderr, "overflow\n");
455 exit(Exit_Input_Fail);
458 memmove(line, line + pos, count);
463 /* called when something happens on stdin */
464 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure)
468 sd_event_source_unref(src);
474 static void on_pws_reply(void *closure, void *request, struct json_object *result, const char *error, const char *info)
476 int iserror = !!error;
477 exitcode = iserror ? Exit_Error : Exit_Success;
478 error = error ?: "success";
480 /* TODO: transitionnal: fake the structured response */
481 struct json_object *x = json_object_new_object(), *y = json_object_new_object();
482 json_object_object_add(x, "jtype", json_object_new_string("afb-reply"));
483 json_object_object_add(x, "request", y);
484 json_object_object_add(y, "status", json_object_new_string(error));
486 json_object_object_add(y, "info", json_object_new_string(info));
488 json_object_object_add(x, "response", json_object_get(result));
490 printf("%s\n", json_object_to_json_string_ext(x, JSON_C_TO_STRING_NOSLASHESCAPE));
494 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));
500 static void on_pws_event_create(void *closure, const char *event_name, int event_id)
502 printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
506 static void on_pws_event_remove(void *closure, const char *event_name, int event_id)
508 printf("ON-EVENT-REMOVE: [%d:%s]\n", event_id, event_name);
512 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
514 printf("ON-EVENT-SUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
518 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
520 printf("ON-EVENT-UNSUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
524 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
527 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));
529 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));
533 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data, const afb_proto_ws_uuid_t uuid, uint8_t hop)
536 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_NOSLASHESCAPE));
538 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));
543 static void pws_call(const char *verb, const char *object)
548 struct json_object *o;
549 enum json_tokener_error jerr;
551 /* allocates an id for the request */
552 rc = asprintf(&key, "%d:%s", ++num, verb);
554 /* echo the command if asked */
556 printf("SEND-CALL: %s %s\n", verb, object?:"null");
558 /* send the request */
560 if (object == NULL || object[0] == 0)
563 o = json_tokener_parse_verbose(object, &jerr);
564 if (jerr != json_tokener_success)
565 o = json_object_new_string(object);
567 rc = afb_proto_ws_client_call(pws, verb, o, sessionid, key, NULL);
570 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
577 /* called when pws hangsup */
578 static void on_pws_hangup(void *closure)
580 printf("ON-HANGUP\n");