ddd4bd772504f74960a2f1e964dbcaf91afcbf7e
[WebKit.git] / Source / WebKit2 / UIProcess / glib / RemoteInspectorClient.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 "RemoteInspectorClient.h"
28
29 #if ENABLE(REMOTE_INSPECTOR)
30
31 #include "RemoteWebInspectorProxy.h"
32 #include <JavaScriptCore/RemoteInspectorUtils.h>
33 #include <gio/gio.h>
34 #include <wtf/glib/GUniquePtr.h>
35 #include <wtf/text/Base64.h>
36
37 #if PLATFORM(GTK)
38 #define REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "org.webkitgtk.RemoteInspectorClient"
39 #define REMOTE_INSPECTOR_CLIENT_OBJECT_PATH "/org/webkitgtk/RemoteInspectorClient"
40 #define INSPECTOR_DBUS_INTERFACE "org.webkitgtk.Inspector"
41 #define INSPECTOR_DBUS_OBJECT_PATH "/org/webkitgtk/Inspector"
42 #endif
43
44 namespace WebKit {
45
46 class RemoteInspectorProxy final : public RemoteWebInspectorProxyClient {
47     WTF_MAKE_FAST_ALLOCATED();
48 public:
49     RemoteInspectorProxy(RemoteInspectorClient& inspectorClient, uint64_t connectionID, uint64_t targetID)
50         : m_proxy(RemoteWebInspectorProxy::create())
51         , m_inspectorClient(inspectorClient)
52         , m_connectionID(connectionID)
53         , m_targetID(targetID)
54     {
55         m_proxy->setClient(this);
56     }
57
58     ~RemoteInspectorProxy()
59     {
60         m_proxy->setClient(nullptr);
61         m_proxy->invalidate();
62     }
63
64     void load()
65     {
66         m_proxy->load("web", m_inspectorClient.backendCommandsURL());
67     }
68
69     void show()
70     {
71         m_proxy->show();
72     }
73
74     void setTargetName(const CString& name)
75     {
76 #if PLATFORM(GTK)
77         m_proxy->updateWindowTitle(name);
78 #endif
79     }
80
81     void sendMessageToFrontend(const String& message)
82     {
83         m_proxy->sendMessageToFrontend(message);
84     }
85
86     void sendMessageToBackend(const String& message) override
87     {
88         m_inspectorClient.sendMessageToBackend(m_connectionID, m_targetID, message);
89     }
90
91     void closeFromFrontend() override
92     {
93         m_inspectorClient.closeFromFrontend(m_connectionID, m_targetID);
94     }
95
96 private:
97     Ref<RemoteWebInspectorProxy> m_proxy;
98     RemoteInspectorClient& m_inspectorClient;
99     uint64_t m_connectionID;
100     uint64_t m_targetID;
101 };
102
103 static const char introspectionXML[] =
104     "<node>"
105     "  <interface name='" REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "'>"
106     "    <method name='SetTargetList'>"
107     "      <arg type='t' name='connectionID' direction='in'/>"
108     "      <arg type='a(tsssb)' name='list' direction='in'/>"
109     "    </method>"
110     "    <method name='SendMessageToFrontend'>"
111     "      <arg type='t' name='connectionID' direction='in'/>"
112     "      <arg type='t' name='target' direction='in'/>"
113     "      <arg type='s' name='message' direction='in'/>"
114     "    </method>"
115     "  </interface>"
116     "</node>";
117
118 const GDBusInterfaceVTable RemoteInspectorClient::s_interfaceVTable = {
119     // method_call
120     [](GDBusConnection* connection, const gchar* sender, const gchar* objectPath, const gchar* interfaceName, const gchar* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) {
121         auto* client = static_cast<RemoteInspectorClient*>(userData);
122         if (!g_strcmp0(methodName, "SetTargetList")) {
123             guint64 connectionID;
124             GUniqueOutPtr<GVariantIter> iter;
125             g_variant_get(parameters, "(ta(tsssb))", &connectionID, &iter.outPtr());
126             size_t targetCount = g_variant_iter_n_children(iter.get());
127             Vector<RemoteInspectorClient::Target> targetList;
128             targetList.reserveInitialCapacity(targetCount);
129             guint64 targetID;
130             const char* type;
131             const char* name;
132             const char* url;
133             gboolean hasLocalDebugger;
134             while (g_variant_iter_loop(iter.get(), "(t&s&s&sb)", &targetID, &type, &name, &url, &hasLocalDebugger)) {
135                 if (!g_strcmp0(type, "Web") || !g_strcmp0(type, "JavaScript"))
136                     targetList.uncheckedAppend({ targetID, type, name, url });
137             }
138             client->setTargetList(connectionID, WTFMove(targetList));
139             g_dbus_method_invocation_return_value(invocation, nullptr);
140         } else if (!g_strcmp0(methodName, "SendMessageToFrontend")) {
141             guint64 connectionID, targetID;
142             const char* message;
143             g_variant_get(parameters, "(tt&s)", &connectionID, &targetID, &message);
144             client->sendMessageToFrontend(connectionID, targetID, message);
145             g_dbus_method_invocation_return_value(invocation, nullptr);
146         } else
147             g_dbus_method_invocation_return_value(invocation, nullptr);
148     },
149     // get_property
150     nullptr,
151     // set_property
152     nullptr,
153     // padding
154     nullptr
155 };
156
157 RemoteInspectorClient::RemoteInspectorClient(const char* address, unsigned port, RemoteInspectorObserver& observer)
158     : m_hostAndPort(String::fromUTF8(address) + ':' + String::number(port))
159     , m_observer(observer)
160     , m_cancellable(adoptGRef(g_cancellable_new()))
161 {
162     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", address, port));
163     g_dbus_connection_new_for_address(dbusAddress.get(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, m_cancellable.get(),
164         [](GObject*, GAsyncResult* result, gpointer userData) {
165             auto* client = static_cast<RemoteInspectorClient*>(userData);
166             GUniqueOutPtr<GError> error;
167             GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr()));
168             if (!connection && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
169                 WTFLogAlways("RemoteInspectorClient failed to connect to inspector server: %s", error->message);
170             client->setupConnection(WTFMove(connection));
171     }, this);
172 }
173
174 RemoteInspectorClient::~RemoteInspectorClient()
175 {
176 }
177
178 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
179 {
180     GUniqueOutPtr<GError> error;
181     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
182     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
183         WTFLogAlways("RemoteInspectorClient failed to send DBus message: %s", error->message);
184 }
185
186 void RemoteInspectorClient::connectionClosedCallback(GDBusConnection* connection, gboolean /*remotePeerVanished*/, GError*, RemoteInspectorClient* client)
187 {
188     ASSERT_UNUSED(connection, client->m_dbusConnection.get() == connection);
189     client->connectionClosed();
190 }
191
192 void RemoteInspectorClient::setupConnection(GRefPtr<GDBusConnection>&& connection)
193 {
194     m_dbusConnection = WTFMove(connection);
195     if (!m_dbusConnection) {
196         m_observer.connectionClosed(*this);
197         return;
198     }
199     g_signal_connect(m_dbusConnection.get(), "closed", G_CALLBACK(connectionClosedCallback), this);
200
201     static GDBusNodeInfo* introspectionData = nullptr;
202     if (!introspectionData)
203         introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
204
205     g_dbus_connection_register_object(m_dbusConnection.get(), REMOTE_INSPECTOR_CLIENT_OBJECT_PATH, introspectionData->interfaces[0], &s_interfaceVTable, this, nullptr, nullptr);
206
207     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
208         INSPECTOR_DBUS_OBJECT_PATH,
209         INSPECTOR_DBUS_INTERFACE,
210         "SetupInspectorClient",
211         g_variant_new("(@ay)", g_variant_new_bytestring(Inspector::backendCommandsHash().data())),
212         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
213         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
214             GUniqueOutPtr<GError> error;
215             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
216             if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
217                 return;
218             if (!resultVariant) {
219                 WTFLogAlways("RemoteInspectorClient failed to send DBus message: %s", error->message);
220                 return;
221             }
222
223             auto* client = static_cast<RemoteInspectorClient*>(userData);
224             GRefPtr<GVariant> backendCommandsVariant;
225             g_variant_get(resultVariant.get(), "(@ay)", &backendCommandsVariant.outPtr());
226             client->setBackendCommands(g_variant_get_bytestring(backendCommandsVariant.get()));
227         }, this);
228 }
229
230 void RemoteInspectorClient::setBackendCommands(const char* backendCommands)
231 {
232     if (!backendCommands || !backendCommands[0]) {
233         m_backendCommandsURL = String();
234         return;
235     }
236
237     Vector<char> base64Data;
238     base64Encode(backendCommands, strlen(backendCommands), base64Data);
239     m_backendCommandsURL = "data:text/javascript;base64," + base64Data;
240 }
241
242 void RemoteInspectorClient::connectionClosed()
243 {
244     g_cancellable_cancel(m_cancellable.get());
245     m_targets.clear();
246     m_inspectorProxyMap.clear();
247     m_dbusConnection = nullptr;
248     m_observer.connectionClosed(*this);
249 }
250
251 void RemoteInspectorClient::inspect(uint64_t connectionID, uint64_t targetID)
252 {
253     auto addResult = m_inspectorProxyMap.ensure(std::make_pair(connectionID, targetID), [this, connectionID, targetID] {
254         return std::make_unique<RemoteInspectorProxy>(*this, connectionID, targetID);
255     });
256     if (!addResult.isNewEntry) {
257         addResult.iterator->value->show();
258         return;
259     }
260
261     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
262         INSPECTOR_DBUS_OBJECT_PATH,
263         INSPECTOR_DBUS_INTERFACE,
264         "Setup",
265         g_variant_new("(tt)", connectionID, targetID),
266         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
267         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
268
269     addResult.iterator->value->load();
270 }
271
272 void RemoteInspectorClient::sendMessageToBackend(uint64_t connectionID, uint64_t targetID, const String& message)
273 {
274     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
275         INSPECTOR_DBUS_OBJECT_PATH,
276         INSPECTOR_DBUS_INTERFACE,
277         "SendMessageToBackend",
278         g_variant_new("(tts)", connectionID, targetID, message.utf8().data()),
279         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
280         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
281 }
282
283 void RemoteInspectorClient::closeFromFrontend(uint64_t connectionID, uint64_t targetID)
284 {
285     ASSERT(m_inspectorProxyMap.contains(std::make_pair(connectionID, targetID)));
286     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
287         INSPECTOR_DBUS_OBJECT_PATH,
288         INSPECTOR_DBUS_INTERFACE,
289         "FrontendDidClose",
290         g_variant_new("(tt)", connectionID, targetID),
291         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
292         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
293     m_inspectorProxyMap.remove(std::make_pair(connectionID, targetID));
294 }
295
296 void RemoteInspectorClient::setTargetList(uint64_t connectionID, Vector<Target>&& targetList)
297 {
298     // Find closed targets to remove them.
299     Vector<uint64_t, 4> targetsToRemove;
300     for (auto& connectionTargetPair : m_inspectorProxyMap.keys()) {
301         if (connectionTargetPair.first != connectionID)
302             continue;
303         bool found = false;
304         for (const auto& target : targetList) {
305             if (target.id == connectionTargetPair.second) {
306                 m_inspectorProxyMap.get(connectionTargetPair)->setTargetName(target.name);
307                 found = true;
308                 break;
309             }
310         }
311         if (!found)
312             targetsToRemove.append(connectionTargetPair.second);
313     }
314     for (auto targetID : targetsToRemove)
315         m_inspectorProxyMap.remove(std::make_pair(connectionID, targetID));
316
317     m_targets.set(connectionID, WTFMove(targetList));
318     m_observer.targetListChanged(*this);
319 }
320
321 void RemoteInspectorClient::sendMessageToFrontend(uint64_t connectionID, uint64_t targetID, const char* message)
322 {
323     auto proxy = m_inspectorProxyMap.get(std::make_pair(connectionID, targetID));
324     ASSERT(proxy);
325     if (!proxy)
326         return;
327     proxy->sendMessageToFrontend(String::fromUTF8(message));
328 }
329
330 } // namespace WebKit
331
332 #endif // ENABLE(REMOTE_INSPECTOR)