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