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