2 * Copyright (C) 2015-2018 "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);
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\n"
124 " --keep-running, -k Keep running until disconnect, even if input closed\n"
126 " %s --human 'localhost:1234/api?token=HELLO&uuid=magic' hello ping\n"
134 int main(int ac, char **av, char **env)
139 /* get the program name */
143 while (ac > 1 && av[1][0] == '-') {
144 if (av[1][1] == '-') {
147 if (!strcmp(av[1], "--human")) /* request for human output */
150 else if (!strcmp(av[1], "--raw")) /* request for raw output */
153 else if (!strcmp(av[1], "--direct")) /* request for direct api */
156 else if (!strcmp(av[1], "--break")) /* request to break connection */
159 else if (!strcmp(av[1], "--keep-running")) /* request to break connection */
162 else if (!strcmp(av[1], "--sync")) /* request to break connection */
165 else if (!strcmp(av[1], "--echo")) /* request to echo inputs */
168 /* emit usage and exit */
170 usage(strcmp(av[1], "--help") ? Exit_Bad_Arg : Exit_Success, a0);
172 /* short option(s) */
173 for (rc = 1 ; av[1][rc] ; rc++)
175 case 'H': human = 1; break;
176 case 'r': raw = 1; break;
177 case 'd': direct = 1; break;
178 case 'b': breakcon = 1; break;
179 case 'k': keeprun = 1; break;
180 case 's': synchro = 1; break;
181 case 'e': echo = 1; break;
182 default: usage(av[1][rc] != 'h' ? Exit_Bad_Arg : Exit_Success, a0);
189 /* check the argument count */
190 if (ac != 2 && ac != 4 && ac != 5)
193 /* set raw by default */
197 /* get the default event loop */
198 rc = sd_event_default(&loop);
200 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
204 /* connect the websocket wsj1 to the uri given by the first argument */
206 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
208 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
209 return Exit_Cant_Connect;
211 afb_proto_ws_on_hangup(pws, on_pws_hangup);
213 wsj1 = afb_ws_client_connect_wsj1(loop, av[1], &wsj1_itf, NULL);
215 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
216 return Exit_Cant_Connect;
220 /* test the behaviour */
222 /* get requests from stdin */
224 fcntl(0, F_SETFL, O_NONBLOCK);
225 if (sd_event_add_io(loop, &evsrc, 0, EPOLLIN, on_stdin, NULL) < 0)
228 /* the request is defined by the arguments */
232 pws_call(av[2], av[3]);
234 wsj1_emit(av[2], av[3], av[4]);
246 if (!keeprun && !callcount)
248 sd_event_run(loop, 30000000);
250 else if (!synchro || !callcount) {
251 if (!process_stdin() && usein)
252 sd_event_run(loop, 100000);
254 sd_event_run(loop, 30000000);
259 /* decrement the count of calls */
260 static void dec_callcount()
263 if (exonrep && !callcount)
267 /* called when wsj1 hangsup */
268 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
270 printf("ON-HANGUP\n");
275 /* called when wsj1 receives a method invocation */
276 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
280 printf("%s\n", afb_wsj1_msg_object_s(msg));
282 printf("ON-CALL %s/%s:\n%s\n", api, verb,
283 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
284 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
286 rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
288 fprintf(stderr, "replying failed: %m\n");
291 /* called when wsj1 receives an event */
292 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
295 printf("%s\n", afb_wsj1_msg_object_s(msg));
297 printf("ON-EVENT %s:\n%s\n", event,
298 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
299 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
303 /* called when wsj1 receives a reply */
304 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
306 int iserror = !afb_wsj1_msg_is_reply_ok(msg);
307 exitcode = iserror ? Exit_Error : Exit_Success;
309 printf("%s\n", afb_wsj1_msg_object_s(msg));
311 printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
312 iserror ? "ERROR" : "OK",
313 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
314 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
321 static void wsj1_call(const char *api, const char *verb, const char *object)
327 /* allocates an id for the request */
328 rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
330 /* echo the command if asked */
332 printf("SEND-CALL %s/%s %s\n", api, verb, object?:"null");
334 /* send the request */
336 rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
338 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
344 static void wsj1_event(const char *event, const char *object)
348 /* echo the command if asked */
350 printf("SEND-EVENT: %s %s\n", event, object?:"null");
352 rc = afb_wsj1_send_event_s(wsj1, event, object);
354 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
357 /* emits either a call (when api!='!') or an event */
358 static void wsj1_emit(const char *api, const char *verb, const char *object)
360 if (object == NULL || object[0] == 0)
363 if (api[0] == '!' && api[1] == 0)
364 wsj1_event(verb, object);
366 wsj1_call(api, verb, object);
372 static int process_stdin()
374 static size_t count = 0;
375 static char line[16384];
376 static char sep[] = " \t";
377 static char sepnl[] = " \t\n";
383 /* read the buffer */
384 while (sizeof line > count) {
385 rc = read(0, line + count, sizeof line - count);
386 if (rc >= 0 || errno != EINTR)
392 fprintf(stderr, "read error: %m\n");
393 exit(Exit_Input_Fail);
397 if (!usein && !keeprun) {
404 if (synchro && callcount)
407 /* normalise the buffer content */
408 /* TODO: handle backspace \x7f ? */
409 /* process the lines */
412 size_t i, api[2], verb[2], rest[2];
414 while(i < count && strchr(sep, line[i])) i++;
415 api[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; api[1] = i;
416 while(i < count && strchr(sep, line[i])) i++;
421 verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
422 while(i < count && strchr(sep, line[i])) i++;
424 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
425 if (i == count) break;
428 if (api[0] == api[1]) {
430 } else if (line[api[0]] == '#') {
432 } else if (verb[0] == verb[1]) {
433 fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
435 line[api[1]] = line[verb[1]] = 0;
437 pws_call(line + verb[0], line + rest[0]);
439 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
445 if (count == sizeof line) {
446 fprintf(stderr, "overflow\n");
447 exit(Exit_Input_Fail);
450 memmove(line, line + pos, count);
455 /* called when something happens on stdin */
456 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure)
460 sd_event_source_unref(src);
466 static void on_pws_reply(void *closure, void *request, struct json_object *result, const char *error, const char *info)
468 int iserror = !!error;
469 exitcode = iserror ? Exit_Error : Exit_Success;
470 error = error ?: "success";
472 /* TODO: transitionnal: fake the structured response */
473 struct json_object *x = json_object_new_object(), *y = json_object_new_object();
474 json_object_object_add(x, "jtype", json_object_new_string("afb-reply"));
475 json_object_object_add(x, "request", y);
476 json_object_object_add(y, "status", json_object_new_string(error));
478 json_object_object_add(y, "info", json_object_new_string(info));
480 json_object_object_add(x, "response", json_object_get(result));
482 printf("%s\n", json_object_to_json_string_ext(x, JSON_C_TO_STRING_NOSLASHESCAPE));
486 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));
492 static void on_pws_event_create(void *closure, const char *event_name, int event_id)
494 printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
498 static void on_pws_event_remove(void *closure, const char *event_name, int event_id)
500 printf("ON-EVENT-REMOVE: [%d:%s]\n", event_id, event_name);
504 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
506 printf("ON-EVENT-SUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
510 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
512 printf("ON-EVENT-UNSUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
516 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
519 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));
521 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));
525 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data)
528 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_NOSLASHESCAPE));
530 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));
535 static void pws_call(const char *verb, const char *object)
540 struct json_object *o;
541 enum json_tokener_error jerr;
543 /* allocates an id for the request */
544 rc = asprintf(&key, "%d:%s", ++num, verb);
546 /* echo the command if asked */
548 printf("SEND-CALL: %s %s\n", verb, object?:"null");
550 /* send the request */
552 if (object == NULL || object[0] == 0)
555 o = json_tokener_parse_verbose(object, &jerr);
556 if (jerr != json_tokener_success)
557 o = json_object_new_string(object);
559 rc = afb_proto_ws_client_call(pws, verb, o, sessionid, key, NULL);
562 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
569 /* called when pws hangsup */
570 static void on_pws_hangup(void *closure)
572 printf("ON-HANGUP\n");