AFBClient: fix port sanity check
[staging/windowmanager.git] / AFBClient.cpp
1 #include "AFBClient.h"
2
3 #include <cassert>
4 #include <cctype>
5 #include <cerrno>
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9
10 #include <atomic>
11 #include <map>
12 #include <mutex>
13 #include <set>
14
15 #include <unistd.h>
16
17 #include <systemd/sd-event.h>
18
19 #include <json-c/json.h>
20
21 extern "C" {
22 #include <afb/afb-ws-client.h>
23 #include <afb/afb-wsj1.h>
24 }
25
26 #define UNUSED(x) (void)(x)
27
28 //       _                 ___                 _
29 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | |
30 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| |
31 // | (__| | (_| \__ \__ \  | || | | | | | |_) | |
32 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_|
33 //                                      |_|
34 class AFBClient::Impl {
35     friend class AFBClient;
36
37     // This is the AFBClient interface impl
38     int init(int port, char const *token);
39     int dispatch();
40
41     // WM API
42     int requestSurface(const char *label);
43     int activateSurface(const char *label);
44     int deactivateSurface(const char *label);
45     int endDraw(const char *label);
46
47     void set_event_handler(enum EventType et, handler_fun func);
48
49     Impl();
50     ~Impl();
51
52     struct afb_wsj1 *wsj1;
53     struct sd_event *loop;
54
55     std::set<std::string> labels;
56     std::map<EventType, handler_fun> handlers;
57
58     int api_call(const char *verb, json_object *object,
59                  const std::function<void(bool, json_object *)> &onReply);
60     void dispatch_internal();
61
62 public:
63     void event(char const *et, char const *label);
64 };
65
66 namespace {
67
68 constexpr const int token_maxlen = 20;
69 constexpr const char *const wmAPI = "winman";
70
71 #ifdef NDEBUG
72 #define TRACE()
73 #define TRACEN(N)
74 #else
75 #define CONCAT_(X, Y) X##Y
76 #define CONCAT(X, Y) CONCAT_(X, Y)
77
78 #define TRACE() \
79     ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
80 #define TRACEN(N) \
81     ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
82
83 struct ScopeTrace {
84     thread_local static int indent;
85     char const *f{};
86     explicit ScopeTrace(char const *func) : f(func) {
87         fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
88     }
89     ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
90 };
91 thread_local int ScopeTrace::indent = 0;
92 #endif
93
94 /* called when wsj1 receives a method invocation */
95 void onCall(void *closure, const char *api, const char *verb,
96             struct afb_wsj1_msg *msg) {
97     TRACE();
98     UNUSED(closure);
99     UNUSED(verb);
100     UNUSED(api);
101     UNUSED(msg);
102 }
103
104 /* called when wsj1 receives an event */
105 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
106     TRACE();
107     reinterpret_cast<AFBClient::Impl *>(closure)->event(
108         event, json_object_get_string(
109                    json_object_object_get(afb_wsj1_msg_object_j(msg), "data")));
110 }
111
112 /* called when wsj1 hangsup */
113 void onHangup(void *closure, afb_wsj1 *wsj1) {
114     TRACE();
115     UNUSED(closure);
116     UNUSED(wsj1);
117     fputs("Hangup, the WindowManager vanished\n", stderr);
118     exit(1);  // XXX: there should be something ... *better* here.
119 }
120
121 constexpr struct afb_wsj1_itf itf = {
122     onHangup, onCall, onEvent,
123 };
124
125 // XXX: I am not sure this is the right thing to do though...
126 std::recursive_mutex dispatch_mutex;
127
128 json_object *drawing_name_json_argument(char const *label) {
129     json_object *j = json_object_new_object();
130     json_object_object_add(j, "drawing_name", json_object_new_string(label));
131     return j;
132 }
133
134 }  // namespace
135
136 //       _                 ___                 _   _                 _
137 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | | (_)_ __ ___  _ __ | |
138 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
139 // | (__| | (_| \__ \__ \  | || | | | | | |_) | | | | | | | | | |_) | |
140 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
141 //                                      |_|                   |_|
142 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
143
144 AFBClient::Impl::~Impl() {
145     TRACE();
146     afb_wsj1_unref(wsj1);
147     sd_event_unref(loop);
148 }
149
150 int AFBClient::Impl::init(int port, char const *token) {
151     TRACE();
152     char *uribuf = nullptr;
153     int rc = -1;
154
155     if (this->loop != nullptr && this->wsj1 != nullptr) {
156         fputs("AFBClient instance is already initialized!\n", stderr);
157         rc = -EALREADY;
158         goto fail;
159     }
160
161     if ((token == nullptr) || strlen(token) > token_maxlen) {
162         fputs("Token is invalid\n", stderr);
163         rc = -EINVAL;
164         goto fail;
165     }
166
167     for (char const *p = token; *p != 0; p++) {
168         if (isalnum(*p) == 0) {
169             fputs("Token is invalid\n", stderr);
170             rc = -EINVAL;
171             goto fail;
172         }
173     }
174
175     if (port < 1 || port > 0xffff) {
176         fputs("Port is invalid\n", stderr);
177         rc = -EINVAL;
178         goto fail;
179     }
180
181     /* get the default event loop */
182     rc = sd_event_default(&this->loop);
183     if (rc < 0) {
184         fprintf(stderr, "Connection to default event loop failed: %s\n",
185                 strerror(-rc));
186         goto fail;
187     }
188
189     asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
190
191     /* connect the websocket wsj1 to the uri given by the first argument */
192     this->wsj1 = afb_ws_client_connect_wsj1(
193         this->loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
194     if (this->wsj1 == nullptr) {
195         sd_event_unref(this->loop);
196         this->loop = nullptr;
197         fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
198         rc = -errno;
199         goto fail;
200     }
201
202     return 0;
203
204 fail:
205     return rc;
206 }
207
208 int AFBClient::Impl::dispatch() {
209     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
210     return sd_event_run(this->loop, 1);
211 }
212
213 int AFBClient::Impl::requestSurface(const char *label) {
214     TRACE();
215
216     if (this->labels.find(label) != this->labels.end()) {
217         fputs("Surface label already known!\n", stderr);
218         return -EINVAL;
219     }
220
221     json_object *j = drawing_name_json_argument(label);
222
223     int rc = -1;
224     /* send the request */
225     int rc2 =
226         this->api_call("request_surface", j, [&rc](bool ok, json_object *j) {
227             if (ok) {
228                 int id =
229                     json_object_get_int(json_object_object_get(j, "response"));
230                 char *buf;
231                 asprintf(&buf, "%d", id);
232                 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
233                 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
234                     fprintf(stderr, "putenv failed: %m\n");
235                     rc = -errno;
236                 } else {
237                     rc = 0;  // Single point of success
238                 }
239             } else {
240                 fprintf(stderr, "Could not get surface ID from WM: %s\n",
241                         j != nullptr ? json_object_to_json_string_ext(
242                                            j, JSON_C_TO_STRING_PRETTY)
243                                      : "no-info");
244                 rc = -EINVAL;
245             }
246         });
247
248     if (rc2 < 0) {
249         rc = rc2;
250     }
251
252     if (rc >= 0) {
253         this->labels.insert(this->labels.end(), label);
254     }
255
256     return rc;
257 }
258
259 int AFBClient::Impl::activateSurface(const char *label) {
260     TRACE();
261     json_object *j = drawing_name_json_argument(label);
262     return this->api_call("activate_surface", j, [](bool ok, json_object *j) {
263         if (!ok) {
264             fprintf(stderr, "API Call activate_surface() failed: %s\n",
265                     j != nullptr ? json_object_to_json_string_ext(
266                                        j, JSON_C_TO_STRING_PRETTY)
267                                  : "no-info");
268         }
269     });
270 }
271
272 int AFBClient::Impl::deactivateSurface(const char *label) {
273     TRACE();
274     json_object *j = drawing_name_json_argument(label);
275     return this->api_call("deactivate_surface", j, [](bool ok, json_object *j) {
276         if (!ok) {
277             fprintf(stderr, "API Call deactivate_surface() failed: %s\n",
278                     j != nullptr ? json_object_to_json_string_ext(
279                                        j, JSON_C_TO_STRING_PRETTY)
280                                  : "no-info");
281         }
282     });
283 }
284
285 int AFBClient::Impl::endDraw(const char *label) {
286     TRACE();
287     json_object *j = drawing_name_json_argument(label);
288     return this->api_call("enddraw", j, [](bool ok, json_object *j) {
289         if (!ok) {
290             fprintf(stderr, "API Call endDraw() failed: %s\n",
291                     j != nullptr ? json_object_to_json_string_ext(
292                                        j, JSON_C_TO_STRING_PRETTY)
293                                  : "no-info");
294         }
295     });
296 }
297
298 void AFBClient::Impl::set_event_handler(
299     enum EventType et, std::function<void(char const *)> func) {
300     TRACE();
301
302     if (et >= 1 && et <= 6) {  // Yeah ... just go with it!
303         this->handlers[et] = std::move(func);
304     }
305 }
306
307 namespace {
308 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
309     // Event have the form "$API/$EVENT", just try to find the first / and
310     // get on with it.
311     char const *et2 = strchr(et, '/');
312     if (et2 != nullptr) {
313         et = et2 + 1;
314     }
315
316 #define ET(N, A)                                          \
317     do {                                                  \
318         if (strcasecmp(et, N) == 0)                       \
319             return std::pair<bool, AFBClient::EventType>( \
320                 true, CONCAT(AFBClient::Event_, A));      \
321     } while (false)
322
323     ET("activated", Active);
324     ET("deactivated", Inactive);
325     ET("visible", Visible);
326     ET("invisible", Invisible);
327     ET("syncdraw", SyncDraw);
328     ET("flushdraw", FlushDraw);
329 #undef ET
330
331     return std::pair<bool, AFBClient::EventType>(false,
332                                                  AFBClient::Event_Active);
333 }
334 }  // namespace
335
336 /// object will be json_object_put
337 int AFBClient::Impl::api_call(
338     const char *verb, json_object *object,
339     const std::function<void(bool, json_object *)> &onReply) {
340     TRACE();
341
342     // We need to wrap the actual onReply call once in order to
343     // *look* like a normal functions pointer (std::functions<>
344     // with captures cannot convert to function pointers).
345     // Alternatively we could setup a local struct and use it as
346     // closure, but I think it is cleaner this way.
347     int call_rc = 0;
348     std::atomic<bool> returned{};
349     returned.store(false, std::memory_order_relaxed);
350     std::function<void(bool, json_object *)> wrappedOnReply =
351         [&returned, &call_rc, &onReply](bool ok, json_object *j) {
352             TRACEN(wrappedOnReply);
353             call_rc = ok ? 0 : -EINVAL;
354             // We know it failed, but there may be an explanation in the
355             // json object.
356             {
357                 TRACEN(onReply);
358                 onReply(ok, j);
359             }
360             returned.store(true, std::memory_order_release);
361         };
362
363     // make the actual call, use wrappedOnReply as closure
364     int rc = afb_wsj1_call_j(
365         this->wsj1, wmAPI, verb, object,
366         [](void *closure, afb_wsj1_msg *msg) {
367             TRACEN(callClosure);
368             auto *onReply =
369                 reinterpret_cast<std::function<void(bool, json_object *)> *>(
370                     closure);
371             (*onReply)(!(afb_wsj1_msg_is_reply_ok(msg) == 0),
372                        afb_wsj1_msg_object_j(msg));
373         },
374         &wrappedOnReply);
375
376     if (rc < 0) {
377         fprintf(
378             stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
379             json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
380         // Call the reply handler regardless with a NULL json_object*
381         onReply(false, nullptr);
382     } else {
383         // We need to dispatch until "returned" got set, this is necessary
384         // if events get triggered by the call (and would be dispatched before
385         // the actual call-reply).
386         while (!returned.load(std::memory_order_consume)) {
387             std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
388             if (!returned.load(std::memory_order_consume)) {
389                 this->dispatch_internal();
390             }
391         }
392
393         // return the actual API call result
394         rc = call_rc;
395     }
396
397     return rc;
398 }
399
400 void AFBClient::Impl::dispatch_internal() {
401     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
402     TRACE();
403     sd_event_run(this->loop, -1);
404 }
405
406 void AFBClient::Impl::event(char const *et, char const *label) {
407     TRACE();
408     auto oet = make_event_type(et);
409     if (!oet.first) {
410         fprintf(stderr, "Unknown event type string '%s'\n", et);
411         return;
412     }
413
414     auto i = this->handlers.find(oet.second);
415     if (i != this->handlers.end()) {
416         if (this->labels.find(label) != this->labels.end()) {
417             i->second(label);
418         }
419     }
420 }
421
422 //       _                    _    _____ ____   ____ _ _            _
423 //   ___| | __ _ ___ ___     / \  |  ___| __ ) / ___| (_) ___ _ __ | |_
424 //  / __| |/ _` / __/ __|   / _ \ | |_  |  _ \| |   | | |/ _ \ '_ \| __|
425 // | (__| | (_| \__ \__ \  / ___ \|  _| | |_) | |___| | |  __/ | | | |_
426 //  \___|_|\__,_|___/___/ /_/   \_\_|   |____/ \____|_|_|\___|_| |_|\__|
427 //
428 int AFBClient::init(int port, char const *token) {
429     return this->d->init(port, token);
430 }
431
432 int AFBClient::dispatch() { return this->d->dispatch(); }
433
434 int AFBClient::requestSurface(const char *label) {
435     return this->d->requestSurface(label);
436 }
437
438 int AFBClient::activateSurface(const char *label) {
439     return this->d->activateSurface(label);
440 }
441
442 int AFBClient::deactivateSurface(const char *label) {
443     return this->d->deactivateSurface(label);
444 }
445
446 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
447
448 void AFBClient::set_event_handler(enum EventType et,
449                                   std::function<void(char const *label)> f) {
450     return this->d->set_event_handler(et, std::move(f));
451 }
452
453 AFBClient &AFBClient::instance() {
454     TRACE();
455     static AFBClient obj;
456     return obj;
457 }
458
459 AFBClient::AFBClient() : d(new Impl) {}
460
461 AFBClient::~AFBClient() { delete d; }