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"
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);
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);
56 static int process_stdin();
57 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure);
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);
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
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,
80 /* global variables */
81 static struct afb_wsj1 *wsj1;
82 static struct afb_proto_ws *pws;
93 static sd_event *loop;
94 static sd_event_source *evsrc;
95 static char *sessionid = "afb-client-demo";
97 /* print usage of the program */
98 static void usage(int status, char *arg0)
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"
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"
115 " %s --human 'localhost:1234/api?token=HELLO&uuid=magic' hello ping\n"
123 int main(int ac, char **av, char **env)
128 /* get the program name */
132 while (ac > 1 && av[1][0] == '-') {
133 if (av[1][1] == '-') {
136 if (!strcmp(av[1], "--human")) /* request for human output */
139 else if (!strcmp(av[1], "--raw")) /* request for raw output */
142 else if (!strcmp(av[1], "--direct")) /* request for direct api */
145 else if (!strcmp(av[1], "--break")) /* request to break connection */
148 else if (!strcmp(av[1], "--keep-running")) /* request to break connection */
151 else if (!strcmp(av[1], "--sync")) /* request to break connection */
154 else if (!strcmp(av[1], "--echo")) /* request to echo inputs */
157 /* emit usage and exit */
159 usage(!!strcmp(av[1], "--help"), a0);
161 /* short option(s) */
162 for (rc = 1 ; av[1][rc] ; 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);
178 /* check the argument count */
179 if (ac != 2 && ac != 4 && ac != 5)
182 /* set raw by default */
186 /* get the default event loop */
187 rc = sd_event_default(&loop);
189 fprintf(stderr, "connection to default event loop failed: %s\n", strerror(-rc));
193 /* connect the websocket wsj1 to the uri given by the first argument */
195 pws = afb_ws_client_connect_api(loop, av[1], &pws_itf, NULL);
197 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
200 afb_proto_ws_on_hangup(pws, on_pws_hangup);
202 wsj1 = afb_ws_client_connect_wsj1(loop, av[1], &wsj1_itf, NULL);
204 fprintf(stderr, "connection to %s failed: %m\n", av[1]);
209 /* test the behaviour */
211 /* get requests from stdin */
213 fcntl(0, F_SETFL, O_NONBLOCK);
214 if (sd_event_add_io(loop, &evsrc, 0, EPOLLIN, on_stdin, NULL) < 0)
217 /* the request is defined by the arguments */
221 pws_call(av[2], av[3]);
223 wsj1_emit(av[2], av[3], av[4]);
235 if (!keeprun && !callcount)
237 sd_event_run(loop, 30000000);
239 else if (!synchro || !callcount) {
240 if (!process_stdin() && usein)
241 sd_event_run(loop, 100000);
243 sd_event_run(loop, 30000000);
248 /* decrement the count of calls */
249 static void dec_callcount()
252 if (exonrep && !callcount)
256 /* called when wsj1 hangsup */
257 static void on_wsj1_hangup(void *closure, struct afb_wsj1 *wsj1)
259 printf("ON-HANGUP\n");
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)
269 printf("%s\n", afb_wsj1_msg_object_s(msg));
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));
275 rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", NULL);
277 fprintf(stderr, "replying failed: %m\n");
280 /* called when wsj1 receives an event */
281 static void on_wsj1_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
284 printf("%s\n", afb_wsj1_msg_object_s(msg));
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));
292 /* called when wsj1 receives a reply */
293 static void on_wsj1_reply(void *closure, struct afb_wsj1_msg *msg)
296 printf("%s\n", afb_wsj1_msg_object_s(msg));
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));
308 static void wsj1_call(const char *api, const char *verb, const char *object)
314 /* allocates an id for the request */
315 rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);
317 /* echo the command if asked */
319 printf("SEND-CALL %s/%s %s\n", api, verb, object?:"null");
321 /* send the request */
323 rc = afb_wsj1_call_s(wsj1, api, verb, object, on_wsj1_reply, key);
325 fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);
331 static void wsj1_event(const char *event, const char *object)
335 /* echo the command if asked */
337 printf("SEND-EVENT: %s %s\n", event, object?:"null");
339 rc = afb_wsj1_send_event_s(wsj1, event, object);
341 fprintf(stderr, "sending !%s(%s) failed: %m\n", event, object);
344 /* emits either a call (when api!='!') or an event */
345 static void wsj1_emit(const char *api, const char *verb, const char *object)
347 if (object == NULL || object[0] == 0)
350 if (api[0] == '!' && api[1] == 0)
351 wsj1_event(verb, object);
353 wsj1_call(api, verb, object);
359 static int process_stdin()
361 static size_t count = 0;
362 static char line[16384];
363 static char sep[] = " \t";
364 static char sepnl[] = " \t\n";
370 /* read the buffer */
371 while (sizeof line > count) {
372 rc = read(0, line + count, sizeof line - count);
373 if (rc >= 0 || errno != EINTR)
379 fprintf(stderr, "read error: %m\n");
384 if (!usein && !keeprun) {
391 if (synchro && callcount)
394 /* normalise the buffer content */
395 /* TODO: handle backspace \x7f ? */
396 /* process the lines */
399 size_t i, api[2], verb[2], rest[2];
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++;
408 verb[0] = i; while(i < count && !strchr(sepnl, line[i])) i++; verb[1] = i;
409 while(i < count && strchr(sep, line[i])) i++;
411 rest[0] = i; while(i < count && line[i] != '\n') i++; rest[1] = i;
412 if (i == count) break;
415 if (api[0] == api[1]) {
417 } else if (line[api[0]] == '#') {
419 } else if (verb[0] == verb[1]) {
420 fprintf(stderr, "verb missing, bad line: %s\n", line+pos);
422 line[api[1]] = line[verb[1]] = 0;
424 pws_call(line + verb[0], line + rest[0]);
426 wsj1_emit(line + api[0], line + verb[0], line + rest[0]);
432 if (count == sizeof line) {
433 fprintf(stderr, "overflow\n");
437 memmove(line, line + pos, count);
442 /* called when something happens on stdin */
443 static int on_stdin(sd_event_source *src, int fd, uint32_t revents, void *closure)
447 sd_event_source_unref(src);
453 static void on_pws_reply(void *closure, void *request, struct json_object *result, const char *error, const char *info)
455 error = error ?: "success";
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));
463 json_object_object_add(y, "info", json_object_new_string(info));
465 json_object_object_add(x, "response", json_object_get(result));
467 printf("%s\n", json_object_to_json_string_ext(x, JSON_C_TO_STRING_NOSLASHESCAPE));
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));
477 static void on_pws_event_create(void *closure, const char *event_name, int event_id)
479 printf("ON-EVENT-CREATE: [%d:%s]\n", event_id, event_name);
483 static void on_pws_event_remove(void *closure, const char *event_name, int event_id)
485 printf("ON-EVENT-REMOVE: [%d:%s]\n", event_id, event_name);
489 static void on_pws_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
491 printf("ON-EVENT-SUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
495 static void on_pws_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
497 printf("ON-EVENT-UNSUBSCRIBE %s: [%d:%s]\n", (char*)request, event_id, event_name);
501 static void on_pws_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
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));
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));
510 static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data)
513 printf("ON-EVENT-BROADCAST: [%s]\n%s\n", event_name, json_object_to_json_string_ext(data, JSON_C_TO_STRING_NOSLASHESCAPE));
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));
520 static void pws_call(const char *verb, const char *object)
525 struct json_object *o;
527 /* allocates an id for the request */
528 rc = asprintf(&key, "%d:%s", ++num, verb);
530 /* echo the command if asked */
532 printf("SEND-CALL: %s %s\n", verb, object?:"null");
534 /* send the request */
536 if (object == NULL || object[0] == 0 || !strcmp(object, "null"))
539 o = json_tokener_parse(object);
541 o = json_object_new_string(object);
543 rc = afb_proto_ws_client_call(pws, verb, o, sessionid, key, NULL);
546 fprintf(stderr, "calling %s(%s) failed: %m\n", verb, object?:"");
553 /* called when pws hangsup */
554 static void on_pws_hangup(void *closure)
556 printf("ON-HANGUP\n");