2 * Copyright (C) 2015-2020 "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, uint16_t event_id, const char *event_name);
59 static void on_pws_event_remove(void *closure, uint16_t event_id);
60 static void on_pws_event_subscribe(void *closure, void *request, uint16_t event_id);
61 static void on_pws_event_unsubscribe(void *closure, void *request, uint16_t event_id);
62 static void on_pws_event_push(void *closure, uint16_t 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;
107 static uint16_t numuuid;
108 static uint16_t numtoken;
110 static int exitcode = 0;
112 /* print usage of the program */
113 static void usage(int status, char *arg0)
115 char *name = strrchr(arg0, '/');
116 name = name ? name + 1 : arg0;
117 fprintf(status ? stderr : stdout, "usage: %s [options]... uri [api verb [data]]\n", name);
118 fprintf(status ? stderr : stdout, " %s -d [options]... uri [verb [data]]\n", name);
119 fprintf(status ? stderr : stdout, "\n"
121 " -b, --break Break connection just after event/call has been emitted.\n"
122 " -d, --direct Direct api\n"
123 " -e, --echo Echo inputs\n"
124 " -h, --help Display this help\n"
125 " -H, --human Display human readable JSON\n"
126 " -k, --keep-running Keep running until disconnect, even if input closed\n"
127 " -p, --pipe COUNT Allow to pipe COUNT requests\n"
128 " -r, --raw Raw output (default)\n"
129 " -s, --sync Synchronous: wait for answers (like -p 1)\n"
130 " -t, --token TOKEN The token to use\n"
131 " -u, --uuid UUID The identifier of session to use\n"
133 " %s --human 'localhost:1234/api?token=HELLO&uuid=magic' hello ping\n"
141 int main(int ac, char **av, char **env)
146 /* get the program name */
150 while (ac > 1 && (an = av[1])[0] == '-') {
154 if (!strcmp(an, "--human")) /* request for human output */
157 else if (!strcmp(an, "--raw")) /* request for raw output */
160 else if (!strcmp(an, "--direct")) /* request for direct api */
163 else if (!strcmp(an, "--break")) /* request to break connection */
166 else if (!strcmp(an, "--keep-running")) /* request to break connection */
169 else if (!strcmp(an, "--sync")) /* request to break connection */
172 else if (!strcmp(an, "--echo")) /* request to echo inputs */
175 else if (!strcmp(an, "--pipe") && av[2] && atoi(av[2]) > 0) {
176 synchro = atoi(av[2]);
180 else if (!strcmp(an, "--token") && av[2]) { /* token to use */
185 else if (!strcmp(an, "--uuid") && av[2]) { /* session id to join */
190 /* emit usage and exit */
192 usage(strcmp(an, "--help") ? Exit_Bad_Arg : Exit_Success, a0);
194 /* short option(s) */
195 for (rc = 1 ; an[rc] ; rc++)
197 case 'H': human = 1; break;
198 case 'r': raw = 1; break;
199 case 'd': direct = 1; break;
200 case 'b': breakcon = 1; break;
201 case 'k': keeprun = 1; break;
202 case 's': synchro = 1; break;
203 case 'e': echo = 1; break;
204 case 't': if (!av[2]) usage(Exit_Bad_Arg, a0); token = av[2]; av++; ac--; break;
205 case 'u': if (!av[2]) usage(Exit_Bad_Arg, a0); uuid = av[2]; av++; ac--; break;
206 case 'p': if (av[2] && atoi(av[2]) > 0) { synchro = atoi(av[2]); av++; ac--; break; } /*@fallthrough@*/
208 usage(an[rc] != 'h' ? Exit_Bad_Arg : Exit_Success, a0);
216 /* check the argument count */
217 if (ac != 2 && ac != 4 && ac != 5)
220 /* set raw by default */
224 /* get the default event loop */
225 rc = sd_event_default(&loop);
227 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
231 /* connect the websocket wsj1 to the uri given by the first argument */
233 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
235 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
236 return Exit_Cant_Connect;
238 afb_proto_ws_on_hangup(pws, on_pws_hangup);
241 afb_proto_ws_client_session_create(pws, numuuid, uuid);
245 afb_proto_ws_client_token_create(pws, numtoken, token);
248 rc = asprintf(&url, "%s%s%s%s%s%s%s",
250 uuid || token ? "?" : "",
253 uuid && token ? "&" : "",
254 token ? "token=" : "",
257 wsj1 = afb_ws_client_connect_wsj1(loop, url, &wsj1_itf, NULL);
259 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
260 return Exit_Cant_Connect;
264 /* test the behaviour */
266 /* get requests from stdin */
268 fcntl(0, F_SETFL, O_NONBLOCK);
269 if (sd_event_add_io(loop, &evsrc, 0, EPOLLIN, on_stdin, NULL) < 0)
272 /* the request is defined by the arguments */
276 pws_call(av[2], av[3]);
278 wsj1_emit(av[2], av[3], av[4]);
290 if (!keeprun && !callcount)
292 sd_event_run(loop, 30000000);
294 else if (!synchro || callcount < synchro) {
295 if (!process_stdin() && usein)
296 sd_event_run(loop, 100000);
298 sd_event_run(loop, 30000000);
303 /* decrement the count of calls */
304 static void dec_callcount()
307 if (exonrep && !callcount)
311 /* called when wsj1 hangsup */
312 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
314 printf("ON-HANGUP\n");
319 /* called when wsj1 receives a method invocation */
320 static void on_wsj1_call(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
324 printf("%s\n", afb_wsj1_msg_object_s(msg));
326 printf("ON-CALL %s/%s:\n%s\n", api, verb,
327 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
328 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
330 rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
332 fprintf(stderr, "replying failed: %m\n");
335 /* called when wsj1 receives an event */
336 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
339 printf("%s\n", afb_wsj1_msg_object_s(msg));
341 printf("ON-EVENT %s:\n%s\n", event,
342 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
343 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
347 /* called when wsj1 receives a reply */
348 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
350 int iserror = !afb_wsj1_msg_is_reply_ok(msg);
351 exitcode = iserror ? Exit_Error : Exit_Success;
353 printf("%s\n", afb_wsj1_msg_object_s(msg));
355 printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
356 iserror ? "ERROR" : "OK",
357 json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
358 JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
365 static void wsj1_call(const char *api, const char *verb, const char *object)
371 /* allocates an id for the request */
372 rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
374 /* echo the command if asked */
376 printf("SEND-CALL %s/%s %s\n", api, verb, object?:"null");
378 /* send the request */
380 rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
382 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
388 static void wsj1_event(const char *event, const char *object)
392 /* echo the command if asked */
394 printf("SEND-EVENT: %s %s\n", event, object?:"null");
396 rc = afb_wsj1_send_event_s(wsj1, event, object);
398 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
401 /* emits either a call (when api!='!') or an event */
402 static void wsj1_emit(const char *api, const char *verb, const char *object)
404 if (object == NULL || object[0] == 0)
407 if (api[0] == '!' && api[1] == 0)
408 wsj1_event(verb, object);
410 wsj1_call(api, verb, object);
416 static int process_stdin()
418 static size_t count = 0;
419 static char line[16384];
420 static char sep[] = " \t";
421 static char sepnl[] = " \t\n";
427 /* read the buffer */
428 while (sizeof line > count) {
429 rc = read(0, line + count, sizeof line - count);
430 if (rc >= 0 || errno != EINTR)
436 fprintf(stderr, "read error: %m\n");
437 exit(Exit_Input_Fail);
441 if (!usein && !keeprun) {
448 if (synchro && callcount >= synchro)
451 /* normalise the buffer content */
452 /* TODO: handle backspace \x7f ? */
453 /* process the lines */
456 size_t i, api[2], verb[2], rest[2];
458 while(i < count && strchr(sep, line[i])) i++;
459 api[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; api[1] = i;
460 while(i < count && strchr(sep, line[i])) i++;
465 verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
466 while(i < count && strchr(sep, line[i])) i++;
468 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
469 if (i == count) break;
472 if (api[0] == api[1]) {
474 } else if (line[api[0]] == '#') {
476 } else if (verb[0] == verb[1]) {
477 fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
479 line[api[1]] = line[verb[1]] = 0;
481 pws_call(line + verb[0], line + rest[0]);
483 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
489 if (count == sizeof line) {
490 fprintf(stderr, "overflow\n");
491 exit(Exit_Input_Fail);
494 memmove(line, line + pos, count);
499 /* called when something happens on stdin */
500 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure)
504 sd_event_source_unref(src);
510 static void on_pws_reply(void *closure, void *request, struct json_object *result, const char *error, const char *info)
512 int iserror = !!error;
513 exitcode = iserror ? Exit_Error : Exit_Success;
514 error = error ?: "success";
516 /* TODO: transitionnal: fake the structured response */
517 struct json_object *x = json_object_new_object(), *y = json_object_new_object();
518 json_object_object_add(x, "jtype", json_object_new_string("afb-reply"));
519 json_object_object_add(x, "request", y);
520 json_object_object_add(y, "status", json_object_new_string(error));
522 json_object_object_add(y, "info", json_object_new_string(info));
524 json_object_object_add(x, "response", json_object_get(result));
526 printf("%s\n", json_object_to_json_string_ext(x, JSON_C_TO_STRING_NOSLASHESCAPE));
530 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));
536 static void on_pws_event_create(void *closure, uint16_t event_id, const char *event_name)
538 printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
542 static void on_pws_event_remove(void *closure, uint16_t event_id)
544 printf("ON-EVENT-REMOVE: [%d]\n", event_id);
548 static void on_pws_event_subscribe(void *closure, void *request, uint16_t event_id)
550 printf("ON-EVENT-SUBSCRIBE %s: [%d]\n", (char*)request, event_id);
554 static void on_pws_event_unsubscribe(void *closure, void *request, uint16_t event_id)
556 printf("ON-EVENT-UNSUBSCRIBE %s: [%d]\n", (char*)request, event_id);
560 static void on_pws_event_push(void *closure, uint16_t event_id, struct json_object *data)
563 printf("ON-EVENT-PUSH: [%d]\n%s\n", event_id, json_object_to_json_string_ext(data, JSON_C_TO_STRING_NOSLASHESCAPE));
565 printf("ON-EVENT-PUSH: [%d]\n%s\n", event_id, json_object_to_json_string_ext(data, JSON_C_TO_STRING_PRETTY|JSON_C_TO_STRING_NOSLASHESCAPE));
569 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)
572 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_NOSLASHESCAPE));
574 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));
579 static void pws_call(const char *verb, const char *object)
584 struct json_object *o;
585 enum json_tokener_error jerr;
587 /* allocates an id for the request */
588 rc = asprintf(&key, "%d:%s", ++num, verb);
590 /* echo the command if asked */
592 printf("SEND-CALL: %s %s\n", verb, object?:"null");
594 /* send the request */
596 if (object == NULL || object[0] == 0)
599 o = json_tokener_parse_verbose(object, &jerr);
600 if (jerr != json_tokener_success)
601 o = json_object_new_string(object);
603 rc = afb_proto_ws_client_call(pws, verb, o, numuuid, numtoken, key, NULL);
606 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
613 /* called when pws hangsup */
614 static void on_pws_hangup(void *closure)
616 printf("ON-HANGUP\n");