[GLIB] Make remote inspector DBus protocol common to all glib based ports
[WebKit.git] / Source / JavaScriptCore / inspector / remote / glib / RemoteInspectorGlib.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 "RemoteInspector.h"
28
29 #if ENABLE(REMOTE_INSPECTOR)
30
31 #include "RemoteAutomationTarget.h"
32 #include "RemoteConnectionToTarget.h"
33 #include "RemoteInspectionTarget.h"
34 #include <gio/gio.h>
35 #include <wtf/NeverDestroyed.h>
36 #include <wtf/RunLoop.h>
37 #include <wtf/glib/GUniquePtr.h>
38
39 #define REMOTE_INSPECTOR_DBUS_INTERFACE "org.webkit.RemoteInspector"
40 #define REMOTE_INSPECTOR_DBUS_OBJECT_PATH "/org/webkit/RemoteInspector"
41 #define INSPECTOR_DBUS_INTERFACE "org.webkit.Inspector"
42 #define INSPECTOR_DBUS_OBJECT_PATH "/org/webkit/Inspector"
43
44 namespace Inspector {
45
46 RemoteInspector& RemoteInspector::singleton()
47 {
48     static NeverDestroyed<RemoteInspector> shared;
49     return shared;
50 }
51
52 RemoteInspector::RemoteInspector()
53 {
54     if (g_getenv("WEBKIT_INSPECTOR_SERVER"))
55         start();
56 }
57
58 void RemoteInspector::start()
59 {
60     std::lock_guard<Lock> lock(m_mutex);
61
62     if (m_enabled)
63         return;
64
65     m_enabled = true;
66     m_cancellable = adoptGRef(g_cancellable_new());
67
68     GUniquePtr<char> inspectorAddress(g_strdup(g_getenv("WEBKIT_INSPECTOR_SERVER")));
69     char* portPtr = g_strrstr(inspectorAddress.get(), ":");
70     ASSERT(portPtr);
71     *portPtr = '\0';
72     portPtr++;
73     unsigned port = g_ascii_strtoull(portPtr, nullptr, 10);
74     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", inspectorAddress.get(), port));
75     g_dbus_connection_new_for_address(dbusAddress.get(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, m_cancellable.get(),
76         [](GObject*, GAsyncResult* result, gpointer userData) {
77             RemoteInspector* inspector = static_cast<RemoteInspector*>(userData);
78             GUniqueOutPtr<GError> error;
79             if (GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr())))
80                 inspector->setupConnection(WTFMove(connection));
81             else if (!g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
82                 WTFLogAlways("RemoteInspector failed to connect to inspector server at: %s: %s", g_getenv("WEBKIT_INSPECTOR_SERVER"), error->message);
83     }, this);
84 }
85
86 void RemoteInspector::stopInternal(StopSource)
87 {
88     if (!m_enabled)
89         return;
90
91     m_enabled = false;
92     m_pushScheduled = false;
93     g_cancellable_cancel(m_cancellable.get());
94     m_cancellable = nullptr;
95
96     for (auto targetConnection : m_targetConnectionMap.values())
97         targetConnection->close();
98     m_targetConnectionMap.clear();
99
100     updateHasActiveDebugSession();
101
102     m_automaticInspectionPaused = false;
103     m_dbusConnection = nullptr;
104 }
105
106 static const char introspectionXML[] =
107     "<node>"
108     "  <interface name='" REMOTE_INSPECTOR_DBUS_INTERFACE "'>"
109     "    <method name='GetTargetList'>"
110     "    </method>"
111     "    <method name='Setup'>"
112     "      <arg type='t' name='target' direction='in'/>"
113     "    </method>"
114     "    <method name='SendMessageToTarget'>"
115     "      <arg type='t' name='target' direction='in'/>"
116     "      <arg type='s' name='message' direction='in'/>"
117     "    </method>"
118     "    <method name='FrontendDidClose'>"
119     "      <arg type='t' name='target' direction='in'/>"
120     "    </method>"
121     "  </interface>"
122     "</node>";
123
124 const GDBusInterfaceVTable RemoteInspector::s_interfaceVTable = {
125     // method_call
126     [] (GDBusConnection*, const gchar* /*sender*/, const gchar* /*objectPath*/, const gchar* /*interfaceName*/, const gchar* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) {
127         auto* inspector = static_cast<RemoteInspector*>(userData);
128         if (!g_strcmp0(methodName, "GetTargetList")) {
129             inspector->receivedGetTargetListMessage();
130             g_dbus_method_invocation_return_value(invocation, nullptr);
131         } else if (!g_strcmp0(methodName, "Setup")) {
132             guint64 targetID;
133             g_variant_get(parameters, "(t)", &targetID);
134             inspector->receivedSetupMessage(targetID);
135             g_dbus_method_invocation_return_value(invocation, nullptr);
136         } else if (!g_strcmp0(methodName, "SendMessageToTarget")) {
137             guint64 targetID;
138             const char* message;
139             g_variant_get(parameters, "(t&s)", &targetID, &message);
140             inspector->receivedDataMessage(targetID, message);
141             g_dbus_method_invocation_return_value(invocation, nullptr);
142         } else if (!g_strcmp0(methodName, "FrontendDidClose")) {
143             guint64 targetID;
144             g_variant_get(parameters, "(t)", &targetID);
145             inspector->receivedCloseMessage(targetID);
146             g_dbus_method_invocation_return_value(invocation, nullptr);
147         }
148     },
149     // get_property
150     nullptr,
151     // set_property
152     nullptr,
153     // padding
154     nullptr
155 };
156
157 void RemoteInspector::setupConnection(GRefPtr<GDBusConnection>&& connection)
158 {
159     std::lock_guard<Lock> lock(m_mutex);
160
161     ASSERT(connection);
162     ASSERT(!m_dbusConnection);
163     m_dbusConnection = WTFMove(connection);
164
165     static GDBusNodeInfo* introspectionData = nullptr;
166     if (!introspectionData)
167         introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
168
169     g_dbus_connection_register_object(m_dbusConnection.get(), REMOTE_INSPECTOR_DBUS_OBJECT_PATH,
170         introspectionData->interfaces[0], &s_interfaceVTable, this, nullptr, nullptr);
171
172     if (!m_targetMap.isEmpty())
173         pushListingsSoon();
174 }
175
176 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
177 {
178     GUniqueOutPtr<GError> error;
179     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
180     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
181         WTFLogAlways("RemoteInspector failed to send DBus message: %s", error->message);
182 }
183
184 TargetListing RemoteInspector::listingForInspectionTarget(const RemoteInspectionTarget& target) const
185 {
186     if (!target.remoteDebuggingAllowed())
187         return nullptr;
188
189     ASSERT(target.type() == RemoteInspectionTarget::Type::Web || target.type() == RemoteInspectionTarget::Type::JavaScript);
190     return g_variant_new("(tsssb)", target.targetIdentifier(), target.type() == RemoteInspectionTarget::Type::Web ? "Web" : "JavaScript",
191         target.name().utf8().data(), target.type() == RemoteInspectionTarget::Type::Web ? target.url().utf8().data() : "null",
192         target.hasLocalDebugger());
193 }
194
195 TargetListing RemoteInspector::listingForAutomationTarget(const RemoteAutomationTarget& target) const
196 {
197     return g_variant_new("(tsssb)", target.targetIdentifier(), "Automation", target.name().utf8().data(), "null", target.isPaired());
198 }
199
200 void RemoteInspector::pushListingsNow()
201 {
202     if (!m_dbusConnection)
203         return;
204
205     m_pushScheduled = false;
206
207     GVariantBuilder builder;
208     g_variant_builder_init(&builder, G_VARIANT_TYPE("(a(tsssb)b)"));
209     g_variant_builder_open(&builder, G_VARIANT_TYPE("a(tsssb)"));
210     for (auto listing : m_targetListingMap.values())
211         g_variant_builder_add_value(&builder, listing.get());
212     g_variant_builder_close(&builder);
213     g_variant_builder_add(&builder, "b", m_clientCapabilities && m_clientCapabilities->remoteAutomationAllowed);
214     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
215         INSPECTOR_DBUS_OBJECT_PATH, INSPECTOR_DBUS_INTERFACE, "SetTargetList",
216         g_variant_builder_end(&builder), nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
217         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
218 }
219
220 void RemoteInspector::pushListingsSoon()
221 {
222     if (!m_dbusConnection)
223         return;
224
225     if (m_pushScheduled)
226         return;
227
228     m_pushScheduled = true;
229
230     RunLoop::current().dispatch([this] {
231         std::lock_guard<Lock> lock(m_mutex);
232         if (m_pushScheduled)
233             pushListingsNow();
234     });
235 }
236
237 void RemoteInspector::updateAutomaticInspectionCandidate(RemoteInspectionTarget* target)
238 {
239     std::lock_guard<Lock> lock(m_mutex);
240
241     ASSERT(target);
242     unsigned targetIdentifier = target->targetIdentifier();
243     if (!targetIdentifier)
244         return;
245
246     auto result = m_targetMap.set(targetIdentifier, target);
247     ASSERT_UNUSED(result, !result.isNewEntry);
248
249     // If the target has just allowed remote control, then the listing won't exist yet.
250     // If the target has no identifier remove the old listing.
251     if (auto targetListing = listingForTarget(*target))
252         m_targetListingMap.set(targetIdentifier, targetListing);
253     else
254         m_targetListingMap.remove(targetIdentifier);
255     // FIXME: Implement automatic inspection.
256     pushListingsSoon();
257 }
258
259 void RemoteInspector::sendAutomaticInspectionCandidateMessage()
260 {
261     ASSERT(m_enabled);
262     ASSERT(m_automaticInspectionEnabled);
263     ASSERT(m_automaticInspectionPaused);
264     ASSERT(m_automaticInspectionCandidateTargetIdentifier);
265     ASSERT(m_dbusConnection);
266     // FIXME: Implement automatic inspection.
267 }
268
269 void RemoteInspector::sendMessageToRemote(unsigned targetIdentifier, const String& message)
270 {
271     std::lock_guard<Lock> lock(m_mutex);
272     if (!m_dbusConnection)
273         return;
274
275     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
276         INSPECTOR_DBUS_OBJECT_PATH, INSPECTOR_DBUS_INTERFACE, "SendMessageToFrontend",
277         g_variant_new("(ts)", targetIdentifier, message.utf8().data()),
278         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
279         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
280 }
281
282 void RemoteInspector::receivedGetTargetListMessage()
283 {
284     std::lock_guard<Lock> lock(m_mutex);
285     pushListingsNow();
286 }
287
288 void RemoteInspector::receivedSetupMessage(unsigned targetIdentifier)
289 {
290     std::lock_guard<Lock> lock(m_mutex);
291     setup(targetIdentifier);
292 }
293
294 void RemoteInspector::receivedDataMessage(unsigned targetIdentifier, const char* message)
295 {
296     RefPtr<RemoteConnectionToTarget> connectionToTarget;
297     {
298         std::lock_guard<Lock> lock(m_mutex);
299         connectionToTarget = m_targetConnectionMap.get(targetIdentifier);
300         if (!connectionToTarget)
301             return;
302     }
303     connectionToTarget->sendMessageToTarget(String::fromUTF8(message));
304 }
305
306 void RemoteInspector::receivedCloseMessage(unsigned targetIdentifier)
307 {
308     RefPtr<RemoteConnectionToTarget> connectionToTarget;
309     {
310         std::lock_guard<Lock> lock(m_mutex);
311         RemoteControllableTarget* target = m_targetMap.get(targetIdentifier);
312         if (!target)
313             return;
314
315         connectionToTarget = m_targetConnectionMap.take(targetIdentifier);
316         updateHasActiveDebugSession();
317     }
318
319     if (connectionToTarget)
320         connectionToTarget->close();
321 }
322
323 void RemoteInspector::setup(unsigned targetIdentifier)
324 {
325     RemoteControllableTarget* target = m_targetMap.get(targetIdentifier);
326     if (!target)
327         return;
328
329     auto connectionToTarget = adoptRef(*new RemoteConnectionToTarget(*target));
330     ASSERT(is<RemoteInspectionTarget>(target) || is<RemoteAutomationTarget>(target));
331     if (!connectionToTarget->setup()) {
332         connectionToTarget->close();
333         return;
334     }
335     m_targetConnectionMap.set(targetIdentifier, WTFMove(connectionToTarget));
336
337     updateHasActiveDebugSession();
338 }
339
340 void RemoteInspector::sendMessageToTarget(unsigned targetIdentifier, const char* message)
341 {
342     if (auto connectionToTarget = m_targetConnectionMap.get(targetIdentifier))
343         connectionToTarget->sendMessageToTarget(String::fromUTF8(message));
344 }
345
346 void RemoteInspector::requestAutomationSession(const char* sessionID)
347 {
348     if (!m_client)
349         return;
350
351     if (!m_clientCapabilities || !m_clientCapabilities->remoteAutomationAllowed)
352         return;
353
354     if (!sessionID || !sessionID[0])
355         return;
356
357     m_client->requestAutomationSession(String::fromUTF8(sessionID));
358 }
359
360 } // namespace Inspector
361
362 #endif // ENABLE(REMOTE_INSPECTOR)