520b5547ddfd155892467f2e1c8dd209b2715f52
[WebKit.git] / Source / JavaScriptCore / inspector / remote / glib / RemoteInspectorServer.cpp
1 /*
2  * Copyright (C) 2017 Igalia S.L.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "RemoteInspectorServer.h"
28
29 #if ENABLE(REMOTE_INSPECTOR)
30
31 #include "RemoteInspector.h"
32 #include "RemoteInspectorUtils.h"
33 #include <gio/gio.h>
34 #include <wtf/Vector.h>
35 #include <wtf/glib/GUniquePtr.h>
36
37 #if PLATFORM(GTK)
38 #define INSPECTOR_DBUS_INTERFACE "org.webkitgtk.Inspector"
39 #define INSPECTOR_DBUS_OBJECT_PATH "/org/webkitgtk/Inspector"
40 #define REMOTE_INSPECTOR_DBUS_INTERFACE "org.webkitgtk.RemoteInspector"
41 #define REMOTE_INSPECTOR_DBUS_OBJECT_PATH "/org/webkitgtk/RemoteInspector"
42 #define REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "org.webkitgtk.RemoteInspectorClient"
43 #define REMOTE_INSPECTOR_CLIENT_OBJECT_PATH "/org/webkitgtk/RemoteInspectorClient"
44 #endif
45
46 namespace Inspector {
47
48 static uint64_t generateConnectionID()
49 {
50     static uint64_t connectionID = 0;
51     return ++connectionID;
52 }
53
54 static const char introspectionXML[] =
55     "<node>"
56     "  <interface name='" INSPECTOR_DBUS_INTERFACE "'>"
57     "    <method name='SetTargetList'>"
58     "      <arg type='a(tsssb)' name='list' direction='in'/>"
59     "      <arg type='b' name='remoteAutomationEnabled' direction='in'/>"
60     "    </method>"
61     "    <method name='SetupInspectorClient'>"
62     "      <arg type='ay' name='backendCommandsHash' direction='in'/>"
63     "      <arg type='ay' name='backendCommands' direction='out'/>"
64     "    </method>"
65     "    <method name='Setup'>"
66     "      <arg type='t' name='connection' direction='in'/>"
67     "      <arg type='t' name='target' direction='in'/>"
68     "    </method>"
69     "    <method name='FrontendDidClose'>"
70     "      <arg type='t' name='connection' direction='in'/>"
71     "      <arg type='t' name='target' direction='in'/>"
72     "    </method>"
73     "    <method name='SendMessageToFrontend'>"
74     "      <arg type='t' name='target' direction='in'/>"
75     "      <arg type='s' name='message' direction='in'/>"
76     "    </method>"
77     "    <method name='SendMessageToBackend'>"
78     "      <arg type='t' name='connection' direction='in'/>"
79     "      <arg type='t' name='target' direction='in'/>"
80     "      <arg type='s' name='message' direction='in'/>"
81     "    </method>"
82     "    <method name='StartAutomationSession'>"
83     "      <arg type='s' name='sessionID' direction='in'/>"
84     "    </method>"
85     "  </interface>"
86     "</node>";
87
88 const GDBusInterfaceVTable RemoteInspectorServer::s_interfaceVTable = {
89     // method_call
90     [] (GDBusConnection* connection, const gchar* /*sender*/, const gchar* /*objectPath*/, const gchar* /*interfaceName*/, const gchar* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) {
91         auto* inspectorServer = static_cast<RemoteInspectorServer*>(userData);
92         if (!g_strcmp0(methodName, "SetTargetList")) {
93             inspectorServer->setTargetList(connection, parameters);
94             g_dbus_method_invocation_return_value(invocation, nullptr);
95         } else if (!g_strcmp0(methodName, "SetupInspectorClient")) {
96             GRefPtr<GVariant> backendCommandsHash;
97             g_variant_get(parameters, "(@ay)", &backendCommandsHash.outPtr());
98             auto* backendCommands = inspectorServer->setupInspectorClient(connection, g_variant_get_bytestring(backendCommandsHash.get()));
99             g_dbus_method_invocation_return_value(invocation, g_variant_new("(@ay)", backendCommands));
100         } else if (!g_strcmp0(methodName, "Setup")) {
101             guint64 connectionID, targetID;
102             g_variant_get(parameters, "(tt)", &connectionID, &targetID);
103             inspectorServer->setup(connection, connectionID, targetID);
104             g_dbus_method_invocation_return_value(invocation, nullptr);
105         } else if (!g_strcmp0(methodName, "FrontendDidClose")) {
106             guint64 connectionID, targetID;
107             g_variant_get(parameters, "(tt)", &connectionID, &targetID);
108             inspectorServer->close(connection, connectionID, targetID);
109             g_dbus_method_invocation_return_value(invocation, nullptr);
110         } else if (!g_strcmp0(methodName, "SendMessageToFrontend")) {
111             guint64 targetID;
112             const char* message;
113             g_variant_get(parameters, "(t&s)", &targetID, &message);
114             inspectorServer->sendMessageToFrontend(connection, targetID, message);
115             g_dbus_method_invocation_return_value(invocation, nullptr);
116         } else if (!g_strcmp0(methodName, "SendMessageToBackend")) {
117             guint64 connectionID, targetID;
118             const char* message;
119             g_variant_get(parameters, "(tt&s)", &connectionID, &targetID, &message);
120             inspectorServer->sendMessageToBackend(connection, connectionID, targetID, message);
121             g_dbus_method_invocation_return_value(invocation, nullptr);
122         } else if (!g_strcmp0(methodName, "StartAutomationSession")) {
123             const char* sessionID;
124             g_variant_get(parameters, "(&s)", &sessionID);
125             inspectorServer->startAutomationSession(connection, sessionID);
126             g_dbus_method_invocation_return_value(invocation, nullptr);
127         } else
128             g_dbus_method_invocation_return_value(invocation, nullptr);
129     },
130     // get_property
131     nullptr,
132     // set_property
133     nullptr,
134     // padding
135     nullptr
136 };
137
138 RemoteInspectorServer& RemoteInspectorServer::singleton()
139 {
140     static RemoteInspectorServer server;
141     return server;
142 }
143
144 RemoteInspectorServer::~RemoteInspectorServer()
145 {
146     g_cancellable_cancel(m_cancellable.get());
147     if (m_dbusServer)
148         g_dbus_server_stop(m_dbusServer.get());
149     if (m_introspectionData)
150         g_dbus_node_info_unref(m_introspectionData);
151 }
152
153 GDBusInterfaceInfo* RemoteInspectorServer::interfaceInfo()
154 {
155     if (!m_introspectionData) {
156         m_introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
157         ASSERT(m_introspectionData);
158     }
159     return m_introspectionData->interfaces[0];
160 }
161
162 bool RemoteInspectorServer::start(const char* address, unsigned port)
163 {
164     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", address, port));
165     GUniquePtr<char> uid(g_dbus_generate_guid());
166
167     m_cancellable = adoptGRef(g_cancellable_new());
168
169     GUniqueOutPtr<GError> error;
170     m_dbusServer = adoptGRef(g_dbus_server_new_sync(dbusAddress.get(), G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS, uid.get(), nullptr, m_cancellable.get(), &error.outPtr()));
171     if (!m_dbusServer) {
172         if (!g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
173             WTFLogAlways("Failed to start remote inspector server on %s: %s\n", dbusAddress.get(), error->message);
174         return false;
175     }
176
177     g_signal_connect(m_dbusServer.get(), "new-connection", G_CALLBACK(newConnectionCallback), this);
178     g_dbus_server_start(m_dbusServer.get());
179
180     return true;
181 }
182
183 gboolean RemoteInspectorServer::newConnectionCallback(GDBusServer*, GDBusConnection* connection, RemoteInspectorServer* inspectorServer)
184 {
185     inspectorServer->newConnection(connection);
186     return TRUE;
187 }
188
189 void RemoteInspectorServer::connectionClosedCallback(GDBusConnection* connection, gboolean /*remotePeerVanished*/, GError*, RemoteInspectorServer* server)
190 {
191     server->connectionClosed(connection);
192 }
193
194 void RemoteInspectorServer::newConnection(GDBusConnection* connection)
195 {
196     ASSERT(!m_connections.contains(connection));
197     m_connections.add(connection);
198     g_signal_connect(connection, "closed", G_CALLBACK(connectionClosedCallback), this);
199
200     g_dbus_connection_register_object(connection, INSPECTOR_DBUS_OBJECT_PATH, interfaceInfo(), &s_interfaceVTable, this, nullptr, nullptr);
201 }
202
203 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
204 {
205     GUniqueOutPtr<GError> error;
206     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
207     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
208         WTFLogAlways("RemoteInspectorServer failed to send DBus message: %s", error->message);
209 }
210
211 void RemoteInspectorServer::setTargetList(GDBusConnection* remoteInspectorConnection, GVariant* parameters)
212 {
213     ASSERT(m_connections.contains(remoteInspectorConnection));
214     auto addResult = m_remoteInspectorConnectionToIDMap.add(remoteInspectorConnection, 0);
215     if (addResult.isNewEntry) {
216         addResult.iterator->value = generateConnectionID();
217         m_idToRemoteInspectorConnectionMap.add(addResult.iterator->value, remoteInspectorConnection);
218     }
219
220     gboolean remoteAutomationEnabled;
221     GRefPtr<GVariant> targetList;
222     g_variant_get(parameters, "(@a(tsssb)b)", &targetList.outPtr(), &remoteAutomationEnabled);
223     GDBusConnection* clientConnection = remoteAutomationEnabled && m_automationConnection ? m_automationConnection.get() : m_clientConnection.get();
224     if (!clientConnection)
225         return;
226
227     g_dbus_connection_call(clientConnection, nullptr,
228         REMOTE_INSPECTOR_CLIENT_OBJECT_PATH,
229         REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE,
230         "SetTargetList",
231         g_variant_new("(t@a(tsssb))", m_remoteInspectorConnectionToIDMap.get(remoteInspectorConnection), targetList.get()),
232         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
233         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
234 }
235
236 void RemoteInspectorServer::clientConnectionClosedCallback(GDBusConnection* connection, gboolean /*remotePeerVanished*/, GError*, RemoteInspectorServer* server)
237 {
238     server->clientConnectionClosed(connection);
239 }
240
241 GVariant* RemoteInspectorServer::setupInspectorClient(GDBusConnection* clientConnection, const char* clientBackendCommandsHash)
242 {
243     ASSERT(!m_clientConnection);
244     m_clientConnection = clientConnection;
245     g_signal_connect(m_clientConnection.get(), "closed", G_CALLBACK(clientConnectionClosedCallback), this);
246
247     GVariant* backendCommands;
248     if (strcmp(clientBackendCommandsHash, backendCommandsHash().data())) {
249         auto bytes = Inspector::backendCommands();
250         backendCommands = g_variant_new_bytestring(static_cast<const char*>(g_bytes_get_data(bytes.get(), nullptr)));
251     } else
252         backendCommands = g_variant_new_bytestring("");
253
254     // Ask all remote inspectors to push their target lists to notify the new client.
255     for (auto* remoteInspectorConnection : m_remoteInspectorConnectionToIDMap.keys()) {
256         g_dbus_connection_call(remoteInspectorConnection, nullptr,
257             REMOTE_INSPECTOR_DBUS_OBJECT_PATH,
258             REMOTE_INSPECTOR_DBUS_INTERFACE,
259             "GetTargetList",
260             nullptr,
261             nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
262             -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
263     }
264
265     return backendCommands;
266 }
267
268 void RemoteInspectorServer::setup(GDBusConnection* clientConnection, uint64_t connectionID, uint64_t targetID)
269 {
270     ASSERT(m_clientConnection.get() == clientConnection || m_automationConnection.get() == clientConnection);
271     ASSERT(m_idToRemoteInspectorConnectionMap.contains(connectionID));
272     if (clientConnection == m_automationConnection.get()) {
273         m_automationTargets.add(std::make_pair(connectionID, targetID));
274         RemoteInspector::singleton().setup(targetID);
275         return;
276     }
277
278     m_inspectionTargets.add(std::make_pair(connectionID, targetID));
279     auto* remoteInspectorConnection = m_idToRemoteInspectorConnectionMap.get(connectionID);
280     g_dbus_connection_call(remoteInspectorConnection, nullptr,
281         REMOTE_INSPECTOR_DBUS_OBJECT_PATH,
282         REMOTE_INSPECTOR_DBUS_INTERFACE,
283         "Setup",
284         g_variant_new("(t)", targetID),
285         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
286         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
287 }
288
289 void RemoteInspectorServer::close(GDBusConnection* clientConnection, uint64_t connectionID, uint64_t targetID)
290 {
291     ASSERT(m_clientConnection.get() == clientConnection || m_automationConnection.get() == clientConnection);
292     ASSERT(m_idToRemoteInspectorConnectionMap.contains(connectionID));
293     if (clientConnection == m_automationConnection.get()) {
294         // FIXME: automation.
295         return;
296     }
297
298     ASSERT(m_inspectionTargets.contains(std::make_pair(connectionID, targetID)));
299     auto* remoteInspectorConnection = m_idToRemoteInspectorConnectionMap.get(connectionID);
300     g_dbus_connection_call(remoteInspectorConnection, nullptr,
301         REMOTE_INSPECTOR_DBUS_OBJECT_PATH,
302         REMOTE_INSPECTOR_DBUS_INTERFACE,
303         "FrontendDidClose",
304         g_variant_new("(t)", targetID),
305         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
306         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
307     m_inspectionTargets.remove(std::make_pair(connectionID, targetID));
308 }
309
310 void RemoteInspectorServer::clientConnectionClosed(GDBusConnection* clientConnection)
311 {
312     ASSERT(m_clientConnection.get() == clientConnection || m_automationConnection.get() == clientConnection);
313     if (clientConnection == m_automationConnection.get()) {
314         for (auto connectionTargetPair : m_automationTargets)
315             close(clientConnection, connectionTargetPair.first, connectionTargetPair.second);
316         m_automationConnection = nullptr;
317         return;
318     }
319
320     for (auto connectionTargetPair : m_inspectionTargets)
321         close(clientConnection, connectionTargetPair.first, connectionTargetPair.second);
322     m_clientConnection = nullptr;
323 }
324
325 void RemoteInspectorServer::connectionClosed(GDBusConnection* remoteInspectorConnection)
326 {
327     ASSERT(m_connections.contains(remoteInspectorConnection));
328     if (m_remoteInspectorConnectionToIDMap.contains(remoteInspectorConnection)) {
329         uint64_t connectionID = m_remoteInspectorConnectionToIDMap.take(remoteInspectorConnection);
330         m_idToRemoteInspectorConnectionMap.remove(connectionID);
331         // Send an empty target list to the clients.
332         Vector<GRefPtr<GDBusConnection>> clientConnections = { m_automationConnection, m_clientConnection };
333         for (auto& clientConnection : clientConnections) {
334             if (!clientConnection)
335                 continue;
336             g_dbus_connection_call(clientConnection.get(), nullptr,
337                 REMOTE_INSPECTOR_CLIENT_OBJECT_PATH,
338                 REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE,
339                 "SetTargetList",
340                 g_variant_new("(t@a(tsssb))", connectionID, g_variant_new_array(G_VARIANT_TYPE("(tsssb)"), nullptr, 0)),
341                 nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
342                 -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
343         }
344     }
345     m_connections.remove(remoteInspectorConnection);
346 }
347
348 void RemoteInspectorServer::sendMessageToBackend(GDBusConnection* clientConnection, uint64_t connectionID, uint64_t targetID, const char* message)
349 {
350     ASSERT(m_clientConnection.get() == clientConnection || m_automationConnection.get() == clientConnection);
351     ASSERT(m_idToRemoteInspectorConnectionMap.contains(connectionID));
352     if (clientConnection == m_automationConnection.get()) {
353         RemoteInspector::singleton().sendMessageToTarget(targetID, message);
354         return;
355     }
356
357     auto* remoteInspectorConnection = m_idToRemoteInspectorConnectionMap.get(connectionID);
358     g_dbus_connection_call(remoteInspectorConnection, nullptr,
359         REMOTE_INSPECTOR_DBUS_OBJECT_PATH,
360         REMOTE_INSPECTOR_DBUS_INTERFACE,
361         "SendMessageToTarget",
362         g_variant_new("(t&s)", targetID, message),
363         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
364         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
365 }
366
367 void RemoteInspectorServer::sendMessageToFrontend(GDBusConnection* remoteInspectorConnection, uint64_t targetID, const char* message)
368 {
369     ASSERT(m_connections.contains(remoteInspectorConnection));
370     ASSERT(m_remoteInspectorConnectionToIDMap.contains(remoteInspectorConnection));
371
372     uint64_t connectionID = m_remoteInspectorConnectionToIDMap.get(remoteInspectorConnection);
373     auto connectionTargetPair = std::make_pair(connectionID, targetID);
374     ASSERT(m_automationTargets.contains(connectionTargetPair) || m_inspectionTargets.contains(connectionTargetPair));
375     GDBusConnection* clientConnection = m_inspectionTargets.contains(connectionTargetPair) ? m_clientConnection.get() : m_automationConnection.get();
376     ASSERT(clientConnection);
377
378     g_dbus_connection_call(clientConnection, nullptr,
379         REMOTE_INSPECTOR_CLIENT_OBJECT_PATH,
380         REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE,
381         "SendMessageToFrontend",
382         g_variant_new("(tt&s)", m_remoteInspectorConnectionToIDMap.get(remoteInspectorConnection), targetID, message),
383         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
384         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
385 }
386
387 void RemoteInspectorServer::startAutomationSession(GDBusConnection* automationConnection, const char* sessionID)
388 {
389     if (!m_automationConnection)
390         m_automationConnection = automationConnection;
391     ASSERT(m_automationConnection.get() == automationConnection);
392
393     RemoteInspector::singleton().requestAutomationSession(sessionID);
394 }
395
396 } // namespace Inspector
397
398 #endif // ENABLE(REMOTE_INSPECTOR)